@moq/net 0.2.3 → 0.2.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 +1 -0
- package/announced.d.ts +75 -1
- package/announced.d.ts.map +1 -1
- package/announced.js +140 -1
- package/announced.js.map +1 -1
- package/announced.test.js +3 -3
- package/announced.test.js.map +1 -1
- package/broadcast.d.ts.map +1 -1
- package/broadcast.js +11 -8
- package/broadcast.js.map +1 -1
- package/broadcast.test.js +24 -0
- package/broadcast.test.js.map +1 -1
- package/connection/established.d.ts +14 -1
- package/connection/established.d.ts.map +1 -1
- package/connection/established.js.map +1 -1
- package/connection/reload.d.ts +26 -5
- package/connection/reload.d.ts.map +1 -1
- package/connection/reload.js +55 -26
- package/connection/reload.js.map +1 -1
- package/connection/reload.test.js +56 -0
- package/connection/reload.test.js.map +1 -1
- package/consume.d.ts +18 -0
- package/consume.d.ts.map +1 -1
- package/consume.js +20 -0
- package/consume.js.map +1 -1
- package/ietf/connection.d.ts +8 -1
- package/ietf/connection.d.ts.map +1 -1
- package/ietf/connection.js +11 -0
- package/ietf/connection.js.map +1 -1
- package/ietf/ietf.test.js +57 -0
- package/ietf/ietf.test.js.map +1 -1
- package/ietf/properties.d.ts +6 -2
- package/ietf/properties.d.ts.map +1 -1
- package/ietf/properties.js +43 -20
- package/ietf/properties.js.map +1 -1
- package/ietf/publish.d.ts.map +1 -1
- package/ietf/publish.js +13 -3
- package/ietf/publish.js.map +1 -1
- package/ietf/publisher.d.ts +14 -2
- package/ietf/publisher.d.ts.map +1 -1
- package/ietf/publisher.js +148 -104
- package/ietf/publisher.js.map +1 -1
- package/ietf/subscribe.d.ts.map +1 -1
- package/ietf/subscribe.js +9 -5
- package/ietf/subscribe.js.map +1 -1
- package/ietf/subscriber.d.ts.map +1 -1
- package/ietf/subscriber.js +9 -0
- package/ietf/subscriber.js.map +1 -1
- package/integration.test.js +294 -0
- package/integration.test.js.map +1 -1
- package/internal.d.ts +1 -1
- package/internal.d.ts.map +1 -1
- package/internal.js.map +1 -1
- package/lite/connection.d.ts +8 -1
- package/lite/connection.d.ts.map +1 -1
- package/lite/connection.js +10 -0
- package/lite/connection.js.map +1 -1
- package/lite/publisher.d.ts.map +1 -1
- package/lite/publisher.js +30 -5
- package/lite/publisher.js.map +1 -1
- package/lite/subscribe.test.js +43 -1
- package/lite/subscribe.test.js.map +1 -1
- package/lite/subscriber.d.ts.map +1 -1
- package/lite/subscriber.js +91 -25
- package/lite/subscriber.js.map +1 -1
- package/lite/subscriber.test.js +78 -0
- package/lite/subscriber.test.js.map +1 -1
- package/package.json +1 -1
- package/track.d.ts +26 -6
- package/track.d.ts.map +1 -1
- package/track.js +112 -27
- package/track.js.map +1 -1
- package/track.test.js +52 -5
- package/track.test.js.map +1 -1
package/README.md
CHANGED
|
@@ -60,6 +60,7 @@ await quicheLoaded; //This is a promise, connect after it resolves
|
|
|
60
60
|
- **[Publishing](examples/publish.ts)** - Publish data to a broadcast
|
|
61
61
|
- **[Subscribing](examples/subscribe.ts)** - Subscribe to and receive broadcast data
|
|
62
62
|
- **[Discovery](examples/discovery.ts)** - Discover broadcasts announced by the server
|
|
63
|
+
- **[Waiting](examples/wait.ts)** - Wait for one known broadcast to come online, and follow it
|
|
63
64
|
- **[Server side usage](https://github.com/sb2702/webcodecs-examples/tree/main/src/moq-server)** - Publish from browser to a server
|
|
64
65
|
|
|
65
66
|
## License
|
package/announced.d.ts
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
|
-
import { type GetPromise } from "@moq/signals";
|
|
6
|
+
import { type GetPromise, type Getter, type GetterInit } from "@moq/signals";
|
|
7
|
+
import type * as broadcast from "./broadcast.js";
|
|
8
|
+
import type { Established } from "./connection/established.js";
|
|
7
9
|
import * as Path from "./path.js";
|
|
8
10
|
/**
|
|
9
11
|
* The availability of a broadcast.
|
|
@@ -58,4 +60,76 @@ export declare class Consumer {
|
|
|
58
60
|
/** Closes the reader. Idempotent. */
|
|
59
61
|
close(abort?: Error): void;
|
|
60
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* What to watch, for {@link Broadcast}.
|
|
65
|
+
*
|
|
66
|
+
* @public
|
|
67
|
+
*/
|
|
68
|
+
export interface BroadcastProps {
|
|
69
|
+
/**
|
|
70
|
+
* The connection to watch on. Accepts a live {@link Established} session, or a reactive one
|
|
71
|
+
* (a `Connection.Reload`'s `established`), which is how the handle survives reconnects.
|
|
72
|
+
*/
|
|
73
|
+
connection: GetterInit<Established | undefined>;
|
|
74
|
+
/** The broadcast path to watch. */
|
|
75
|
+
path: Path.Valid;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A reactive handle to a single broadcast: {@link Broadcast.active} holds a live
|
|
79
|
+
* {@link broadcast.Consumer} while the path is announced and `undefined` while nobody
|
|
80
|
+
* publishes it.
|
|
81
|
+
*
|
|
82
|
+
* Use this instead of {@link Established.consume} whenever the broadcast may not exist yet.
|
|
83
|
+
* Subscribing to a path nobody publishes gets the stream reset, so a consumer that races the
|
|
84
|
+
* publisher stays silent forever unless it retries; this waits for the announcement instead.
|
|
85
|
+
*
|
|
86
|
+
* A same-name republish re-consumes, so the handle attaches to the new instance rather than
|
|
87
|
+
* clinging to the dead one. A relay failover that keeps the same publisher does *not*: the
|
|
88
|
+
* subscription resumes across the new route, so `active` holds the same consumer throughout and
|
|
89
|
+
* never goes offline. Only a change of publisher produces an offline/online transition.
|
|
90
|
+
*
|
|
91
|
+
* Built from a reconnecting `Connection.Reload`, the handle also spans reconnects: the broadcast
|
|
92
|
+
* drops to `undefined` while disconnected and resolves again once the new connection announces it.
|
|
93
|
+
*
|
|
94
|
+
* Falls back to consuming blind (and warns once) on a relay without
|
|
95
|
+
* {@link Established.discovery}, where there is no announcement to wait for. `active` then
|
|
96
|
+
* means *assumed present* rather than known live: nothing reports whether the path exists, so
|
|
97
|
+
* a subscribe to a missing broadcast is how a caller finds out. The handle stays usable either
|
|
98
|
+
* way, and because it is scoped to the path rather than to one publisher, a subscribe made
|
|
99
|
+
* after a publisher finally appears succeeds.
|
|
100
|
+
*
|
|
101
|
+
* If discovery fails on a live session (the announcement stream is reset, or the relay
|
|
102
|
+
* refuses it) the handle goes offline and stays there: nothing reopens the stream on that
|
|
103
|
+
* connection. Build it from a `Connection.Reload` if you need it to recover, since a new
|
|
104
|
+
* connection starts a new stream.
|
|
105
|
+
*
|
|
106
|
+
* Close it to release the announcement stream and the current broadcast.
|
|
107
|
+
*
|
|
108
|
+
* @public
|
|
109
|
+
*/
|
|
110
|
+
export declare class Broadcast {
|
|
111
|
+
#private;
|
|
112
|
+
/** The broadcast path this handle watches. */
|
|
113
|
+
readonly path: Path.Valid;
|
|
114
|
+
/**
|
|
115
|
+
* The live broadcast, or `undefined` while it is offline.
|
|
116
|
+
*
|
|
117
|
+
* Borrowed, not yours to close: this handle owns the consumer and swaps it when the path is
|
|
118
|
+
* republished. `active` keeps pointing at whatever you closed, so once you drop the last
|
|
119
|
+
* reference the shared broadcast is gone and reads fail until the next announcement replaces
|
|
120
|
+
* it. Take a {@link broadcast.Consumer.clone} for a lifetime of your own, or close this whole
|
|
121
|
+
* handle to release everything.
|
|
122
|
+
*/
|
|
123
|
+
readonly active: Getter<broadcast.Consumer | undefined>;
|
|
124
|
+
/**
|
|
125
|
+
* Watch a path on a connection.
|
|
126
|
+
*
|
|
127
|
+
* Prefer `announcedBroadcast(path)` on the connection itself. Reach for this when the
|
|
128
|
+
* session you want to follow isn't either connection type, e.g. your own
|
|
129
|
+
* `Getter<Established | undefined>`.
|
|
130
|
+
*/
|
|
131
|
+
constructor({ connection, path }: BroadcastProps);
|
|
132
|
+
/** Closes the handle and the broadcast it currently holds. Idempotent. */
|
|
133
|
+
close(): void;
|
|
134
|
+
}
|
|
61
135
|
//# sourceMappingURL=announced.d.ts.map
|
package/announced.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"announced.d.ts","sourceRoot":"","sources":["../src/announced.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,UAAU,
|
|
1
|
+
{"version":3,"file":"announced.d.ts","sourceRoot":"","sources":["../src/announced.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAU,KAAK,UAAU,EAAE,KAAK,MAAM,EAAE,KAAK,UAAU,EAAwB,MAAM,cAAc,CAAC;AAC3G,OAAO,KAAK,KAAK,SAAS,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC;;;;GAIG;AACH,MAAM,WAAW,KAAK;IACrB,qEAAqE;IACrE,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC;IACjB,uEAAuE;IACvE,MAAM,EAAE,OAAO,CAAC;CAChB;AAiBD;;;;GAIG;AACH,qBAAa,QAAQ;;IACpB,4CAA4C;IAC5C,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC;IAInB,YAAY,MAAM,aAAe,EAEhC;IAED;;;OAGG;IACH,IAAI,MAAM,IAAI,UAAU,CAAC,KAAK,GAAG,IAAI,CAAC,CAErC;IAED,kDAAkD;IAClD,OAAO,IAAI,QAAQ,CAElB;IAED,2CAA2C;IAC3C,MAAM,CAAC,KAAK,EAAE,KAAK,QAKlB;IAED,qCAAqC;IACrC,KAAK,CAAC,KAAK,CAAC,EAAE,KAAK,QAElB;CACD;AAMD;;;;;;;GAOG;AACH,qBAAa,QAAQ;;IACpB,4CAA4C;IAC5C,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC;IAInB,OAAO,eAGN;IAED,mEAAmE;IACnE,IAAI,MAAM,IAAI,UAAU,CAAC,KAAK,GAAG,IAAI,CAAC,CAErC;IAMD,qCAAqC;IAC/B,IAAI,IAAI,OAAO,CAAC,KAAK,GAAG,SAAS,CAAC,CAWvC;IAED,qCAAqC;IACrC,KAAK,CAAC,KAAK,CAAC,EAAE,KAAK,QAElB;CACD;AAMD;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC9B;;;OAGG;IACH,UAAU,EAAE,UAAU,CAAC,WAAW,GAAG,SAAS,CAAC,CAAC;IAEhD,mCAAmC;IACnC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,SAAS;;IACrB,8CAA8C;IAC9C,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC;IAE1B;;;;;;;;OAQG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,SAAS,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAC;IAKxD;;;;;;OAMG;IACH,YAAY,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,cAAc,EA6E/C;IAED,0EAA0E;IAC1E,KAAK,SAEJ;CACD"}
|
package/announced.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* @module
|
|
6
6
|
*/
|
|
7
|
-
import { Once, Signal } from "@moq/signals";
|
|
7
|
+
import { Effect, getter, Once, Signal } from "@moq/signals";
|
|
8
8
|
import * as Path from "./path.js";
|
|
9
9
|
/** Reactive backing state shared by announcement producers and consumers. */
|
|
10
10
|
class AnnounceState {
|
|
@@ -101,4 +101,143 @@ export class Consumer {
|
|
|
101
101
|
closeState(this.#state, abort);
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
|
+
// Connections already warned about missing broadcast discovery, so the fallback logs at most
|
|
105
|
+
// once per connection instead of once per watched path.
|
|
106
|
+
const warnedNoDiscovery = new WeakSet();
|
|
107
|
+
/**
|
|
108
|
+
* A reactive handle to a single broadcast: {@link Broadcast.active} holds a live
|
|
109
|
+
* {@link broadcast.Consumer} while the path is announced and `undefined` while nobody
|
|
110
|
+
* publishes it.
|
|
111
|
+
*
|
|
112
|
+
* Use this instead of {@link Established.consume} whenever the broadcast may not exist yet.
|
|
113
|
+
* Subscribing to a path nobody publishes gets the stream reset, so a consumer that races the
|
|
114
|
+
* publisher stays silent forever unless it retries; this waits for the announcement instead.
|
|
115
|
+
*
|
|
116
|
+
* A same-name republish re-consumes, so the handle attaches to the new instance rather than
|
|
117
|
+
* clinging to the dead one. A relay failover that keeps the same publisher does *not*: the
|
|
118
|
+
* subscription resumes across the new route, so `active` holds the same consumer throughout and
|
|
119
|
+
* never goes offline. Only a change of publisher produces an offline/online transition.
|
|
120
|
+
*
|
|
121
|
+
* Built from a reconnecting `Connection.Reload`, the handle also spans reconnects: the broadcast
|
|
122
|
+
* drops to `undefined` while disconnected and resolves again once the new connection announces it.
|
|
123
|
+
*
|
|
124
|
+
* Falls back to consuming blind (and warns once) on a relay without
|
|
125
|
+
* {@link Established.discovery}, where there is no announcement to wait for. `active` then
|
|
126
|
+
* means *assumed present* rather than known live: nothing reports whether the path exists, so
|
|
127
|
+
* a subscribe to a missing broadcast is how a caller finds out. The handle stays usable either
|
|
128
|
+
* way, and because it is scoped to the path rather than to one publisher, a subscribe made
|
|
129
|
+
* after a publisher finally appears succeeds.
|
|
130
|
+
*
|
|
131
|
+
* If discovery fails on a live session (the announcement stream is reset, or the relay
|
|
132
|
+
* refuses it) the handle goes offline and stays there: nothing reopens the stream on that
|
|
133
|
+
* connection. Build it from a `Connection.Reload` if you need it to recover, since a new
|
|
134
|
+
* connection starts a new stream.
|
|
135
|
+
*
|
|
136
|
+
* Close it to release the announcement stream and the current broadcast.
|
|
137
|
+
*
|
|
138
|
+
* @public
|
|
139
|
+
*/
|
|
140
|
+
export class Broadcast {
|
|
141
|
+
/** The broadcast path this handle watches. */
|
|
142
|
+
path;
|
|
143
|
+
/**
|
|
144
|
+
* The live broadcast, or `undefined` while it is offline.
|
|
145
|
+
*
|
|
146
|
+
* Borrowed, not yours to close: this handle owns the consumer and swaps it when the path is
|
|
147
|
+
* republished. `active` keeps pointing at whatever you closed, so once you drop the last
|
|
148
|
+
* reference the shared broadcast is gone and reads fail until the next announcement replaces
|
|
149
|
+
* it. Take a {@link broadcast.Consumer.clone} for a lifetime of your own, or close this whole
|
|
150
|
+
* handle to release everything.
|
|
151
|
+
*/
|
|
152
|
+
active;
|
|
153
|
+
#active = new Signal(undefined);
|
|
154
|
+
#signals = new Effect();
|
|
155
|
+
/**
|
|
156
|
+
* Watch a path on a connection.
|
|
157
|
+
*
|
|
158
|
+
* Prefer `announcedBroadcast(path)` on the connection itself. Reach for this when the
|
|
159
|
+
* session you want to follow isn't either connection type, e.g. your own
|
|
160
|
+
* `Getter<Established | undefined>`.
|
|
161
|
+
*/
|
|
162
|
+
constructor({ connection, path }) {
|
|
163
|
+
this.path = path;
|
|
164
|
+
this.active = this.#active;
|
|
165
|
+
const source = getter(connection);
|
|
166
|
+
this.#signals.run((effect) => {
|
|
167
|
+
const conn = effect.get(source);
|
|
168
|
+
if (!conn)
|
|
169
|
+
return;
|
|
170
|
+
// Without discovery no announcement ever arrives, so waiting would hang forever.
|
|
171
|
+
if (!conn.discovery) {
|
|
172
|
+
if (!warnedNoDiscovery.has(conn)) {
|
|
173
|
+
warnedNoDiscovery.add(conn);
|
|
174
|
+
console.warn("relay does not support broadcast discovery; consuming without waiting.");
|
|
175
|
+
}
|
|
176
|
+
const blind = conn.consume(path);
|
|
177
|
+
effect.cleanup(() => blind.close());
|
|
178
|
+
effect.set(this.#active, blind, undefined);
|
|
179
|
+
// The announcement-gated path below goes offline when the stream ends with the
|
|
180
|
+
// session; without discovery there is no stream, so watch the session itself.
|
|
181
|
+
// A consumed broadcast is a path-scoped handle, not a subscription, so its own
|
|
182
|
+
// `closed` says nothing about whether the path exists or the session is alive.
|
|
183
|
+
// Raced against the run's teardown so a closed handle isn't retained until the
|
|
184
|
+
// session ends; the cleanup above has already cleared `active` in that case.
|
|
185
|
+
effect.spawn(async () => {
|
|
186
|
+
await Promise.race([effect.cancel, conn.closed]);
|
|
187
|
+
if (this.#active.peek() === blind)
|
|
188
|
+
this.#active.set(undefined);
|
|
189
|
+
});
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const announced = conn.announced(path);
|
|
193
|
+
effect.cleanup(() => announced.close());
|
|
194
|
+
let current;
|
|
195
|
+
const offline = () => {
|
|
196
|
+
const mine = current;
|
|
197
|
+
current?.close();
|
|
198
|
+
current = undefined;
|
|
199
|
+
// Only clear what this run put there. A spawn task that resumes after its run was
|
|
200
|
+
// torn down would otherwise wipe the consumer a newer run already installed.
|
|
201
|
+
if (this.#active.peek() === mine)
|
|
202
|
+
this.#active.set(undefined);
|
|
203
|
+
};
|
|
204
|
+
effect.cleanup(offline);
|
|
205
|
+
effect.spawn(async () => {
|
|
206
|
+
try {
|
|
207
|
+
for (;;) {
|
|
208
|
+
const event = await Promise.race([effect.cancel, announced.next()]);
|
|
209
|
+
if (!event)
|
|
210
|
+
break;
|
|
211
|
+
// Scoped to `path`, so the exact broadcast arrives with an empty suffix; ignore children.
|
|
212
|
+
if (event.path !== Path.empty())
|
|
213
|
+
continue;
|
|
214
|
+
if (event.active) {
|
|
215
|
+
// A live subscription survives a redundant (re-)announce; only replace a dead one.
|
|
216
|
+
if (current && current.closed.peek() === undefined)
|
|
217
|
+
continue;
|
|
218
|
+
current?.close();
|
|
219
|
+
current = conn.consume(path);
|
|
220
|
+
this.#active.set(current);
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
offline();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
// Discovery failed: the session died under the stream, or the relay refused
|
|
229
|
+
// to answer. Nothing reopens it on this connection, so say so out loud.
|
|
230
|
+
console.warn("broadcast discovery failed", err);
|
|
231
|
+
}
|
|
232
|
+
// The stream ended, or this run was torn down (its cleanup already ran). Either
|
|
233
|
+
// way there is nothing left announcing the path, so don't hold a dead broadcast.
|
|
234
|
+
offline();
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
/** Closes the handle and the broadcast it currently holds. Idempotent. */
|
|
239
|
+
close() {
|
|
240
|
+
this.#signals.close();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
104
243
|
//# sourceMappingURL=announced.js.map
|
package/announced.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"announced.js","sourceRoot":"","sources":["../src/announced.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmB,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAclC,6EAA6E;AAC7E,MAAM,aAAa;IAClB,KAAK,GAAG,IAAI,MAAM,CAAU,EAAE,CAAC,CAAC;IAChC,MAAM,GAAG,IAAI,IAAI,EAAgB,CAAC;CAClC;AAED,yFAAyF;AACzF,SAAS,UAAU,CAAC,KAAoB,EAAE,KAAa;IACtD,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS;QAAE,OAAO;IAC9C,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;IAChC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QAC5B,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,OAAO,QAAQ;IACpB,4CAA4C;IAC5C,MAAM,CAAa;IAEnB,MAAM,GAAG,IAAI,aAAa,EAAE,CAAC;IAE7B,YAAY,MAAM,GAAG,IAAI,CAAC,KAAK,EAAE;QAChC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;IAED;;;OAGG;IACH,IAAI,MAAM;QACT,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IAC3B,CAAC;IAED,kDAAkD;IAClD,OAAO;QACN,OAAO,YAAY,CAAC,IAAI,CAAC,MAAM,EA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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,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;IAED,qCAAqC;IACrC,KAAK,CAAC,KAAa;QAClB,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAChC,CAAC;CACD","sourcesContent":["/**\n * Broadcast announcement streams: which broadcast paths are available under a prefix.\n *\n * @module\n */\nimport { type GetPromise, Once, Signal } from \"@moq/signals\";\nimport * as Path from \"./path.js\";\n\n/**\n * The availability of a broadcast.\n *\n * @public\n */\nexport interface Event {\n\t/** Broadcast path relative to the prefix passed to `announced()`. */\n\tpath: Path.Valid;\n\t/** True when the broadcast is available, false when it was removed. */\n\tactive: boolean;\n}\n\n/** Reactive backing state shared by announcement producers and consumers. */\nclass AnnounceState {\n\tqueue = new Signal<Event[]>([]);\n\tclosed = new Once<Error | null>();\n}\n\n// Once.set throws on a second settle, and both ends of a stream can close independently.\nfunction closeState(state: AnnounceState, abort?: Error) {\n\tif (state.closed.peek() !== undefined) return;\n\tstate.closed.set(abort ?? null);\n\tstate.queue.mutate((queue) => {\n\t\tqueue.length = 0;\n\t});\n}\n\n/**\n * The write side of an announcement stream.\n *\n * @public\n */\nexport class Producer {\n\t/** Path prefix this stream is scoped to. */\n\tprefix: Path.Valid;\n\n\t#state = new AnnounceState();\n\n\tconstructor(prefix = Path.empty()) {\n\t\tthis.prefix = prefix;\n\t}\n\n\t/**\n\t * Settles once the stream 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 announcement stream. */\n\tconsume(): Consumer {\n\t\treturn makeConsumer(this.prefix, this.#state);\n\t}\n\n\t/** Writes an announcement to the queue. */\n\tappend(event: Event) {\n\t\tif (this.#state.closed.peek() !== undefined) throw new Error(\"announcements are closed\");\n\t\tthis.#state.queue.mutate((queue) => {\n\t\t\tqueue.push(event);\n\t\t});\n\t}\n\n\t/** Closes the writer. 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 AnnounceState. Assigned in the class's static block.\nlet makeConsumer: (prefix: Path.Valid, state: AnnounceState) => Consumer;\n\n/**\n * The read side of an announcement stream.\n *\n * Created internally: obtain one from {@link Producer.consume} or the connection's\n * `announced(prefix)`.\n *\n * @public\n */\nexport class Consumer {\n\t/** Path prefix this stream is scoped to. */\n\tprefix: Path.Valid;\n\n\t#state: AnnounceState;\n\n\tprivate constructor(prefix: Path.Valid, state: AnnounceState) {\n\t\tthis.prefix = prefix;\n\t\tthis.#state = state;\n\t}\n\n\t/** Settles once the stream closes; see {@link Producer.closed}. */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\tstatic {\n\t\tmakeConsumer = (prefix, state) => new Consumer(prefix, state);\n\t}\n\n\t/** Returns the next announcement. */\n\tasync next(): Promise<Event | undefined> {\n\t\tfor (;;) {\n\t\t\tconst announce = this.#state.queue.peek().shift();\n\t\t\tif (announce) return announce;\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.queue, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Closes the reader. Idempotent. */\n\tclose(abort?: Error) {\n\t\tcloseState(this.#state, abort);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"announced.js","sourceRoot":"","sources":["../src/announced.ts"],"names":[],"m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C,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;wBACpE,IAAI,CAAC,KAAK;4BAAE,MAAM;wBAElB,0FAA0F;wBAC1F,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,KAAK,EAAE;4BAAE,SAAS;wBAE1C,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC;4BAClB,mFAAmF;4BACnF,IAAI,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS;gCAAE,SAAS;4BAC7D,OAAO,EAAE,KAAK,EAAE,CAAC;4BACjB,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;4BAC7B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;wBAC3B,CAAC;6BAAM,CAAC;4BACP,OAAO,EAAE,CAAC;wBACX,CAAC;oBACF,CAAC;gBACF,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACd,4EAA4E;oBAC5E,wEAAwE;oBACxE,OAAO,CAAC,IAAI,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAAC;gBACjD,CAAC;gBAED,gFAAgF;gBAChF,iFAAiF;gBACjF,OAAO,EAAE,CAAC;YACX,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACJ,CAAC;IAED,0EAA0E;IAC1E,KAAK;QACJ,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;CACD","sourcesContent":["/**\n * Broadcast announcement streams: which broadcast paths are available under a prefix.\n *\n * @module\n */\nimport { Effect, type GetPromise, type Getter, type GetterInit, getter, Once, Signal } from \"@moq/signals\";\nimport type * as broadcast from \"./broadcast.js\";\nimport type { Established } from \"./connection/established.js\";\nimport * as Path from \"./path.js\";\n\n/**\n * The availability of a broadcast.\n *\n * @public\n */\nexport interface Event {\n\t/** Broadcast path relative to the prefix passed to `announced()`. */\n\tpath: Path.Valid;\n\t/** True when the broadcast is available, false when it was removed. */\n\tactive: boolean;\n}\n\n/** Reactive backing state shared by announcement producers and consumers. */\nclass AnnounceState {\n\tqueue = new Signal<Event[]>([]);\n\tclosed = new Once<Error | null>();\n}\n\n// Once.set throws on a second settle, and both ends of a stream can close independently.\nfunction closeState(state: AnnounceState, abort?: Error) {\n\tif (state.closed.peek() !== undefined) return;\n\tstate.closed.set(abort ?? null);\n\tstate.queue.mutate((queue) => {\n\t\tqueue.length = 0;\n\t});\n}\n\n/**\n * The write side of an announcement stream.\n *\n * @public\n */\nexport class Producer {\n\t/** Path prefix this stream is scoped to. */\n\tprefix: Path.Valid;\n\n\t#state = new AnnounceState();\n\n\tconstructor(prefix = Path.empty()) {\n\t\tthis.prefix = prefix;\n\t}\n\n\t/**\n\t * Settles once the stream 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 announcement stream. */\n\tconsume(): Consumer {\n\t\treturn makeConsumer(this.prefix, this.#state);\n\t}\n\n\t/** Writes an announcement to the queue. */\n\tappend(event: Event) {\n\t\tif (this.#state.closed.peek() !== undefined) throw new Error(\"announcements are closed\");\n\t\tthis.#state.queue.mutate((queue) => {\n\t\t\tqueue.push(event);\n\t\t});\n\t}\n\n\t/** Closes the writer. 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 AnnounceState. Assigned in the class's static block.\nlet makeConsumer: (prefix: Path.Valid, state: AnnounceState) => Consumer;\n\n/**\n * The read side of an announcement stream.\n *\n * Created internally: obtain one from {@link Producer.consume} or the connection's\n * `announced(prefix)`.\n *\n * @public\n */\nexport class Consumer {\n\t/** Path prefix this stream is scoped to. */\n\tprefix: Path.Valid;\n\n\t#state: AnnounceState;\n\n\tprivate constructor(prefix: Path.Valid, state: AnnounceState) {\n\t\tthis.prefix = prefix;\n\t\tthis.#state = state;\n\t}\n\n\t/** Settles once the stream closes; see {@link Producer.closed}. */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\tstatic {\n\t\tmakeConsumer = (prefix, state) => new Consumer(prefix, state);\n\t}\n\n\t/** Returns the next announcement. */\n\tasync next(): Promise<Event | undefined> {\n\t\tfor (;;) {\n\t\t\tconst announce = this.#state.queue.peek().shift();\n\t\t\tif (announce) return announce;\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.queue, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Closes the reader. Idempotent. */\n\tclose(abort?: Error) {\n\t\tcloseState(this.#state, abort);\n\t}\n}\n\n// Connections already warned about missing broadcast discovery, so the fallback logs at most\n// once per connection instead of once per watched path.\nconst warnedNoDiscovery = new WeakSet<Established>();\n\n/**\n * What to watch, for {@link Broadcast}.\n *\n * @public\n */\nexport interface BroadcastProps {\n\t/**\n\t * The connection to watch on. Accepts a live {@link Established} session, or a reactive one\n\t * (a `Connection.Reload`'s `established`), which is how the handle survives reconnects.\n\t */\n\tconnection: GetterInit<Established | undefined>;\n\n\t/** The broadcast path to watch. */\n\tpath: Path.Valid;\n}\n\n/**\n * A reactive handle to a single broadcast: {@link Broadcast.active} holds a live\n * {@link broadcast.Consumer} while the path is announced and `undefined` while nobody\n * publishes it.\n *\n * Use this instead of {@link Established.consume} whenever the broadcast may not exist yet.\n * Subscribing to a path nobody publishes gets the stream reset, so a consumer that races the\n * publisher stays silent forever unless it retries; this waits for the announcement instead.\n *\n * A same-name republish re-consumes, so the handle attaches to the new instance rather than\n * clinging to the dead one. A relay failover that keeps the same publisher does *not*: the\n * subscription resumes across the new route, so `active` holds the same consumer throughout and\n * never goes offline. Only a change of publisher produces an offline/online transition.\n *\n * Built from a reconnecting `Connection.Reload`, the handle also spans reconnects: the broadcast\n * drops to `undefined` while disconnected and resolves again once the new connection announces it.\n *\n * Falls back to consuming blind (and warns once) on a relay without\n * {@link Established.discovery}, where there is no announcement to wait for. `active` then\n * means *assumed present* rather than known live: nothing reports whether the path exists, so\n * a subscribe to a missing broadcast is how a caller finds out. The handle stays usable either\n * way, and because it is scoped to the path rather than to one publisher, a subscribe made\n * after a publisher finally appears succeeds.\n *\n * If discovery fails on a live session (the announcement stream is reset, or the relay\n * refuses it) the handle goes offline and stays there: nothing reopens the stream on that\n * connection. Build it from a `Connection.Reload` if you need it to recover, since a new\n * connection starts a new stream.\n *\n * Close it to release the announcement stream and the current broadcast.\n *\n * @public\n */\nexport class Broadcast {\n\t/** The broadcast path this handle watches. */\n\treadonly path: Path.Valid;\n\n\t/**\n\t * The live broadcast, or `undefined` while it is offline.\n\t *\n\t * Borrowed, not yours to close: this handle owns the consumer and swaps it when the path is\n\t * republished. `active` keeps pointing at whatever you closed, so once you drop the last\n\t * reference the shared broadcast is gone and reads fail until the next announcement replaces\n\t * it. Take a {@link broadcast.Consumer.clone} for a lifetime of your own, or close this whole\n\t * handle to release everything.\n\t */\n\treadonly active: Getter<broadcast.Consumer | undefined>;\n\n\t#active = new Signal<broadcast.Consumer | undefined>(undefined);\n\t#signals = new Effect();\n\n\t/**\n\t * Watch a path on a connection.\n\t *\n\t * Prefer `announcedBroadcast(path)` on the connection itself. Reach for this when the\n\t * session you want to follow isn't either connection type, e.g. your own\n\t * `Getter<Established | undefined>`.\n\t */\n\tconstructor({ connection, path }: BroadcastProps) {\n\t\tthis.path = path;\n\t\tthis.active = this.#active;\n\n\t\tconst source = getter(connection);\n\t\tthis.#signals.run((effect) => {\n\t\t\tconst conn = effect.get(source);\n\t\t\tif (!conn) return;\n\n\t\t\t// Without discovery no announcement ever arrives, so waiting would hang forever.\n\t\t\tif (!conn.discovery) {\n\t\t\t\tif (!warnedNoDiscovery.has(conn)) {\n\t\t\t\t\twarnedNoDiscovery.add(conn);\n\t\t\t\t\tconsole.warn(\"relay does not support broadcast discovery; consuming without waiting.\");\n\t\t\t\t}\n\n\t\t\t\tconst blind = conn.consume(path);\n\t\t\t\teffect.cleanup(() => blind.close());\n\t\t\t\teffect.set(this.#active, blind, undefined);\n\n\t\t\t\t// The announcement-gated path below goes offline when the stream ends with the\n\t\t\t\t// session; without discovery there is no stream, so watch the session itself.\n\t\t\t\t// A consumed broadcast is a path-scoped handle, not a subscription, so its own\n\t\t\t\t// `closed` says nothing about whether the path exists or the session is alive.\n\t\t\t\t// Raced against the run's teardown so a closed handle isn't retained until the\n\t\t\t\t// session ends; the cleanup above has already cleared `active` in that case.\n\t\t\t\teffect.spawn(async () => {\n\t\t\t\t\tawait Promise.race([effect.cancel, conn.closed]);\n\t\t\t\t\tif (this.#active.peek() === blind) this.#active.set(undefined);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst announced = conn.announced(path);\n\t\t\teffect.cleanup(() => announced.close());\n\n\t\t\tlet current: broadcast.Consumer | undefined;\n\t\t\tconst offline = () => {\n\t\t\t\tconst mine = current;\n\t\t\t\tcurrent?.close();\n\t\t\t\tcurrent = undefined;\n\t\t\t\t// Only clear what this run put there. A spawn task that resumes after its run was\n\t\t\t\t// torn down would otherwise wipe the consumer a newer run already installed.\n\t\t\t\tif (this.#active.peek() === mine) this.#active.set(undefined);\n\t\t\t};\n\t\t\teffect.cleanup(offline);\n\n\t\t\teffect.spawn(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tconst event = await Promise.race([effect.cancel, announced.next()]);\n\t\t\t\t\t\tif (!event) break;\n\n\t\t\t\t\t\t// Scoped to `path`, so the exact broadcast arrives with an empty suffix; ignore children.\n\t\t\t\t\t\tif (event.path !== Path.empty()) continue;\n\n\t\t\t\t\t\tif (event.active) {\n\t\t\t\t\t\t\t// A live subscription survives a redundant (re-)announce; only replace a dead one.\n\t\t\t\t\t\t\tif (current && current.closed.peek() === undefined) continue;\n\t\t\t\t\t\t\tcurrent?.close();\n\t\t\t\t\t\t\tcurrent = conn.consume(path);\n\t\t\t\t\t\t\tthis.#active.set(current);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\toffline();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\t// Discovery failed: the session died under the stream, or the relay refused\n\t\t\t\t\t// to answer. Nothing reopens it on this connection, so say so out loud.\n\t\t\t\t\tconsole.warn(\"broadcast discovery failed\", err);\n\t\t\t\t}\n\n\t\t\t\t// The stream ended, or this run was torn down (its cleanup already ran). Either\n\t\t\t\t// way there is nothing left announcing the path, so don't hold a dead broadcast.\n\t\t\t\toffline();\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Closes the handle and the broadcast it currently holds. Idempotent. */\n\tclose() {\n\t\tthis.#signals.close();\n\t}\n}\n"]}
|
package/announced.test.js
CHANGED
|
@@ -14,9 +14,9 @@ test("next streams every appended event in order", async () => {
|
|
|
14
14
|
test("a same-name re-announce is a distinct update", async () => {
|
|
15
15
|
const producer = new Announce.Producer();
|
|
16
16
|
const consumer = producer.consume();
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
17
|
+
// The stream is a log, not a set: it carries a redundant active:true as its own update rather
|
|
18
|
+
// than collapsing it. Deciding what a repeat means belongs to the session layer, which resolves
|
|
19
|
+
// a restart into either nothing (a route change) or an end + start (a new publisher).
|
|
20
20
|
producer.append({ path: p("a"), active: true });
|
|
21
21
|
producer.append({ path: p("a"), active: true });
|
|
22
22
|
expect(await consumer.next()).toEqual({ path: p("a"), active: true });
|
package/announced.test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"announced.test.js","sourceRoot":"","sources":["../src/announced.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AACxC,OA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ts\";\nimport * as Path from \"./path.ts\";\n\nconst p = (s: string) => Path.from(s);\n\ntest(\"next streams every appended event in order\", async () => {\n\tconst producer = new Announce.Producer();\n\tconst consumer = producer.consume();\n\n\tproducer.append({ path: p(\"a\"), active: true });\n\tproducer.append({ path: p(\"a\"), active: false });\n\n\texpect(await consumer.next()).toEqual({ path: p(\"a\"), active: true });\n\texpect(await consumer.next()).toEqual({ path: p(\"a\"), active: false });\n});\n\ntest(\"a same-name re-announce is a distinct update\", async () => {\n\tconst producer = new Announce.Producer();\n\tconst consumer = producer.consume();\n\n\t// The stream is a log, not a set: it carries a redundant active:true as its own update rather\n\t// than collapsing it. Deciding what a repeat means belongs to the session layer, which resolves\n\t// a restart into either nothing (a route change) or an end + start (a new publisher).\n\tproducer.append({ path: p(\"a\"), active: true });\n\tproducer.append({ path: p(\"a\"), active: true });\n\n\texpect(await consumer.next()).toEqual({ path: p(\"a\"), active: true });\n\texpect(await consumer.next()).toEqual({ path: p(\"a\"), active: true });\n});\n\ntest(\"closing resolves next with undefined\", async () => {\n\tconst producer = new Announce.Producer();\n\tconst consumer = producer.consume();\n\n\tproducer.close();\n\texpect(await consumer.next()).toBeUndefined();\n});\n\ntest(\"aborting rejects next\", async () => {\n\tconst producer = new Announce.Producer();\n\tconst consumer = producer.consume();\n\n\tproducer.close(new Error(\"boom\"));\n\tawait expect(consumer.next()).rejects.toThrow(\"boom\");\n});\n"]}
|
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":"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,CAElC;IAED,kFAAkF;IAClF,KAAK,CAAC,KAAK,CAAC,EAAE,KAAK,QAElB;CACD;AAMD;;;;;;;GAOG;AACH,qBAAa,QAAS,YAAW,KAAK,CAAC,SAAS;;IAM/C,SAAS,aAAa,KAAK,CAAC,EAAE,KAAK,EAAE;IAUrC;;;;;;OAMG;IACH,IAAI,MAAM,IAAI,UAAU,CAAC,KAAK,GAAG,IAAI,CAAC,CAErC;IAED;;;;;;;OAOG;IACH,KAAK,IAAI,QAAQ,CAEhB;IAID,SAAS,CAAC,UAAU,IAAI,KAAK,CAE5B;IAED,mHAAmH;IACnH,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,QAAQ,CAElC;IAED,uJAAuJ;IACvJ,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC,UAAU,CAEtE;IAED,iGAAiG;IAC3F,SAAS,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
|
@@ -16,6 +16,11 @@ class BroadcastState {
|
|
|
16
16
|
// closes once the last one closes, so a shared consumer can be handed to several callers.
|
|
17
17
|
consumers = 0;
|
|
18
18
|
}
|
|
19
|
+
function dequeueRequest(state) {
|
|
20
|
+
const requested = state.requested.peek();
|
|
21
|
+
requested.sort((a, b) => a.priority - b.priority);
|
|
22
|
+
return requested.pop();
|
|
23
|
+
}
|
|
19
24
|
// Close the broadcast and reject any requests still pending in the queue, so a
|
|
20
25
|
// subscriber blocked on the track's info() or group reads is unblocked rather
|
|
21
26
|
// than left waiting on a producer that will never be served.
|
|
@@ -46,11 +51,11 @@ function subscribe(state, name, options = {}, register = false) {
|
|
|
46
51
|
const existing = state.tracks.get(name);
|
|
47
52
|
if (existing) {
|
|
48
53
|
if (existing.closed.peek() === undefined)
|
|
49
|
-
return existing.subscribe();
|
|
54
|
+
return existing.subscribe(options);
|
|
50
55
|
state.tracks.delete(name);
|
|
51
56
|
}
|
|
52
57
|
const producer = new track.Producer(name);
|
|
53
|
-
const subscriber = producer.subscribe();
|
|
58
|
+
const subscriber = producer.subscribe(options);
|
|
54
59
|
if (register) {
|
|
55
60
|
state.tracks.set(name, producer);
|
|
56
61
|
// Drop the cache entry once the upstream closes (the wire tears it down when its last
|
|
@@ -61,8 +66,7 @@ function subscribe(state, name, options = {}, register = false) {
|
|
|
61
66
|
});
|
|
62
67
|
}
|
|
63
68
|
state.requested.mutate((requested) => {
|
|
64
|
-
requested.push(hooks.makeRequest(name, producer
|
|
65
|
-
requested.sort((a, b) => a.priority - b.priority);
|
|
69
|
+
requested.push(hooks.makeRequest(name, producer));
|
|
66
70
|
});
|
|
67
71
|
return subscriber;
|
|
68
72
|
}
|
|
@@ -76,8 +80,7 @@ async function resolveTrackInfo(state, name) {
|
|
|
76
80
|
}
|
|
77
81
|
const producer = new track.Producer(name);
|
|
78
82
|
state.requested.mutate((requested) => {
|
|
79
|
-
requested.push(hooks.makeRequest(name, producer
|
|
80
|
-
requested.sort((a, b) => a.priority - b.priority);
|
|
83
|
+
requested.push(hooks.makeRequest(name, producer));
|
|
81
84
|
});
|
|
82
85
|
try {
|
|
83
86
|
return await producer.info();
|
|
@@ -134,7 +137,7 @@ export class Producer {
|
|
|
134
137
|
/** Return the next track requested by a peer. */
|
|
135
138
|
async requested() {
|
|
136
139
|
for (;;) {
|
|
137
|
-
const request = this.#state
|
|
140
|
+
const request = dequeueRequest(this.#state);
|
|
138
141
|
if (request)
|
|
139
142
|
return request;
|
|
140
143
|
const closed = this.#state.closed.peek();
|
|
@@ -251,7 +254,7 @@ export class Consumer {
|
|
|
251
254
|
/** Return the next track requested by the local consumer. Used by the subscribing wire layer. */
|
|
252
255
|
async requested() {
|
|
253
256
|
for (;;) {
|
|
254
|
-
const request = this.#state
|
|
257
|
+
const request = dequeueRequest(this.#state);
|
|
255
258
|
if (request)
|
|
256
259
|
return request;
|
|
257
260
|
const closed = this.#state.closed.peek();
|
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,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,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;IAChC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE;QACnC,KAAK,MAAM,OA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AAC;IAED,iGAAiG;IACjG,KAAK,CAAC,SAAS;QACd,SAAS,CAAC;YACT,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,CAAC;YACnD,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 } 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"]}
|
|
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,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,KAAa;IACvD,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS;QAAE,OAAO;IAC9C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O,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 } 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\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));\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));\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"]}
|
package/broadcast.test.js
CHANGED
|
@@ -43,6 +43,30 @@ test("consumer dedupes repeat subscriptions onto one upstream request", async ()
|
|
|
43
43
|
consumer.subscribe("video");
|
|
44
44
|
expect((await pendingRequest(consumer))?.name).toBe("video");
|
|
45
45
|
});
|
|
46
|
+
test("a request exposes the aggregate subscription options", async () => {
|
|
47
|
+
const consumer = new TestConsumer();
|
|
48
|
+
consumer.subscribe("video", { priority: 3, ordered: true, latencyMax: 100, startGroup: 10, endGroup: 20 });
|
|
49
|
+
consumer.subscribe("video", { priority: 7, ordered: true, latencyMax: 250, startGroup: 0, endGroup: 30 });
|
|
50
|
+
const request = await pendingRequest(consumer);
|
|
51
|
+
expect(request?.subscription).toEqual({
|
|
52
|
+
priority: 7,
|
|
53
|
+
ordered: true,
|
|
54
|
+
latencyMax: 250,
|
|
55
|
+
startGroup: 0,
|
|
56
|
+
endGroup: 30,
|
|
57
|
+
});
|
|
58
|
+
expect(request?.priority).toBe(7);
|
|
59
|
+
});
|
|
60
|
+
test("requested selects the highest current priority", async () => {
|
|
61
|
+
const consumer = new TestConsumer();
|
|
62
|
+
const first = consumer.subscribe("first", { priority: 1 });
|
|
63
|
+
consumer.subscribe("second", { priority: 5 });
|
|
64
|
+
const updated = first.subscription.changed();
|
|
65
|
+
first.update({ priority: 9 });
|
|
66
|
+
await updated;
|
|
67
|
+
expect((await consumer.requested())?.name).toBe("first");
|
|
68
|
+
expect((await consumer.requested())?.name).toBe("second");
|
|
69
|
+
});
|
|
46
70
|
test("a consumer clone shares the broadcast until every handle closes", () => {
|
|
47
71
|
const consumer = new TestConsumer();
|
|
48
72
|
const clone = consumer.clone();
|