@moq/net 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) 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/group.d.ts +125 -36
  71. package/group.d.ts.map +1 -1
  72. package/group.js +244 -67
  73. package/group.js.map +1 -1
  74. package/group.test.js +121 -35
  75. package/group.test.js.map +1 -1
  76. package/ietf/adapter.d.ts +2 -2
  77. package/ietf/adapter.d.ts.map +1 -1
  78. package/ietf/adapter.js +15 -5
  79. package/ietf/adapter.js.map +1 -1
  80. package/ietf/connection.d.ts +19 -6
  81. package/ietf/connection.d.ts.map +1 -1
  82. package/ietf/connection.js +23 -8
  83. package/ietf/connection.js.map +1 -1
  84. package/ietf/ietf.test.js +58 -1
  85. package/ietf/ietf.test.js.map +1 -1
  86. package/ietf/object.d.ts +12 -4
  87. package/ietf/object.d.ts.map +1 -1
  88. package/ietf/object.js +92 -9
  89. package/ietf/object.js.map +1 -1
  90. package/ietf/publisher.d.ts +2 -2
  91. package/ietf/publisher.d.ts.map +1 -1
  92. package/ietf/publisher.js +12 -12
  93. package/ietf/publisher.js.map +1 -1
  94. package/ietf/subscribe_namespace.d.ts +0 -4
  95. package/ietf/subscribe_namespace.d.ts.map +1 -1
  96. package/ietf/subscribe_namespace.js +0 -5
  97. package/ietf/subscribe_namespace.js.map +1 -1
  98. package/ietf/subscriber.d.ts +8 -4
  99. package/ietf/subscriber.d.ts.map +1 -1
  100. package/ietf/subscriber.js +171 -93
  101. package/ietf/subscriber.js.map +1 -1
  102. package/index.d.ts +8 -5
  103. package/index.d.ts.map +1 -1
  104. package/index.js +8 -5
  105. package/index.js.map +1 -1
  106. package/integration.test.js +598 -12
  107. package/integration.test.js.map +1 -1
  108. package/internal.d.ts +14 -0
  109. package/internal.d.ts.map +1 -0
  110. package/internal.js +8 -0
  111. package/internal.js.map +1 -0
  112. package/lite/announce.d.ts +55 -13
  113. package/lite/announce.d.ts.map +1 -1
  114. package/lite/announce.js +221 -68
  115. package/lite/announce.js.map +1 -1
  116. package/lite/announce.test.d.ts +2 -0
  117. package/lite/announce.test.d.ts.map +1 -0
  118. package/lite/announce.test.js +71 -0
  119. package/lite/announce.test.js.map +1 -0
  120. package/lite/connection.d.ts +45 -19
  121. package/lite/connection.d.ts.map +1 -1
  122. package/lite/connection.js +85 -80
  123. package/lite/connection.js.map +1 -1
  124. package/lite/datagram.d.ts +23 -0
  125. package/lite/datagram.d.ts.map +1 -0
  126. package/lite/datagram.js +57 -0
  127. package/lite/datagram.js.map +1 -0
  128. package/lite/datagram.test.d.ts +2 -0
  129. package/lite/datagram.test.d.ts.map +1 -0
  130. package/lite/datagram.test.js +26 -0
  131. package/lite/datagram.test.js.map +1 -0
  132. package/lite/datagram_stream.d.ts +8 -0
  133. package/lite/datagram_stream.d.ts.map +1 -0
  134. package/lite/datagram_stream.js +44 -0
  135. package/lite/datagram_stream.js.map +1 -0
  136. package/lite/datagram_stream.test.d.ts +2 -0
  137. package/lite/datagram_stream.test.d.ts.map +1 -0
  138. package/lite/datagram_stream.test.js +15 -0
  139. package/lite/datagram_stream.test.js.map +1 -0
  140. package/lite/fetch.d.ts.map +1 -1
  141. package/lite/fetch.js +2 -2
  142. package/lite/fetch.js.map +1 -1
  143. package/lite/fetch.test.d.ts +2 -0
  144. package/lite/fetch.test.d.ts.map +1 -0
  145. package/lite/fetch.test.js +41 -0
  146. package/lite/fetch.test.js.map +1 -0
  147. package/lite/index.d.ts +3 -0
  148. package/lite/index.d.ts.map +1 -1
  149. package/lite/index.js +3 -0
  150. package/lite/index.js.map +1 -1
  151. package/lite/publisher.d.ts +13 -6
  152. package/lite/publisher.d.ts.map +1 -1
  153. package/lite/publisher.js +274 -64
  154. package/lite/publisher.js.map +1 -1
  155. package/lite/publisher.test.d.ts +2 -0
  156. package/lite/publisher.test.d.ts.map +1 -0
  157. package/lite/publisher.test.js +65 -0
  158. package/lite/publisher.test.js.map +1 -0
  159. package/lite/setup.d.ts +72 -6
  160. package/lite/setup.d.ts.map +1 -1
  161. package/lite/setup.js +184 -31
  162. package/lite/setup.js.map +1 -1
  163. package/lite/setup.test.d.ts +2 -0
  164. package/lite/setup.test.d.ts.map +1 -0
  165. package/lite/setup.test.js +122 -0
  166. package/lite/setup.test.js.map +1 -0
  167. package/lite/stream.d.ts +12 -3
  168. package/lite/stream.d.ts.map +1 -1
  169. package/lite/stream.js +7 -4
  170. package/lite/stream.js.map +1 -1
  171. package/lite/subscribe.d.ts +37 -23
  172. package/lite/subscribe.d.ts.map +1 -1
  173. package/lite/subscribe.js +70 -55
  174. package/lite/subscribe.js.map +1 -1
  175. package/lite/subscribe.test.d.ts +2 -0
  176. package/lite/subscribe.test.d.ts.map +1 -0
  177. package/lite/subscribe.test.js +68 -0
  178. package/lite/subscribe.test.js.map +1 -0
  179. package/lite/subscriber.d.ts +24 -17
  180. package/lite/subscriber.d.ts.map +1 -1
  181. package/lite/subscriber.js +515 -90
  182. package/lite/subscriber.js.map +1 -1
  183. package/lite/subscriber.test.js +2 -2
  184. package/lite/subscriber.test.js.map +1 -1
  185. package/lite/track.d.ts +25 -13
  186. package/lite/track.d.ts.map +1 -1
  187. package/lite/track.js +60 -35
  188. package/lite/track.js.map +1 -1
  189. package/lite/track.test.js +12 -10
  190. package/lite/track.test.js.map +1 -1
  191. package/lite/version.d.ts +17 -4
  192. package/lite/version.d.ts.map +1 -1
  193. package/lite/version.js +88 -17
  194. package/lite/version.js.map +1 -1
  195. package/mock.d.ts +42 -3
  196. package/mock.d.ts.map +1 -1
  197. package/mock.js +88 -17
  198. package/mock.js.map +1 -1
  199. package/package.json +3 -3
  200. package/path.d.ts +30 -0
  201. package/path.d.ts.map +1 -1
  202. package/path.js +49 -0
  203. package/path.js.map +1 -1
  204. package/path.test.js +41 -0
  205. package/path.test.js.map +1 -1
  206. package/stream.test.js +10 -0
  207. package/stream.test.js.map +1 -1
  208. package/time.d.ts +109 -86
  209. package/time.d.ts.map +1 -1
  210. package/time.js +80 -30
  211. package/time.js.map +1 -1
  212. package/time.test.d.ts +2 -0
  213. package/time.test.d.ts.map +1 -0
  214. package/time.test.js +12 -0
  215. package/time.test.js.map +1 -0
  216. package/track.d.ts +225 -45
  217. package/track.d.ts.map +1 -1
  218. package/track.js +505 -93
  219. package/track.js.map +1 -1
  220. package/track.test.js +138 -29
  221. package/track.test.js.map +1 -1
  222. package/util/error.d.ts +9 -0
  223. package/util/error.d.ts.map +1 -1
  224. package/util/error.js +21 -0
  225. package/util/error.js.map +1 -1
  226. package/util/error.test.d.ts +2 -0
  227. package/util/error.test.d.ts.map +1 -0
  228. package/util/error.test.js +45 -0
  229. package/util/error.test.js.map +1 -0
  230. package/util/index.d.ts +1 -0
  231. package/util/index.d.ts.map +1 -1
  232. package/util/index.js +1 -0
  233. package/util/index.js.map +1 -1
  234. package/util/timeout.d.ts +5 -0
  235. package/util/timeout.d.ts.map +1 -0
  236. package/util/timeout.js +18 -0
  237. package/util/timeout.js.map +1 -0
  238. package/util/timeout.test.d.ts +2 -0
  239. package/util/timeout.test.d.ts.map +1 -0
  240. package/util/timeout.test.js +18 -0
  241. package/util/timeout.test.js.map +1 -0
  242. package/varint.d.ts +6 -0
  243. package/varint.d.ts.map +1 -1
  244. package/varint.js +6 -2
  245. package/varint.js.map +1 -1
  246. package/zod.d.ts +4 -4
  247. package/zod.d.ts.map +1 -1
  248. package/zod.js.map +1 -1
  249. package/bandwidth.d.ts +0 -11
  250. package/bandwidth.d.ts.map +0 -1
  251. package/bandwidth.js +0 -7
  252. package/bandwidth.js.map +0 -1
