@moq/net 0.1.9 → 0.2.1

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.
Files changed (259) hide show
  1. package/announced.d.ts +40 -24
  2. package/announced.d.ts.map +1 -1
  3. package/announced.js +74 -40
  4. package/announced.js.map +1 -1
  5. package/announced.test.d.ts +2 -0
  6. package/announced.test.d.ts.map +1 -0
  7. package/announced.test.js +37 -0
  8. package/announced.test.js.map +1 -0
  9. package/broadcast.d.ts +80 -25
  10. package/broadcast.d.ts.map +1 -1
  11. package/broadcast.js +266 -49
  12. package/broadcast.js.map +1 -1
  13. package/broadcast.test.d.ts +2 -0
  14. package/broadcast.test.d.ts.map +1 -0
  15. package/broadcast.test.js +219 -0
  16. package/broadcast.test.js.map +1 -0
  17. package/connection/accept.d.ts +6 -0
  18. package/connection/accept.d.ts.map +1 -1
  19. package/connection/accept.js +30 -10
  20. package/connection/accept.js.map +1 -1
  21. package/connection/browser.d.ts +5 -0
  22. package/connection/browser.d.ts.map +1 -0
  23. package/connection/browser.js +25 -0
  24. package/connection/browser.js.map +1 -0
  25. package/connection/browser.test.d.ts +2 -0
  26. package/connection/browser.test.d.ts.map +1 -0
  27. package/connection/browser.test.js +29 -0
  28. package/connection/browser.test.js.map +1 -0
  29. package/connection/connect.d.ts +43 -1
  30. package/connection/connect.d.ts.map +1 -1
  31. package/connection/connect.js +96 -107
  32. package/connection/connect.js.map +1 -1
  33. package/connection/connect.test.d.ts +2 -0
  34. package/connection/connect.test.d.ts.map +1 -0
  35. package/connection/connect.test.js +118 -0
  36. package/connection/connect.test.js.map +1 -0
  37. package/connection/established.d.ts +29 -15
  38. package/connection/established.d.ts.map +1 -1
  39. package/connection/established.js.map +1 -1
  40. package/connection/index.d.ts +8 -0
  41. package/connection/index.d.ts.map +1 -1
  42. package/connection/index.js +6 -0
  43. package/connection/index.js.map +1 -1
  44. package/connection/reload.d.ts +43 -7
  45. package/connection/reload.d.ts.map +1 -1
  46. package/connection/reload.js +159 -62
  47. package/connection/reload.js.map +1 -1
  48. package/connection/reload.test.js +65 -0
  49. package/connection/reload.test.js.map +1 -1
  50. package/connection/stats.d.ts +92 -0
  51. package/connection/stats.d.ts.map +1 -0
  52. package/connection/stats.js +35 -0
  53. package/connection/stats.js.map +1 -0
  54. package/connection/stats.test.d.ts +2 -0
  55. package/connection/stats.test.d.ts.map +1 -0
  56. package/connection/stats.test.js +120 -0
  57. package/connection/stats.test.js.map +1 -0
  58. package/connection/transport.d.ts +10 -0
  59. package/connection/transport.d.ts.map +1 -0
  60. package/connection/transport.js +12 -0
  61. package/connection/transport.js.map +1 -0
  62. package/consume.d.ts +26 -0
  63. package/consume.d.ts.map +1 -0
  64. package/consume.js +40 -0
  65. package/consume.js.map +1 -0
  66. package/datagram.d.ts +23 -0
  67. package/datagram.d.ts.map +1 -0
  68. package/datagram.js +3 -0
  69. package/datagram.js.map +1 -0
  70. package/error.d.ts +62 -0
  71. package/error.d.ts.map +1 -0
  72. package/error.js +92 -0
  73. package/error.js.map +1 -0
  74. package/error.test.d.ts +2 -0
  75. package/error.test.d.ts.map +1 -0
  76. package/error.test.js +89 -0
  77. package/error.test.js.map +1 -0
  78. package/group.d.ts +125 -36
  79. package/group.d.ts.map +1 -1
  80. package/group.js +244 -67
  81. package/group.js.map +1 -1
  82. package/group.test.js +121 -35
  83. package/group.test.js.map +1 -1
  84. package/ietf/adapter.d.ts +2 -2
  85. package/ietf/adapter.d.ts.map +1 -1
  86. package/ietf/adapter.js +15 -5
  87. package/ietf/adapter.js.map +1 -1
  88. package/ietf/connection.d.ts +19 -6
  89. package/ietf/connection.d.ts.map +1 -1
  90. package/ietf/connection.js +23 -8
  91. package/ietf/connection.js.map +1 -1
  92. package/ietf/ietf.test.js +58 -1
  93. package/ietf/ietf.test.js.map +1 -1
  94. package/ietf/object.d.ts +12 -4
  95. package/ietf/object.d.ts.map +1 -1
  96. package/ietf/object.js +92 -9
  97. package/ietf/object.js.map +1 -1
  98. package/ietf/publisher.d.ts +2 -2
  99. package/ietf/publisher.d.ts.map +1 -1
  100. package/ietf/publisher.js +12 -12
  101. package/ietf/publisher.js.map +1 -1
  102. package/ietf/subscribe_namespace.d.ts +0 -4
  103. package/ietf/subscribe_namespace.d.ts.map +1 -1
  104. package/ietf/subscribe_namespace.js +0 -5
  105. package/ietf/subscribe_namespace.js.map +1 -1
  106. package/ietf/subscriber.d.ts +8 -4
  107. package/ietf/subscriber.d.ts.map +1 -1
  108. package/ietf/subscriber.js +171 -93
  109. package/ietf/subscriber.js.map +1 -1
  110. package/index.d.ts +10 -5
  111. package/index.d.ts.map +1 -1
  112. package/index.js +10 -5
  113. package/index.js.map +1 -1
  114. package/integration.test.js +634 -12
  115. package/integration.test.js.map +1 -1
  116. package/internal.d.ts +14 -0
  117. package/internal.d.ts.map +1 -0
  118. package/internal.js +8 -0
  119. package/internal.js.map +1 -0
  120. package/lite/announce.d.ts +55 -13
  121. package/lite/announce.d.ts.map +1 -1
  122. package/lite/announce.js +221 -68
  123. package/lite/announce.js.map +1 -1
  124. package/lite/announce.test.d.ts +2 -0
  125. package/lite/announce.test.d.ts.map +1 -0
  126. package/lite/announce.test.js +71 -0
  127. package/lite/announce.test.js.map +1 -0
  128. package/lite/connection.d.ts +45 -19
  129. package/lite/connection.d.ts.map +1 -1
  130. package/lite/connection.js +85 -80
  131. package/lite/connection.js.map +1 -1
  132. package/lite/datagram.d.ts +23 -0
  133. package/lite/datagram.d.ts.map +1 -0
  134. package/lite/datagram.js +57 -0
  135. package/lite/datagram.js.map +1 -0
  136. package/lite/datagram.test.d.ts +2 -0
  137. package/lite/datagram.test.d.ts.map +1 -0
  138. package/lite/datagram.test.js +26 -0
  139. package/lite/datagram.test.js.map +1 -0
  140. package/lite/datagram_stream.d.ts +8 -0
  141. package/lite/datagram_stream.d.ts.map +1 -0
  142. package/lite/datagram_stream.js +44 -0
  143. package/lite/datagram_stream.js.map +1 -0
  144. package/lite/datagram_stream.test.d.ts +2 -0
  145. package/lite/datagram_stream.test.d.ts.map +1 -0
  146. package/lite/datagram_stream.test.js +15 -0
  147. package/lite/datagram_stream.test.js.map +1 -0
  148. package/lite/fetch.d.ts.map +1 -1
  149. package/lite/fetch.js +2 -2
  150. package/lite/fetch.js.map +1 -1
  151. package/lite/fetch.test.d.ts +2 -0
  152. package/lite/fetch.test.d.ts.map +1 -0
  153. package/lite/fetch.test.js +41 -0
  154. package/lite/fetch.test.js.map +1 -0
  155. package/lite/index.d.ts +3 -0
  156. package/lite/index.d.ts.map +1 -1
  157. package/lite/index.js +3 -0
  158. package/lite/index.js.map +1 -1
  159. package/lite/publisher.d.ts +13 -6
  160. package/lite/publisher.d.ts.map +1 -1
  161. package/lite/publisher.js +274 -64
  162. package/lite/publisher.js.map +1 -1
  163. package/lite/publisher.test.d.ts +2 -0
  164. package/lite/publisher.test.d.ts.map +1 -0
  165. package/lite/publisher.test.js +65 -0
  166. package/lite/publisher.test.js.map +1 -0
  167. package/lite/setup.d.ts +72 -6
  168. package/lite/setup.d.ts.map +1 -1
  169. package/lite/setup.js +184 -31
  170. package/lite/setup.js.map +1 -1
  171. package/lite/setup.test.d.ts +2 -0
  172. package/lite/setup.test.d.ts.map +1 -0
  173. package/lite/setup.test.js +122 -0
  174. package/lite/setup.test.js.map +1 -0
  175. package/lite/stream.d.ts +12 -3
  176. package/lite/stream.d.ts.map +1 -1
  177. package/lite/stream.js +7 -4
  178. package/lite/stream.js.map +1 -1
  179. package/lite/subscribe.d.ts +37 -23
  180. package/lite/subscribe.d.ts.map +1 -1
  181. package/lite/subscribe.js +70 -55
  182. package/lite/subscribe.js.map +1 -1
  183. package/lite/subscribe.test.d.ts +2 -0
  184. package/lite/subscribe.test.d.ts.map +1 -0
  185. package/lite/subscribe.test.js +68 -0
  186. package/lite/subscribe.test.js.map +1 -0
  187. package/lite/subscriber.d.ts +24 -17
  188. package/lite/subscriber.d.ts.map +1 -1
  189. package/lite/subscriber.js +515 -90
  190. package/lite/subscriber.js.map +1 -1
  191. package/lite/subscriber.test.js +2 -2
  192. package/lite/subscriber.test.js.map +1 -1
  193. package/lite/track.d.ts +25 -13
  194. package/lite/track.d.ts.map +1 -1
  195. package/lite/track.js +60 -35
  196. package/lite/track.js.map +1 -1
  197. package/lite/track.test.js +12 -10
  198. package/lite/track.test.js.map +1 -1
  199. package/lite/version.d.ts +17 -4
  200. package/lite/version.d.ts.map +1 -1
  201. package/lite/version.js +88 -17
  202. package/lite/version.js.map +1 -1
  203. package/mock.d.ts +42 -3
  204. package/mock.d.ts.map +1 -1
  205. package/mock.js +88 -17
  206. package/mock.js.map +1 -1
  207. package/package.json +3 -3
  208. package/path.d.ts +30 -0
  209. package/path.d.ts.map +1 -1
  210. package/path.js +49 -0
  211. package/path.js.map +1 -1
  212. package/path.test.js +41 -0
  213. package/path.test.js.map +1 -1
  214. package/stream.d.ts.map +1 -1
  215. package/stream.js +25 -4
  216. package/stream.js.map +1 -1
  217. package/stream.test.js +42 -0
  218. package/stream.test.js.map +1 -1
  219. package/time.d.ts +109 -86
  220. package/time.d.ts.map +1 -1
  221. package/time.js +80 -30
  222. package/time.js.map +1 -1
  223. package/time.test.d.ts +2 -0
  224. package/time.test.d.ts.map +1 -0
  225. package/time.test.js +12 -0
  226. package/time.test.js.map +1 -0
  227. package/track.d.ts +225 -45
  228. package/track.d.ts.map +1 -1
  229. package/track.js +505 -93
  230. package/track.js.map +1 -1
  231. package/track.test.js +138 -29
  232. package/track.test.js.map +1 -1
  233. package/util/timeout.d.ts +5 -0
  234. package/util/timeout.d.ts.map +1 -0
  235. package/util/timeout.js +18 -0
  236. package/util/timeout.js.map +1 -0
  237. package/util/timeout.test.d.ts +2 -0
  238. package/util/timeout.test.d.ts.map +1 -0
  239. package/util/timeout.test.js +18 -0
  240. package/util/timeout.test.js.map +1 -0
  241. package/varint.d.ts +6 -0
  242. package/varint.d.ts.map +1 -1
  243. package/varint.js +6 -2
  244. package/varint.js.map +1 -1
  245. package/zod.d.ts +4 -4
  246. package/zod.d.ts.map +1 -1
  247. package/zod.js.map +1 -1
  248. package/bandwidth.d.ts +0 -11
  249. package/bandwidth.d.ts.map +0 -1
  250. package/bandwidth.js +0 -7
  251. package/bandwidth.js.map +0 -1
  252. package/util/error.d.ts +0 -3
  253. package/util/error.d.ts.map +0 -1
  254. package/util/error.js +0 -9
  255. package/util/error.js.map +0 -1
  256. package/util/index.d.ts +0 -2
  257. package/util/index.d.ts.map +0 -1
  258. package/util/index.js +0 -3
  259. package/util/index.js.map +0 -1
