@moq/net 0.1.8 → 0.2.0
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/announced.d.ts +40 -24
- package/announced.d.ts.map +1 -1
- package/announced.js +74 -40
- package/announced.js.map +1 -1
- package/announced.test.d.ts +2 -0
- package/announced.test.d.ts.map +1 -0
- package/announced.test.js +37 -0
- package/announced.test.js.map +1 -0
- package/broadcast.d.ts +80 -25
- package/broadcast.d.ts.map +1 -1
- package/broadcast.js +266 -49
- package/broadcast.js.map +1 -1
- package/broadcast.test.d.ts +2 -0
- package/broadcast.test.d.ts.map +1 -0
- package/broadcast.test.js +219 -0
- package/broadcast.test.js.map +1 -0
- package/connection/accept.d.ts +6 -0
- package/connection/accept.d.ts.map +1 -1
- package/connection/accept.js +30 -10
- package/connection/accept.js.map +1 -1
- package/connection/browser.d.ts +5 -0
- package/connection/browser.d.ts.map +1 -0
- package/connection/browser.js +25 -0
- package/connection/browser.js.map +1 -0
- package/connection/browser.test.d.ts +2 -0
- package/connection/browser.test.d.ts.map +1 -0
- package/connection/browser.test.js +29 -0
- package/connection/browser.test.js.map +1 -0
- package/connection/connect.d.ts +43 -1
- package/connection/connect.d.ts.map +1 -1
- package/connection/connect.js +96 -107
- package/connection/connect.js.map +1 -1
- package/connection/connect.test.d.ts +2 -0
- package/connection/connect.test.d.ts.map +1 -0
- package/connection/connect.test.js +118 -0
- package/connection/connect.test.js.map +1 -0
- package/connection/established.d.ts +29 -15
- package/connection/established.d.ts.map +1 -1
- package/connection/established.js.map +1 -1
- package/connection/index.d.ts +8 -0
- package/connection/index.d.ts.map +1 -1
- package/connection/index.js +6 -0
- package/connection/index.js.map +1 -1
- package/connection/reload.d.ts +43 -7
- package/connection/reload.d.ts.map +1 -1
- package/connection/reload.js +165 -63
- package/connection/reload.js.map +1 -1
- package/connection/reload.test.d.ts +2 -0
- package/connection/reload.test.d.ts.map +1 -0
- package/connection/reload.test.js +104 -0
- package/connection/reload.test.js.map +1 -0
- package/connection/stats.d.ts +92 -0
- package/connection/stats.d.ts.map +1 -0
- package/connection/stats.js +35 -0
- package/connection/stats.js.map +1 -0
- package/connection/stats.test.d.ts +2 -0
- package/connection/stats.test.d.ts.map +1 -0
- package/connection/stats.test.js +120 -0
- package/connection/stats.test.js.map +1 -0
- package/connection/transport.d.ts +10 -0
- package/connection/transport.d.ts.map +1 -0
- package/connection/transport.js +12 -0
- package/connection/transport.js.map +1 -0
- package/consume.d.ts +26 -0
- package/consume.d.ts.map +1 -0
- package/consume.js +40 -0
- package/consume.js.map +1 -0
- package/datagram.d.ts +23 -0
- package/datagram.d.ts.map +1 -0
- package/datagram.js +3 -0
- package/datagram.js.map +1 -0
- package/group.d.ts +125 -36
- package/group.d.ts.map +1 -1
- package/group.js +244 -67
- package/group.js.map +1 -1
- package/group.test.js +121 -35
- package/group.test.js.map +1 -1
- package/ietf/adapter.d.ts +5 -3
- package/ietf/adapter.d.ts.map +1 -1
- package/ietf/adapter.js +19 -5
- package/ietf/adapter.js.map +1 -1
- package/ietf/aliases.d.ts +11 -0
- package/ietf/aliases.d.ts.map +1 -0
- package/ietf/aliases.js +52 -0
- package/ietf/aliases.js.map +1 -0
- package/ietf/aliases.test.d.ts +2 -0
- package/ietf/aliases.test.d.ts.map +1 -0
- package/ietf/aliases.test.js +30 -0
- package/ietf/aliases.test.js.map +1 -0
- package/ietf/connection.d.ts +19 -6
- package/ietf/connection.d.ts.map +1 -1
- package/ietf/connection.js +24 -9
- package/ietf/connection.js.map +1 -1
- package/ietf/ietf.test.js +58 -1
- package/ietf/ietf.test.js.map +1 -1
- package/ietf/object.d.ts +12 -4
- package/ietf/object.d.ts.map +1 -1
- package/ietf/object.js +92 -9
- package/ietf/object.js.map +1 -1
- package/ietf/publisher.d.ts +2 -2
- package/ietf/publisher.d.ts.map +1 -1
- package/ietf/publisher.js +12 -12
- package/ietf/publisher.js.map +1 -1
- package/ietf/subscribe_namespace.d.ts +0 -4
- package/ietf/subscribe_namespace.d.ts.map +1 -1
- package/ietf/subscribe_namespace.js +0 -5
- package/ietf/subscribe_namespace.js.map +1 -1
- package/ietf/subscriber.d.ts +8 -4
- package/ietf/subscriber.d.ts.map +1 -1
- package/ietf/subscriber.js +176 -105
- package/ietf/subscriber.js.map +1 -1
- package/index.d.ts +8 -5
- package/index.d.ts.map +1 -1
- package/index.js +8 -5
- package/index.js.map +1 -1
- package/integration.test.js +598 -12
- package/integration.test.js.map +1 -1
- package/internal.d.ts +14 -0
- package/internal.d.ts.map +1 -0
- package/internal.js +8 -0
- package/internal.js.map +1 -0
- package/lite/announce.d.ts +55 -13
- package/lite/announce.d.ts.map +1 -1
- package/lite/announce.js +221 -68
- package/lite/announce.js.map +1 -1
- package/lite/announce.test.d.ts +2 -0
- package/lite/announce.test.d.ts.map +1 -0
- package/lite/announce.test.js +71 -0
- package/lite/announce.test.js.map +1 -0
- package/lite/connection.d.ts +45 -19
- package/lite/connection.d.ts.map +1 -1
- package/lite/connection.js +85 -80
- package/lite/connection.js.map +1 -1
- package/lite/datagram.d.ts +23 -0
- package/lite/datagram.d.ts.map +1 -0
- package/lite/datagram.js +57 -0
- package/lite/datagram.js.map +1 -0
- package/lite/datagram.test.d.ts +2 -0
- package/lite/datagram.test.d.ts.map +1 -0
- package/lite/datagram.test.js +26 -0
- package/lite/datagram.test.js.map +1 -0
- package/lite/datagram_stream.d.ts +8 -0
- package/lite/datagram_stream.d.ts.map +1 -0
- package/lite/datagram_stream.js +44 -0
- package/lite/datagram_stream.js.map +1 -0
- package/lite/datagram_stream.test.d.ts +2 -0
- package/lite/datagram_stream.test.d.ts.map +1 -0
- package/lite/datagram_stream.test.js +15 -0
- package/lite/datagram_stream.test.js.map +1 -0
- package/lite/fetch.d.ts.map +1 -1
- package/lite/fetch.js +2 -2
- package/lite/fetch.js.map +1 -1
- package/lite/fetch.test.d.ts +2 -0
- package/lite/fetch.test.d.ts.map +1 -0
- package/lite/fetch.test.js +41 -0
- package/lite/fetch.test.js.map +1 -0
- package/lite/index.d.ts +3 -0
- package/lite/index.d.ts.map +1 -1
- package/lite/index.js +3 -0
- package/lite/index.js.map +1 -1
- package/lite/publisher.d.ts +13 -6
- package/lite/publisher.d.ts.map +1 -1
- package/lite/publisher.js +274 -64
- package/lite/publisher.js.map +1 -1
- package/lite/publisher.test.d.ts +2 -0
- package/lite/publisher.test.d.ts.map +1 -0
- package/lite/publisher.test.js +65 -0
- package/lite/publisher.test.js.map +1 -0
- package/lite/setup.d.ts +72 -6
- package/lite/setup.d.ts.map +1 -1
- package/lite/setup.js +184 -31
- package/lite/setup.js.map +1 -1
- package/lite/setup.test.d.ts +2 -0
- package/lite/setup.test.d.ts.map +1 -0
- package/lite/setup.test.js +122 -0
- package/lite/setup.test.js.map +1 -0
- package/lite/stream.d.ts +12 -3
- package/lite/stream.d.ts.map +1 -1
- package/lite/stream.js +7 -4
- package/lite/stream.js.map +1 -1
- package/lite/subscribe.d.ts +37 -23
- package/lite/subscribe.d.ts.map +1 -1
- package/lite/subscribe.js +70 -55
- package/lite/subscribe.js.map +1 -1
- package/lite/subscribe.test.d.ts +2 -0
- package/lite/subscribe.test.d.ts.map +1 -0
- package/lite/subscribe.test.js +68 -0
- package/lite/subscribe.test.js.map +1 -0
- package/lite/subscriber.d.ts +24 -17
- package/lite/subscriber.d.ts.map +1 -1
- package/lite/subscriber.js +521 -91
- package/lite/subscriber.js.map +1 -1
- package/lite/subscriber.test.d.ts +2 -0
- package/lite/subscriber.test.d.ts.map +1 -0
- package/lite/subscriber.test.js +30 -0
- package/lite/subscriber.test.js.map +1 -0
- package/lite/track.d.ts +25 -13
- package/lite/track.d.ts.map +1 -1
- package/lite/track.js +60 -35
- package/lite/track.js.map +1 -1
- package/lite/track.test.js +12 -10
- package/lite/track.test.js.map +1 -1
- package/lite/version.d.ts +17 -4
- package/lite/version.d.ts.map +1 -1
- package/lite/version.js +88 -17
- package/lite/version.js.map +1 -1
- package/mock.d.ts +42 -3
- package/mock.d.ts.map +1 -1
- package/mock.js +88 -17
- package/mock.js.map +1 -1
- package/package.json +3 -3
- package/path.d.ts +30 -0
- package/path.d.ts.map +1 -1
- package/path.js +49 -0
- package/path.js.map +1 -1
- package/path.test.js +41 -0
- package/path.test.js.map +1 -1
- package/stream.test.js +10 -0
- package/stream.test.js.map +1 -1
- package/time.d.ts +109 -86
- package/time.d.ts.map +1 -1
- package/time.js +80 -30
- package/time.js.map +1 -1
- package/time.test.d.ts +2 -0
- package/time.test.d.ts.map +1 -0
- package/time.test.js +12 -0
- package/time.test.js.map +1 -0
- package/track.d.ts +225 -45
- package/track.d.ts.map +1 -1
- package/track.js +505 -93
- package/track.js.map +1 -1
- package/track.test.js +138 -29
- package/track.test.js.map +1 -1
- package/util/error.d.ts +9 -0
- package/util/error.d.ts.map +1 -1
- package/util/error.js +21 -0
- package/util/error.js.map +1 -1
- package/util/error.test.d.ts +2 -0
- package/util/error.test.d.ts.map +1 -0
- package/util/error.test.js +45 -0
- package/util/error.test.js.map +1 -0
- package/util/index.d.ts +1 -0
- package/util/index.d.ts.map +1 -1
- package/util/index.js +1 -0
- package/util/index.js.map +1 -1
- package/util/timeout.d.ts +5 -0
- package/util/timeout.d.ts.map +1 -0
- package/util/timeout.js +18 -0
- package/util/timeout.js.map +1 -0
- package/util/timeout.test.d.ts +2 -0
- package/util/timeout.test.d.ts.map +1 -0
- package/util/timeout.test.js +18 -0
- package/util/timeout.test.js.map +1 -0
- package/varint.d.ts +6 -0
- package/varint.d.ts.map +1 -1
- package/varint.js +6 -2
- package/varint.js.map +1 -1
- package/zod.d.ts +4 -4
- package/zod.d.ts.map +1 -1
- package/zod.js.map +1 -1
- package/bandwidth.d.ts +0 -11
- package/bandwidth.d.ts.map +0 -1
- package/bandwidth.js +0 -7
- package/bandwidth.js.map +0 -1
package/broadcast.js
CHANGED
|
@@ -1,76 +1,293 @@
|
|
|
1
1
|
/* @ts-self-types="./broadcast.d.ts" */
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Broadcast role handles: a named collection of tracks produced by a publisher.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { Once, Signal } from "@moq/signals";
|
|
8
|
+
import { hooks } from "./internal.js";
|
|
9
|
+
import * as track from "./track.js";
|
|
10
|
+
/** Reactive backing state shared by broadcast producers and consumers. */
|
|
11
|
+
class BroadcastState {
|
|
6
12
|
requested = new Signal([]);
|
|
7
|
-
closed = new
|
|
13
|
+
closed = new Once();
|
|
14
|
+
tracks = new Map();
|
|
15
|
+
// Live consumer handles sharing this state (see {@link Consumer.clone}). The broadcast
|
|
16
|
+
// closes once the last one closes, so a shared consumer can be handed to several callers.
|
|
17
|
+
consumers = 0;
|
|
18
|
+
}
|
|
19
|
+
// Close the broadcast and reject any requests still pending in the queue, so a
|
|
20
|
+
// subscriber blocked on the track's info() or group reads is unblocked rather
|
|
21
|
+
// than left waiting on a producer that will never be served.
|
|
22
|
+
//
|
|
23
|
+
// Once.set throws on a second settle, and the producer and each consumer handle close
|
|
24
|
+
// independently, so this has to be idempotent.
|
|
25
|
+
function closeState(state, abort) {
|
|
26
|
+
if (state.closed.peek() !== undefined)
|
|
27
|
+
return;
|
|
28
|
+
state.closed.set(abort ?? null);
|
|
29
|
+
state.requested.mutate((requests) => {
|
|
30
|
+
for (const request of requests)
|
|
31
|
+
request.reject(abort);
|
|
32
|
+
requests.length = 0;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
// `register` is set on the subscribing (consumer) side: the fresh producer is cached in
|
|
36
|
+
// `state.tracks` so repeat subscriptions to the same track fan out from one upstream subscription
|
|
37
|
+
// instead of opening a new one, mirroring the Rust `broadcast::Consumer::track` weak-dedup. The
|
|
38
|
+
// consumer wire watches the producer's demand ({@link track.Producer.used}) and tears the upstream
|
|
39
|
+
// down once its last subscriber leaves, closing the producer, which evicts the cache entry below.
|
|
40
|
+
// The publishing side leaves `register` false: `state.tracks` there holds only the tracks the app
|
|
41
|
+
// inserted, and a dynamic serve stays one request per peer subscription.
|
|
42
|
+
function subscribe(state, name, options = {}, register = false) {
|
|
43
|
+
if (state.closed.peek() !== undefined) {
|
|
44
|
+
throw new Error(`broadcast is closed: ${state.closed.peek()}`);
|
|
45
|
+
}
|
|
46
|
+
const existing = state.tracks.get(name);
|
|
47
|
+
if (existing) {
|
|
48
|
+
if (existing.closed.peek() === undefined)
|
|
49
|
+
return existing.subscribe();
|
|
50
|
+
state.tracks.delete(name);
|
|
51
|
+
}
|
|
52
|
+
const producer = new track.Producer(name);
|
|
53
|
+
const subscriber = producer.subscribe();
|
|
54
|
+
if (register) {
|
|
55
|
+
state.tracks.set(name, producer);
|
|
56
|
+
// Drop the cache entry once the upstream closes (the wire tears it down when its last
|
|
57
|
+
// subscriber leaves), so a later subscribe re-opens it.
|
|
58
|
+
void producer.closed.then(() => {
|
|
59
|
+
if (state.tracks.get(name) === producer)
|
|
60
|
+
state.tracks.delete(name);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
state.requested.mutate((requested) => {
|
|
64
|
+
requested.push(hooks.makeRequest(name, producer, options.priority ?? 0));
|
|
65
|
+
requested.sort((a, b) => a.priority - b.priority);
|
|
66
|
+
});
|
|
67
|
+
return subscriber;
|
|
68
|
+
}
|
|
69
|
+
async function resolveTrackInfo(state, name) {
|
|
70
|
+
const existing = state.tracks.get(name);
|
|
71
|
+
if (existing && existing.closed.peek() === undefined) {
|
|
72
|
+
return existing.info();
|
|
73
|
+
}
|
|
74
|
+
if (state.closed.peek() !== undefined) {
|
|
75
|
+
return Promise.reject(new Error(`broadcast is closed: ${state.closed.peek()}`));
|
|
76
|
+
}
|
|
77
|
+
const producer = new track.Producer(name);
|
|
78
|
+
state.requested.mutate((requested) => {
|
|
79
|
+
requested.push(hooks.makeRequest(name, producer, 0));
|
|
80
|
+
requested.sort((a, b) => a.priority - b.priority);
|
|
81
|
+
});
|
|
82
|
+
try {
|
|
83
|
+
return await producer.info();
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
producer.close();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
// Serve a group from the local retained window by subscribing and scanning to the
|
|
90
|
+
// requested sequence. The default for a produced broadcast; the consuming wire layer
|
|
91
|
+
// overrides it to fetch over the network (or to reject when the transport has no FETCH).
|
|
92
|
+
async function fetchGroup(state, name, sequence, options = {}) {
|
|
93
|
+
const subscriber = subscribe(state, name, { priority: options.priority });
|
|
94
|
+
try {
|
|
95
|
+
for (;;) {
|
|
96
|
+
const group = await subscriber.recvGroup();
|
|
97
|
+
if (!group)
|
|
98
|
+
throw new Error(`group not found: ${sequence}`);
|
|
99
|
+
if (group.sequence === sequence) {
|
|
100
|
+
// Close the subscription when the returned group finishes, not now: an
|
|
101
|
+
// in-progress group must keep receiving frames for its lifetime (mirrors
|
|
102
|
+
// Rust poll_fetch). Also fires if the caller closes the group early.
|
|
103
|
+
void group.closed.then(() => subscriber.close());
|
|
104
|
+
return group;
|
|
105
|
+
}
|
|
106
|
+
group.close();
|
|
107
|
+
if (group.sequence > sequence)
|
|
108
|
+
throw new Error(`group not found: ${sequence}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
subscriber.close();
|
|
113
|
+
throw err;
|
|
114
|
+
}
|
|
8
115
|
}
|
|
9
116
|
/**
|
|
10
|
-
*
|
|
117
|
+
* The write side of a broadcast.
|
|
11
118
|
*
|
|
12
119
|
* @public
|
|
13
120
|
*/
|
|
14
|
-
export class
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
121
|
+
export class Producer {
|
|
122
|
+
#state = new BroadcastState();
|
|
123
|
+
/**
|
|
124
|
+
* Settles once the broadcast closes: `null` on a clean close, or the abort {@link Error}.
|
|
125
|
+
* Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
|
|
126
|
+
*/
|
|
127
|
+
get closed() {
|
|
128
|
+
return this.#state.closed;
|
|
129
|
+
}
|
|
130
|
+
/** A read handle for this broadcast. */
|
|
131
|
+
consume() {
|
|
132
|
+
return makeConsumer(this.#state);
|
|
133
|
+
}
|
|
134
|
+
/** Return the next track requested by a peer. */
|
|
135
|
+
async requested() {
|
|
136
|
+
for (;;) {
|
|
137
|
+
const request = this.#state.requested.peek().pop();
|
|
138
|
+
if (request)
|
|
139
|
+
return request;
|
|
140
|
+
const closed = this.#state.closed.peek();
|
|
141
|
+
if (closed instanceof Error)
|
|
142
|
+
throw closed;
|
|
143
|
+
if (closed !== undefined)
|
|
144
|
+
return undefined;
|
|
145
|
+
await Signal.race(this.#state.requested, this.#state.closed);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** Insert a track that is served directly, without an on-demand request round-trip. */
|
|
149
|
+
insertTrack(track) {
|
|
150
|
+
if (this.#state.closed.peek() !== undefined) {
|
|
151
|
+
throw new Error(`broadcast is closed: ${this.#state.closed.peek()}`);
|
|
152
|
+
}
|
|
153
|
+
const existing = this.#state.tracks.get(track.name);
|
|
154
|
+
if (existing && existing.closed.peek() === undefined) {
|
|
155
|
+
throw new Error(`duplicate track: ${track.name}`);
|
|
156
|
+
}
|
|
157
|
+
this.#state.tracks.set(track.name, track);
|
|
158
|
+
void track.closed.then(() => {
|
|
159
|
+
if (this.#state.tracks.get(track.name) === track) {
|
|
160
|
+
this.#state.tracks.delete(track.name);
|
|
161
|
+
}
|
|
27
162
|
});
|
|
28
163
|
}
|
|
164
|
+
/** Create a track, insert it into the broadcast, and return its producer. */
|
|
165
|
+
createTrack(name, info = {}) {
|
|
166
|
+
const producer = new track.Producer(name).accept(info);
|
|
167
|
+
this.insertTrack(producer);
|
|
168
|
+
return producer;
|
|
169
|
+
}
|
|
170
|
+
/** Remove a statically inserted track by name. */
|
|
171
|
+
removeTrack(name) {
|
|
172
|
+
this.#state.tracks.delete(name);
|
|
173
|
+
}
|
|
174
|
+
/** Open a live subscription to a track. Used by the publishing wire layer. */
|
|
175
|
+
subscribe(name, options) {
|
|
176
|
+
return subscribe(this.#state, name, options);
|
|
177
|
+
}
|
|
178
|
+
/** Resolve a track's immutable info. Used by the publishing wire layer. */
|
|
179
|
+
resolveTrackInfo(name) {
|
|
180
|
+
return resolveTrackInfo(this.#state, name);
|
|
181
|
+
}
|
|
182
|
+
/** Fetch a single group from the local retained window. Used by track handles. */
|
|
183
|
+
fetchGroup(name, sequence, options) {
|
|
184
|
+
return fetchGroup(this.#state, name, sequence, options);
|
|
185
|
+
}
|
|
186
|
+
/** A lazy read handle for a track on this broadcast. */
|
|
187
|
+
track(name) {
|
|
188
|
+
return new track.Consumer(name, this);
|
|
189
|
+
}
|
|
190
|
+
/** Close the broadcast, optionally with an error to abort waiters. Idempotent. */
|
|
191
|
+
close(abort) {
|
|
192
|
+
closeState(this.#state, abort);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
// Constructs a Consumer from within this module without exposing a public constructor
|
|
196
|
+
// that would leak the unexported BroadcastState. Assigned in the class's static block.
|
|
197
|
+
let makeConsumer;
|
|
198
|
+
/**
|
|
199
|
+
* The read side of a broadcast.
|
|
200
|
+
*
|
|
201
|
+
* Created internally: obtain one from {@link Producer.consume} or the connection's
|
|
202
|
+
* `consume(path)`. The wire layers subclass it to resolve tracks over the network.
|
|
203
|
+
*
|
|
204
|
+
* @public
|
|
205
|
+
*/
|
|
206
|
+
export class Consumer {
|
|
207
|
+
#state;
|
|
208
|
+
// Guards against a double close() on this handle over-decrementing the consumer count.
|
|
209
|
+
#closed = false;
|
|
210
|
+
constructor(state) {
|
|
211
|
+
this.#state = state ?? new BroadcastState();
|
|
212
|
+
this.#state.consumers++;
|
|
213
|
+
}
|
|
214
|
+
static {
|
|
215
|
+
makeConsumer = (state) => new Consumer(state);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Settles once the broadcast closes: `null` on a clean close, or the abort {@link Error}.
|
|
219
|
+
* Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
|
|
220
|
+
*
|
|
221
|
+
* Shared by every {@link clone}: it settles once the last handle closes. The subscribing
|
|
222
|
+
* wire layer peeks it to evict a closed entry from its per-path consume cache.
|
|
223
|
+
*/
|
|
224
|
+
get closed() {
|
|
225
|
+
return this.#state.closed;
|
|
226
|
+
}
|
|
29
227
|
/**
|
|
30
|
-
*
|
|
228
|
+
* Return another handle to the same broadcast, reference-counted with this one.
|
|
229
|
+
*
|
|
230
|
+
* Both handles read the same tracks and share one {@link closed} state; the broadcast
|
|
231
|
+
* closes only once *every* handle has {@link close}d. Used by the connection's per-path
|
|
232
|
+
* consume cache to share one subscription across callers. Subclasses that resolve info over
|
|
233
|
+
* the wire override this to preserve their type (see the wire layer's consumed broadcast).
|
|
31
234
|
*/
|
|
235
|
+
clone() {
|
|
236
|
+
return new Consumer(this.shareState());
|
|
237
|
+
}
|
|
238
|
+
// Hand this consumer's backing state to a clone. Opaque (`never`) so the state type stays
|
|
239
|
+
// unexported; a subclass passes it straight back into its own `super(...)`.
|
|
240
|
+
shareState() {
|
|
241
|
+
return this.#state;
|
|
242
|
+
}
|
|
243
|
+
/** Get a lazy handle for a track on this broadcast. Repeat subscriptions dedupe onto one upstream subscription. */
|
|
244
|
+
track(name) {
|
|
245
|
+
return new track.Consumer(name, this);
|
|
246
|
+
}
|
|
247
|
+
/** Open a live subscription to a track. Used by the subscribing wire layer. Repeat subscriptions to the same track share one upstream subscription. */
|
|
248
|
+
subscribe(name, options) {
|
|
249
|
+
return subscribe(this.#state, name, options, true);
|
|
250
|
+
}
|
|
251
|
+
/** Return the next track requested by the local consumer. Used by the subscribing wire layer. */
|
|
32
252
|
async requested() {
|
|
33
253
|
for (;;) {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const closed = this.state.closed.peek();
|
|
254
|
+
const request = this.#state.requested.peek().pop();
|
|
255
|
+
if (request)
|
|
256
|
+
return request;
|
|
257
|
+
const closed = this.#state.closed.peek();
|
|
39
258
|
if (closed instanceof Error)
|
|
40
259
|
throw closed;
|
|
41
|
-
if (closed)
|
|
260
|
+
if (closed !== undefined)
|
|
42
261
|
return undefined;
|
|
43
|
-
await Signal.race(this
|
|
262
|
+
await Signal.race(this.#state.requested, this.#state.closed);
|
|
44
263
|
}
|
|
45
264
|
}
|
|
46
265
|
/**
|
|
47
|
-
*
|
|
266
|
+
* Resolve a track's immutable info. Used by track handles. This base resolves it from
|
|
267
|
+
* the local producers; the consuming wire layer overrides it to fetch over the wire.
|
|
48
268
|
*/
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
if (this.state.closed.peek()) {
|
|
52
|
-
throw new Error(`broadcast is closed: ${this.state.closed.peek()}`);
|
|
53
|
-
}
|
|
54
|
-
this.state.requested.mutate((requested) => {
|
|
55
|
-
requested.push({ track, priority });
|
|
56
|
-
// Sort the tracks by priority in ascending order (we will pop)
|
|
57
|
-
requested.sort((a, b) => a.priority - b.priority);
|
|
58
|
-
});
|
|
59
|
-
return track;
|
|
269
|
+
resolveTrackInfo(name) {
|
|
270
|
+
return resolveTrackInfo(this.#state, name);
|
|
60
271
|
}
|
|
61
272
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
273
|
+
* Fetch a single group by sequence. Used by track handles. This base serves from the
|
|
274
|
+
* local retained window; the consuming wire layer overrides it to fetch over the wire
|
|
275
|
+
* (or to reject when the transport has no FETCH).
|
|
276
|
+
*/
|
|
277
|
+
fetchGroup(name, sequence, options) {
|
|
278
|
+
return fetchGroup(this.#state, name, sequence, options);
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Release this handle. The broadcast is closed (optionally with an error to abort waiters)
|
|
282
|
+
* once this was the last live handle; while other {@link clone}s remain open it stays live.
|
|
65
283
|
*/
|
|
66
284
|
close(abort) {
|
|
67
|
-
this
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
});
|
|
285
|
+
if (this.#closed)
|
|
286
|
+
return;
|
|
287
|
+
this.#closed = true;
|
|
288
|
+
if (--this.#state.consumers > 0)
|
|
289
|
+
return;
|
|
290
|
+
closeState(this.#state, abort);
|
|
74
291
|
}
|
|
75
292
|
}
|
|
76
293
|
//# sourceMappingURL=broadcast.js.map
|
package/broadcast.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broadcast.js","sourceRoot":"","sources":["../src/broadcast.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAQnC,2FAA2F;AAC3F,MAAM,OAAO,cAAc;IAC1B,SAAS,GAAG,IAAI,MAAM,CAAiB,EAAE,CAAC,CAAC;IAC3C,MAAM,GAAG,IAAI,MAAM,CAAkB,KAAK,CAAC,CAAC;CAC5C;AAED;;;;GAIG;AACH,MAAM,OAAO,SAAS;IACrB,8BAA8B;IAC9B,KAAK,GAAG,IAAI,cAAc,EAAE,CAAC;IAE7B,gEAAgE;IACvD,MAAM,CAA6B;IAE5C;QACC,IAAI,CAAC,MAAM,GAAG,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YACrC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE;gBACtD,IAAI,CAAC,MAAM;oBAAE,OAAO;gBACpB,OAAO,CAAC,MAAM,YAAY,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;gBACtD,OAAO,EAAE,CAAC;YACX,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,SAAS;QACd,SAAS,CAAC;YACT,oEAAoE;YACpE,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KAAK,MAAM,EAAE,KAAK,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,CAAC;YACrD,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACpB,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE;YACzC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { Signal } from \"@moq/signals\";\nimport { Track } from \"./track.ts\";\n\n/** A track a subscriber asked for, along with its requested delivery priority. */\nexport interface TrackRequest {\n\ttrack: Track;\n\tpriority: number;\n}\n\n/** Reactive backing state for a {@link Broadcast}: requested tracks plus a closed flag. */\nexport class BroadcastState {\n\trequested = new Signal<TrackRequest[]>([]);\n\tclosed = new Signal<boolean | Error>(false);\n}\n\n/**\n * Handles writing and managing tracks in a broadcast.\n *\n * @public\n */\nexport class Broadcast {\n\t/** Reactive backing state. */\n\tstate = new BroadcastState();\n\n\t/** Resolves with the abort error (or undefined) once closed. */\n\treadonly closed: Promise<Error | undefined>;\n\n\tconstructor() {\n\t\tthis.closed = new Promise((resolve) => {\n\t\t\tconst dispose = this.state.closed.subscribe((closed) => {\n\t\t\t\tif (!closed) return;\n\t\t\t\tresolve(closed instanceof Error ? closed : undefined);\n\t\t\t\tdispose();\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * A track requested over the network.\n\t */\n\tasync requested(): Promise<TrackRequest | undefined> {\n\t\tfor (;;) {\n\t\t\t// We use pop instead of shift because it's slightly more efficient.\n\t\t\tconst track = this.state.requested.peek().pop();\n\t\t\tif (track) return track;\n\n\t\t\tconst closed = this.state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed) 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 * Populates the provided track over the network.\n\t */\n\tsubscribe(name: string, priority: number): Track {\n\t\tconst track = new Track(name);\n\n\t\tif (this.state.closed.peek()) {\n\t\t\tthrow new Error(`broadcast is closed: ${this.state.closed.peek()}`);\n\t\t}\n\t\tthis.state.requested.mutate((requested) => {\n\t\t\trequested.push({ track, priority });\n\t\t\t// Sort the tracks by priority in ascending order (we will pop)\n\t\t\trequested.sort((a, b) => a.priority - b.priority);\n\t\t});\n\n\t\treturn track;\n\t}\n\n\t/**\n\t * Closes the writer and all associated tracks.\n\t *\n\t * @param abort - If provided, throw this exception instead of returning undefined.\n\t */\n\tclose(abort?: Error) {\n\t\tthis.state.closed.set(abort ?? true);\n\t\tfor (const { track } of this.state.requested.peek()) {\n\t\t\ttrack.close(abort);\n\t\t}\n\t\tthis.state.requested.mutate((requested) => {\n\t\t\trequested.length = 0;\n\t\t});\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,EAAE,MAAM,eAAe,CAAC;AACtC,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,uFAAuF;IACvF,0FAA0F;IAC1F,SAAS,GAAG,CAAC,CAAC;CACd;AAED,+EAA+E;AAC/E,8EAA8E;AAC9E,6DAA6D;AAC7D,EAAE;AACF,sFAAsF;AACtF,+CAA+C;AAC/C,SAAS,UAAU,CAAC,KAAqB,EAAE,KAAa;IACvD,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS;QAAE,OAAO;IAC9C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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 } 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\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\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();\n\t\tstate.tracks.delete(name);\n\t}\n\n\tconst producer = new track.Producer(name);\n\tconst subscriber = producer.subscribe();\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, options.priority ?? 0));\n\t\trequested.sort((a, b) => a.priority - b.priority);\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, 0));\n\t\trequested.sort((a, b) => a.priority - b.priority);\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 = this.#state.requested.peek().pop();\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 = this.#state.requested.peek().pop();\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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"broadcast.test.d.ts","sourceRoot":"","sources":["../src/broadcast.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/* @ts-self-types="./broadcast.test.d.ts" */
|
|
2
|
+
import { expect, setSystemTime, test } from "bun:test";
|
|
3
|
+
import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.js";
|
|
4
|
+
import { Lagged, MAX_GROUP_FRAMES } from "./group.js";
|
|
5
|
+
import { Timestamp } from "./time.js";
|
|
6
|
+
import { Producer as TrackProducer } from "./track.js";
|
|
7
|
+
// The public API mints consumers internally (Producer.consume, the wire layers); tests act
|
|
8
|
+
// as a wire layer by subclassing, the same way lite's ConsumeBroadcast does.
|
|
9
|
+
class TestConsumer extends BroadcastConsumer {
|
|
10
|
+
// biome-ignore lint/complexity/noUselessConstructor: widens the protected base constructor to public
|
|
11
|
+
constructor() {
|
|
12
|
+
super();
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
// Observe whether an on-demand track request is pending without blocking: returns the
|
|
16
|
+
// next request if one has already been emitted, or undefined if none is (yet) waiting.
|
|
17
|
+
async function pendingRequest(broadcast) {
|
|
18
|
+
const none = Symbol("none");
|
|
19
|
+
const result = await Promise.race([broadcast.requested(), Promise.resolve(none)]);
|
|
20
|
+
return result === none ? undefined : result;
|
|
21
|
+
}
|
|
22
|
+
test("consumer dedupes repeat subscriptions onto one upstream request", async () => {
|
|
23
|
+
const consumer = new TestConsumer();
|
|
24
|
+
// Two subscriptions to the same track share one upstream subscription...
|
|
25
|
+
const a = consumer.track("video").subscribe();
|
|
26
|
+
const b = consumer.subscribe("video");
|
|
27
|
+
const request = await pendingRequest(consumer);
|
|
28
|
+
expect(request?.name).toBe("video");
|
|
29
|
+
// ...so only one on-demand request is emitted for it.
|
|
30
|
+
expect(await pendingRequest(consumer)).toBeUndefined();
|
|
31
|
+
// Serving that single request fans out to both subscribers.
|
|
32
|
+
if (!request)
|
|
33
|
+
throw new Error("expected request");
|
|
34
|
+
const producer = request.accept();
|
|
35
|
+
producer.writeString("hello");
|
|
36
|
+
expect(await a.readString()).toBe("hello");
|
|
37
|
+
expect(await b.readString()).toBe("hello");
|
|
38
|
+
// A different track still opens its own request.
|
|
39
|
+
consumer.subscribe("audio");
|
|
40
|
+
expect((await pendingRequest(consumer))?.name).toBe("audio");
|
|
41
|
+
// Once the shared track closes, a later subscribe re-opens it.
|
|
42
|
+
producer.close();
|
|
43
|
+
consumer.subscribe("video");
|
|
44
|
+
expect((await pendingRequest(consumer))?.name).toBe("video");
|
|
45
|
+
});
|
|
46
|
+
test("a consumer clone shares the broadcast until every handle closes", () => {
|
|
47
|
+
const consumer = new TestConsumer();
|
|
48
|
+
const clone = consumer.clone();
|
|
49
|
+
// Closing one handle leaves the shared broadcast live for the other...
|
|
50
|
+
consumer.close();
|
|
51
|
+
expect(consumer.closed.peek()).toBeUndefined();
|
|
52
|
+
expect(clone.closed.peek()).toBeUndefined();
|
|
53
|
+
// ...and closing the last handle closes it for both.
|
|
54
|
+
clone.close();
|
|
55
|
+
expect(consumer.closed.peek()).toBeDefined();
|
|
56
|
+
expect(clone.closed.peek()).toBeDefined();
|
|
57
|
+
});
|
|
58
|
+
test("double-closing a consumer handle does not prematurely close the broadcast", () => {
|
|
59
|
+
const consumer = new TestConsumer();
|
|
60
|
+
const clone = consumer.clone();
|
|
61
|
+
// The double close must decrement the shared count only once...
|
|
62
|
+
clone.close();
|
|
63
|
+
clone.close();
|
|
64
|
+
expect(consumer.closed.peek()).toBeUndefined();
|
|
65
|
+
// ...so the broadcast still stays live until the other handle closes.
|
|
66
|
+
consumer.close();
|
|
67
|
+
expect(consumer.closed.peek()).toBeDefined();
|
|
68
|
+
});
|
|
69
|
+
test("consumer track subscriptions fan out and close independently", async () => {
|
|
70
|
+
const consumer = new TestConsumer();
|
|
71
|
+
// Two subscriptions to one track dedupe onto a single upstream request...
|
|
72
|
+
const a = consumer.subscribe("video");
|
|
73
|
+
const b = consumer.subscribe("video");
|
|
74
|
+
const request = await pendingRequest(consumer);
|
|
75
|
+
if (!request)
|
|
76
|
+
throw new Error("expected request");
|
|
77
|
+
expect(await pendingRequest(consumer)).toBeUndefined();
|
|
78
|
+
const producer = request.accept();
|
|
79
|
+
producer.writeString("one");
|
|
80
|
+
expect(await a.readString()).toBe("one");
|
|
81
|
+
expect(await b.readString()).toBe("one");
|
|
82
|
+
// ...and closing one subscriber leaves the other (and the shared upstream) delivering.
|
|
83
|
+
a.close();
|
|
84
|
+
producer.writeString("two");
|
|
85
|
+
expect(await b.readString()).toBe("two");
|
|
86
|
+
});
|
|
87
|
+
test("subscribe serves a statically inserted track without a request", async () => {
|
|
88
|
+
const broadcast = new BroadcastProducer();
|
|
89
|
+
const track1 = new TrackProducer("track1").accept();
|
|
90
|
+
broadcast.insertTrack(track1);
|
|
91
|
+
track1.appendGroup().close();
|
|
92
|
+
// The track already exists, so subscribe resolves immediately (no requested()).
|
|
93
|
+
const sub1 = broadcast.track("track1").subscribe();
|
|
94
|
+
expect((await sub1.nextGroup())?.sequence).toBe(0);
|
|
95
|
+
// No on-demand request was emitted for it.
|
|
96
|
+
expect(await pendingRequest(broadcast)).toBeUndefined();
|
|
97
|
+
// A second static track behaves the same.
|
|
98
|
+
const track2 = new TrackProducer("track2").accept();
|
|
99
|
+
broadcast.insertTrack(track2);
|
|
100
|
+
const sub2 = broadcast.track("track2").subscribe();
|
|
101
|
+
track2.appendGroup().close();
|
|
102
|
+
expect((await sub2.nextGroup())?.sequence).toBe(0);
|
|
103
|
+
});
|
|
104
|
+
test("two subscribers to one inserted track each get a full copy", async () => {
|
|
105
|
+
const broadcast = new BroadcastProducer();
|
|
106
|
+
const producer = broadcast.createTrack("video");
|
|
107
|
+
const a = broadcast.track("video").subscribe();
|
|
108
|
+
const b = broadcast.track("video").subscribe();
|
|
109
|
+
producer.writeString("hello");
|
|
110
|
+
producer.writeString("world");
|
|
111
|
+
// Neither subscriber steals from the other: both see every frame in order.
|
|
112
|
+
expect(await a.readString()).toBe("hello");
|
|
113
|
+
expect(await b.readString()).toBe("hello");
|
|
114
|
+
expect(await a.readString()).toBe("world");
|
|
115
|
+
expect(await b.readString()).toBe("world");
|
|
116
|
+
});
|
|
117
|
+
test("a late subscriber replays the cached window", async () => {
|
|
118
|
+
const broadcast = new BroadcastProducer();
|
|
119
|
+
const producer = broadcast.createTrack("video");
|
|
120
|
+
// Written before anyone subscribes; retained in the cache for replay.
|
|
121
|
+
producer.writeString("early");
|
|
122
|
+
const late = broadcast.track("video").subscribe();
|
|
123
|
+
expect(await late.readString()).toBe("early");
|
|
124
|
+
producer.writeString("later");
|
|
125
|
+
expect(await late.readString()).toBe("later");
|
|
126
|
+
});
|
|
127
|
+
test("a read throws Lagged on a gap, then resyncs to the next group", async () => {
|
|
128
|
+
const broadcast = new BroadcastProducer();
|
|
129
|
+
const producer = broadcast.createTrack("video");
|
|
130
|
+
const sub = broadcast.track("video").subscribe();
|
|
131
|
+
// Group 0 overflows its frame cap without being read, evicting the front: a gap.
|
|
132
|
+
const g0 = producer.appendGroup();
|
|
133
|
+
for (let i = 0; i < MAX_GROUP_FRAMES + 10; i++)
|
|
134
|
+
g0.writeFrame({ payload: new Uint8Array([i & 0xff]), timestamp: Timestamp.now() });
|
|
135
|
+
g0.close();
|
|
136
|
+
// Group 1 is clean.
|
|
137
|
+
const g1 = producer.appendGroup();
|
|
138
|
+
g1.writeFrame({ payload: new TextEncoder().encode("ok"), timestamp: Timestamp.now() });
|
|
139
|
+
g1.close();
|
|
140
|
+
// The reader hits the gap in group 0 (error, not a silent skip), then the next
|
|
141
|
+
// read resyncs from group 1.
|
|
142
|
+
expect(sub.readFrame()).rejects.toBeInstanceOf(Lagged);
|
|
143
|
+
expect(await sub.readString()).toBe("ok");
|
|
144
|
+
});
|
|
145
|
+
test("a stalled consumer does not pin evicted groups", async () => {
|
|
146
|
+
try {
|
|
147
|
+
setSystemTime(new Date(10_000));
|
|
148
|
+
const broadcast = new BroadcastProducer();
|
|
149
|
+
const producer = broadcast.createTrack("video", { latencyMax: 1000 });
|
|
150
|
+
// A subscriber that never reads. Its sink must not grow without bound.
|
|
151
|
+
const stalled = broadcast.track("video").subscribe();
|
|
152
|
+
producer.writeString("old");
|
|
153
|
+
// Advance past the cache window and write again to trigger a prune. The old
|
|
154
|
+
// (closed, aged-out) group is dropped from the stalled sink, not retained.
|
|
155
|
+
setSystemTime(new Date(12_000));
|
|
156
|
+
producer.writeString("fresh");
|
|
157
|
+
// The next group in arrival order is the fresh one (seq 1): the old (seq 0) group
|
|
158
|
+
// was evicted, not still buffered ahead of it.
|
|
159
|
+
expect((await stalled.recvGroup())?.sequence).toBe(1);
|
|
160
|
+
// Nothing else is buffered: a second recvGroup stays pending (the track is open),
|
|
161
|
+
// proving exactly one group remained in the sink rather than two.
|
|
162
|
+
const pending = Symbol("pending");
|
|
163
|
+
const next = await Promise.race([stalled.recvGroup(), Promise.resolve(pending)]);
|
|
164
|
+
expect(next).toBe(pending);
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
setSystemTime();
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
test("createTrack commits info up front", async () => {
|
|
171
|
+
const broadcast = new BroadcastProducer();
|
|
172
|
+
const producer = broadcast.createTrack("video", { latencyMax: 2000, priority: 3 });
|
|
173
|
+
expect(producer.name).toBe("video");
|
|
174
|
+
const info = await broadcast.track("video").info();
|
|
175
|
+
expect(info.latencyMax).toBe(2000);
|
|
176
|
+
expect(info.priority).toBe(3);
|
|
177
|
+
});
|
|
178
|
+
test("insertTrack rejects a duplicate live name", () => {
|
|
179
|
+
const broadcast = new BroadcastProducer();
|
|
180
|
+
broadcast.createTrack("dup");
|
|
181
|
+
expect(() => broadcast.insertTrack(new TrackProducer("dup").accept())).toThrow();
|
|
182
|
+
});
|
|
183
|
+
test("a closed track is evicted and re-subscribing falls through to a request", async () => {
|
|
184
|
+
const broadcast = new BroadcastProducer();
|
|
185
|
+
const track1 = broadcast.createTrack("track1");
|
|
186
|
+
track1.close();
|
|
187
|
+
// The stale entry is gone, so subscribe creates an on-demand request instead.
|
|
188
|
+
const pending = broadcast.track("track1").subscribe();
|
|
189
|
+
expect(pending).toBeDefined();
|
|
190
|
+
// That on-demand request is now waiting to be answered.
|
|
191
|
+
const request = await broadcast.requested();
|
|
192
|
+
expect(request?.name).toBe("track1");
|
|
193
|
+
});
|
|
194
|
+
test("removeTrack drops the static entry", async () => {
|
|
195
|
+
// While the static entry exists, subscribing takes the fast path: no on-demand request.
|
|
196
|
+
const kept = new BroadcastProducer();
|
|
197
|
+
kept.createTrack("track1");
|
|
198
|
+
kept.track("track1").subscribe();
|
|
199
|
+
expect(await pendingRequest(kept)).toBeUndefined();
|
|
200
|
+
// With the entry removed, subscribing falls through to an on-demand request.
|
|
201
|
+
const removed = new BroadcastProducer();
|
|
202
|
+
removed.createTrack("track1");
|
|
203
|
+
removed.removeTrack("track1");
|
|
204
|
+
removed.track("track1").subscribe();
|
|
205
|
+
expect((await pendingRequest(removed))?.name).toBe("track1");
|
|
206
|
+
});
|
|
207
|
+
test("close rejects a still-pending track request so its subscriber unblocks", async () => {
|
|
208
|
+
const broadcast = new TestConsumer();
|
|
209
|
+
// Subscribing with no static entry queues an on-demand request; the subscriber
|
|
210
|
+
// blocks on info() until that request is answered.
|
|
211
|
+
const subscriber = broadcast.track("video").subscribe();
|
|
212
|
+
const info = subscriber.info();
|
|
213
|
+
// Closing must reject the still-queued request rather than silently dropping it,
|
|
214
|
+
// so the awaiting subscriber rejects instead of hanging on a producer that will
|
|
215
|
+
// never be served.
|
|
216
|
+
broadcast.close();
|
|
217
|
+
await expect(info).rejects.toThrow();
|
|
218
|
+
});
|
|
219
|
+
//# sourceMappingURL=broadcast.test.js.map
|