package/group.d.ts CHANGED
@@ -1,64 +1,153 @@
1
- /** An ordered stream of frames within a track, delivered over a single QUIC stream. */
2
- export declare class Group {
1
+ /**
2
+ * Group role handles: an ordered stream of frames within a track, delivered over one QUIC stream.
3
+ *
4
+ * @module
5
+ */
6
+ import { type GetPromise, type Getter } from "@moq/signals";
7
+ import { Timestamp } from "./time";
8
+ /** Maximum bytes of frames cached in a group before old frames are evicted from the front. */
9
+ export declare const MAX_GROUP_CACHE_BYTES: number;
10
+ /** Maximum number of frames cached in a group before old frames are evicted from the front. */
11
+ export declare const MAX_GROUP_FRAMES = 1024;
12
+ /**
13
+ * A frame buffered in a group: its presentation {@link Timestamp} and payload bytes.
14
+ *
15
+ * The timestamp carries its own scale, so a track can pick its units; the wire layer
16
+ * converts it into the track's negotiated timescale.
17
+ */
18
+ export interface Frame {
19
+ /** The frame payload. */
20
+ payload: Uint8Array;
21
+ /**
22
+ * Presentation timestamp. Required: for a payload with no presentation time of its own
23
+ * (a JSON catalog, control state) pass {@link Timestamp.now} explicitly.
24
+ */
25
+ timestamp: Timestamp;
26
+ }
27
+ /** Immutable group metadata. */
28
+ export interface Info {
29
+ /** Sequence number of this group within its track. */
30
+ sequence: number;
31
+ }
32
+ /**
33
+ * Thrown by a frame read when the reader fell behind the group's eviction window: frames
34
+ * it had not yet read were dropped to stay under the cache cap, so the stream has a gap.
35
+ */
36
+ export declare class Lagged extends Error {
37
+ constructor();
38
+ }
39
+ /**
40
+ * The write side of an ordered stream of frames within a track.
41
+ *
42
+ * @public
43
+ */
44
+ export declare class Producer {
3
45
  #private;
4
46
  /** Sequence number of this group within its track. */
5
47
  readonly sequence: number;
6
- /** Resolves with the abort error (or undefined) once closed. */
7
- readonly closed: Promise<Error | undefined>;
8
48
  constructor(sequence: number);
9
49
  /**
10
- * Writes a frame to the group.
11
- * @param frame - The frame to write
50
+ * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.
51
+ * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
52
+ */
53
+ get closed(): GetPromise<Error | null>;
54
+ /** A read handle for this group. */
55
+ consume(): Consumer;
56
+ /**
57
+ * Create an independent read handle that receives every frame written here.
58
+ *
59
+ * Frames written so far are replayed synchronously; later writes and close are teed
60
+ * in as they happen.
61
+ *
62
+ * @internal Track fan-out and fetch coalescing only. Use {@link consume} instead.
63
+ */
64
+ mirror(): Consumer;
65
+ /**
66
+ * Whether any mirror reader is currently attached.
67
+ *
68
+ * Pairs with {@link unused}. Fetch coalescing watches it to cancel a download once every reader
69
+ * has gone: a group can stay open indefinitely (a catalog track, a JSON stream), so it can't
70
+ * rely on the stream ending on its own.
71
+ *
72
+ * @internal Track fan-out and fetch coalescing only.
12
73
  */
13
- writeFrame(frame: Uint8Array): void;
14
- /** Write a string as a single UTF-8 encoded frame. */
74
+ get used(): Getter<boolean>;
75
+ /**
76
+ * Resolves once no mirror reader remains (or the group closes).
77
+ *
78
+ * @internal Track fan-out and fetch coalescing only.
79
+ */
80
+ unused(): Promise<void>;
81
+ /** Writes a frame to the group. */
82
+ writeFrame(frame: Frame): void;
83
+ /** Write a string as a single UTF-8 encoded frame, stamped with {@link Timestamp.now}. */
15
84
  writeString(str: string): void;
16
- /** Write a value as a single JSON-encoded frame. */
85
+ /** Write a value as a single JSON-encoded frame, stamped with {@link Timestamp.now}. */
17
86
  writeJson(json: unknown): void;
18
- /** Write a boolean as a single one-byte frame. */
87
+ /** Write a boolean as a single one-byte frame, stamped with {@link Timestamp.now}. */
19
88
  writeBool(bool: boolean): void;
89
+ /** True once the group has been closed. */
90
+ get isClosed(): boolean;
91
+ /** Closes the group, optionally with an error to abort readers. */
92
+ close(abort?: Error): void;
93
+ }
94
+ /**
95
+ * The read side of an ordered stream of frames within a track.
96
+ *
97
+ * Created internally: obtain one from {@link Producer.consume} or a track subscriber's
98
+ * group reads.
99
+ *
100
+ * @public
101
+ */
102
+ export declare class Consumer {
103
+ #private;
104
+ /** Sequence number of this group within its track. */
105
+ readonly sequence: number;
106
+ private constructor();
107
+ /**
108
+ * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.
109
+ * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
110
+ */
111
+ get closed(): GetPromise<Error | null>;
20
112
  /** True once no further frames can be read: the group has closed and every buffered frame is read. */
21
113
  get done(): boolean;
114
+ /** True once the group has been closed, regardless of whether buffered frames remain unread. Synchronous complement to the {@link closed} promise. */
115
+ get isClosed(): boolean;
116
+ /** True if frames were evicted from the front of this group before being read. */
117
+ get skipped(): boolean;
22
118
  /**
23
119
  * Reads the next already-buffered frame without blocking.
120
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
24
121
  *
25
- * Returns `undefined` when nothing is buffered right now. That is *not* by itself end-of-group:
26
- * check {@link done} to tell "no frame buffered yet" (more may arrive) from "the group finished".
27
- * Drain a backlog by looping until this returns `undefined`, then branch on {@link done}: if not
28
- * done, {@link readable} resolves when the next frame arrives.
122
+ * Returns `undefined` when nothing is buffered right now. That is not by itself
123
+ * end-of-group: check {@link done} to tell "no frame buffered yet" from "finished".
29
124
  */
30
- tryReadFrame(): Uint8Array | undefined;
125
+ tryReadFrame(): Frame | undefined;
31
126
  /** Like {@link tryReadFrame} but also reports the frame's sequence number within the group. */
32
- tryReadFrameSequence(): {
127
+ tryReadFrameSequence(): ({
33
128
  sequence: number;
34
- data: Uint8Array;
35
- } | undefined;
36
- /**
37
- * Resolves once {@link readFrame} would not block: a frame is buffered, or the group has closed.
38
- * Always settles (never hangs), so on a finished group it resolves immediately; pair it with
39
- * {@link done} to avoid re-waiting on a group that has nothing left.
40
- *
41
- * Lets a caller fold "this group has a frame" into a larger wait (e.g. racing it against a new
42
- * group arriving) without touching the group's internal signals.
43
- */
129
+ } & Frame) | undefined;
130
+ /** Resolves once {@link readFrame} would not block. */
44
131
  readable(): Promise<void>;
45
132
  /**
46
133
  * Reads the next frame from the group.
47
- * @returns A promise that resolves to the next frame or undefined
134
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
48
135
  */
49
- readFrame(): Promise<Uint8Array | undefined>;
50
- /** Reads the next frame along with its sequence number within the group. */
51
- readFrameSequence(): Promise<{
136
+ readFrame(): Promise<Frame | undefined>;
137
+ /**
138
+ * Reads the next frame along with its sequence number within the group.
139
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
140
+ */
141
+ readFrameSequence(): Promise<({
52
142
  sequence: number;
53
- data: Uint8Array;
54
- } | undefined>;
55
- /** Reads the next frame and decodes it as a UTF-8 string. */
143
+ } & Frame) | undefined>;
144
+ /** Reads the next frame and decodes its payload as a UTF-8 string. */
56
145
  readString(): Promise<string | undefined>;
57
- /** Reads the next frame and parses it as JSON. */
146
+ /** Reads the next frame and parses its payload as JSON. */
58
147
  readJson(): Promise<unknown | undefined>;
59
- /** Reads the next frame and decodes it as a one-byte boolean. */
148
+ /** Reads the next frame and decodes its payload as a one-byte boolean. */
60
149
  readBool(): Promise<boolean | undefined>;
61
- /** Closes the group, optionally with an error to abort readers. */
150
+ /** Closes the group, optionally with an error to abort readers. Idempotent. */
62
151
  close(abort?: Error): void;
63
152
  }
64
153
  //# sourceMappingURL=group.d.ts.map
package/group.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"group.d.ts","sourceRoot":"","sources":["../src/group.ts"],"names":[],"mappings":"AASA,uFAAuF;AACvF,qBAAa,KAAK;;IACjB,sDAAsD;IACtD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAM1B,gEAAgE;IAChE,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,GAAG,SAAS,CAAC,CAAC;IAE5C,YAAY,QAAQ,EAAE,MAAM,EAW3B;IAED;;;OAGG;IACH,UAAU,CAAC,KAAK,EAAE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E,MAAM,CAAC;IAI1B,OAAO,eAGN;IAED;;;OAGG;IACH,IAAI,MAAM,IAAI,UAAU,CAAC,KAAK,GAAG,IAAI,CAAC,CAErC;IAeD,sGAAsG;IACtG,IAAI,IAAI,IAAI,OAAO,CAElB;IAED,sJAAsJ;IACtJ,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAED,kFAAkF;IAClF,IAAI,OAAO,IAAI,OAAO,CAErB;IAED;;;;;;OAMG;IACH,YAAY,IAAI,KAAK,GAAG,SAAS,CAGhC;IAED,+FAA+F;IAC/F,oBAAoB,IAAI,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,KAAK,CAAC,GAAG,SAAS,CAIjE;IAED,uDAAuD;IACjD,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAM9B;IAED;;;OAGG;IACG,SAAS,IAAI,OAAO,CAAC,KAAK,GAAG,SAAS,CAAC,CAa5C;IAED;;;OAGG;IACG,iBAAiB,IAAI,OAAO,CAAC,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,KAAK,CAAC,GAAG,SAAS,CAAC,CAa7E;IAED,sEAAsE;IAChE,UAAU,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAG9C;IAED,2DAA2D;IACrD,QAAQ,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAG7C;IAED,0EAA0E;IACpE,QAAQ,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAG7C;IAED,+EAA+E;IAC/E,KAAK,CAAC,KAAK,CAAC,EAAE,KAAK,QAGlB;CACD"}
package/group.js CHANGED
@@ -1,136 +1,313 @@
1
1
  /* @ts-self-types="./group.d.ts" */
