@moq/net 0.3.4 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/broadcast.d.ts.map +1 -1
- package/broadcast.js +5 -4
- package/broadcast.js.map +1 -1
- package/connection/connect.d.ts.map +1 -1
- package/connection/connect.js +12 -5
- package/connection/connect.js.map +1 -1
- package/ietf/publisher.d.ts.map +1 -1
- package/ietf/publisher.js +55 -28
- package/ietf/publisher.js.map +1 -1
- package/internal.d.ts +2 -0
- package/internal.d.ts.map +1 -1
- package/internal.js.map +1 -1
- package/lite/publisher.d.ts.map +1 -1
- package/lite/publisher.js +98 -78
- package/lite/publisher.js.map +1 -1
- package/package.json +1 -1
- package/stream.js +2 -2
- package/stream.js.map +1 -1
- package/track.d.ts +7 -1
- package/track.d.ts.map +1 -1
- package/track.js +21 -2
- package/track.js.map +1 -1
- package/util/log.d.ts +5 -0
- package/util/log.d.ts.map +1 -0
- package/util/log.js +17 -0
- package/util/log.js.map +1 -0
package/README.md
CHANGED
|
@@ -8,11 +8,11 @@
|
|
|
8
8
|
[](https://www.typescriptlang.org/)
|
|
9
9
|
|
|
10
10
|
A TypeScript [Media over QUIC](https://moq.dev/) (MoQ) client for both browsers and server JS/TS environments.
|
|
11
|
-
`@moq/net` is the **networking layer**: real-time pub/sub with built-in caching, fan-out, and prioritization, on top of QUIC. At session setup it negotiates one of two wire protocols, either the simplified [moq-lite](https://doc.moq.dev/concept/
|
|
11
|
+
`@moq/net` is the **networking layer**: real-time pub/sub with built-in caching, fan-out, and prioritization, on top of QUIC. At session setup it negotiates one of two wire protocols, either the simplified [moq-lite](https://doc.moq.dev/concept/moq-lite) protocol or the full IETF [moq-transport](https://datatracker.ietf.org/doc/draft-ietf-moq-transport/) draft.
|
|
12
12
|
|
|
13
13
|
Check out [hang](../hang) for a higher-level media library that uses this package.
|
|
14
14
|
|
|
15
|
-
> **Note:** moq-lite is a subset of moq-transport and is forwards compatible with it, so this client works with any moq-transport CDN (ex. [Cloudflare](https://moq.dev/blog/first-cdn/)). See the [compatibility docs](https://doc.moq.dev/concept/
|
|
15
|
+
> **Note:** moq-lite is a subset of moq-transport and is forwards compatible with it, so this client works with any moq-transport CDN (ex. [Cloudflare](https://moq.dev/blog/first-cdn/)). See the [compatibility docs](https://doc.moq.dev/concept/moq-lite#compatibility) for details.
|
|
16
16
|
|
|
17
17
|
## Quick Start
|
|
18
18
|
|
package/broadcast.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broadcast.d.ts","sourceRoot":"","sources":["../src/broadcast.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,UAAU,EAAgB,MAAM,cAAc,CAAC;AAC7D,OAAO,KAAK,EAAE,QAAQ,IAAI,aAAa,EAAE,MAAM,YAAY,CAAC;AAE5D,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"broadcast.d.ts","sourceRoot":"","sources":["../src/broadcast.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,UAAU,EAAgB,MAAM,cAAc,CAAC;AAC7D,OAAO,KAAK,EAAE,QAAQ,IAAI,aAAa,EAAE,MAAM,YAAY,CAAC;AAE5D,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AAkIpC;;;;GAIG;AACH,qBAAa,QAAS,YAAW,KAAK,CAAC,SAAS;;IAG/C;;;OAGG;IACH,IAAI,MAAM,IAAI,UAAU,CAAC,KAAK,GAAG,IAAI,CAAC,CAErC;IAED,wCAAwC;IACxC,OAAO,IAAI,QAAQ,CAElB;IAED,iDAAiD;IAC3C,SAAS,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,GAAG,SAAS,CAAC,CAWpD;IAED,uFAAuF;IACvF,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,CAiBvC;IAED,6EAA6E;IAC7E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S,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,GAAG,SAAS,CAAC,CAWpD;IAED;;;OAGG;IACH,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAElD;IAED;;;;OAIG;IACH,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,CAAC,iBAAiB,GAAG,OAAO,CAAC,aAAa,CAAC,CAEpG;IAED;;;OAGG;IACH,KAAK,CAAC,KAAK,CAAC,EAAE,KAAK,QAKlB;CACD"}
|
package/broadcast.js
CHANGED
|
@@ -10,6 +10,7 @@ import * as track from "./track.js";
|
|
|
10
10
|
/** Reactive backing state shared by broadcast producers and consumers. */
|
|
11
11
|
class BroadcastState {
|
|
12
12
|
requested = new Signal([]);
|
|
13
|
+
pending = new Set();
|
|
13
14
|
closed = new Once();
|
|
14
15
|
tracks = new Map();
|
|
15
16
|
sequences = new Map();
|
|
@@ -32,9 +33,9 @@ function closeState(state, abort) {
|
|
|
32
33
|
if (state.closed.peek() !== undefined)
|
|
33
34
|
return;
|
|
34
35
|
state.closed.set(abort ?? null);
|
|
36
|
+
for (const request of state.pending)
|
|
37
|
+
request.reject(abort);
|
|
35
38
|
state.requested.mutate((requests) => {
|
|
36
|
-
for (const request of requests)
|
|
37
|
-
request.reject(abort);
|
|
38
39
|
requests.length = 0;
|
|
39
40
|
});
|
|
40
41
|
}
|
|
@@ -67,7 +68,7 @@ function subscribe(state, name, options = {}, register = false) {
|
|
|
67
68
|
});
|
|
68
69
|
}
|
|
69
70
|
state.requested.mutate((requested) => {
|
|
70
|
-
requested.push(hooks.makeRequest({ name, producer, sequences: state.sequences }));
|
|
71
|
+
requested.push(hooks.makeRequest({ name, producer, sequences: state.sequences, pending: state.pending }));
|
|
71
72
|
});
|
|
72
73
|
return subscriber;
|
|
73
74
|
}
|
|
@@ -81,7 +82,7 @@ async function resolveTrackInfo(state, name) {
|
|
|
81
82
|
}
|
|
82
83
|
const producer = new track.Producer(name);
|
|
83
84
|
state.requested.mutate((requested) => {
|
|
84
|
-
requested.push(hooks.makeRequest({ name, producer, sequences: state.sequences }));
|
|
85
|
+
requested.push(hooks.makeRequest({ name, producer, sequences: state.sequences, pending: state.pending }));
|
|
85
86
|
});
|
|
86
87
|
try {
|
|
87
88
|
return await producer.info();
|
package/broadcast.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broadcast.js","sourceRoot":"","sources":["../src/broadcast.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmB,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAE7D,OAAO,EAAE,KAAK,EAAsB,MAAM,eAAe,CAAC;AAC1D,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AAEpC,0EAA0E;AAC1E,MAAM,cAAc;IACnB,SAAS,GAAG,IAAI,MAAM,CAAkB,EAAE,CAAC,CAAC;IAC5C,MAAM,GAAG,IAAI,IAAI,EAAgB,CAAC;IAClC,MAAM,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC3C,SAAS,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC7C,uFAAuF;IACvF,0FAA0F;IAC1F,SAAS,GAAG,CAAC,CAAC;CACd;AAED,SAAS,cAAc,CAAC,KAAqB;IAC5C,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;IACzC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC;IAClD,OAAO,SAAS,CAAC,GAAG,EAAE,CAAC;AACxB,CAAC;AAED,+EAA+E;AAC/E,8EAA8E;AAC9E,6DAA6D;AAC7D,EAAE;AACF,sFAAsF;AACtF,+CAA+C;AAC/C,SAAS,UAAU,CAAC,KAAqB,EAAE,KAA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AI,CAAC,CAAC;IACpD,CAAC;IAED,iGAAiG;IACjG,KAAK,CAAC,SAAS;QACd,SAAS,CAAC;YACT,MAAM,OAAO,GAAG,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC5C,IAAI,OAAO;gBAAE,OAAO,OAAO,CAAC;YAE5B,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;YACzC,IAAI,MAAM,YAAY,KAAK;gBAAE,MAAM,MAAM,CAAC;YAC1C,IAAI,MAAM,KAAK,SAAS;gBAAE,OAAO,SAAS,CAAC;YAE3C,MAAM,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC9D,CAAC;IACF,CAAC;IAED;;;OAGG;IACH,gBAAgB,CAAC,IAAY;QAC5B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC;IAED;;;;OAIG;IACH,UAAU,CAAC,IAAY,EAAE,QAAgB,EAAE,OAAiC;QAC3E,OAAO,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IACzD,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,KAAa;QAClB,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO;QACzB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC;YAAE,OAAO;QACxC,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAChC,CAAC;CACD","sourcesContent":["/**\n * Broadcast role handles: a named collection of tracks produced by a publisher.\n *\n * @module\n */\nimport { type GetPromise, Once, Signal } from \"@moq/signals\";\nimport type { Consumer as GroupConsumer } from \"./group.ts\";\nimport { hooks, type TrackSequence } from \"./internal.ts\";\nimport * as track from \"./track.ts\";\n\n/** Reactive backing state shared by broadcast producers and consumers. */\nclass BroadcastState {\n\trequested = new Signal<track.Request[]>([]);\n\tclosed = new Once<Error | null>();\n\ttracks = new Map<string, track.Producer>();\n\tsequences = new Map<string, TrackSequence>();\n\t// Live consumer handles sharing this state (see {@link Consumer.clone}). The broadcast\n\t// closes once the last one closes, so a shared consumer can be handed to several callers.\n\tconsumers = 0;\n}\n\nfunction dequeueRequest(state: BroadcastState): track.Request | undefined {\n\tconst requested = state.requested.peek();\n\trequested.sort((a, b) => a.priority - b.priority);\n\treturn requested.pop();\n}\n\n// Close the broadcast and reject any requests still pending in the queue, so a\n// subscriber blocked on the track's info() or group reads is unblocked rather\n// than left waiting on a producer that will never be served.\n//\n// Once.set throws on a second settle, and the producer and each consumer handle close\n// independently, so this has to be idempotent.\nfunction closeState(state: BroadcastState, abort?: Error) {\n\tif (state.closed.peek() !== undefined) return;\n\tstate.closed.set(abort ?? null);\n\tstate.requested.mutate((requests) => {\n\t\tfor (const request of requests) request.reject(abort);\n\t\trequests.length = 0;\n\t});\n}\n\n// `register` is set on the subscribing (consumer) side: the fresh producer is cached in\n// `state.tracks` so repeat subscriptions to the same track fan out from one upstream subscription\n// instead of opening a new one, mirroring the Rust `broadcast::Consumer::track` weak-dedup. The\n// consumer wire watches the producer's demand ({@link track.Producer.used}) and tears the upstream\n// down once its last subscriber leaves, closing the producer, which evicts the cache entry below.\n// The publishing side leaves `register` false: `state.tracks` there holds only the tracks the app\n// inserted, and a dynamic serve stays one request per peer subscription.\nfunction subscribe(\n\tstate: BroadcastState,\n\tname: string,\n\toptions: track.Subscription = {},\n\tregister = false,\n): track.Subscriber {\n\tif (state.closed.peek() !== undefined) {\n\t\tthrow new Error(`broadcast is closed: ${state.closed.peek()}`);\n\t}\n\n\tconst existing = state.tracks.get(name);\n\tif (existing) {\n\t\tif (existing.closed.peek() === undefined) return existing.subscribe(options);\n\t\tstate.tracks.delete(name);\n\t}\n\n\tconst producer = new track.Producer(name);\n\tconst subscriber = producer.subscribe(options);\n\n\tif (register) {\n\t\tstate.tracks.set(name, producer);\n\t\t// Drop the cache entry once the upstream closes (the wire tears it down when its last\n\t\t// subscriber leaves), so a later subscribe re-opens it.\n\t\tvoid producer.closed.then(() => {\n\t\t\tif (state.tracks.get(name) === producer) state.tracks.delete(name);\n\t\t});\n\t}\n\n\tstate.requested.mutate((requested) => {\n\t\trequested.push(hooks.makeRequest({ name, producer, sequences: state.sequences }));\n\t});\n\n\treturn subscriber;\n}\n\nasync function resolveTrackInfo(state: BroadcastState, name: string): Promise<track.Info> {\n\tconst existing = state.tracks.get(name);\n\tif (existing && existing.closed.peek() === undefined) {\n\t\treturn existing.info();\n\t}\n\n\tif (state.closed.peek() !== undefined) {\n\t\treturn Promise.reject(new Error(`broadcast is closed: ${state.closed.peek()}`));\n\t}\n\n\tconst producer = new track.Producer(name);\n\tstate.requested.mutate((requested) => {\n\t\trequested.push(hooks.makeRequest({ name, producer, sequences: state.sequences }));\n\t});\n\n\ttry {\n\t\treturn await producer.info();\n\t} finally {\n\t\tproducer.close();\n\t}\n}\n\n// Serve a group from the local retained window by subscribing and scanning to the\n// requested sequence. The default for a produced broadcast; the consuming wire layer\n// overrides it to fetch over the network (or to reject when the transport has no FETCH).\nasync function fetchGroup(\n\tstate: BroadcastState,\n\tname: string,\n\tsequence: number,\n\toptions: track.FetchGroupOptions = {},\n): Promise<GroupConsumer> {\n\tconst subscriber = subscribe(state, name, { priority: options.priority });\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst group = await subscriber.recvGroup();\n\t\t\tif (!group) throw new Error(`group not found: ${sequence}`);\n\t\t\tif (group.sequence === sequence) {\n\t\t\t\t// Close the subscription when the returned group finishes, not now: an\n\t\t\t\t// in-progress group must keep receiving frames for its lifetime (mirrors\n\t\t\t\t// Rust poll_fetch). Also fires if the caller closes the group early.\n\t\t\t\tvoid group.closed.then(() => subscriber.close());\n\t\t\t\treturn group;\n\t\t\t}\n\n\t\t\tgroup.close();\n\t\t\tif (group.sequence > sequence) throw new Error(`group not found: ${sequence}`);\n\t\t}\n\t} catch (err) {\n\t\tsubscriber.close();\n\t\tthrow err;\n\t}\n}\n\n/**\n * The write side of a broadcast.\n *\n * @public\n */\nexport class Producer implements track.Broadcast {\n\t#state = new BroadcastState();\n\n\t/**\n\t * Settles once the broadcast closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\t/** A read handle for this broadcast. */\n\tconsume(): Consumer {\n\t\treturn makeConsumer(this.#state);\n\t}\n\n\t/** Return the next track requested by a peer. */\n\tasync requested(): Promise<track.Request | undefined> {\n\t\tfor (;;) {\n\t\t\tconst request = dequeueRequest(this.#state);\n\t\t\tif (request) return request;\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) return undefined;\n\n\t\t\tawait Signal.race(this.#state.requested, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Insert a track that is served directly, without an on-demand request round-trip. */\n\tinsertTrack(track: track.Producer): void {\n\t\tif (this.#state.closed.peek() !== undefined) {\n\t\t\tthrow new Error(`broadcast is closed: ${this.#state.closed.peek()}`);\n\t\t}\n\n\t\tconst existing = this.#state.tracks.get(track.name);\n\t\tif (existing && existing.closed.peek() === undefined) {\n\t\t\tthrow new Error(`duplicate track: ${track.name}`);\n\t\t}\n\n\t\tthis.#state.tracks.set(track.name, track);\n\n\t\tvoid track.closed.then(() => {\n\t\t\tif (this.#state.tracks.get(track.name) === track) {\n\t\t\t\tthis.#state.tracks.delete(track.name);\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Create a track, insert it into the broadcast, and return its producer. */\n\tcreateTrack(name: string, info: Partial<track.Info> = {}): track.Producer {\n\t\tconst producer = new track.Producer(name).accept(info);\n\t\tthis.insertTrack(producer);\n\t\treturn producer;\n\t}\n\n\t/** Remove a statically inserted track by name. */\n\tremoveTrack(name: string): void {\n\t\tthis.#state.tracks.delete(name);\n\t}\n\n\t/** Open a live subscription to a track. Used by the publishing wire layer. */\n\tsubscribe(name: string, options?: track.Subscription): track.Subscriber {\n\t\treturn subscribe(this.#state, name, options);\n\t}\n\n\t/** Resolve a track's immutable info. Used by the publishing wire layer. */\n\tresolveTrackInfo(name: string): Promise<track.Info> {\n\t\treturn resolveTrackInfo(this.#state, name);\n\t}\n\n\t/** Fetch a single group from the local retained window. Used by track handles. */\n\tfetchGroup(name: string, sequence: number, options?: track.FetchGroupOptions): Promise<GroupConsumer> {\n\t\treturn fetchGroup(this.#state, name, sequence, options);\n\t}\n\n\t/** A lazy read handle for a track on this broadcast. */\n\ttrack(name: string): track.Consumer {\n\t\treturn new track.Consumer(name, this);\n\t}\n\n\t/** Close the broadcast, optionally with an error to abort waiters. Idempotent. */\n\tclose(abort?: Error) {\n\t\tcloseState(this.#state, abort);\n\t}\n}\n\n// Constructs a Consumer from within this module without exposing a public constructor\n// that would leak the unexported BroadcastState. Assigned in the class's static block.\nlet makeConsumer: (state: BroadcastState) => Consumer;\n\n/**\n * The read side of a broadcast.\n *\n * Created internally: obtain one from {@link Producer.consume} or the connection's\n * `consume(path)`. The wire layers subclass it to resolve tracks over the network.\n *\n * @public\n */\nexport class Consumer implements track.Broadcast {\n\t#state: BroadcastState;\n\n\t// Guards against a double close() on this handle over-decrementing the consumer count.\n\t#closed = false;\n\n\tprotected constructor(state?: never);\n\tprotected constructor(state?: BroadcastState) {\n\t\tthis.#state = state ?? new BroadcastState();\n\t\tthis.#state.consumers++;\n\t}\n\n\tstatic {\n\t\tmakeConsumer = (state) => new Consumer(state as never);\n\t}\n\n\t/**\n\t * Settles once the broadcast closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t *\n\t * Shared by every {@link clone}: it settles once the last handle closes. The subscribing\n\t * wire layer peeks it to evict a closed entry from its per-path consume cache.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\t/**\n\t * Return another handle to the same broadcast, reference-counted with this one.\n\t *\n\t * Both handles read the same tracks and share one {@link closed} state; the broadcast\n\t * closes only once *every* handle has {@link close}d. Used by the connection's per-path\n\t * consume cache to share one subscription across callers. Subclasses that resolve info over\n\t * the wire override this to preserve their type (see the wire layer's consumed broadcast).\n\t */\n\tclone(): Consumer {\n\t\treturn new Consumer(this.shareState());\n\t}\n\n\t// Hand this consumer's backing state to a clone. Opaque (`never`) so the state type stays\n\t// unexported; a subclass passes it straight back into its own `super(...)`.\n\tprotected shareState(): never {\n\t\treturn this.#state as never;\n\t}\n\n\t/** Get a lazy handle for a track on this broadcast. Repeat subscriptions dedupe onto one upstream subscription. */\n\ttrack(name: string): track.Consumer {\n\t\treturn new track.Consumer(name, this);\n\t}\n\n\t/** Open a live subscription to a track. Used by the subscribing wire layer. Repeat subscriptions to the same track share one upstream subscription. */\n\tsubscribe(name: string, options?: track.Subscription): track.Subscriber {\n\t\treturn subscribe(this.#state, name, options, true);\n\t}\n\n\t/** Return the next track requested by the local consumer. Used by the subscribing wire layer. */\n\tasync requested(): Promise<track.Request | undefined> {\n\t\tfor (;;) {\n\t\t\tconst request = dequeueRequest(this.#state);\n\t\t\tif (request) return request;\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) return undefined;\n\n\t\t\tawait Signal.race(this.#state.requested, this.#state.closed);\n\t\t}\n\t}\n\n\t/**\n\t * Resolve a track's immutable info. Used by track handles. This base resolves it from\n\t * the local producers; the consuming wire layer overrides it to fetch over the wire.\n\t */\n\tresolveTrackInfo(name: string): Promise<track.Info> {\n\t\treturn resolveTrackInfo(this.#state, name);\n\t}\n\n\t/**\n\t * Fetch a single group by sequence. Used by track handles. This base serves from the\n\t * local retained window; the consuming wire layer overrides it to fetch over the wire\n\t * (or to reject when the transport has no FETCH).\n\t */\n\tfetchGroup(name: string, sequence: number, options?: track.FetchGroupOptions): Promise<GroupConsumer> {\n\t\treturn fetchGroup(this.#state, name, sequence, options);\n\t}\n\n\t/**\n\t * Release this handle. The broadcast is closed (optionally with an error to abort waiters)\n\t * once this was the last live handle; while other {@link clone}s remain open it stays live.\n\t */\n\tclose(abort?: Error) {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tif (--this.#state.consumers > 0) return;\n\t\tcloseState(this.#state, abort);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"broadcast.js","sourceRoot":"","sources":["../src/broadcast.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmB,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAE7D,OAAO,EAAE,KAAK,EAAsB,MAAM,eAAe,CAAC;AAC1D,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AAEpC,0EAA0E;AAC1E,MAAM,cAAc;IACnB,SAAS,GAAG,IAAI,MAAM,CAAkB,EAAE,CAAC,CAAC;IAC5C,OAAO,GAAG,IAAI,GAAG,EAAiB,CAAC;IACnC,MAAM,GAAG,IAAI,IAAI,EAAgB,CAAC;IAClC,MAAM,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC3C,SAAS,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC7C,uFAAuF;IACvF,0FAA0F;IAC1F,SAAS,GAAG,CAAC,CAAC;CACd;AAED,SAAS,cAAc,CAAC,KAAqB;IAC5C,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;IACzC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC;IAClD,OAAO,SAAS,CAAC,GAAG,EAAE,CAAC;AACxB,CAAC;AAED,+EAA+E;AAC/E,8EAA8E;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KAAK,CAAC,CAAC;IAChC,CAAC;CACD","sourcesContent":["/**\n * Broadcast role handles: a named collection of tracks produced by a publisher.\n *\n * @module\n */\nimport { type GetPromise, Once, Signal } from \"@moq/signals\";\nimport type { Consumer as GroupConsumer } from \"./group.ts\";\nimport { hooks, type TrackSequence } from \"./internal.ts\";\nimport * as track from \"./track.ts\";\n\n/** Reactive backing state shared by broadcast producers and consumers. */\nclass BroadcastState {\n\trequested = new Signal<track.Request[]>([]);\n\tpending = new Set<track.Request>();\n\tclosed = new Once<Error | null>();\n\ttracks = new Map<string, track.Producer>();\n\tsequences = new Map<string, TrackSequence>();\n\t// Live consumer handles sharing this state (see {@link Consumer.clone}). The broadcast\n\t// closes once the last one closes, so a shared consumer can be handed to several callers.\n\tconsumers = 0;\n}\n\nfunction dequeueRequest(state: BroadcastState): track.Request | undefined {\n\tconst requested = state.requested.peek();\n\trequested.sort((a, b) => a.priority - b.priority);\n\treturn requested.pop();\n}\n\n// Close the broadcast and reject any requests still pending in the queue, so a\n// subscriber blocked on the track's info() or group reads is unblocked rather\n// than left waiting on a producer that will never be served.\n//\n// Once.set throws on a second settle, and the producer and each consumer handle close\n// independently, so this has to be idempotent.\nfunction closeState(state: BroadcastState, abort?: Error) {\n\tif (state.closed.peek() !== undefined) return;\n\tstate.closed.set(abort ?? null);\n\tfor (const request of state.pending) request.reject(abort);\n\tstate.requested.mutate((requests) => {\n\t\trequests.length = 0;\n\t});\n}\n\n// `register` is set on the subscribing (consumer) side: the fresh producer is cached in\n// `state.tracks` so repeat subscriptions to the same track fan out from one upstream subscription\n// instead of opening a new one, mirroring the Rust `broadcast::Consumer::track` weak-dedup. The\n// consumer wire watches the producer's demand ({@link track.Producer.used}) and tears the upstream\n// down once its last subscriber leaves, closing the producer, which evicts the cache entry below.\n// The publishing side leaves `register` false: `state.tracks` there holds only the tracks the app\n// inserted, and a dynamic serve stays one request per peer subscription.\nfunction subscribe(\n\tstate: BroadcastState,\n\tname: string,\n\toptions: track.Subscription = {},\n\tregister = false,\n): track.Subscriber {\n\tif (state.closed.peek() !== undefined) {\n\t\tthrow new Error(`broadcast is closed: ${state.closed.peek()}`);\n\t}\n\n\tconst existing = state.tracks.get(name);\n\tif (existing) {\n\t\tif (existing.closed.peek() === undefined) return existing.subscribe(options);\n\t\tstate.tracks.delete(name);\n\t}\n\n\tconst producer = new track.Producer(name);\n\tconst subscriber = producer.subscribe(options);\n\n\tif (register) {\n\t\tstate.tracks.set(name, producer);\n\t\t// Drop the cache entry once the upstream closes (the wire tears it down when its last\n\t\t// subscriber leaves), so a later subscribe re-opens it.\n\t\tvoid producer.closed.then(() => {\n\t\t\tif (state.tracks.get(name) === producer) state.tracks.delete(name);\n\t\t});\n\t}\n\n\tstate.requested.mutate((requested) => {\n\t\trequested.push(hooks.makeRequest({ name, producer, sequences: state.sequences, pending: state.pending }));\n\t});\n\n\treturn subscriber;\n}\n\nasync function resolveTrackInfo(state: BroadcastState, name: string): Promise<track.Info> {\n\tconst existing = state.tracks.get(name);\n\tif (existing && existing.closed.peek() === undefined) {\n\t\treturn existing.info();\n\t}\n\n\tif (state.closed.peek() !== undefined) {\n\t\treturn Promise.reject(new Error(`broadcast is closed: ${state.closed.peek()}`));\n\t}\n\n\tconst producer = new track.Producer(name);\n\tstate.requested.mutate((requested) => {\n\t\trequested.push(hooks.makeRequest({ name, producer, sequences: state.sequences, pending: state.pending }));\n\t});\n\n\ttry {\n\t\treturn await producer.info();\n\t} finally {\n\t\tproducer.close();\n\t}\n}\n\n// Serve a group from the local retained window by subscribing and scanning to the\n// requested sequence. The default for a produced broadcast; the consuming wire layer\n// overrides it to fetch over the network (or to reject when the transport has no FETCH).\nasync function fetchGroup(\n\tstate: BroadcastState,\n\tname: string,\n\tsequence: number,\n\toptions: track.FetchGroupOptions = {},\n): Promise<GroupConsumer> {\n\tconst subscriber = subscribe(state, name, { priority: options.priority });\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst group = await subscriber.recvGroup();\n\t\t\tif (!group) throw new Error(`group not found: ${sequence}`);\n\t\t\tif (group.sequence === sequence) {\n\t\t\t\t// Close the subscription when the returned group finishes, not now: an\n\t\t\t\t// in-progress group must keep receiving frames for its lifetime (mirrors\n\t\t\t\t// Rust poll_fetch). Also fires if the caller closes the group early.\n\t\t\t\tvoid group.closed.then(() => subscriber.close());\n\t\t\t\treturn group;\n\t\t\t}\n\n\t\t\tgroup.close();\n\t\t\tif (group.sequence > sequence) throw new Error(`group not found: ${sequence}`);\n\t\t}\n\t} catch (err) {\n\t\tsubscriber.close();\n\t\tthrow err;\n\t}\n}\n\n/**\n * The write side of a broadcast.\n *\n * @public\n */\nexport class Producer implements track.Broadcast {\n\t#state = new BroadcastState();\n\n\t/**\n\t * Settles once the broadcast closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\t/** A read handle for this broadcast. */\n\tconsume(): Consumer {\n\t\treturn makeConsumer(this.#state);\n\t}\n\n\t/** Return the next track requested by a peer. */\n\tasync requested(): Promise<track.Request | undefined> {\n\t\tfor (;;) {\n\t\t\tconst request = dequeueRequest(this.#state);\n\t\t\tif (request) return request;\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) return undefined;\n\n\t\t\tawait Signal.race(this.#state.requested, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Insert a track that is served directly, without an on-demand request round-trip. */\n\tinsertTrack(track: track.Producer): void {\n\t\tif (this.#state.closed.peek() !== undefined) {\n\t\t\tthrow new Error(`broadcast is closed: ${this.#state.closed.peek()}`);\n\t\t}\n\n\t\tconst existing = this.#state.tracks.get(track.name);\n\t\tif (existing && existing.closed.peek() === undefined) {\n\t\t\tthrow new Error(`duplicate track: ${track.name}`);\n\t\t}\n\n\t\tthis.#state.tracks.set(track.name, track);\n\n\t\tvoid track.closed.then(() => {\n\t\t\tif (this.#state.tracks.get(track.name) === track) {\n\t\t\t\tthis.#state.tracks.delete(track.name);\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Create a track, insert it into the broadcast, and return its producer. */\n\tcreateTrack(name: string, info: Partial<track.Info> = {}): track.Producer {\n\t\tconst producer = new track.Producer(name).accept(info);\n\t\tthis.insertTrack(producer);\n\t\treturn producer;\n\t}\n\n\t/** Remove a statically inserted track by name. */\n\tremoveTrack(name: string): void {\n\t\tthis.#state.tracks.delete(name);\n\t}\n\n\t/** Open a live subscription to a track. Used by the publishing wire layer. */\n\tsubscribe(name: string, options?: track.Subscription): track.Subscriber {\n\t\treturn subscribe(this.#state, name, options);\n\t}\n\n\t/** Resolve a track's immutable info. Used by the publishing wire layer. */\n\tresolveTrackInfo(name: string): Promise<track.Info> {\n\t\treturn resolveTrackInfo(this.#state, name);\n\t}\n\n\t/** Fetch a single group from the local retained window. Used by track handles. */\n\tfetchGroup(name: string, sequence: number, options?: track.FetchGroupOptions): Promise<GroupConsumer> {\n\t\treturn fetchGroup(this.#state, name, sequence, options);\n\t}\n\n\t/** A lazy read handle for a track on this broadcast. */\n\ttrack(name: string): track.Consumer {\n\t\treturn new track.Consumer(name, this);\n\t}\n\n\t/** Close the broadcast, optionally with an error to abort waiters. Idempotent. */\n\tclose(abort?: Error) {\n\t\tcloseState(this.#state, abort);\n\t}\n}\n\n// Constructs a Consumer from within this module without exposing a public constructor\n// that would leak the unexported BroadcastState. Assigned in the class's static block.\nlet makeConsumer: (state: BroadcastState) => Consumer;\n\n/**\n * The read side of a broadcast.\n *\n * Created internally: obtain one from {@link Producer.consume} or the connection's\n * `consume(path)`. The wire layers subclass it to resolve tracks over the network.\n *\n * @public\n */\nexport class Consumer implements track.Broadcast {\n\t#state: BroadcastState;\n\n\t// Guards against a double close() on this handle over-decrementing the consumer count.\n\t#closed = false;\n\n\tprotected constructor(state?: never);\n\tprotected constructor(state?: BroadcastState) {\n\t\tthis.#state = state ?? new BroadcastState();\n\t\tthis.#state.consumers++;\n\t}\n\n\tstatic {\n\t\tmakeConsumer = (state) => new Consumer(state as never);\n\t}\n\n\t/**\n\t * Settles once the broadcast closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t *\n\t * Shared by every {@link clone}: it settles once the last handle closes. The subscribing\n\t * wire layer peeks it to evict a closed entry from its per-path consume cache.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\t/**\n\t * Return another handle to the same broadcast, reference-counted with this one.\n\t *\n\t * Both handles read the same tracks and share one {@link closed} state; the broadcast\n\t * closes only once *every* handle has {@link close}d. Used by the connection's per-path\n\t * consume cache to share one subscription across callers. Subclasses that resolve info over\n\t * the wire override this to preserve their type (see the wire layer's consumed broadcast).\n\t */\n\tclone(): Consumer {\n\t\treturn new Consumer(this.shareState());\n\t}\n\n\t// Hand this consumer's backing state to a clone. Opaque (`never`) so the state type stays\n\t// unexported; a subclass passes it straight back into its own `super(...)`.\n\tprotected shareState(): never {\n\t\treturn this.#state as never;\n\t}\n\n\t/** Get a lazy handle for a track on this broadcast. Repeat subscriptions dedupe onto one upstream subscription. */\n\ttrack(name: string): track.Consumer {\n\t\treturn new track.Consumer(name, this);\n\t}\n\n\t/** Open a live subscription to a track. Used by the subscribing wire layer. Repeat subscriptions to the same track share one upstream subscription. */\n\tsubscribe(name: string, options?: track.Subscription): track.Subscriber {\n\t\treturn subscribe(this.#state, name, options, true);\n\t}\n\n\t/** Return the next track requested by the local consumer. Used by the subscribing wire layer. */\n\tasync requested(): Promise<track.Request | undefined> {\n\t\tfor (;;) {\n\t\t\tconst request = dequeueRequest(this.#state);\n\t\t\tif (request) return request;\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) return undefined;\n\n\t\t\tawait Signal.race(this.#state.requested, this.#state.closed);\n\t\t}\n\t}\n\n\t/**\n\t * Resolve a track's immutable info. Used by track handles. This base resolves it from\n\t * the local producers; the consuming wire layer overrides it to fetch over the wire.\n\t */\n\tresolveTrackInfo(name: string): Promise<track.Info> {\n\t\treturn resolveTrackInfo(this.#state, name);\n\t}\n\n\t/**\n\t * Fetch a single group by sequence. Used by track handles. This base serves from the\n\t * local retained window; the consuming wire layer overrides it to fetch over the wire\n\t * (or to reject when the transport has no FETCH).\n\t */\n\tfetchGroup(name: string, sequence: number, options?: track.FetchGroupOptions): Promise<GroupConsumer> {\n\t\treturn fetchGroup(this.#state, name, sequence, options);\n\t}\n\n\t/**\n\t * Release this handle. The broadcast is closed (optionally with an error to abort waiters)\n\t * once this was the last live handle; while other {@link clone}s remain open it stays live.\n\t */\n\tclose(abort?: Error) {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tif (--this.#state.consumers > 0) return;\n\t\tcloseState(this.#state, abort);\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/connection/connect.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/connection/connect.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAMpD,yGAAyG;AACzG,MAAM,WAAW,gBAAgB;IAChC,yDAAyD;IACzD,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB,mGAAmG;IACnG,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV;;;OAGG;IACH,KAAK,CAAC,EAAE,mBAAmB,CAAC;CAC5B;AAED;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC/B,4EAA4E;IAC5E,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,uDAAuD;IACvD,KAAK,EAAE,YAAY,GAAG,MAAM,CAAC;CAC7B;AAED,2GAA2G;AAC3G,MAAM,WAAW,iBAAkB,SAAQ,IAAI,CAAC,mBAAmB,EAAE,yBAAyB,CAAC;IAC9F;;;OAGG;IACH,uBAAuB,CAAC,EAAE,eAAe,EAAE,CAAC;IAE5C;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;CAC1C;AAED,mCAAmC;AACnC,MAAM,WAAW,YAAY;IAC5B,4BAA4B;IAC5B,YAAY,CAAC,EAAE,iBAAiB,CAAC;IAEjC,oCAAoC;IACpC,SAAS,CAAC,EAAE,gBAAgB,CAAC;IAE7B;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,YAAY,CAAC;IAEzB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;;;OAIG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAkBD;;;;;;GAMG;AACH,wBAAsB,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,CAqBlF;AAmMD;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAInG"}
|
package/connection/connect.js
CHANGED
|
@@ -4,6 +4,7 @@ import * as Ietf from "../ietf/index.js";
|
|
|
4
4
|
import * as Lite from "../lite/index.js";
|
|
5
5
|
import { Stream } from "../stream.js";
|
|
6
6
|
import * as Hex from "../util/hex.js";
|
|
7
|
+
import { dev, redact } from "../util/log.js";
|
|
7
8
|
import { isWebTransportSupported } from "./browser.js";
|
|
8
9
|
import { exchangeSetup } from "./handshake.js";
|
|
9
10
|
// Default head start for WebTransport before attempting the WebSocket fallback.
|
|
@@ -83,11 +84,13 @@ async function connectInner(url, props, abort) {
|
|
|
83
84
|
void abort.then(() => session.close());
|
|
84
85
|
// Save if WebSocket won the last race, so we won't give QUIC a head start next time.
|
|
85
86
|
if (session instanceof Session) {
|
|
86
|
-
|
|
87
|
+
// Still a warning, not a debug line: losing the race means we fell back off QUIC.
|
|
88
|
+
if (dev())
|
|
89
|
+
console.warn(redact(url), "connected via WebSocket");
|
|
87
90
|
websocketWon.add(url.toString());
|
|
88
91
|
}
|
|
89
|
-
else {
|
|
90
|
-
console.debug(url
|
|
92
|
+
else if (dev()) {
|
|
93
|
+
console.debug(redact(url), "connected via WebTransport");
|
|
91
94
|
}
|
|
92
95
|
// The remaining setup is identical whether the transport was raced or supplied.
|
|
93
96
|
return await connectTransport(url, session, discovery);
|
|
@@ -96,7 +99,8 @@ async function connectTransport(url, session, discovery) {
|
|
|
96
99
|
// qmux Session exposes the negotiated protocol directly (as "" when there is none);
|
|
97
100
|
// native WebTransport doesn't have a standard .protocol property yet.
|
|
98
101
|
const protocol = session.protocol || undefined;
|
|
99
|
-
|
|
102
|
+
if (dev())
|
|
103
|
+
console.debug(redact(url), "negotiated ALPN:", protocol ?? "(none)");
|
|
100
104
|
// Choose setup encoding based on negotiated WebTransport protocol (if any).
|
|
101
105
|
let setupVersion;
|
|
102
106
|
const modernVersion = protocol === Ietf.ALPN.DRAFT_20
|
|
@@ -267,11 +271,14 @@ async function connectWebTransport(url, cancel, options) {
|
|
|
267
271
|
if (url.protocol === "http:") {
|
|
268
272
|
const fingerprintUrl = new URL(url);
|
|
269
273
|
fingerprintUrl.pathname = "/certificate.sha256";
|
|
274
|
+
// The certificate endpoint is unauthenticated, so don't hand it the token.
|
|
270
275
|
fingerprintUrl.search = "";
|
|
271
276
|
// Dev-only path: http:// can't be a real WebTransport origin, so we fetch the
|
|
272
277
|
// self-signed cert's hash over plain HTTP and pin it. Production uses https://
|
|
273
278
|
// and never reaches here. Keep this at debug so it doesn't read as a problem.
|
|
274
|
-
|
|
279
|
+
if (dev()) {
|
|
280
|
+
console.debug(redact(fingerprintUrl), "performing an insecure fingerprint fetch; use https:// in production");
|
|
281
|
+
}
|
|
275
282
|
// Fetch the fingerprint from the server.
|
|
276
283
|
// TODO cancel the request if the effect is cancelled.
|
|
277
284
|
const fingerprint = await Promise.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CAAC,CAAC;IAEH,2EAA2E;IAC3E,kFAAkF;IAClF,4EAA4E;IAC5E,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACzE,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import Session, { type Version as QmuxVersion } from \"@moq/qmux\";\nimport * as Ietf from \"../ietf/index.ts\";\nimport * as Lite from \"../lite/index.ts\";\nimport { Stream } from \"../stream.ts\";\nimport * as Hex from \"../util/hex.ts\";\nimport { isWebTransportSupported } from \"./browser.ts\";\nimport type { Established } from \"./established.ts\";\nimport { exchangeSetup } from \"./handshake.ts\";\n\n// Default head start for WebTransport before attempting the WebSocket fallback.\nconst DEFAULT_WEBSOCKET_DELAY_MS = 500;\n\n/** Tuning for the WebSocket fallback used when WebTransport is unavailable or loses the connect race. */\nexport interface WebSocketOptions {\n\t/** Enable the WebSocket fallback. Defaults to `true`. */\n\tenabled?: boolean;\n\n\t/** Use a different URL than WebTransport. By default, `https` maps to `wss` and `http` to `ws`. */\n\turl?: URL;\n\n\t/**\n\t * The delay in milliseconds before attempting the WebSocket fallback (default: 500).\n\t * If WebSocket won the previous race for a given URL, this is 0.\n\t */\n\tdelay?: DOMHighResTimeStamp;\n}\n\n/**\n * A server certificate hash used to pin a self-signed server, one entry of\n * `serverCertificateHashes`. Unlike the DOM type, `value` also accepts a hex string (the\n * format moq servers report via their certificate fingerprints), decoded automatically.\n */\nexport interface CertificateHash {\n\t/** The hash algorithm. Defaults to `sha-256` (the only supported value). */\n\talgorithm?: \"sha-256\";\n\t/** The certificate hash: raw bytes or a hex string. */\n\tvalue: BufferSource | string;\n}\n\n/** WebTransport options extended with friendlier certificate pinning (hex hashes or a raw certificate). */\nexport interface WebTransportProps extends Omit<WebTransportOptions, \"serverCertificateHashes\"> {\n\t/**\n\t * Pin the server to one or more certificate hashes. Each `value` may be raw\n\t * bytes or a hex string; the algorithm defaults to `sha-256`.\n\t */\n\tserverCertificateHashes?: CertificateHash[];\n\n\t/**\n\t * Pin the server by supplying its certificate directly; the SHA-256 hash is\n\t * computed for you. Accepts a PEM string or raw DER bytes. Use this when you\n\t * have the certificate but not its precomputed fingerprint.\n\t */\n\tserverCertificate?: string | BufferSource;\n}\n\n/** Options for {@link connect}. */\nexport interface ConnectProps {\n\t/** WebTransport options. */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket (fallback) options. */\n\twebsocket?: WebSocketOptions;\n\n\t/**\n\t * Use a pre-existing WebTransport session instead of connecting; skips the\n\t * WebTransport/WebSocket race. The publisher acquires the session's datagram\n\t * writer lock (`datagrams.writable.getWriter()`) for the session's lifetime,\n\t * so the caller must not hold it. Aborting via {@link ConnectProps.signal}\n\t * closes this session, so don't share one you intend to reuse afterwards.\n\t */\n\ttransport?: WebTransport;\n\n\t/**\n\t * Whether the relay supports broadcast discovery; see {@link Established.discovery}.\n\t * Defaults to true, except for relays known to lack it.\n\t */\n\tdiscovery?: boolean;\n\n\t/**\n\t * Aborts the connection attempt with the signal's reason. An already-aborted\n\t * signal rejects before anything opens, and aborting after the connection is\n\t * established has no effect. Use `AbortSignal.timeout(ms)` for a deadline.\n\t */\n\tsignal?: AbortSignal;\n}\n\n// Relays that don't implement broadcast discovery (SUBSCRIBE_NAMESPACE), so `announced()` would\n// never yield and a consumer waiting on an announcement would hang forever. Override with the\n// `discovery` option. Drop a host once its relay ships discovery.\nconst NO_DISCOVERY_HOSTS = [\"mediaoverquic.com\"];\n\n/** Whether the relay at `url` is expected to support broadcast discovery. */\nfunction defaultDiscovery(url: URL): boolean {\n\treturn !NO_DISCOVERY_HOSTS.some((host) => url.hostname.endsWith(host));\n}\n\n// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\nconst websocketWon = new Set<string>();\n\n/** The default connect signal: never aborts. */\nconst NEVER_ABORTED = new AbortController().signal;\n\n/**\n * Establishes a connection to a MOQ server.\n *\n * @param url - The URL of the server to connect to\n * @param props - Connection options\n * @returns A promise that resolves to a Connection instance\n */\nexport async function connect(url: URL, props?: ConnectProps): Promise<Established> {\n\tconst signal = props?.signal ?? NEVER_ABORTED;\n\tsignal.throwIfAborted();\n\n\t// Resolves on abort so every in-flight transport tears itself down.\n\tconst { promise: abort, resolve } = Promise.withResolvers<void>();\n\tconst onAbort = () => resolve();\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst pending = connectInner(url, props, abort);\n\ttry {\n\t\t// A `pending` rejection propagates unless the abort beat it to the finish line.\n\t\tconst connection = await Promise.race([pending, abort.then(() => undefined)]);\n\t\tif (connection && !signal.aborted) return connection;\n\n\t\t// Close a connection that settles after the abort.\n\t\tpending.then((conn) => conn.close()).catch(() => {});\n\t\tthrow signal.reason;\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nasync function connectInner(url: URL, props: ConnectProps | undefined, abort: Promise<void>): Promise<Established> {\n\tconst discovery = props?.discovery ?? defaultDiscovery(url);\n\n\tif (props?.transport) {\n\t\tconst transport = props.transport;\n\t\tvoid abort.then(() => transport.close());\n\t\treturn connectTransport(url, transport, discovery);\n\t}\n\n\t// Stop transports after one connects or the caller aborts.\n\tconst { promise: raced, resolve: done } = Promise.withResolvers<void>();\n\tconst cancel = Promise.race([raced, abort]);\n\n\tconst webtransport = isWebTransportSupported() ? connectWebTransport(url, cancel, props?.webtransport) : undefined;\n\n\t// Give QUIC a head start to connect before trying WebSocket, unless WebSocket has won in the past.\n\t// NOTE that QUIC should be faster because it involves 1/2 fewer RTTs.\n\tconst headstart =\n\t\t!webtransport || websocketWon.has(url.toString()) ? 0 : (props?.websocket?.delay ?? DEFAULT_WEBSOCKET_DELAY_MS);\n\tconst websocket =\n\t\tprops?.websocket?.enabled !== false\n\t\t\t? connectWebSocket(props?.websocket?.url ?? url, headstart, cancel)\n\t\t\t: undefined;\n\n\tif (!websocket && !webtransport) {\n\t\tthrow new Error(\"no transport available; WebTransport not supported and WebSocket is disabled\");\n\t}\n\n\t// Race the available transports, using `.any` to ignore if one participant has an error.\n\t// `webtransport`/`websocket` are `Promise | undefined`, so test existence explicitly: a\n\t// promise is always truthy, so bare truthiness here would be a misused-promise.\n\tconst session = await Promise.any(\n\t\twebtransport !== undefined\n\t\t\t? websocket !== undefined\n\t\t\t\t? [websocket, webtransport]\n\t\t\t\t: [webtransport]\n\t\t\t: [websocket],\n\t);\n\tdone();\n\n\tif (!session) throw new Error(\"no transport available\");\n\n\t// Abort the setup handshake without leaking the selected transport.\n\tvoid abort.then(() => session.close());\n\n\t// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\n\tif (session instanceof Session) {\n\t\tconsole.warn(url.toString(), \"connected via WebSocket\");\n\t\twebsocketWon.add(url.toString());\n\t} else {\n\t\tconsole.debug(url.toString(), \"connected via WebTransport\");\n\t}\n\n\t// The remaining setup is identical whether the transport was raced or supplied.\n\treturn await connectTransport(url, session as WebTransport, discovery);\n}\n\nasync function connectTransport(url: URL, session: WebTransport, discovery: boolean): Promise<Established> {\n\t// qmux Session exposes the negotiated protocol directly (as \"\" when there is none);\n\t// native WebTransport doesn't have a standard .protocol property yet.\n\tconst protocol: string | undefined = (session as { protocol?: string }).protocol || undefined;\n\tconsole.debug(url.toString(), \"negotiated ALPN:\", protocol ?? \"(none)\");\n\n\t// Choose setup encoding based on negotiated WebTransport protocol (if any).\n\tlet setupVersion: Ietf.Version;\n\tconst modernVersion =\n\t\tprotocol === Ietf.ALPN.DRAFT_20\n\t\t\t? Ietf.Version.DRAFT_20\n\t\t\t: protocol === Ietf.ALPN.DRAFT_19\n\t\t\t\t? Ietf.Version.DRAFT_19\n\t\t\t\t: protocol === Ietf.ALPN.DRAFT_18\n\t\t\t\t\t? Ietf.Version.DRAFT_18\n\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_17\n\t\t\t\t\t\t? Ietf.Version.DRAFT_17\n\t\t\t\t\t\t: undefined;\n\tif (modernVersion !== undefined) {\n\t\treturn await handshakeAlpn(url, session, modernVersion, discovery);\n\t} else if (protocol === Ietf.ALPN.DRAFT_16) {\n\t\tsetupVersion = Ietf.Version.DRAFT_16;\n\t} else if (protocol === Ietf.ALPN.DRAFT_15) {\n\t\tsetupVersion = Ietf.Version.DRAFT_15;\n\t} else if (protocol === Lite.ALPN_06_WIP) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_06, discovery });\n\t} else if (protocol === Lite.ALPN_05) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_05, discovery });\n\t} else if (protocol === Lite.ALPN_04) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_04, discovery });\n\t} else if (protocol === Lite.ALPN_03) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_03, discovery });\n\t} else if (protocol === Lite.ALPN || protocol === \"\" || protocol === undefined) {\n\t\tsetupVersion = Ietf.Version.DRAFT_14;\n\t} else {\n\t\tthrow new Error(`unsupported WebTransport protocol: ${protocol}`);\n\t}\n\n\tconst stream = await Stream.open(session);\n\tawait stream.writer.u53(Lite.StreamId.ClientCompat);\n\n\tconst encoder = new TextEncoder();\n\n\tconst params = new Ietf.SetupOptions();\n\tparams.setVarint(Ietf.SetupOption.MaxRequestId, 42069n);\n\tparams.setBytes(Ietf.SetupOption.Implementation, encoder.encode(\"moq-lite-js\"));\n\tIetf.solicitIntoSetup(params);\n\n\tconst client = new Ietf.ClientSetup({\n\t\tversions:\n\t\t\tsetupVersion === Ietf.Version.DRAFT_16\n\t\t\t\t? [Ietf.Version.DRAFT_16]\n\t\t\t\t: setupVersion === Ietf.Version.DRAFT_15\n\t\t\t\t\t? [Ietf.Version.DRAFT_15]\n\t\t\t\t\t: [Lite.Version.DRAFT_02, Lite.Version.DRAFT_01, Ietf.Version.DRAFT_14],\n\t\tparameters: params,\n\t});\n\tawait client.encode(stream.writer, setupVersion);\n\n\tconst serverCompat = await stream.reader.u53();\n\tif (serverCompat !== Lite.StreamId.ServerCompat) {\n\t\tthrow new Error(`unsupported server message type: ${serverCompat.toString()}`);\n\t}\n\n\tconst server = await Ietf.ServerSetup.decode(stream.reader, setupVersion);\n\n\tif (Object.values(Lite.Version).includes(server.version as Lite.Version)) {\n\t\treturn new Lite.Connection({\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tversion: server.version as Lite.Version,\n\t\t\tsession: stream,\n\t\t\tdiscovery,\n\t\t});\n\t} else if (Object.values(Ietf.Version).includes(server.version as Ietf.Version)) {\n\t\tconst maxRequestId = server.parameters.getVarint(Ietf.SetupOption.MaxRequestId) ?? 0n;\n\t\treturn new Ietf.Connection({\n\t\t\tdiscovery,\n\t\t\tclient: true,\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tcontrol: stream,\n\t\t\tmaxRequestId,\n\t\t\tversion: server.version as Ietf.IetfVersion,\n\t\t\tsolicit: Ietf.solicitFromSetup(server.parameters),\n\t\t});\n\t} else {\n\t\tthrow new Error(`unsupported server version: ${server.version.toString()}`);\n\t}\n}\n\n/**\n * Draft-17+ client handshake. ALPN already pinned the version; SETUP is\n * exchanged over a pair of uni streams using stream type 0x2F00.\n */\nasync function handshakeAlpn(\n\turl: URL,\n\tsession: WebTransport,\n\tversion: Ietf.IetfVersion,\n\tdiscovery: boolean,\n): Promise<Established> {\n\tconst { control, solicit, cluster } = await exchangeSetup(session, version, \"moq-lite-js\");\n\n\treturn new Ietf.Connection({\n\t\tdiscovery,\n\t\tclient: true,\n\t\turl,\n\t\tquic: session,\n\t\tcontrol,\n\t\tsolicit,\n\t\tcluster,\n\t\t// v17+ uses NativeSession which manages its own request IDs; maxRequestId is unused.\n\t\tmaxRequestId: 0n,\n\t\tversion,\n\t});\n}\n\n// One entry of the DOM `serverCertificateHashes`, derived without naming the lib type.\ntype WebTransportHash = NonNullable<WebTransportOptions[\"serverCertificateHashes\"]>[number];\n\n// Strip PEM armor and base64-decode to the raw DER bytes.\nfunction pemToDer(pem: string): Uint8Array<ArrayBuffer> {\n\tconst match = pem.match(/-----BEGIN CERTIFICATE-----([\\s\\S]+?)-----END CERTIFICATE-----/);\n\tif (!match) {\n\t\tthrow new Error(\"invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor\");\n\t}\n\n\tconst binary = atob(match[1].replace(/\\s+/g, \"\"));\n\tconst der = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i++) {\n\t\tder[i] = binary.charCodeAt(i);\n\t}\n\treturn der;\n}\n\n/**\n * Compute the SHA-256 hash of a certificate, the value `serverCertificateHashes`\n * pins. Accepts a PEM string or raw DER bytes. Matches the hex fingerprints a moq\n * server reports, so `Hex.fromBytes(await certificateHash(pem))` round-trips.\n */\nexport async function certificateHash(cert: string | BufferSource): Promise<Uint8Array<ArrayBuffer>> {\n\tconst der = typeof cert === \"string\" ? pemToDer(cert) : cert;\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", der);\n\treturn new Uint8Array(digest);\n}\n\n// Normalize our friendlier pinning options into the DOM `serverCertificateHashes`.\nasync function resolveCertificateHashes(options?: WebTransportProps): Promise<WebTransportHash[] | undefined> {\n\tconst hashes: WebTransportHash[] = [];\n\n\tfor (const hash of options?.serverCertificateHashes ?? []) {\n\t\tconst value = typeof hash.value === \"string\" ? Hex.toBytes(hash.value) : hash.value;\n\t\thashes.push({ algorithm: hash.algorithm ?? \"sha-256\", value });\n\t}\n\n\tif (options?.serverCertificate !== undefined) {\n\t\thashes.push({ algorithm: \"sha-256\", value: await certificateHash(options.serverCertificate) });\n\t}\n\n\treturn hashes.length > 0 ? hashes : undefined;\n}\n\nasync function connectWebTransport(\n\turl: URL,\n\tcancel: Promise<void>,\n\toptions?: WebTransportProps,\n): Promise<WebTransport | undefined> {\n\tlet finalUrl = url;\n\n\t// Our custom pinning fields are normalized separately; the rest are DOM options.\n\tconst { serverCertificate: _cert, serverCertificateHashes: _hashes, ...webtransport } = options ?? {};\n\n\tconst finalOptions: WebTransportOptions = {\n\t\tallowPooling: false,\n\t\tcongestionControl: \"low-latency\",\n\t\tprotocols: [\n\t\t\t// Lite.ALPN_06_WIP is intentionally omitted: lite-06 is work-in-progress and\n\t\t\t// not advertised by default (connect.ts still accepts it if a server negotiates it).\n\t\t\tLite.ALPN_05,\n\t\t\tLite.ALPN_04,\n\t\t\tLite.ALPN_03,\n\t\t\tLite.ALPN,\n\t\t\tIetf.ALPN.DRAFT_20,\n\t\t\tIetf.ALPN.DRAFT_19,\n\t\t\tIetf.ALPN.DRAFT_18,\n\t\t\tIetf.ALPN.DRAFT_17,\n\t\t\tIetf.ALPN.DRAFT_16,\n\t\t\tIetf.ALPN.DRAFT_15,\n\t\t],\n\t\t...webtransport,\n\t};\n\n\t// Accumulate caller-provided pins first, then append anything we fetch below,\n\t// so a fetched fingerprint never clobbers hashes passed in via options.\n\tconst hashes = (await resolveCertificateHashes(options)) ?? [];\n\n\t// Only perform certificate fetch and URL rewrite when polyfill is not needed\n\t// This is needed because WebTransport is a butt to work with in local development.\n\tif (url.protocol === \"http:\") {\n\t\tconst fingerprintUrl = new URL(url);\n\t\tfingerprintUrl.pathname = \"/certificate.sha256\";\n\t\tfingerprintUrl.search = \"\";\n\t\t// Dev-only path: http:// can't be a real WebTransport origin, so we fetch the\n\t\t// self-signed cert's hash over plain HTTP and pin it. Production uses https://\n\t\t// and never reaches here. Keep this at debug so it doesn't read as a problem.\n\t\tconsole.debug(\n\t\t\tfingerprintUrl.toString(),\n\t\t\t\"performing an insecure fingerprint fetch; use https:// in production\",\n\t\t);\n\n\t\t// Fetch the fingerprint from the server.\n\t\t// TODO cancel the request if the effect is cancelled.\n\t\tconst fingerprint = await Promise.race([fetch(fingerprintUrl), cancel]);\n\t\tif (!fingerprint) return undefined;\n\n\t\tconst fingerprintText = await Promise.race([fingerprint.text(), cancel]);\n\t\tif (fingerprintText === undefined) return undefined;\n\n\t\thashes.push({ algorithm: \"sha-256\", value: Hex.toBytes(fingerprintText) });\n\n\t\tfinalUrl = new URL(url);\n\t\tfinalUrl.protocol = \"https:\";\n\t}\n\n\tif (hashes.length > 0) {\n\t\tfinalOptions.serverCertificateHashes = hashes;\n\t}\n\n\tconst quic = new WebTransport(finalUrl, finalOptions);\n\n\t// Both .ready and .closed reject on failure; catch .closed to avoid an unhandled rejection.\n\tquic.closed.catch(() => {});\n\n\t// Wait for the WebTransport to connect, or for the cancel promise to resolve.\n\t// Close the connection if we lost the race.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n\n// TODO accept arguments to control the port/path used.\nasync function connectWebSocket(url: URL, delay: number, cancel: Promise<void>): Promise<Session | undefined> {\n\tconst timer = new Promise<void>((resolve) => setTimeout(resolve, delay));\n\n\tconst active = await Promise.race([cancel, timer.then(() => true)]);\n\tif (!active) return undefined;\n\n\t// Only moq-transport-18 is pinned to qmux-01 today. Every other ALPN we\n\t// support is currently negotiated as `qmux-00.{alpn}` on the wire, but we\n\t// don't want to lock that in: set the value to `null` so the polyfill\n\t// advertises every QMux draft it knows about and the server picks one.\n\t// Insertion order is the negotiation preference on the wire.\n\tconst versions = {\n\t\t// Lite.ALPN_06_WIP omitted on purpose: lite-06 is work-in-progress, not advertised by default.\n\t\t[Lite.ALPN_05]: null,\n\t\t[Lite.ALPN_04]: null,\n\t\t[Lite.ALPN_03]: null,\n\t\t[Lite.ALPN]: null,\n\t\t[Ietf.ALPN.DRAFT_20]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_18]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_17]: null,\n\t\t[Ietf.ALPN.DRAFT_16]: null,\n\t\t[Ietf.ALPN.DRAFT_15]: null,\n\t} as const satisfies Record<string, QmuxVersion | QmuxVersion[] | null>;\n\n\t// The default (`requireProtocol: false`) also advertises bare `qmux-01`,\n\t// `qmux-00`, and `webtransport` so we still interop with relays that only\n\t// know a wire-format version (today's moq-relay only accepts bare\n\t// `webtransport`).\n\tconst quic = new Session(url, {\n\t\tprotocols: Object.keys(versions),\n\t\tversions,\n\t});\n\n\t// Wait for the WebSocket to connect, or for the cancel promise to resolve.\n\t// `ready` rejects on a refused/failed connection, so a throw here is the caller's\n\t// cue to retry; a lost cancel race instead resolves and we close the loser.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/connection/connect.ts"],"names":[],"mappings":"AAAA,OAAO,OAAwC,MAAM,WAAW,CAAC;AACjE,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,GAAG,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C,gFAAgF;AAChF,MAAM,0BAA0B,GAAG,GAAG,CAAC;AA4EvC,gGAAgG;AAChG,8FAA8F;AAC9F,kEAAkE;AAClE,MAAM,kBAAkB,GAAG,CAAC,mBAAmB,CAAC,CAAC;AAEjD,6EAA6E;AAC7E,SAAS,gBAAgB,CAAC,GAAQ;IACjC,OAAO,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;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CAAC,OAAO,CAAC,EAAE,IAAI;QACpB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI;QACjB,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,SAAS;QAC/B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,SAAS;QAC/B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;QAC1B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;QAC1B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;KAC4C,CAAC;IAExE,yEAAyE;IACzE,0EAA0E;IAC1E,kEAAkE;IAClE,mBAAmB;IACnB,MAAM,IAAI,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;QAC7B,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;QAChC,QAAQ;KACR,CAAC,CAAC;IAEH,2EAA2E;IAC3E,kFAAkF;IAClF,4EAA4E;IAC5E,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACzE,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import Session, { type Version as QmuxVersion } from \"@moq/qmux\";\nimport * as Ietf from \"../ietf/index.ts\";\nimport * as Lite from \"../lite/index.ts\";\nimport { Stream } from \"../stream.ts\";\nimport * as Hex from \"../util/hex.ts\";\nimport { dev, redact } from \"../util/log.ts\";\nimport { isWebTransportSupported } from \"./browser.ts\";\nimport type { Established } from \"./established.ts\";\nimport { exchangeSetup } from \"./handshake.ts\";\n\n// Default head start for WebTransport before attempting the WebSocket fallback.\nconst DEFAULT_WEBSOCKET_DELAY_MS = 500;\n\n/** Tuning for the WebSocket fallback used when WebTransport is unavailable or loses the connect race. */\nexport interface WebSocketOptions {\n\t/** Enable the WebSocket fallback. Defaults to `true`. */\n\tenabled?: boolean;\n\n\t/** Use a different URL than WebTransport. By default, `https` maps to `wss` and `http` to `ws`. */\n\turl?: URL;\n\n\t/**\n\t * The delay in milliseconds before attempting the WebSocket fallback (default: 500).\n\t * If WebSocket won the previous race for a given URL, this is 0.\n\t */\n\tdelay?: DOMHighResTimeStamp;\n}\n\n/**\n * A server certificate hash used to pin a self-signed server, one entry of\n * `serverCertificateHashes`. Unlike the DOM type, `value` also accepts a hex string (the\n * format moq servers report via their certificate fingerprints), decoded automatically.\n */\nexport interface CertificateHash {\n\t/** The hash algorithm. Defaults to `sha-256` (the only supported value). */\n\talgorithm?: \"sha-256\";\n\t/** The certificate hash: raw bytes or a hex string. */\n\tvalue: BufferSource | string;\n}\n\n/** WebTransport options extended with friendlier certificate pinning (hex hashes or a raw certificate). */\nexport interface WebTransportProps extends Omit<WebTransportOptions, \"serverCertificateHashes\"> {\n\t/**\n\t * Pin the server to one or more certificate hashes. Each `value` may be raw\n\t * bytes or a hex string; the algorithm defaults to `sha-256`.\n\t */\n\tserverCertificateHashes?: CertificateHash[];\n\n\t/**\n\t * Pin the server by supplying its certificate directly; the SHA-256 hash is\n\t * computed for you. Accepts a PEM string or raw DER bytes. Use this when you\n\t * have the certificate but not its precomputed fingerprint.\n\t */\n\tserverCertificate?: string | BufferSource;\n}\n\n/** Options for {@link connect}. */\nexport interface ConnectProps {\n\t/** WebTransport options. */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket (fallback) options. */\n\twebsocket?: WebSocketOptions;\n\n\t/**\n\t * Use a pre-existing WebTransport session instead of connecting; skips the\n\t * WebTransport/WebSocket race. The publisher acquires the session's datagram\n\t * writer lock (`datagrams.writable.getWriter()`) for the session's lifetime,\n\t * so the caller must not hold it. Aborting via {@link ConnectProps.signal}\n\t * closes this session, so don't share one you intend to reuse afterwards.\n\t */\n\ttransport?: WebTransport;\n\n\t/**\n\t * Whether the relay supports broadcast discovery; see {@link Established.discovery}.\n\t * Defaults to true, except for relays known to lack it.\n\t */\n\tdiscovery?: boolean;\n\n\t/**\n\t * Aborts the connection attempt with the signal's reason. An already-aborted\n\t * signal rejects before anything opens, and aborting after the connection is\n\t * established has no effect. Use `AbortSignal.timeout(ms)` for a deadline.\n\t */\n\tsignal?: AbortSignal;\n}\n\n// Relays that don't implement broadcast discovery (SUBSCRIBE_NAMESPACE), so `announced()` would\n// never yield and a consumer waiting on an announcement would hang forever. Override with the\n// `discovery` option. Drop a host once its relay ships discovery.\nconst NO_DISCOVERY_HOSTS = [\"mediaoverquic.com\"];\n\n/** Whether the relay at `url` is expected to support broadcast discovery. */\nfunction defaultDiscovery(url: URL): boolean {\n\treturn !NO_DISCOVERY_HOSTS.some((host) => url.hostname.endsWith(host));\n}\n\n// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\nconst websocketWon = new Set<string>();\n\n/** The default connect signal: never aborts. */\nconst NEVER_ABORTED = new AbortController().signal;\n\n/**\n * Establishes a connection to a MOQ server.\n *\n * @param url - The URL of the server to connect to\n * @param props - Connection options\n * @returns A promise that resolves to a Connection instance\n */\nexport async function connect(url: URL, props?: ConnectProps): Promise<Established> {\n\tconst signal = props?.signal ?? NEVER_ABORTED;\n\tsignal.throwIfAborted();\n\n\t// Resolves on abort so every in-flight transport tears itself down.\n\tconst { promise: abort, resolve } = Promise.withResolvers<void>();\n\tconst onAbort = () => resolve();\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst pending = connectInner(url, props, abort);\n\ttry {\n\t\t// A `pending` rejection propagates unless the abort beat it to the finish line.\n\t\tconst connection = await Promise.race([pending, abort.then(() => undefined)]);\n\t\tif (connection && !signal.aborted) return connection;\n\n\t\t// Close a connection that settles after the abort.\n\t\tpending.then((conn) => conn.close()).catch(() => {});\n\t\tthrow signal.reason;\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nasync function connectInner(url: URL, props: ConnectProps | undefined, abort: Promise<void>): Promise<Established> {\n\tconst discovery = props?.discovery ?? defaultDiscovery(url);\n\n\tif (props?.transport) {\n\t\tconst transport = props.transport;\n\t\tvoid abort.then(() => transport.close());\n\t\treturn connectTransport(url, transport, discovery);\n\t}\n\n\t// Stop transports after one connects or the caller aborts.\n\tconst { promise: raced, resolve: done } = Promise.withResolvers<void>();\n\tconst cancel = Promise.race([raced, abort]);\n\n\tconst webtransport = isWebTransportSupported() ? connectWebTransport(url, cancel, props?.webtransport) : undefined;\n\n\t// Give QUIC a head start to connect before trying WebSocket, unless WebSocket has won in the past.\n\t// NOTE that QUIC should be faster because it involves 1/2 fewer RTTs.\n\tconst headstart =\n\t\t!webtransport || websocketWon.has(url.toString()) ? 0 : (props?.websocket?.delay ?? DEFAULT_WEBSOCKET_DELAY_MS);\n\tconst websocket =\n\t\tprops?.websocket?.enabled !== false\n\t\t\t? connectWebSocket(props?.websocket?.url ?? url, headstart, cancel)\n\t\t\t: undefined;\n\n\tif (!websocket && !webtransport) {\n\t\tthrow new Error(\"no transport available; WebTransport not supported and WebSocket is disabled\");\n\t}\n\n\t// Race the available transports, using `.any` to ignore if one participant has an error.\n\t// `webtransport`/`websocket` are `Promise | undefined`, so test existence explicitly: a\n\t// promise is always truthy, so bare truthiness here would be a misused-promise.\n\tconst session = await Promise.any(\n\t\twebtransport !== undefined\n\t\t\t? websocket !== undefined\n\t\t\t\t? [websocket, webtransport]\n\t\t\t\t: [webtransport]\n\t\t\t: [websocket],\n\t);\n\tdone();\n\n\tif (!session) throw new Error(\"no transport available\");\n\n\t// Abort the setup handshake without leaking the selected transport.\n\tvoid abort.then(() => session.close());\n\n\t// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\n\tif (session instanceof Session) {\n\t\t// Still a warning, not a debug line: losing the race means we fell back off QUIC.\n\t\tif (dev()) console.warn(redact(url), \"connected via WebSocket\");\n\t\twebsocketWon.add(url.toString());\n\t} else if (dev()) {\n\t\tconsole.debug(redact(url), \"connected via WebTransport\");\n\t}\n\n\t// The remaining setup is identical whether the transport was raced or supplied.\n\treturn await connectTransport(url, session as WebTransport, discovery);\n}\n\nasync function connectTransport(url: URL, session: WebTransport, discovery: boolean): Promise<Established> {\n\t// qmux Session exposes the negotiated protocol directly (as \"\" when there is none);\n\t// native WebTransport doesn't have a standard .protocol property yet.\n\tconst protocol: string | undefined = (session as { protocol?: string }).protocol || undefined;\n\tif (dev()) console.debug(redact(url), \"negotiated ALPN:\", protocol ?? \"(none)\");\n\n\t// Choose setup encoding based on negotiated WebTransport protocol (if any).\n\tlet setupVersion: Ietf.Version;\n\tconst modernVersion =\n\t\tprotocol === Ietf.ALPN.DRAFT_20\n\t\t\t? Ietf.Version.DRAFT_20\n\t\t\t: protocol === Ietf.ALPN.DRAFT_19\n\t\t\t\t? Ietf.Version.DRAFT_19\n\t\t\t\t: protocol === Ietf.ALPN.DRAFT_18\n\t\t\t\t\t? Ietf.Version.DRAFT_18\n\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_17\n\t\t\t\t\t\t? Ietf.Version.DRAFT_17\n\t\t\t\t\t\t: undefined;\n\tif (modernVersion !== undefined) {\n\t\treturn await handshakeAlpn(url, session, modernVersion, discovery);\n\t} else if (protocol === Ietf.ALPN.DRAFT_16) {\n\t\tsetupVersion = Ietf.Version.DRAFT_16;\n\t} else if (protocol === Ietf.ALPN.DRAFT_15) {\n\t\tsetupVersion = Ietf.Version.DRAFT_15;\n\t} else if (protocol === Lite.ALPN_06_WIP) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_06, discovery });\n\t} else if (protocol === Lite.ALPN_05) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_05, discovery });\n\t} else if (protocol === Lite.ALPN_04) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_04, discovery });\n\t} else if (protocol === Lite.ALPN_03) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_03, discovery });\n\t} else if (protocol === Lite.ALPN || protocol === \"\" || protocol === undefined) {\n\t\tsetupVersion = Ietf.Version.DRAFT_14;\n\t} else {\n\t\tthrow new Error(`unsupported WebTransport protocol: ${protocol}`);\n\t}\n\n\tconst stream = await Stream.open(session);\n\tawait stream.writer.u53(Lite.StreamId.ClientCompat);\n\n\tconst encoder = new TextEncoder();\n\n\tconst params = new Ietf.SetupOptions();\n\tparams.setVarint(Ietf.SetupOption.MaxRequestId, 42069n);\n\tparams.setBytes(Ietf.SetupOption.Implementation, encoder.encode(\"moq-lite-js\"));\n\tIetf.solicitIntoSetup(params);\n\n\tconst client = new Ietf.ClientSetup({\n\t\tversions:\n\t\t\tsetupVersion === Ietf.Version.DRAFT_16\n\t\t\t\t? [Ietf.Version.DRAFT_16]\n\t\t\t\t: setupVersion === Ietf.Version.DRAFT_15\n\t\t\t\t\t? [Ietf.Version.DRAFT_15]\n\t\t\t\t\t: [Lite.Version.DRAFT_02, Lite.Version.DRAFT_01, Ietf.Version.DRAFT_14],\n\t\tparameters: params,\n\t});\n\tawait client.encode(stream.writer, setupVersion);\n\n\tconst serverCompat = await stream.reader.u53();\n\tif (serverCompat !== Lite.StreamId.ServerCompat) {\n\t\tthrow new Error(`unsupported server message type: ${serverCompat.toString()}`);\n\t}\n\n\tconst server = await Ietf.ServerSetup.decode(stream.reader, setupVersion);\n\n\tif (Object.values(Lite.Version).includes(server.version as Lite.Version)) {\n\t\treturn new Lite.Connection({\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tversion: server.version as Lite.Version,\n\t\t\tsession: stream,\n\t\t\tdiscovery,\n\t\t});\n\t} else if (Object.values(Ietf.Version).includes(server.version as Ietf.Version)) {\n\t\tconst maxRequestId = server.parameters.getVarint(Ietf.SetupOption.MaxRequestId) ?? 0n;\n\t\treturn new Ietf.Connection({\n\t\t\tdiscovery,\n\t\t\tclient: true,\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tcontrol: stream,\n\t\t\tmaxRequestId,\n\t\t\tversion: server.version as Ietf.IetfVersion,\n\t\t\tsolicit: Ietf.solicitFromSetup(server.parameters),\n\t\t});\n\t} else {\n\t\tthrow new Error(`unsupported server version: ${server.version.toString()}`);\n\t}\n}\n\n/**\n * Draft-17+ client handshake. ALPN already pinned the version; SETUP is\n * exchanged over a pair of uni streams using stream type 0x2F00.\n */\nasync function handshakeAlpn(\n\turl: URL,\n\tsession: WebTransport,\n\tversion: Ietf.IetfVersion,\n\tdiscovery: boolean,\n): Promise<Established> {\n\tconst { control, solicit, cluster } = await exchangeSetup(session, version, \"moq-lite-js\");\n\n\treturn new Ietf.Connection({\n\t\tdiscovery,\n\t\tclient: true,\n\t\turl,\n\t\tquic: session,\n\t\tcontrol,\n\t\tsolicit,\n\t\tcluster,\n\t\t// v17+ uses NativeSession which manages its own request IDs; maxRequestId is unused.\n\t\tmaxRequestId: 0n,\n\t\tversion,\n\t});\n}\n\n// One entry of the DOM `serverCertificateHashes`, derived without naming the lib type.\ntype WebTransportHash = NonNullable<WebTransportOptions[\"serverCertificateHashes\"]>[number];\n\n// Strip PEM armor and base64-decode to the raw DER bytes.\nfunction pemToDer(pem: string): Uint8Array<ArrayBuffer> {\n\tconst match = pem.match(/-----BEGIN CERTIFICATE-----([\\s\\S]+?)-----END CERTIFICATE-----/);\n\tif (!match) {\n\t\tthrow new Error(\"invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor\");\n\t}\n\n\tconst binary = atob(match[1].replace(/\\s+/g, \"\"));\n\tconst der = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i++) {\n\t\tder[i] = binary.charCodeAt(i);\n\t}\n\treturn der;\n}\n\n/**\n * Compute the SHA-256 hash of a certificate, the value `serverCertificateHashes`\n * pins. Accepts a PEM string or raw DER bytes. Matches the hex fingerprints a moq\n * server reports, so `Hex.fromBytes(await certificateHash(pem))` round-trips.\n */\nexport async function certificateHash(cert: string | BufferSource): Promise<Uint8Array<ArrayBuffer>> {\n\tconst der = typeof cert === \"string\" ? pemToDer(cert) : cert;\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", der);\n\treturn new Uint8Array(digest);\n}\n\n// Normalize our friendlier pinning options into the DOM `serverCertificateHashes`.\nasync function resolveCertificateHashes(options?: WebTransportProps): Promise<WebTransportHash[] | undefined> {\n\tconst hashes: WebTransportHash[] = [];\n\n\tfor (const hash of options?.serverCertificateHashes ?? []) {\n\t\tconst value = typeof hash.value === \"string\" ? Hex.toBytes(hash.value) : hash.value;\n\t\thashes.push({ algorithm: hash.algorithm ?? \"sha-256\", value });\n\t}\n\n\tif (options?.serverCertificate !== undefined) {\n\t\thashes.push({ algorithm: \"sha-256\", value: await certificateHash(options.serverCertificate) });\n\t}\n\n\treturn hashes.length > 0 ? hashes : undefined;\n}\n\nasync function connectWebTransport(\n\turl: URL,\n\tcancel: Promise<void>,\n\toptions?: WebTransportProps,\n): Promise<WebTransport | undefined> {\n\tlet finalUrl = url;\n\n\t// Our custom pinning fields are normalized separately; the rest are DOM options.\n\tconst { serverCertificate: _cert, serverCertificateHashes: _hashes, ...webtransport } = options ?? {};\n\n\tconst finalOptions: WebTransportOptions = {\n\t\tallowPooling: false,\n\t\tcongestionControl: \"low-latency\",\n\t\tprotocols: [\n\t\t\t// Lite.ALPN_06_WIP is intentionally omitted: lite-06 is work-in-progress and\n\t\t\t// not advertised by default (connect.ts still accepts it if a server negotiates it).\n\t\t\tLite.ALPN_05,\n\t\t\tLite.ALPN_04,\n\t\t\tLite.ALPN_03,\n\t\t\tLite.ALPN,\n\t\t\tIetf.ALPN.DRAFT_20,\n\t\t\tIetf.ALPN.DRAFT_19,\n\t\t\tIetf.ALPN.DRAFT_18,\n\t\t\tIetf.ALPN.DRAFT_17,\n\t\t\tIetf.ALPN.DRAFT_16,\n\t\t\tIetf.ALPN.DRAFT_15,\n\t\t],\n\t\t...webtransport,\n\t};\n\n\t// Accumulate caller-provided pins first, then append anything we fetch below,\n\t// so a fetched fingerprint never clobbers hashes passed in via options.\n\tconst hashes = (await resolveCertificateHashes(options)) ?? [];\n\n\t// Only perform certificate fetch and URL rewrite when polyfill is not needed\n\t// This is needed because WebTransport is a butt to work with in local development.\n\tif (url.protocol === \"http:\") {\n\t\tconst fingerprintUrl = new URL(url);\n\t\tfingerprintUrl.pathname = \"/certificate.sha256\";\n\t\t// The certificate endpoint is unauthenticated, so don't hand it the token.\n\t\tfingerprintUrl.search = \"\";\n\n\t\t// Dev-only path: http:// can't be a real WebTransport origin, so we fetch the\n\t\t// self-signed cert's hash over plain HTTP and pin it. Production uses https://\n\t\t// and never reaches here. Keep this at debug so it doesn't read as a problem.\n\t\tif (dev()) {\n\t\t\tconsole.debug(\n\t\t\t\tredact(fingerprintUrl),\n\t\t\t\t\"performing an insecure fingerprint fetch; use https:// in production\",\n\t\t\t);\n\t\t}\n\n\t\t// Fetch the fingerprint from the server.\n\t\t// TODO cancel the request if the effect is cancelled.\n\t\tconst fingerprint = await Promise.race([fetch(fingerprintUrl), cancel]);\n\t\tif (!fingerprint) return undefined;\n\n\t\tconst fingerprintText = await Promise.race([fingerprint.text(), cancel]);\n\t\tif (fingerprintText === undefined) return undefined;\n\n\t\thashes.push({ algorithm: \"sha-256\", value: Hex.toBytes(fingerprintText) });\n\n\t\tfinalUrl = new URL(url);\n\t\tfinalUrl.protocol = \"https:\";\n\t}\n\n\tif (hashes.length > 0) {\n\t\tfinalOptions.serverCertificateHashes = hashes;\n\t}\n\n\tconst quic = new WebTransport(finalUrl, finalOptions);\n\n\t// Both .ready and .closed reject on failure; catch .closed to avoid an unhandled rejection.\n\tquic.closed.catch(() => {});\n\n\t// Wait for the WebTransport to connect, or for the cancel promise to resolve.\n\t// Close the connection if we lost the race.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n\n// TODO accept arguments to control the port/path used.\nasync function connectWebSocket(url: URL, delay: number, cancel: Promise<void>): Promise<Session | undefined> {\n\tconst timer = new Promise<void>((resolve) => setTimeout(resolve, delay));\n\n\tconst active = await Promise.race([cancel, timer.then(() => true)]);\n\tif (!active) return undefined;\n\n\t// Only moq-transport-18 is pinned to qmux-01 today. Every other ALPN we\n\t// support is currently negotiated as `qmux-00.{alpn}` on the wire, but we\n\t// don't want to lock that in: set the value to `null` so the polyfill\n\t// advertises every QMux draft it knows about and the server picks one.\n\t// Insertion order is the negotiation preference on the wire.\n\tconst versions = {\n\t\t// Lite.ALPN_06_WIP omitted on purpose: lite-06 is work-in-progress, not advertised by default.\n\t\t[Lite.ALPN_05]: null,\n\t\t[Lite.ALPN_04]: null,\n\t\t[Lite.ALPN_03]: null,\n\t\t[Lite.ALPN]: null,\n\t\t[Ietf.ALPN.DRAFT_20]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_18]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_17]: null,\n\t\t[Ietf.ALPN.DRAFT_16]: null,\n\t\t[Ietf.ALPN.DRAFT_15]: null,\n\t} as const satisfies Record<string, QmuxVersion | QmuxVersion[] | null>;\n\n\t// The default (`requireProtocol: false`) also advertises bare `qmux-01`,\n\t// `qmux-00`, and `webtransport` so we still interop with relays that only\n\t// know a wire-format version (today's moq-relay only accepts bare\n\t// `webtransport`).\n\tconst quic = new Session(url, {\n\t\tprotocols: Object.keys(versions),\n\t\tversions,\n\t});\n\n\t// Wait for the WebSocket to connect, or for the cancel promise to resolve.\n\t// `ready` rejects on a refused/failed connection, so a throw here is the caller's\n\t// cue to retry; a lost cancel race instead resolves and we close the loser.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n"]}
|
package/ietf/publisher.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publisher.d.ts","sourceRoot":"","sources":["../../src/ietf/publisher.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,KAAK,SAAS,MAAM,iBAAiB,CAAC;AAGlD,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,KAAK,MAAM,EAAU,MAAM,cAAc,CAAC;AAInD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AASxC,OAAO,EAAE,KAAK,SAAS,EAA+B,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EACN,KAAK,kBAAkB,EAIvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAe,KAAK,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAiGlE;;;;;GAKG;AACH,qBAAa,SAAS;;IAcrB;;;;OAIG;IACH,YAAY,EACX,IAAI,EACJ,OAAO,EACP,oBAAoB,EACpB,OAAO,GACP,EAAE;QACF,iDAAiD;QACjD,IAAI,EAAE,YAAY,CAAC;QACnB,gEAAgE;QAChE,OAAO,EAAE,OAAO,CAAC;QACjB,0EAA0E;QAC1E,oBAAoB,EAAE,OAAO,CAAC;QAC9B,4DAA4D;QAC5D,OAAO,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC;KACvB,EAKA;IAED;;;;OAIG;IACH,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,CAAC,QAAQ,QActD;IAED;;;;;OAKG;IACG,YAAY,CAAC,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,iBA8LhD;IA2LD;;;;;;;;;;OAUG;IACG,qBAAqB,CAAC,GAAG,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"publisher.d.ts","sourceRoot":"","sources":["../../src/ietf/publisher.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,KAAK,SAAS,MAAM,iBAA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|
|
|
488
488
|
await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version);
|
|
489
489
|
}
|
|
490
490
|
};
|
|
491
|
-
|
|
491
|
+
// Which producer holds each advertised suffix. Keyed on the producer rather than
|
|
492
|
+
// the path alone, so a path handed to a new producer is withdrawn and re-offered
|
|
493
|
+
// instead of diffing away to nothing and leaving the peer on the dead generation.
|
|
494
|
+
let active = new Map();
|
|
492
495
|
let retry = 0;
|
|
493
496
|
// What the peer refused, and whether coming back is worth anything.
|
|
494
497
|
const refused = new Map();
|
|
@@ -506,16 +509,16 @@ export class Publisher {
|
|
|
506
509
|
dispose();
|
|
507
510
|
break;
|
|
508
511
|
}
|
|
509
|
-
const updated = new
|
|
510
|
-
for (const name of broadcasts
|
|
512
|
+
const updated = new Map();
|
|
513
|
+
for (const [name, producer] of broadcasts) {
|
|
511
514
|
const suffix = Path.stripPrefix(prefix, name);
|
|
512
515
|
if (suffix === null)
|
|
513
516
|
continue;
|
|
514
|
-
updated.
|
|
517
|
+
updated.set(suffix, producer);
|
|
515
518
|
}
|
|
516
519
|
// A namespace that is gone takes its refusal with it, so re-announcing the
|
|
517
520
|
// path offers it again.
|
|
518
|
-
const live = new Set([...updated].map((suffix) => Path.join(prefix, suffix)));
|
|
521
|
+
const live = new Set([...updated.keys()].map((suffix) => Path.join(prefix, suffix)));
|
|
519
522
|
for (const path of [...refused.keys()]) {
|
|
520
523
|
if (!live.has(path))
|
|
521
524
|
refused.delete(path);
|
|
@@ -523,22 +526,27 @@ export class Publisher {
|
|
|
523
526
|
// Track what the peer holds rather than what we attempted: a declined
|
|
524
527
|
// advertisement stays out of `held`, so the next turn retries it instead of
|
|
525
528
|
// believing the namespace is already up.
|
|
526
|
-
const held = new
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
529
|
+
const held = new Map(active);
|
|
530
|
+
// Withdraw first, so a replacement reads as an end followed by a start.
|
|
531
|
+
for (const [suffix, producer] of active) {
|
|
532
|
+
if (updated.get(suffix) === producer)
|
|
533
|
+
continue;
|
|
534
|
+
await withdraw(suffix);
|
|
535
|
+
held.delete(suffix);
|
|
532
536
|
}
|
|
533
|
-
for (const
|
|
534
|
-
|
|
535
|
-
|
|
537
|
+
for (const [suffix, producer] of updated) {
|
|
538
|
+
if (active.get(suffix) === producer)
|
|
539
|
+
continue;
|
|
540
|
+
if (this.#offerable(Path.join(prefix, suffix), refused)) {
|
|
541
|
+
if (await advertise(suffix))
|
|
542
|
+
held.set(suffix, producer);
|
|
543
|
+
}
|
|
536
544
|
}
|
|
537
545
|
active = held;
|
|
538
546
|
// Whatever we wanted up and could not get up, as {@link runPublishNamespaces}
|
|
539
547
|
// does: only a legacy request can be declined, and nothing about the peer
|
|
540
548
|
// starting to answer raises a signal this loop is watching.
|
|
541
|
-
const outstanding = [...updated
|
|
549
|
+
const outstanding = [...updated].some(([suffix, producer]) => active.get(suffix) !== producer && this.#pending(Path.join(prefix, suffix), refused));
|
|
542
550
|
retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
|
|
543
551
|
// Wait for the next change, or for the peer to unsubscribe.
|
|
544
552
|
const next = await (retry
|
|
@@ -581,8 +589,10 @@ export class Publisher {
|
|
|
581
589
|
}
|
|
582
590
|
// The open PUBLISH_NAMESPACE request per advertised path.
|
|
583
591
|
const requests = new Map();
|
|
592
|
+
let dispose;
|
|
584
593
|
try {
|
|
585
|
-
|
|
594
|
+
// Which producer holds each advertised path; see {@link runSubscribeNamespace}.
|
|
595
|
+
let active = new Map();
|
|
586
596
|
let retry = 0;
|
|
587
597
|
// What the peer refused, and whether coming back is worth anything.
|
|
588
598
|
const refused = new Map();
|
|
@@ -593,43 +603,53 @@ export class Publisher {
|
|
|
593
603
|
// through it and leave the namespace unadvertised until something unrelated
|
|
594
604
|
// changed.
|
|
595
605
|
// TODO Make a better helper within Signals.
|
|
596
|
-
let dispose;
|
|
597
606
|
const changed = new Promise((resolve) => {
|
|
598
607
|
dispose = this.#broadcasts.changed(resolve);
|
|
599
608
|
});
|
|
600
609
|
const broadcasts = this.#broadcasts.peek();
|
|
601
610
|
if (!broadcasts) {
|
|
602
|
-
dispose();
|
|
611
|
+
dispose?.();
|
|
603
612
|
break;
|
|
604
613
|
}
|
|
605
|
-
const updated = new
|
|
614
|
+
const updated = new Map(broadcasts);
|
|
606
615
|
// A namespace that is gone takes its refusal with it, so re-announcing the
|
|
607
616
|
// path offers it again. Rust gets this by rebuilding the watched entry.
|
|
608
617
|
for (const path of [...refused.keys()]) {
|
|
609
618
|
if (!updated.has(path))
|
|
610
619
|
refused.delete(path);
|
|
611
620
|
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
621
|
+
// Withdraw first, so a replacement reads as an end followed by a start.
|
|
622
|
+
for (const [path, producer] of active) {
|
|
623
|
+
if (updated.get(path) === producer)
|
|
624
|
+
continue;
|
|
625
|
+
await this.#withdraw(path, requests);
|
|
616
626
|
}
|
|
617
|
-
for (const
|
|
618
|
-
|
|
627
|
+
for (const [path, producer] of updated) {
|
|
628
|
+
if (active.get(path) === producer)
|
|
629
|
+
continue;
|
|
630
|
+
if (this.#offerable(path, refused)) {
|
|
631
|
+
await this.#advertise(path, requests, refused);
|
|
632
|
+
}
|
|
619
633
|
}
|
|
620
634
|
// What the peer holds, not what we attempted: a declined PUBLISH_NAMESPACE
|
|
621
635
|
// leaves no request behind, so it stays outstanding below.
|
|
622
|
-
|
|
636
|
+
const held = new Map();
|
|
637
|
+
for (const path of requests.keys()) {
|
|
638
|
+
const producer = updated.get(path);
|
|
639
|
+
if (producer)
|
|
640
|
+
held.set(path, producer);
|
|
641
|
+
}
|
|
642
|
+
active = held;
|
|
623
643
|
// Whatever we wanted up and could not get up. Stream credit freeing, a
|
|
624
644
|
// transient failure clearing, or the peer starting to answer raises no
|
|
625
645
|
// signal of its own, so the only way back is to ask again on a timer.
|
|
626
|
-
const outstanding = [...updated
|
|
646
|
+
const outstanding = [...updated].some(([path, producer]) => active.get(path) !== producer && this.#pending(path, refused));
|
|
627
647
|
retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
|
|
628
648
|
// Wait for the next change, which has already fired if one landed above.
|
|
629
649
|
const next = await (retry
|
|
630
650
|
? Promise.race([changed, retryAfter(retry).then(() => broadcasts)])
|
|
631
651
|
: changed);
|
|
632
|
-
dispose();
|
|
652
|
+
dispose?.();
|
|
633
653
|
if (!next)
|
|
634
654
|
break;
|
|
635
655
|
}
|
|
@@ -640,6 +660,7 @@ export class Publisher {
|
|
|
640
660
|
console.warn(`publish_namespace loop failed: ${reason(error(err))}`);
|
|
641
661
|
}
|
|
642
662
|
finally {
|
|
663
|
+
dispose?.();
|
|
643
664
|
// Close out every open PUBLISH_NAMESPACE request.
|
|
644
665
|
for (const path of [...requests.keys()]) {
|
|
645
666
|
await this.#withdraw(path, requests);
|
|
@@ -753,8 +774,14 @@ export class Publisher {
|
|
|
753
774
|
catch {
|
|
754
775
|
// Stream might already be closed
|
|
755
776
|
}
|
|
777
|
+
request.stream.close();
|
|
778
|
+
return;
|
|
756
779
|
}
|
|
757
780
|
request.stream.close();
|
|
781
|
+
// Wait for transport acknowledgment before opening a replacement request.
|
|
782
|
+
// This assumes the peer processes the withdrawal by then; FIN acknowledgment
|
|
783
|
+
// does not itself acknowledge application processing across streams.
|
|
784
|
+
await request.stream.writer.closed;
|
|
758
785
|
}
|
|
759
786
|
/**
|
|
760
787
|
* Handles an incoming TRACK_STATUS_REQUEST on a bidi stream.
|