package/track.js CHANGED
@@ -1,69 +1,394 @@
1
1
  /* @ts-self-types="./track.d.ts" */
2
- import { Signal } from "@moq/signals";
3
- import { Group } from "./group.js";
4
- /** Reactive backing state for a {@link Track}: buffered groups, a closed flag, and the subscription priority. */
5
- export class TrackState {
2
+ /**
3
+ * Track role handles: a live stream of groups (and best-effort datagrams) within a broadcast.
4
+ *
5
+ * @module
6
+ */
7
+ import { Once, Signal } from "@moq/signals";
8
+ import { Producer as GroupProducer, Lagged } from "./group.js";
9
+ import { hooks } from "./internal.js";
10
+ import { Timescale } from "./time.js";
11
+ /** Default {@link Info.latencyMax} window (milliseconds) when the publisher does not set one. */
12
+ export const DEFAULT_LATENCY_MAX_MS = 5000;
13
+ /**
14
+ * How long (milliseconds) a datagram stays in the per-subscriber buffer before it is dropped.
15
+ *
16
+ * Datagrams are a best-effort send buffer, not a replay cache (unlike groups): only the last few
17
+ * tens of milliseconds are kept, so a consumer that stalls loses stale datagrams instead of
18
+ * replaying them. Mirrors the Rust `MAX_DATAGRAM_AGE`.
19
+ */
20
+ const MAX_DATAGRAM_AGE_MS = 50;
21
+ /**
22
+ * Sanity cap on a datagram payload: the QUIC DATAGRAM frame ceiling. The real limit is
23
+ * per-hop (the negotiated transport datagram size minus a small header) and oversize
24
+ * datagrams are dropped there; a payload above this cap could never fit anywhere.
25
+ */
26
+ const MAX_DATAGRAM_BYTES = 65535;
27
+ /** Fill in any unset {@link Info} fields with their defaults. */
28
+ export function infoDefaults(info = {}) {
29
+ return {
30
+ timescale: info.timescale ?? Timescale.MILLI,
31
+ latencyMax: info.latencyMax ?? DEFAULT_LATENCY_MAX_MS,
32
+ priority: info.priority ?? 0,
33
+ ordered: info.ordered ?? false,
34
+ };
35
+ }
36
+ /**
37
+ * A request for a track the peer wants, yielded by `Broadcast.Producer.requested`.
38
+ *
39
+ * Created internally by the broadcast when a subscription (or info lookup) needs a track
40
+ * served; answer it with {@link accept} or {@link reject}.
41
+ *
42
+ * @public
43
+ */
44
+ export class Request {
45
+ /** The requested track name. */
46
+ name;
47
+ /** The subscriber's priority for this track. */
48
+ priority;
49
+ #producer;
50
+ constructor(name, producer, priority) {
51
+ this.name = name;
52
+ this.#producer = producer;
53
+ this.priority = priority;
54
+ }
55
+ static {
56
+ hooks.makeRequest = (name, producer, priority) => new Request(name, producer, priority);
57
+ }
58
+ /** Accept the request, committing the track's immutable {@link Info}. */
59
+ accept(info = {}) {
60
+ return this.#producer.accept(info);
61
+ }
62
+ /** Reject the request, closing the track optionally with an error. */
63
+ reject(err) {
64
+ this.#producer.close(err);
65
+ }
66
+ }
67
+ /**
68
+ * A lazy handle to a track on a consumed broadcast.
69
+ *
70
+ * @public
71
+ */
72
+ export class Consumer {
73
+ /** The track name. */
74
+ name;
75
+ #broadcast;
76
+ constructor(name, broadcast) {
77
+ this.name = name;
78
+ this.#broadcast = broadcast;
79
+ }
80
+ /** Open a live subscription to the track. */
81
+ subscribe(options) {
82
+ return this.#broadcast.subscribe(this.name, options);
83
+ }
84
+ /** Fetch the track's immutable publisher properties without subscribing. */
85
+ info() {
86
+ return this.#broadcast.resolveTrackInfo(this.name);
87
+ }
88
+ /** Fetch a single group by sequence without holding a live subscription. */
89
+ fetchGroup(sequence, options) {
90
+ return this.#broadcast.fetchGroup(this.name, sequence, options);
91
+ }
92
+ }
93
+ // The shared state behind a Producer / Subscriber pair. Package-internal
94
+ // wiring, unexported so it never appears in the published type declarations.
95
+ class TrackState {
6
96
  groups = new Signal([]);
7
- closed = new Signal(false);
8
- priority = new Signal(undefined);
97
+ /** Best-effort datagram channel, parallel to {@link groups}; an age-evicted send buffer per subscriber. */
98
+ datagrams = new Signal([]);
99
+ closed = new Once();
100
+ update = new Signal(undefined);
101
+ /** Resolved once the producer commits the immutable properties. */
102
+ info = new Signal(undefined);
9
103
  }
10
- /** A live stream of groups within a broadcast, identified by name. */
11
- export class Track {
12
- /** Name of this track within its broadcast. */
104
+ // Settle a track state's closed Once. Idempotent: Once.set throws on a second settle, and a
105
+ // Producer closing its sinks races the Subscriber closing itself (the sink is only removed from
106
+ // #sinks a microtask later, via the closed subscription below).
107
+ function closeTrackState(state, abort) {
108
+ if (state.closed.peek() !== undefined)
109
+ return false;
110
+ state.closed.set(abort ?? null);
111
+ return true;
112
+ }
113
+ // Resolve the track's immutable publisher properties, or reject if it closes first.
114
+ // On a producer this resolves once info is committed (at accept time); on a consumer
115
+ // once the wire layer commits the TRACK_INFO it received (lite-05+) or defaults (older
116
+ // drafts), so awaiting it never yields a placeholder.
117
+ async function resolveInfo(state) {
118
+ for (;;) {
119
+ const info = state.info.peek();
120
+ if (info)
121
+ return info;
122
+ const closed = state.closed.peek();
123
+ if (closed instanceof Error)
124
+ throw closed;
125
+ if (closed !== undefined)
126
+ throw new Error("track closed before info was known");
127
+ await Signal.race(state.info, state.closed);
128
+ }
129
+ }
130
+ // Constructs a Subscriber from within this module without exposing a public
131
+ // constructor that would leak the unexported TrackState. Assigned in the class's
132
+ // static block.
133
+ let makeSubscriber;
134
+ /**
135
+ * The write side of a track, mirroring the Rust `Producer`.
136
+ *
137
+ * A producer is a fan-out source: every {@link subscribe} (including each wire
138
+ * subscription the publisher serves from it) gets an independent
139
+ * {@link Subscriber} that receives a full copy of the groups, each with its own
140
+ * read cursor. Groups are mirrored into every live subscriber and retained for the
141
+ * track's `latencyMax` window so a late subscriber replays the recent groups.
142
+ *
143
+ * Obtained from {@link Request.accept} (the wire asks the application for a track to
144
+ * serve) or constructed directly for an in-process track.
145
+ */
146
+ export class Producer {
147
+ /** The track name. */
13
148
  name;
14
- /** Reactive backing state. */
15
- state = new TrackState();
149
+ // The producer's own state is the source of truth (info/closed); subscribers
150
+ // read mirrored sinks, never this state directly.
151
+ #state = new TrackState();
16
152
  #next;
17
- #nextSequence = 0;
18
- /** Resolves with the abort error (or undefined) once closed. */
19
- closed;
153
+ // Recently written source groups, retained for replay to late subscribers and
154
+ // pruned once closed and older than the cache window. Each entry tracks the mirror
155
+ // it handed to every sink so eviction can drop them too: otherwise a slow consumer
156
+ // that never reads would pin old groups (and their frame bytes) forever.
157
+ #cache = [];
158
+ // One independent downstream state per live subscriber.
159
+ #sinks = new Set();
160
+ // Whether any subscriber is currently attached. Exposed as {@link used}; the consumer wire
161
+ // watches it to tear down an idle upstream, and a publisher can watch it for on-demand capture.
162
+ #used = new Signal(false);
20
163
  constructor(name) {
21
164
  this.name = name;
22
- this.closed = new Promise((resolve) => {
23
- const dispose = this.state.closed.subscribe((closed) => {
24
- if (!closed)
165
+ }
166
+ /**
167
+ * Resolve this track's immutable publisher properties, committed at accept time.
168
+ * Rejects if the track is closed before the properties are known.
169
+ */
170
+ info() {
171
+ return resolveInfo(this.#state);
172
+ }
173
+ /**
174
+ * Settles once the track closes: `null` on a clean close, or the abort {@link Error}.
175
+ * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
176
+ */
177
+ get closed() {
178
+ return this.#state.closed;
179
+ }
180
+ /**
181
+ * The current subscription, or `undefined` until a subscriber first calls
182
+ * {@link Subscriber.update}. The wire layer watches this to emit SUBSCRIBE_UPDATE.
183
+ */
184
+ get subscription() {
185
+ return this.#state.update;
186
+ }
187
+ /** Commit the immutable publisher properties, resolving {@link info}. Returns `this`. */
188
+ accept(info = {}) {
189
+ const resolved = infoDefaults(info);
190
+ this.#state.info.set(resolved);
191
+ // Propagate to any sink handed out before accept (the on-demand path).
192
+ for (const sink of this.#sinks)
193
+ sink.info.set(resolved);
194
+ return this;
195
+ }
196
+ /** An independent {@link Subscriber} receiving a full copy of this track's groups. */
197
+ subscribe() {
198
+ const sink = new TrackState();
199
+ this.#addSink(sink);
200
+ return makeSubscriber(this.name, sink);
201
+ }
202
+ /**
203
+ * Whether the track currently has any subscribers.
204
+ *
205
+ * Watch it (`effect.get` / `.peek()`) to drive on-demand work: a publisher can start and stop
206
+ * capture with demand, and the consumer wire watches it to tear an idle upstream subscription
207
+ * down instead of downloading to nobody. Pairs with {@link unused}. Mirrors the Rust `Demand`.
208
+ */
209
+ get used() {
210
+ return this.#used;
211
+ }
212
+ /** Resolves once the track has no subscribers (or has closed). Await it to react to demand ending. */
213
+ async unused() {
214
+ while (this.#used.peek() && this.#state.closed.peek() === undefined) {
215
+ await Signal.race(this.#used, this.#state.closed);
216
+ }
217
+ }
218
+ // Register a downstream sink: seed its info, replay the retained window, and (while
219
+ // the track is open) mirror future groups into it. A late subscriber to a closed
220
+ // track still drains the buffered groups before seeing the end.
221
+ #addSink(sink) {
222
+ const info = this.#state.info.peek();
223
+ if (info)
224
+ sink.info.set(info);
225
+ const closed = this.#state.closed.peek();
226
+ if (closed === undefined) {
227
+ this.#sinks.add(sink);
228
+ this.#used.set(true);
229
+ // Forward subscription updates from the sink's Subscriber to the producer's own
230
+ // state, which the wire layer (or the serving application) watches.
231
+ const forward = sink.update.subscribe((update) => {
232
+ if (update)
233
+ this.#state.update.set(update, true);
234
+ });
235
+ // Drop the sink once its consumer goes away, closing its mirrors so source
236
+ // groups stop teeing into them, so a long-lived producer doesn't leak. This
237
+ // covers mirrors already handed out via recvGroup (no longer in sink.groups)
238
+ // by closing them through the cache's per-sink tracking.
239
+ const dispose = sink.closed.subscribe((c) => {
240
+ if (c === undefined)
25
241
  return;
26
- resolve(closed instanceof Error ? closed : undefined);
242
+ const abort = c instanceof Error ? c : undefined;
243
+ forward();
244
+ this.#sinks.delete(sink);
245
+ for (const entry of this.#cache) {
246
+ const mirror = entry.mirrors.get(sink);
247
+ if (mirror) {
248
+ mirror.close(abort);
249
+ entry.mirrors.delete(sink);
250
+ }
251
+ }
252
+ for (const group of sink.groups.peek())
253
+ group.close(abort);
27
254
  dispose();
255
+ // Update demand: once the last subscriber leaves, the consumer wire (watching
256
+ // {@link unused}) tears the upstream down instead of downloading to nobody.
257
+ this.#used.set(this.#sinks.size > 0);
28
258
  });
259
+ }
260
+ this.#prune();
261
+ for (const entry of this.#cache)
262
+ this.#mirror(entry, sink);
263
+ if (closed !== undefined)
264
+ closeTrackState(sink, closed instanceof Error ? closed : undefined);
265
+ }
266
+ // Mirror a cached source group into a sink. The mirror fills synchronously as the
267
+ // source is written and keeps its own read cursor; frame bytes are shared by
268
+ // reference. Tracked on the entry so eviction can drop it from the sink.
269
+ #mirror(entry, sink) {
270
+ const dst = entry.group.mirror();
271
+ entry.mirrors.set(sink, dst);
272
+ sink.groups.mutate((groups) => {
273
+ groups.push(dst);
274
+ groups.sort((a, b) => a.sequence - b.sequence);
29
275
  });
30
276
  }
31
- /**
32
- * Appends a new group to the track.
33
- * @returns A GroupProducer for the new group
34
- */
277
+ // Evict cached groups that are closed and older than the cache window, dropping
278
+ // each evicted group's mirror from every sink so no consumer can pin it.
279
+ #prune() {
280
+ const latencyMaxMs = this.#state.info.peek()?.latencyMax ?? DEFAULT_LATENCY_MAX_MS;
281
+ const cutoff = Date.now() - latencyMaxMs;
282
+ const retained = [];
283
+ for (const entry of this.#cache) {
284
+ if (entry.time > cutoff || entry.group.closed.peek() === undefined) {
285
+ retained.push(entry);
286
+ continue;
287
+ }
288
+ for (const [sink, mirror] of entry.mirrors) {
289
+ sink.groups.mutate((groups) => {
290
+ const i = groups.indexOf(mirror);
291
+ if (i >= 0)
292
+ groups.splice(i, 1);
293
+ });
294
+ mirror.close();
295
+ }
296
+ entry.mirrors.clear();
297
+ }
298
+ this.#cache = retained;
299
+ }
300
+ // Retain a source group and fan it out to every live sink.
301
+ #publish(group) {
302
+ const entry = { group, time: Date.now(), mirrors: new Map() };
303
+ this.#cache.push(entry);
304
+ this.#prune();
305
+ for (const sink of this.#sinks)
306
+ this.#mirror(entry, sink);
307
+ }
308
+ /** Append a new group with the next sequence number. */
35
309
  appendGroup() {
36
- if (this.state.closed.peek())
310
+ if (this.#state.closed.peek() !== undefined)
37
311
  throw new Error("track is closed");
38
- const group = new Group(this.#next ?? 0);
312
+ const group = new GroupProducer(this.#next ?? 0);
39
313
  this.#next = group.sequence + 1;
40
- this.state.groups.mutate((groups) => {
41
- groups.push(group);
42
- groups.sort((a, b) => a.sequence - b.sequence);
43
- });
314
+ this.#publish(group);
44
315
  return group;
45
316
  }
46
- /**
47
- * Inserts an existing group into the track.
48
- * @param group - The group to insert
49
- */
317
+ /** Insert an existing group into the track. */
50
318
  writeGroup(group) {
51
- if (this.state.closed.peek())
319
+ if (this.#state.closed.peek() !== undefined)
52
320
  throw new Error("track is closed");
53
321
  // Only advance #next upward (for appendGroup auto-increment).
54
322
  if (group.sequence >= (this.#next ?? 0)) {
55
323
  this.#next = group.sequence + 1;
56
324
  }
57
- this.state.groups.mutate((groups) => {
58
- groups.push(group);
59
- groups.sort((a, b) => a.sequence - b.sequence);
60
- });
325
+ this.#publish(group);
326
+ }
327
+ // Fan a datagram out to every live subscriber, dropping the oldest once the ring is full.
328
+ // Late subscribers do NOT replay old datagrams (best-effort, unlike the group cache).
329
+ #publishDatagram(datagram) {
330
+ const now = performance.now();
331
+ for (const sink of this.#sinks) {
332
+ sink.datagrams.mutate((list) => {
333
+ list.push({ datagram, time: now });
334
+ // Drop anything older than the send-buffer window.
335
+ while (list.length > 0 && now - list[0].time > MAX_DATAGRAM_AGE_MS)
336
+ list.shift();
337
+ });
338
+ }
339
+ }
340
+ /**
341
+ * Append a datagram with the next sequence number, returning the assigned sequence.
342
+ *
343
+ * A datagram is delivered best-effort over a single QUIC datagram, parallel to the track's
344
+ * groups but drawing from the same sequence namespace (interleaving with {@link appendGroup}
345
+ * never reuses a number). The payload must fit the negotiated transport datagram size minus
346
+ * a small header; an oversize payload is dropped at each hop (there is no group fallback), so
347
+ * keep datagram payloads small (e.g. a single audio frame). Datagrams are never delivered
348
+ * over IETF moq-transport or stream-only transports (the WebSocket fallback). A payload over
349
+ * 65535 bytes (the QUIC datagram frame ceiling) throws. An origin publisher uses this; a
350
+ * relay preserving upstream numbering uses {@link writeDatagram}.
351
+ */
352
+ appendDatagram(timestamp, payload) {
353
+ if (this.#state.closed.peek() !== undefined)
354
+ throw new Error("track is closed");
355
+ if (payload.byteLength > MAX_DATAGRAM_BYTES)
356
+ throw new Error("datagram payload too large");
357
+ const sequence = this.#next ?? 0;
358
+ this.#next = sequence + 1;
359
+ this.#publishDatagram({ sequence, timestamp, payload });
360
+ return sequence;
61
361
  }
62
362
  /**
63
- * Appends a frame to the track in its own group.
363
+ * Write a datagram with an explicit sequence number.
64
364
  *
65
- * @param frame - The frame to append
365
+ * Preserves the supplied sequence (advancing the shared counter if needed) so a relay can
366
+ * forward a datagram without renumbering it. The size limits of {@link appendDatagram}
367
+ * apply. Most origin publishers want {@link appendDatagram} instead.
66
368
  */
369
+ writeDatagram(datagram) {
370
+ if (this.#state.closed.peek() !== undefined)
371
+ throw new Error("track is closed");
372
+ if (datagram.payload.byteLength > MAX_DATAGRAM_BYTES)
373
+ throw new Error("datagram payload too large");
374
+ if (datagram.sequence >= (this.#next ?? 0)) {
375
+ this.#next = datagram.sequence + 1;
376
+ }
377
+ this.#publishDatagram(datagram);
378
+ }
379
+ /** Close the track and every subscriber, mirroring the abort to their groups. Idempotent. */
380
+ close(abort) {
381
+ closeTrackState(this.#state, abort);
382
+ for (const { group } of this.#cache)
383
+ group.close(abort);
384
+ for (const sink of this.#sinks) {
385
+ for (const group of sink.groups.peek())
386
+ group.close(abort);
387
+ closeTrackState(sink, abort);
388
+ }
389
+ this.#sinks.clear();
390
+ }
391
+ /** Append a frame as its own single-frame group. */
67
392
  writeFrame(frame) {
68
393
  const group = this.appendGroup();
69
394
  group.writeFrame(frame);
@@ -87,41 +412,111 @@ export class Track {
87
412
  group.writeBool(bool);
88
413
  group.close();
89
414
  }
415
+ }
416
+ /**
417
+ * The read side of a live track subscription, mirroring the Rust `Subscriber`.
418
+ *
419
+ * Obtained from `Broadcast.Consumer.subscribe` / `Track.Consumer.subscribe`, or from
420
+ * {@link Producer.subscribe} for an in-process track. Reads the groups a
421
+ * {@link Producer} on the same underlying state writes.
422
+ */
423
+ export class Subscriber {
424
+ /** The track name. */
425
+ name;
426
+ #state;
427
+ #nextSequence = 0;
428
+ constructor(name, state) {
429
+ this.name = name;
430
+ this.#state = state;
431
+ }
432
+ static {
433
+ makeSubscriber = (name, state) => new Subscriber(name, state);
434
+ }
435
+ /**
436
+ * Resolve this track's immutable publisher properties.
437
+ *
438
+ * Resolves once the wire layer commits the TRACK_INFO it received (lite-05+) or
439
+ * defaults (older drafts), so awaiting it never yields a placeholder. Rejects if
440
+ * the track is closed before the properties are known (e.g. a rejected subscription).
441
+ */
442
+ info() {
443
+ return resolveInfo(this.#state);
444
+ }
445
+ /** Settles once the track closes; see {@link Producer.closed}. */
446
+ get closed() {
447
+ return this.#state.closed;
448
+ }
449
+ /** The last {@link update} requested on this subscriber, or `undefined` if none yet. */
450
+ get subscription() {
451
+ return this.#state.update;
452
+ }
453
+ /** Close the track (optionally with an error), closing any pending groups. Idempotent. */
454
+ close(abort) {
455
+ if (!closeTrackState(this.#state, abort))
456
+ return;
457
+ for (const group of this.#state.groups.peek()) {
458
+ group.close(abort);
459
+ }
460
+ }
90
461
  /**
91
462
  * Receive the next group available on this track, in arrival order.
92
463
  *
93
464
  * Groups may arrive out of order or with gaps due to network conditions.
94
- * Use {@link nextGroupOrdered} if you need groups in sequence order,
95
- * skipping those that arrive too late.
465
+ * Use {@link nextGroup} for sequence order, skipping those that arrive too late.
96
466
  */
97
467
  async recvGroup() {
98
468
  for (;;) {
99
- const groups = this.state.groups.peek();
469
+ const groups = this.#state.groups.peek();
100
470
  if (groups.length > 0) {
101
471
  return groups.shift();
102
472
  }
103
- const closed = this.state.closed.peek();
473
+ const closed = this.#state.closed.peek();
104
474
  if (closed instanceof Error)
105
475
  throw closed;
106
- if (closed)
476
+ if (closed !== undefined)
107
477
  return undefined;
108
- await Signal.race(this.state.groups, this.state.closed);
478
+ await Signal.race(this.#state.groups, this.#state.closed);
109
479
  }
110
480
  }
111
481
  /**
112
- * @deprecated Use {@link recvGroup} for arrival order, or {@link nextGroupOrdered} for sequence order.
482
+ * Receive the next datagram in arrival order.
483
+ *
484
+ * Datagrams are a separate best-effort channel from groups (see
485
+ * {@link Producer.appendDatagram}); they share only the sequence namespace. A consumer
486
+ * that falls too far behind silently loses the oldest datagrams. Read this alongside
487
+ * {@link recvGroup} (e.g. in a separate loop) to receive both channels concurrently. Returning
488
+ * a datagram advances {@link nextGroup} past that sequence.
113
489
  */
114
- async nextGroup() {
115
- return this.recvGroup();
490
+ async recvDatagram() {
491
+ for (;;) {
492
+ const datagrams = this.#state.datagrams.peek();
493
+ // Evict datagrams older than the send-buffer window (also enforced on write), so a
494
+ // reader that stalled skips stale datagrams instead of replaying them.
495
+ const cutoff = performance.now() - MAX_DATAGRAM_AGE_MS;
496
+ while (datagrams.length > 0 && datagrams[0].time < cutoff)
497
+ datagrams.shift();
498
+ if (datagrams.length > 0) {
499
+ const datagram = datagrams.shift()?.datagram;
500
+ if (datagram) {
501
+ this.#nextSequence = Math.max(this.#nextSequence, datagram.sequence + 1);
502
+ }
503
+ return datagram;
504
+ }
505
+ const closed = this.#state.closed.peek();
506
+ if (closed instanceof Error)
507
+ throw closed;
508
+ if (closed !== undefined)
509
+ return undefined;
510
+ await Signal.race(this.#state.datagrams, this.#state.closed);
511
+ }
116
512
  }
117
513
  /**
118
514
  * Return the next group with a strictly-greater sequence number than the last returned.
119
515
  *
120
- * Late arrivals (with a sequence number at or below the last one returned) are silently skipped.
121
- *
122
- * NOTE: This will be renamed to `nextGroup` in the next major version.
516
+ * Late arrivals (sequence at or below the last returned) are silently skipped.
517
+ * Use {@link recvGroup} to see every group in arrival order instead.
123
518
  */
124
- async nextGroupOrdered() {
519
+ async nextGroup() {
125
520
  for (;;) {
126
521
  const group = await this.recvGroup();
127
522
  if (!group)
@@ -134,54 +529,79 @@ export class Track {
134
529
  return group;
135
530
  }
136
531
  }
137
- /** Reads the next frame across all groups, discarding older groups. */
532
+ /**
533
+ * Reads the next frame across all groups, discarding older groups.
534
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
535
+ */
138
536
  async readFrame() {
139
- return (await this.readFrameSequence())?.data;
537
+ const next = await this.readFrameSequence();
538
+ return next ? { payload: next.payload, timestamp: next.timestamp } : undefined;
140
539
  }
141
- /** Reads the next frame along with its group and frame sequence numbers. */
540
+ /**
541
+ * Reads the next frame along with its group and frame sequence numbers.
542
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
543
+ */
142
544
  async readFrameSequence() {
143
545
  for (;;) {
144
- const groups = this.state.groups.peek();
145
- // Discard old groups.
546
+ const groups = this.#state.groups.peek();
547
+ // Drain older groups first, dropping each once empty.
146
548
  while (groups.length > 1) {
549
+ if (groups[0].skipped) {
550
+ // The reader fell behind this group's eviction window. Drop it and
551
+ // signal the gap; the next read resyncs from the following group.
552
+ groups.shift()?.close();
553
+ throw new Lagged();
554
+ }
147
555
  const next = groups[0].tryReadFrameSequence();
148
556
  if (next) {
149
- return { group: groups[0].sequence, frame: next.sequence, data: next.data };
557
+ return {
558
+ group: groups[0].sequence,
559
+ frame: next.sequence,
560
+ payload: next.payload,
561
+ timestamp: next.timestamp,
562
+ };
150
563
  }
151
- // Skip this old group
152
564
  groups.shift()?.close();
153
565
  }
154
- // If there's no groups, wait for a new one.
155
566
  if (groups.length === 0) {
156
- const closed = this.state.closed.peek();
567
+ const closed = this.#state.closed.peek();
157
568
  if (closed instanceof Error)
158
569
  throw closed;
159
- if (closed)
570
+ if (closed !== undefined)
160
571
  return undefined;
161
- await Signal.race(this.state.groups, this.state.closed);
572
+ await Signal.race(this.#state.groups, this.#state.closed);
162
573
  continue;
163
574
  }
164
- // If there's a group, wait for a frame.
165
575
  const group = groups[0];
166
- const next = group.tryReadFrameSequence();
167
- if (next) {
168
- return { group: group.sequence, frame: next.sequence, data: next.data };
576
+ if (group.skipped) {
577
+ // Fell behind this group's eviction window. Drop it and signal the gap;
578
+ // the next read resyncs from the following group.
579
+ groups.shift()?.close();
580
+ throw new Lagged();
169
581
  }
170
- // If the track is closed, return undefined.
171
- const closed = this.state.closed.peek();
582
+ const next = group.tryReadFrameSequence();
583
+ if (next)
584
+ return {
585
+ group: group.sequence,
586
+ frame: next.sequence,
587
+ payload: next.payload,
588
+ timestamp: next.timestamp,
589
+ };
590
+ const closed = this.#state.closed.peek();
172
591
  if (closed instanceof Error)
173
592
  throw closed;
174
- if (closed)
593
+ if (closed !== undefined)
175
594
  return undefined;
176
- // Wake on a new group or the track closing. Only fold in the current group's readability
177
- // while it can still deliver frames: a finished group's readable() resolves immediately, so
178
- // racing it would busy-loop until a newer group arrives instead of waiting.
595
+ // A finished (drained + closed) group has nothing left: drop it and loop, rather than
596
+ // busy-waiting on its already-resolved readable() (which would livelock and starve the
597
+ // macrotask that delivers the next group).
179
598
  if (group.done) {
180
- await Signal.race(this.state.groups, this.state.closed);
181
- }
182
- else {
183
- await Promise.race([Signal.race(this.state.groups, this.state.closed), group.readable()]);
599
+ groups.shift()?.close();
600
+ continue;
184
601
  }
602
+ // Lone open group with nothing buffered yet: wait for a frame on it, a new group, or
603
+ // the track closing.
604
+ await Promise.race([Signal.race(this.#state.groups, this.#state.closed), group.readable()]);
185
605
  }
186
606
  }
187
607
  /** Reads the next frame and decodes it as a UTF-8 string. */
@@ -189,7 +609,7 @@ export class Track {
189
609
  const next = await this.readFrame();
190
610
  if (!next)
191
611
  return undefined;
192
- return new TextDecoder().decode(next);
612
+ return new TextDecoder().decode(next.payload);
193
613
  }
194
614
  /** Reads the next frame and parses it as JSON. */
195
615
  async readJson() {
@@ -203,25 +623,17 @@ export class Track {
203
623
  const next = await this.readFrame();
204
624
  if (!next)
205
625
  return undefined;
206
- if (next.byteLength !== 1 || !(next[0] === 0 || next[0] === 1))
626
+ const payload = next.payload;
627
+ if (payload.byteLength !== 1 || !(payload[0] === 0 || payload[0] === 1))
207
628
  throw new Error("invalid bool frame");
208
- return next[0] === 1;
209
- }
210
- /**
211
- * Update the subscription priority. Triggers a SUBSCRIBE_UPDATE
212
- * to the publisher when used on a subscribed track.
213
- */
214
- updatePriority(priority) {
215
- this.state.priority.set(priority, true);
629
+ return payload[0] === 1;
216
630
  }
217
631
  /**
218
- * Closes the publisher and all associated groups.
632
+ * Update this subscription's options (e.g. priority), triggering a SUBSCRIBE_UPDATE to the
633
+ * publisher. Mirrors the Rust `Subscriber::update`.
219
634
  */
220
- close(abort) {
221
- this.state.closed.set(abort ?? true);
222
- for (const group of this.state.groups.peek()) {
223
- group.close(abort);
224
- }
635
+ update(options) {
636
+ this.#state.update.set(options, true);
225
637
  }
226
638
  }
227
639
  //# sourceMappingURL=track.js.map