2
- import { Signal } from "@moq/signals";
3
- /** Reactive backing state for a {@link Group}: buffered frames, a closed flag, and the running frame count. */
2
+ /**
3
+ * Group role handles: an ordered stream of frames within a track, delivered over one QUIC stream.
4
+ *
5
+ * @module
6
+ */
7
+ import { Once, Signal } from "@moq/signals";
8
+ import { Timestamp } from "./time.js";
9
+ /** Maximum bytes of frames cached in a group before old frames are evicted from the front. */
10
+ export const MAX_GROUP_CACHE_BYTES = 32 * 1024 * 1024;
11
+ /** Maximum number of frames cached in a group before old frames are evicted from the front. */
12
+ export const MAX_GROUP_FRAMES = 1024;
13
+ /**
14
+ * Thrown by a frame read when the reader fell behind the group's eviction window: frames
15
+ * it had not yet read were dropped to stay under the cache cap, so the stream has a gap.
16
+ */
17
+ export class Lagged extends Error {
18
+ constructor() {
19
+ super("lagged: frames were evicted before being read");
20
+ this.name = "Lagged";
21
+ }
22
+ }
23
+ /** Reactive backing state shared by the group producer and one consumer. */
4
24
  class GroupState {
25
+ sequence;
5
26
  frames = new Signal([]);
6
- closed = new Signal(false);
27
+ closed = new Once();
7
28
  total = new Signal(0); // The total number of frames in the group thus far
29
+ // Frames evicted from the front by the cache cap. A reader that had not consumed
30
+ // them has a gap, so its next read throws Lagged rather than skipping silently.
31
+ offset = 0;
32
+ cacheBytes = 0;
33
+ constructor(sequence) {
34
+ this.sequence = sequence;
35
+ }
36
+ }
37
+ function appendFrame(state, frame) {
38
+ if (state.closed.peek() !== undefined)
39
+ throw new Error("group is closed");
40
+ state.cacheBytes += frame.payload.byteLength;
41
+ state.frames.mutate((frames) => {
42
+ frames.push(frame);
43
+ while (frames.length > MAX_GROUP_FRAMES || state.cacheBytes > MAX_GROUP_CACHE_BYTES) {
44
+ const evicted = frames.shift();
45
+ if (!evicted)
46
+ break;
47
+ state.cacheBytes -= evicted.payload.byteLength;
48
+ state.offset++;
49
+ }
50
+ });
51
+ state.total.update((total) => total + 1);
8
52
  }
9
- /** An ordered stream of frames within a track, delivered over a single QUIC stream. */
10
- export class Group {
53
+ /**
54
+ * The write side of an ordered stream of frames within a track.
55
+ *
56
+ * @public
57
+ */
58
+ export class Producer {
11
59
  /** Sequence number of this group within its track. */
12
60
  sequence;
13
- // Reactive backing state, deliberately private: read through the read* methods so callers can't
14
- // poke the signals directly (and so the internal representation can change).
15
- #state = new GroupState();
16
- /** Resolves with the abort error (or undefined) once closed. */
17
- closed;
61
+ #state;
62
+ #mirrors;
63
+ // Whether any mirror reader is attached (see {@link used}). Fetch coalescing watches it to
64
+ // cancel an abandoned download; a group can stay open indefinitely (a catalog or JSON stream),
65
+ // so this is what stops a reader-less fetch instead of the stream ending on its own.
66
+ #used = new Signal(false);
18
67
  constructor(sequence) {
68
+ this.#state = new GroupState(sequence);
19
69
  this.sequence = sequence;
20
- // Cache the closed promise to avoid recreating it every time.
21
- this.closed = new Promise((resolve) => {
22
- const dispose = this.#state.closed.subscribe((closed) => {
23
- if (!closed)
24
- return;
25
- resolve(closed instanceof Error ? closed : undefined);
26
- dispose();
27
- });
70
+ }
71
+ /**
72
+ * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.
73
+ * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
74
+ */
75
+ get closed() {
76
+ return this.#state.closed;
77
+ }
78
+ /** A read handle for this group. */
79
+ consume() {
80
+ return makeConsumer(this.#state);
81
+ }
82
+ /**
83
+ * Create an independent read handle that receives every frame written here.
84
+ *
85
+ * Frames written so far are replayed synchronously; later writes and close are teed
86
+ * in as they happen.
87
+ *
88
+ * @internal Track fan-out and fetch coalescing only. Use {@link consume} instead.
89
+ */
90
+ mirror() {
91
+ const dst = new GroupState(this.sequence);
92
+ for (const frame of this.#state.frames.peek())
93
+ appendFrame(dst, frame);
94
+ dst.offset = this.#state.offset;
95
+ const closed = this.#state.closed.peek();
96
+ if (closed !== undefined) {
97
+ dst.closed.set(closed);
98
+ return makeConsumer(dst);
99
+ }
100
+ this.#mirrors ??= new Set();
101
+ this.#mirrors.add(dst);
102
+ this.#used.set(true);
103
+ // Track this mirror's close eagerly (not just lazily on the next write) so demand drops the
104
+ // moment the last reader leaves, letting an abandoned fetch cancel even with no more frames.
105
+ const dispose = dst.closed.subscribe((c) => {
106
+ if (c === undefined)
107
+ return;
108
+ this.#mirrors?.delete(dst);
109
+ this.#used.set((this.#mirrors?.size ?? 0) > 0);
110
+ dispose();
28
111
  });
112
+ return makeConsumer(dst);
113
+ }
114
+ /**
115
+ * Whether any mirror reader is currently attached.
116
+ *
117
+ * Pairs with {@link unused}. Fetch coalescing watches it to cancel a download once every reader
118
+ * has gone: a group can stay open indefinitely (a catalog track, a JSON stream), so it can't
119
+ * rely on the stream ending on its own.
120
+ *
121
+ * @internal Track fan-out and fetch coalescing only.
122
+ */
123
+ get used() {
124
+ return this.#used;
29
125
  }
30
126
  /**
31
- * Writes a frame to the group.
32
- * @param frame - The frame to write
127
+ * Resolves once no mirror reader remains (or the group closes).
128
+ *
129
+ * @internal Track fan-out and fetch coalescing only.
33
130
  */
131
+ async unused() {
132
+ while (this.#used.peek() && this.#state.closed.peek() === undefined) {
133
+ await Signal.race(this.#used, this.#state.closed);
134
+ }
135
+ }
136
+ /** Writes a frame to the group. */
34
137
  writeFrame(frame) {
35
- if (this.#state.closed.peek())
36
- throw new Error("group is closed");
37
- this.#state.frames.mutate((frames) => {
38
- frames.push(frame);
39
- });
40
- this.#state.total.update((total) => total + 1);
138
+ appendFrame(this.#state, frame);
139
+ if (this.#mirrors) {
140
+ for (const mirror of this.#mirrors) {
141
+ if (mirror.closed.peek() !== undefined)
142
+ this.#mirrors.delete(mirror);
143
+ else
144
+ appendFrame(mirror, frame);
145
+ }
146
+ }
41
147
  }
42
- /** Write a string as a single UTF-8 encoded frame. */
148
+ /** Write a string as a single UTF-8 encoded frame, stamped with {@link Timestamp.now}. */
43
149
  writeString(str) {
44
- this.writeFrame(new TextEncoder().encode(str));
150
+ this.writeFrame({ payload: new TextEncoder().encode(str), timestamp: Timestamp.now() });
45
151
  }
46
- /** Write a value as a single JSON-encoded frame. */
152
+ /** Write a value as a single JSON-encoded frame, stamped with {@link Timestamp.now}. */
47
153
  writeJson(json) {
48
154
  this.writeString(JSON.stringify(json));
49
155
  }
50
- /** Write a boolean as a single one-byte frame. */
156
+ /** Write a boolean as a single one-byte frame, stamped with {@link Timestamp.now}. */
51
157
  writeBool(bool) {
52
- this.writeFrame(new Uint8Array([bool ? 1 : 0]));
158
+ this.writeFrame({ payload: new Uint8Array([bool ? 1 : 0]), timestamp: Timestamp.now() });
159
+ }
160
+ /** True once the group has been closed. */
161
+ get isClosed() {
162
+ return this.#state.closed.peek() !== undefined;
163
+ }
164
+ /** Closes the group, optionally with an error to abort readers. */
165
+ close(abort) {
166
+ if (this.#state.closed.peek() !== undefined)
167
+ return;
168
+ this.#state.closed.set(abort ?? null);
169
+ if (this.#mirrors) {
170
+ for (const mirror of this.#mirrors) {
171
+ if (mirror.closed.peek() === undefined)
172
+ mirror.closed.set(abort ?? null);
173
+ }
174
+ this.#mirrors.clear();
175
+ }
176
+ }
177
+ }
178
+ let makeConsumer;
179
+ /**
180
+ * The read side of an ordered stream of frames within a track.
181
+ *
182
+ * Created internally: obtain one from {@link Producer.consume} or a track subscriber's
183
+ * group reads.
184
+ *
185
+ * @public
186
+ */
187
+ export class Consumer {
188
+ /** Sequence number of this group within its track. */
189
+ sequence;
190
+ #state;
191
+ constructor(state) {
192
+ this.#state = state;
193
+ this.sequence = state.sequence;
194
+ }
195
+ /**
196
+ * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.
197
+ * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
198
+ */
199
+ get closed() {
200
+ return this.#state.closed;
201
+ }
202
+ static {
203
+ makeConsumer = (state) => new Consumer(state);
204
+ }
205
+ #readBufferedFrame() {
206
+ const frames = this.#state.frames.peek();
207
+ const frame = frames.shift();
208
+ if (!frame)
209
+ return undefined;
210
+ this.#state.cacheBytes -= frame.payload.byteLength;
211
+ return { sequence: this.#state.total.peek() - frames.length - 1, frame };
53
212
  }
54
213
  /** True once no further frames can be read: the group has closed and every buffered frame is read. */
55
214
  get done() {
56
- return this.#state.frames.peek().length === 0 && this.#state.closed.peek() !== false;
215
+ return this.#state.frames.peek().length === 0 && this.#state.closed.peek() !== undefined;
216
+ }
217
+ /** True once the group has been closed, regardless of whether buffered frames remain unread. Synchronous complement to the {@link closed} promise. */
218
+ get isClosed() {
219
+ return this.#state.closed.peek() !== undefined;
220
+ }
221
+ /** True if frames were evicted from the front of this group before being read. */
222
+ get skipped() {
223
+ return this.#state.offset > 0;
57
224
  }
58
225
  /**
59
226
  * Reads the next already-buffered frame without blocking.
227
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
60
228
  *
61
- * Returns `undefined` when nothing is buffered right now. That is *not* by itself end-of-group:
62
- * check {@link done} to tell "no frame buffered yet" (more may arrive) from "the group finished".
63
- * Drain a backlog by looping until this returns `undefined`, then branch on {@link done}: if not
64
- * done, {@link readable} resolves when the next frame arrives.
229
+ * Returns `undefined` when nothing is buffered right now. That is not by itself
230
+ * end-of-group: check {@link done} to tell "no frame buffered yet" from "finished".
65
231
  */
66
232
  tryReadFrame() {
67
- return this.tryReadFrameSequence()?.data;
233
+ const read = this.#readBufferedFrame();
234
+ return read?.frame;
68
235
  }
69
236
  /** Like {@link tryReadFrame} but also reports the frame's sequence number within the group. */
70
237
  tryReadFrameSequence() {
71
- const frames = this.#state.frames.peek();
72
- const data = frames.shift();
73
- if (data === undefined)
238
+ const read = this.#readBufferedFrame();
239
+ if (!read)
74
240
  return undefined;
75
- return { sequence: this.#state.total.peek() - frames.length - 1, data };
241
+ return { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };
76
242
  }
77
- /**
78
- * Resolves once {@link readFrame} would not block: a frame is buffered, or the group has closed.
79
- * Always settles (never hangs), so on a finished group it resolves immediately; pair it with
80
- * {@link done} to avoid re-waiting on a group that has nothing left.
81
- *
82
- * Lets a caller fold "this group has a frame" into a larger wait (e.g. racing it against a new
83
- * group arriving) without touching the group's internal signals.
84
- */
243
+ /** Resolves once {@link readFrame} would not block. */
85
244
  async readable() {
86
245
  for (;;) {
87
246
  if (this.#state.frames.peek().length > 0)
88
247
  return;
89
- if (this.#state.closed.peek())
248
+ if (this.#state.closed.peek() !== undefined)
90
249
  return;
91
250
  await Signal.race(this.#state.frames, this.#state.closed);
92
251
  }
93
252
  }
94
253
  /**
95
254
  * Reads the next frame from the group.
96
- * @returns A promise that resolves to the next frame or undefined
255
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
97
256
  */
98
257
  async readFrame() {
99
- return (await this.readFrameSequence())?.data;
258
+ for (;;) {
259
+ if (this.#state.offset > 0)
260
+ throw new Lagged();
261
+ const read = this.#readBufferedFrame();
262
+ if (read)
263
+ return read.frame;
264
+ const closed = this.#state.closed.peek();
265
+ if (closed instanceof Error)
266
+ throw closed;
267
+ if (closed !== undefined)
268
+ return;
269
+ await Signal.race(this.#state.frames, this.#state.closed);
270
+ }
100
271
  }
101
- /** Reads the next frame along with its sequence number within the group. */
272
+ /**
273
+ * Reads the next frame along with its sequence number within the group.
274
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
275
+ */
102
276
  async readFrameSequence() {
103
277
  for (;;) {
104
- const next = this.tryReadFrameSequence();
105
- if (next)
106
- return next;
107
- // Drain buffered frames before observing the close, so a closed group still yields them.
278
+ if (this.#state.offset > 0)
279
+ throw new Lagged();
280
+ const read = this.#readBufferedFrame();
281
+ if (read)
282
+ return { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };
108
283
  const closed = this.#state.closed.peek();
109
284
  if (closed instanceof Error)
110
285
  throw closed;
111
- if (closed)
112
- return undefined;
113
- await this.readable();
286
+ if (closed !== undefined)
287
+ return;
288
+ await Signal.race(this.#state.frames, this.#state.closed);
114
289
  }
115
290
  }
116
- /** Reads the next frame and decodes it as a UTF-8 string. */
291
+ /** Reads the next frame and decodes its payload as a UTF-8 string. */
117
292
  async readString() {
118
293
  const frame = await this.readFrame();
119
- return frame ? new TextDecoder().decode(frame) : undefined;
294
+ return frame ? new TextDecoder().decode(frame.payload) : undefined;
120
295
  }
121
- /** Reads the next frame and parses it as JSON. */
296
+ /** Reads the next frame and parses its payload as JSON. */
122
297
  async readJson() {
123
298
  const frame = await this.readString();
124
299
  return frame ? JSON.parse(frame) : undefined;
125
300
  }
126
- /** Reads the next frame and decodes it as a one-byte boolean. */
301
+ /** Reads the next frame and decodes its payload as a one-byte boolean. */
127
302
  async readBool() {
128
303
  const frame = await this.readFrame();
129
- return frame ? frame[0] === 1 : undefined;
304
+ return frame ? frame.payload[0] === 1 : undefined;
130
305
  }
131
- /** Closes the group, optionally with an error to abort readers. */
306
+ /** Closes the group, optionally with an error to abort readers. Idempotent. */
132
307
  close(abort) {
133
- this.#state.closed.set(abort ?? true);
308
+ if (this.#state.closed.peek() !== undefined)
309
+ return; // already closed
310
+ this.#state.closed.set(abort ?? null);
134
311
  }
135
312
  }
136
313
  //# sourceMappingURL=group.js.map
package/group.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"group.js","sourceRoot":"","sources":["../src/group.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC,+GAA+G;AAC/G,MAAM,UAAU;IACf,MAAM,GAAG,IAAI,MAAM,CAAe,EAAE,CAAC,CAAC;IACtC,MAAM,GAAG,IAAI,MAAM,CAAkB,KAAK,CAAC,CAAC;IAC5C,KAAK,GAAG,IAAI,MAAM,CAAS,CAAC,CAAC,CAAC,CAAC,mDAAmD;CAClF;AAED,uFAAuF;AACvF,MAAM,OAAO,KAAK;IACjB,sDAAsD;IAC7C,QAAQ,CAAS;IAE1B,gGAAgG;IAChG,6EAA6E;IAC7E,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;IAE1B,gEAAgE;IACvD,MAAM,CAA6B;IAE5C,YAAY,QAAgB;QAC3B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,8DAA8D;QAC9D,IAAI,CAAC,MAAM,GAAG,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YACrC,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE;gBACv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,MAAM,CAAC,IAAI,EAAE,CAAC;YACzC,IAAI,MAAM,YAAY,KAAK;gBAAE,MAAM,MAAM,CAAC;YAC1C,IAAI,MAAM;gBAAE,OAAO,SAAS,CAAC;YAE7B,MAAM,IAAI,CAAC,QAAQ,EAAE,CAAC;QACvB,CAAC;IACF,CAAC;IAED,6DAA6D;IAC7D,KAAK,CAAC,UAAU;QACf,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC5D,CAAC;IAED,kDAAkD;IAClD,KAAK,CAAC,QAAQ;QACb,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;QACtC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC9C,CAAC;IAED,iEAAiE;IACjE,KAAK,CAAC,QAAQ;QACb,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC3C,CAAC;IAED,mEAAmE;IACnE,KAAK,CAAC,KAAa;QAClB,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;IACvC,CAAC;CACD","sourcesContent":["import { Signal } from \"@moq/signals\";\n\n/** Reactive backing state for a {@link Group}: buffered frames, a closed flag, and the running frame count. */\nclass GroupState {\n\tframes = new Signal<Uint8Array[]>([]);\n\tclosed = new Signal<boolean | Error>(false);\n\ttotal = new Signal<number>(0); // The total number of frames in the group thus far\n}\n\n/** An ordered stream of frames within a track, delivered over a single QUIC stream. */\nexport class Group {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t// Reactive backing state, deliberately private: read through the read* methods so callers can't\n\t// poke the signals directly (and so the internal representation can change).\n\t#state = new GroupState();\n\n\t/** Resolves with the abort error (or undefined) once closed. */\n\treadonly closed: Promise<Error | undefined>;\n\n\tconstructor(sequence: number) {\n\t\tthis.sequence = sequence;\n\n\t\t// Cache the closed promise to avoid recreating it every time.\n\t\tthis.closed = new Promise((resolve) => {\n\t\t\tconst dispose = this.#state.closed.subscribe((closed) => {\n\t\t\t\tif (!closed) return;\n\t\t\t\tresolve(closed instanceof Error ? closed : undefined);\n\t\t\t\tdispose();\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Writes a frame to the group.\n\t * @param frame - The frame to write\n\t */\n\twriteFrame(frame: Uint8Array) {\n\t\tif (this.#state.closed.peek()) throw new Error(\"group is closed\");\n\n\t\tthis.#state.frames.mutate((frames) => {\n\t\t\tframes.push(frame);\n\t\t});\n\n\t\tthis.#state.total.update((total) => total + 1);\n\t}\n\n\t/** Write a string as a single UTF-8 encoded frame. */\n\twriteString(str: string) {\n\t\tthis.writeFrame(new TextEncoder().encode(str));\n\t}\n\n\t/** Write a value as a single JSON-encoded frame. */\n\twriteJson(json: unknown) {\n\t\tthis.writeString(JSON.stringify(json));\n\t}\n\n\t/** Write a boolean as a single one-byte frame. */\n\twriteBool(bool: boolean) {\n\t\tthis.writeFrame(new Uint8Array([bool ? 1 : 0]));\n\t}\n\n\t/** True once no further frames can be read: the group has closed and every buffered frame is read. */\n\tget done(): boolean {\n\t\treturn this.#state.frames.peek().length === 0 && this.#state.closed.peek() !== false;\n\t}\n\n\t/**\n\t * Reads the next already-buffered frame without blocking.\n\t *\n\t * Returns `undefined` when nothing is buffered right now. That is *not* by itself end-of-group:\n\t * check {@link done} to tell \"no frame buffered yet\" (more may arrive) from \"the group finished\".\n\t * Drain a backlog by looping until this returns `undefined`, then branch on {@link done}: if not\n\t * done, {@link readable} resolves when the next frame arrives.\n\t */\n\ttryReadFrame(): Uint8Array | undefined {\n\t\treturn this.tryReadFrameSequence()?.data;\n\t}\n\n\t/** Like {@link tryReadFrame} but also reports the frame's sequence number within the group. */\n\ttryReadFrameSequence(): { sequence: number; data: Uint8Array } | undefined {\n\t\tconst frames = this.#state.frames.peek();\n\t\tconst data = frames.shift();\n\t\tif (data === undefined) return undefined;\n\t\treturn { sequence: this.#state.total.peek() - frames.length - 1, data };\n\t}\n\n\t/**\n\t * Resolves once {@link readFrame} would not block: a frame is buffered, or the group has closed.\n\t * Always settles (never hangs), so on a finished group it resolves immediately; pair it with\n\t * {@link done} to avoid re-waiting on a group that has nothing left.\n\t *\n\t * Lets a caller fold \"this group has a frame\" into a larger wait (e.g. racing it against a new\n\t * group arriving) without touching the group's internal signals.\n\t */\n\tasync readable(): Promise<void> {\n\t\tfor (;;) {\n\t\t\tif (this.#state.frames.peek().length > 0) return;\n\t\t\tif (this.#state.closed.peek()) return;\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame from the group.\n\t * @returns A promise that resolves to the next frame or undefined\n\t */\n\tasync readFrame(): Promise<Uint8Array | undefined> {\n\t\treturn (await this.readFrameSequence())?.data;\n\t}\n\n\t/** Reads the next frame along with its sequence number within the group. */\n\tasync readFrameSequence(): Promise<{ sequence: number; data: Uint8Array } | undefined> {\n\t\tfor (;;) {\n\t\t\tconst next = this.tryReadFrameSequence();\n\t\t\tif (next) return next;\n\n\t\t\t// Drain buffered frames before observing the close, so a closed group still yields them.\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed) return undefined;\n\n\t\t\tawait this.readable();\n\t\t}\n\t}\n\n\t/** Reads the next frame and decodes it as a UTF-8 string. */\n\tasync readString(): Promise<string | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? new TextDecoder().decode(frame) : undefined;\n\t}\n\n\t/** Reads the next frame and parses it as JSON. */\n\tasync readJson(): Promise<unknown | undefined> {\n\t\tconst frame = await this.readString();\n\t\treturn frame ? JSON.parse(frame) : undefined;\n\t}\n\n\t/** Reads the next frame and decodes it as a one-byte boolean. */\n\tasync readBool(): Promise<boolean | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? frame[0] === 1 : undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. */\n\tclose(abort?: Error) {\n\t\tthis.#state.closed.set(abort ?? true);\n\t}\n}\n"]}
1
+ {"version":3,"file":"group.js","sourceRoot":"","sources":["../src/group.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAgC,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,8FAA8F;AAC9F,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEtD,+FAA+F;AAC/F,MAAM,CAAC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAwBrC;;;GAGG;AACH,MAAM,OAAO,MAAO,SAAQ,KAAK;IAChC;QACC,KAAK,CAAC,+CAA+C,CAAC,CAAC;QACvD,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;IACtB,CAAC;CACD;AAED,4EAA4E;AAC5E,MAAM,UAAU;IACN,QAAQ,CAAS;IAC1B,MAAM,GAAG,IAAI,MAAM,CAAU,EAAE,CAAC,CAAC;IACjC,MAAM,GAAG,IAAI,IAAI,EAAgB,CAAC;IAClC,KAAK,GAAG,IAAI,MAAM,CAAS,CAAC,CAAC,CAAC,CAAC,mDAAmD;IAElF,iFAAiF;IACjF,gFAAgF;IAChF,MAAM,GAAG,CAAC,CAAC;IACX,UAAU,GAAG,CAAC,CAAC;IAEf,YAAY,QAAgB;QAC3B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,SAAS,WAAW,CAAC,KAAiB,E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AI,EAAE,KAAK,SAAS;YAAE,OAAO,CAAC,iBAAiB;QACtE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;IACvC,CAAC;CACD","sourcesContent":["/**\n * Group role handles: an ordered stream of frames within a track, delivered over one QUIC stream.\n *\n * @module\n */\nimport { type GetPromise, type Getter, Once, Signal } from \"@moq/signals\";\nimport { Timestamp } from \"./time.ts\";\n\n/** Maximum bytes of frames cached in a group before old frames are evicted from the front. */\nexport const MAX_GROUP_CACHE_BYTES = 32 * 1024 * 1024;\n\n/** Maximum number of frames cached in a group before old frames are evicted from the front. */\nexport const MAX_GROUP_FRAMES = 1024;\n\n/**\n * A frame buffered in a group: its presentation {@link Timestamp} and payload bytes.\n *\n * The timestamp carries its own scale, so a track can pick its units; the wire layer\n * converts it into the track's negotiated timescale.\n */\nexport interface Frame {\n\t/** The frame payload. */\n\tpayload: Uint8Array;\n\t/**\n\t * Presentation timestamp. Required: for a payload with no presentation time of its own\n\t * (a JSON catalog, control state) pass {@link Timestamp.now} explicitly.\n\t */\n\ttimestamp: Timestamp;\n}\n\n/** Immutable group metadata. */\nexport interface Info {\n\t/** Sequence number of this group within its track. */\n\tsequence: number;\n}\n\n/**\n * Thrown by a frame read when the reader fell behind the group's eviction window: frames\n * it had not yet read were dropped to stay under the cache cap, so the stream has a gap.\n */\nexport class Lagged extends Error {\n\tconstructor() {\n\t\tsuper(\"lagged: frames were evicted before being read\");\n\t\tthis.name = \"Lagged\";\n\t}\n}\n\n/** Reactive backing state shared by the group producer and one consumer. */\nclass GroupState {\n\treadonly sequence: number;\n\tframes = new Signal<Frame[]>([]);\n\tclosed = new Once<Error | null>();\n\ttotal = new Signal<number>(0); // The total number of frames in the group thus far\n\n\t// Frames evicted from the front by the cache cap. A reader that had not consumed\n\t// them has a gap, so its next read throws Lagged rather than skipping silently.\n\toffset = 0;\n\tcacheBytes = 0;\n\n\tconstructor(sequence: number) {\n\t\tthis.sequence = sequence;\n\t}\n}\n\nfunction appendFrame(state: GroupState, frame: Frame) {\n\tif (state.closed.peek() !== undefined) throw new Error(\"group is closed\");\n\n\tstate.cacheBytes += frame.payload.byteLength;\n\tstate.frames.mutate((frames) => {\n\t\tframes.push(frame);\n\n\t\twhile (frames.length > MAX_GROUP_FRAMES || state.cacheBytes > MAX_GROUP_CACHE_BYTES) {\n\t\t\tconst evicted = frames.shift();\n\t\t\tif (!evicted) break;\n\t\t\tstate.cacheBytes -= evicted.payload.byteLength;\n\t\t\tstate.offset++;\n\t\t}\n\t});\n\n\tstate.total.update((total) => total + 1);\n}\n\n/**\n * The write side of an ordered stream of frames within a track.\n *\n * @public\n */\nexport class Producer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\t#mirrors?: Set<GroupState>;\n\n\t// Whether any mirror reader is attached (see {@link used}). Fetch coalescing watches it to\n\t// cancel an abandoned download; a group can stay open indefinitely (a catalog or JSON stream),\n\t// so this is what stops a reader-less fetch instead of the stream ending on its own.\n\t#used = new Signal<boolean>(false);\n\n\tconstructor(sequence: number) {\n\t\tthis.#state = new GroupState(sequence);\n\t\tthis.sequence = sequence;\n\t}\n\n\t/**\n\t * Settles once the group 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 group. */\n\tconsume(): Consumer {\n\t\treturn makeConsumer(this.#state);\n\t}\n\n\t/**\n\t * Create an independent read handle that receives every frame written here.\n\t *\n\t * Frames written so far are replayed synchronously; later writes and close are teed\n\t * in as they happen.\n\t *\n\t * @internal Track fan-out and fetch coalescing only. Use {@link consume} instead.\n\t */\n\tmirror(): Consumer {\n\t\tconst dst = new GroupState(this.sequence);\n\t\tfor (const frame of this.#state.frames.peek()) appendFrame(dst, frame);\n\t\tdst.offset = this.#state.offset;\n\n\t\tconst closed = this.#state.closed.peek();\n\t\tif (closed !== undefined) {\n\t\t\tdst.closed.set(closed);\n\t\t\treturn makeConsumer(dst);\n\t\t}\n\n\t\tthis.#mirrors ??= new Set();\n\t\tthis.#mirrors.add(dst);\n\t\tthis.#used.set(true);\n\n\t\t// Track this mirror's close eagerly (not just lazily on the next write) so demand drops the\n\t\t// moment the last reader leaves, letting an abandoned fetch cancel even with no more frames.\n\t\tconst dispose = dst.closed.subscribe((c) => {\n\t\t\tif (c === undefined) return;\n\t\t\tthis.#mirrors?.delete(dst);\n\t\t\tthis.#used.set((this.#mirrors?.size ?? 0) > 0);\n\t\t\tdispose();\n\t\t});\n\n\t\treturn makeConsumer(dst);\n\t}\n\n\t/**\n\t * Whether any mirror reader is currently attached.\n\t *\n\t * Pairs with {@link unused}. Fetch coalescing watches it to cancel a download once every reader\n\t * has gone: a group can stay open indefinitely (a catalog track, a JSON stream), so it can't\n\t * rely on the stream ending on its own.\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tget used(): Getter<boolean> {\n\t\treturn this.#used;\n\t}\n\n\t/**\n\t * Resolves once no mirror reader remains (or the group closes).\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tasync unused(): Promise<void> {\n\t\twhile (this.#used.peek() && this.#state.closed.peek() === undefined) {\n\t\t\tawait Signal.race(this.#used, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Writes a frame to the group. */\n\twriteFrame(frame: Frame) {\n\t\tappendFrame(this.#state, frame);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() !== undefined) this.#mirrors.delete(mirror);\n\t\t\t\telse appendFrame(mirror, frame);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Write a string as a single UTF-8 encoded frame, stamped with {@link Timestamp.now}. */\n\twriteString(str: string) {\n\t\tthis.writeFrame({ payload: new TextEncoder().encode(str), timestamp: Timestamp.now() });\n\t}\n\n\t/** Write a value as a single JSON-encoded frame, stamped with {@link Timestamp.now}. */\n\twriteJson(json: unknown) {\n\t\tthis.writeString(JSON.stringify(json));\n\t}\n\n\t/** Write a boolean as a single one-byte frame, stamped with {@link Timestamp.now}. */\n\twriteBool(bool: boolean) {\n\t\tthis.writeFrame({ payload: new Uint8Array([bool ? 1 : 0]), timestamp: Timestamp.now() });\n\t}\n\n\t/** True once the group has been closed. */\n\tget isClosed(): boolean {\n\t\treturn this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return;\n\t\tthis.#state.closed.set(abort ?? null);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() === undefined) mirror.closed.set(abort ?? null);\n\t\t\t}\n\t\t\tthis.#mirrors.clear();\n\t\t}\n\t}\n}\n\nlet makeConsumer: (state: GroupState) => Consumer;\n\n/**\n * The read side of an ordered stream of frames within a track.\n *\n * Created internally: obtain one from {@link Producer.consume} or a track subscriber's\n * group reads.\n *\n * @public\n */\nexport class Consumer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\n\tprivate constructor(state: GroupState) {\n\t\tthis.#state = state;\n\t\tthis.sequence = state.sequence;\n\t}\n\n\t/**\n\t * Settles once the group 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\tstatic {\n\t\tmakeConsumer = (state) => new Consumer(state);\n\t}\n\n\t#readBufferedFrame(): { sequence: number; frame: Frame } | undefined {\n\t\tconst frames = this.#state.frames.peek();\n\t\tconst frame = frames.shift();\n\t\tif (!frame) return undefined;\n\n\t\tthis.#state.cacheBytes -= frame.payload.byteLength;\n\t\treturn { sequence: this.#state.total.peek() - frames.length - 1, frame };\n\t}\n\n\t/** True once no further frames can be read: the group has closed and every buffered frame is read. */\n\tget done(): boolean {\n\t\treturn this.#state.frames.peek().length === 0 && this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** True once the group has been closed, regardless of whether buffered frames remain unread. Synchronous complement to the {@link closed} promise. */\n\tget isClosed(): boolean {\n\t\treturn this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** True if frames were evicted from the front of this group before being read. */\n\tget skipped(): boolean {\n\t\treturn this.#state.offset > 0;\n\t}\n\n\t/**\n\t * Reads the next already-buffered frame without blocking.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t *\n\t * Returns `undefined` when nothing is buffered right now. That is not by itself\n\t * end-of-group: check {@link done} to tell \"no frame buffered yet\" from \"finished\".\n\t */\n\ttryReadFrame(): Frame | undefined {\n\t\tconst read = this.#readBufferedFrame();\n\t\treturn read?.frame;\n\t}\n\n\t/** Like {@link tryReadFrame} but also reports the frame's sequence number within the group. */\n\ttryReadFrameSequence(): ({ sequence: number } & Frame) | undefined {\n\t\tconst read = this.#readBufferedFrame();\n\t\tif (!read) return undefined;\n\t\treturn { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\n\t}\n\n\t/** Resolves once {@link readFrame} would not block. */\n\tasync readable(): Promise<void> {\n\t\tfor (;;) {\n\t\t\tif (this.#state.frames.peek().length > 0) return;\n\t\t\tif (this.#state.closed.peek() !== undefined) return;\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame from the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrame(): Promise<Frame | undefined> {\n\t\tfor (;;) {\n\t\t\tif (this.#state.offset > 0) throw new Lagged();\n\n\t\t\tconst read = this.#readBufferedFrame();\n\t\t\tif (read) return read.frame;\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;\n\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame along with its sequence number within the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrameSequence(): Promise<({ sequence: number } & Frame) | undefined> {\n\t\tfor (;;) {\n\t\t\tif (this.#state.offset > 0) throw new Lagged();\n\n\t\t\tconst read = this.#readBufferedFrame();\n\t\t\tif (read) return { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\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;\n\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Reads the next frame and decodes its payload as a UTF-8 string. */\n\tasync readString(): Promise<string | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? new TextDecoder().decode(frame.payload) : undefined;\n\t}\n\n\t/** Reads the next frame and parses its payload as JSON. */\n\tasync readJson(): Promise<unknown | undefined> {\n\t\tconst frame = await this.readString();\n\t\treturn frame ? JSON.parse(frame) : undefined;\n\t}\n\n\t/** Reads the next frame and decodes its payload as a one-byte boolean. */\n\tasync readBool(): Promise<boolean | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? frame.payload[0] === 1 : undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. Idempotent. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return; // already closed\n\t\tthis.#state.closed.set(abort ?? null);\n\t}\n}\n"]}