@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.
- package/announced.d.ts +40 -24
- package/announced.d.ts.map +1 -1
- package/announced.js +74 -40
- package/announced.js.map +1 -1
- package/announced.test.d.ts +2 -0
- package/announced.test.d.ts.map +1 -0
- package/announced.test.js +37 -0
- package/announced.test.js.map +1 -0
- package/broadcast.d.ts +80 -25
- package/broadcast.d.ts.map +1 -1
- package/broadcast.js +266 -49
- package/broadcast.js.map +1 -1
- package/broadcast.test.d.ts +2 -0
- package/broadcast.test.d.ts.map +1 -0
- package/broadcast.test.js +219 -0
- package/broadcast.test.js.map +1 -0
- package/connection/accept.d.ts +6 -0
- package/connection/accept.d.ts.map +1 -1
- package/connection/accept.js +30 -10
- package/connection/accept.js.map +1 -1
- package/connection/browser.d.ts +5 -0
- package/connection/browser.d.ts.map +1 -0
- package/connection/browser.js +25 -0
- package/connection/browser.js.map +1 -0
- package/connection/browser.test.d.ts +2 -0
- package/connection/browser.test.d.ts.map +1 -0
- package/connection/browser.test.js +29 -0
- package/connection/browser.test.js.map +1 -0
- package/connection/connect.d.ts +43 -1
- package/connection/connect.d.ts.map +1 -1
- package/connection/connect.js +96 -107
- package/connection/connect.js.map +1 -1
- package/connection/connect.test.d.ts +2 -0
- package/connection/connect.test.d.ts.map +1 -0
- package/connection/connect.test.js +118 -0
- package/connection/connect.test.js.map +1 -0
- package/connection/established.d.ts +29 -15
- package/connection/established.d.ts.map +1 -1
- package/connection/established.js.map +1 -1
- package/connection/index.d.ts +8 -0
- package/connection/index.d.ts.map +1 -1
- package/connection/index.js +6 -0
- package/connection/index.js.map +1 -1
- package/connection/reload.d.ts +43 -7
- package/connection/reload.d.ts.map +1 -1
- package/connection/reload.js +159 -62
- package/connection/reload.js.map +1 -1
- package/connection/reload.test.js +65 -0
- package/connection/reload.test.js.map +1 -1
- package/connection/stats.d.ts +92 -0
- package/connection/stats.d.ts.map +1 -0
- package/connection/stats.js +35 -0
- package/connection/stats.js.map +1 -0
- package/connection/stats.test.d.ts +2 -0
- package/connection/stats.test.d.ts.map +1 -0
- package/connection/stats.test.js +120 -0
- package/connection/stats.test.js.map +1 -0
- package/connection/transport.d.ts +10 -0
- package/connection/transport.d.ts.map +1 -0
- package/connection/transport.js +12 -0
- package/connection/transport.js.map +1 -0
- package/consume.d.ts +26 -0
- package/consume.d.ts.map +1 -0
- package/consume.js +40 -0
- package/consume.js.map +1 -0
- package/datagram.d.ts +23 -0
- package/datagram.d.ts.map +1 -0
- package/datagram.js +3 -0
- package/datagram.js.map +1 -0
- package/error.d.ts +62 -0
- package/error.d.ts.map +1 -0
- package/error.js +92 -0
- package/error.js.map +1 -0
- package/error.test.d.ts +2 -0
- package/error.test.d.ts.map +1 -0
- package/error.test.js +89 -0
- package/error.test.js.map +1 -0
- package/group.d.ts +125 -36
- package/group.d.ts.map +1 -1
- package/group.js +244 -67
- package/group.js.map +1 -1
- package/group.test.js +121 -35
- package/group.test.js.map +1 -1
- package/ietf/adapter.d.ts +2 -2
- package/ietf/adapter.d.ts.map +1 -1
- package/ietf/adapter.js +15 -5
- package/ietf/adapter.js.map +1 -1
- package/ietf/connection.d.ts +19 -6
- package/ietf/connection.d.ts.map +1 -1
- package/ietf/connection.js +23 -8
- package/ietf/connection.js.map +1 -1
- package/ietf/ietf.test.js +58 -1
- package/ietf/ietf.test.js.map +1 -1
- package/ietf/object.d.ts +12 -4
- package/ietf/object.d.ts.map +1 -1
- package/ietf/object.js +92 -9
- package/ietf/object.js.map +1 -1
- package/ietf/publisher.d.ts +2 -2
- package/ietf/publisher.d.ts.map +1 -1
- package/ietf/publisher.js +12 -12
- package/ietf/publisher.js.map +1 -1
- package/ietf/subscribe_namespace.d.ts +0 -4
- package/ietf/subscribe_namespace.d.ts.map +1 -1
- package/ietf/subscribe_namespace.js +0 -5
- package/ietf/subscribe_namespace.js.map +1 -1
- package/ietf/subscriber.d.ts +8 -4
- package/ietf/subscriber.d.ts.map +1 -1
- package/ietf/subscriber.js +171 -93
- package/ietf/subscriber.js.map +1 -1
- package/index.d.ts +10 -5
- package/index.d.ts.map +1 -1
- package/index.js +10 -5
- package/index.js.map +1 -1
- package/integration.test.js +634 -12
- package/integration.test.js.map +1 -1
- package/internal.d.ts +14 -0
- package/internal.d.ts.map +1 -0
- package/internal.js +8 -0
- package/internal.js.map +1 -0
- package/lite/announce.d.ts +55 -13
- package/lite/announce.d.ts.map +1 -1
- package/lite/announce.js +221 -68
- package/lite/announce.js.map +1 -1
- package/lite/announce.test.d.ts +2 -0
- package/lite/announce.test.d.ts.map +1 -0
- package/lite/announce.test.js +71 -0
- package/lite/announce.test.js.map +1 -0
- package/lite/connection.d.ts +45 -19
- package/lite/connection.d.ts.map +1 -1
- package/lite/connection.js +85 -80
- package/lite/connection.js.map +1 -1
- package/lite/datagram.d.ts +23 -0
- package/lite/datagram.d.ts.map +1 -0
- package/lite/datagram.js +57 -0
- package/lite/datagram.js.map +1 -0
- package/lite/datagram.test.d.ts +2 -0
- package/lite/datagram.test.d.ts.map +1 -0
- package/lite/datagram.test.js +26 -0
- package/lite/datagram.test.js.map +1 -0
- package/lite/datagram_stream.d.ts +8 -0
- package/lite/datagram_stream.d.ts.map +1 -0
- package/lite/datagram_stream.js +44 -0
- package/lite/datagram_stream.js.map +1 -0
- package/lite/datagram_stream.test.d.ts +2 -0
- package/lite/datagram_stream.test.d.ts.map +1 -0
- package/lite/datagram_stream.test.js +15 -0
- package/lite/datagram_stream.test.js.map +1 -0
- package/lite/fetch.d.ts.map +1 -1
- package/lite/fetch.js +2 -2
- package/lite/fetch.js.map +1 -1
- package/lite/fetch.test.d.ts +2 -0
- package/lite/fetch.test.d.ts.map +1 -0
- package/lite/fetch.test.js +41 -0
- package/lite/fetch.test.js.map +1 -0
- package/lite/index.d.ts +3 -0
- package/lite/index.d.ts.map +1 -1
- package/lite/index.js +3 -0
- package/lite/index.js.map +1 -1
- package/lite/publisher.d.ts +13 -6
- package/lite/publisher.d.ts.map +1 -1
- package/lite/publisher.js +274 -64
- package/lite/publisher.js.map +1 -1
- package/lite/publisher.test.d.ts +2 -0
- package/lite/publisher.test.d.ts.map +1 -0
- package/lite/publisher.test.js +65 -0
- package/lite/publisher.test.js.map +1 -0
- package/lite/setup.d.ts +72 -6
- package/lite/setup.d.ts.map +1 -1
- package/lite/setup.js +184 -31
- package/lite/setup.js.map +1 -1
- package/lite/setup.test.d.ts +2 -0
- package/lite/setup.test.d.ts.map +1 -0
- package/lite/setup.test.js +122 -0
- package/lite/setup.test.js.map +1 -0
- package/lite/stream.d.ts +12 -3
- package/lite/stream.d.ts.map +1 -1
- package/lite/stream.js +7 -4
- package/lite/stream.js.map +1 -1
- package/lite/subscribe.d.ts +37 -23
- package/lite/subscribe.d.ts.map +1 -1
- package/lite/subscribe.js +70 -55
- package/lite/subscribe.js.map +1 -1
- package/lite/subscribe.test.d.ts +2 -0
- package/lite/subscribe.test.d.ts.map +1 -0
- package/lite/subscribe.test.js +68 -0
- package/lite/subscribe.test.js.map +1 -0
- package/lite/subscriber.d.ts +24 -17
- package/lite/subscriber.d.ts.map +1 -1
- package/lite/subscriber.js +515 -90
- package/lite/subscriber.js.map +1 -1
- package/lite/subscriber.test.js +2 -2
- package/lite/subscriber.test.js.map +1 -1
- package/lite/track.d.ts +25 -13
- package/lite/track.d.ts.map +1 -1
- package/lite/track.js +60 -35
- package/lite/track.js.map +1 -1
- package/lite/track.test.js +12 -10
- package/lite/track.test.js.map +1 -1
- package/lite/version.d.ts +17 -4
- package/lite/version.d.ts.map +1 -1
- package/lite/version.js +88 -17
- package/lite/version.js.map +1 -1
- package/mock.d.ts +42 -3
- package/mock.d.ts.map +1 -1
- package/mock.js +88 -17
- package/mock.js.map +1 -1
- package/package.json +3 -3
- package/path.d.ts +30 -0
- package/path.d.ts.map +1 -1
- package/path.js +49 -0
- package/path.js.map +1 -1
- package/path.test.js +41 -0
- package/path.test.js.map +1 -1
- package/stream.d.ts.map +1 -1
- package/stream.js +25 -4
- package/stream.js.map +1 -1
- package/stream.test.js +42 -0
- package/stream.test.js.map +1 -1
- package/time.d.ts +109 -86
- package/time.d.ts.map +1 -1
- package/time.js +80 -30
- package/time.js.map +1 -1
- package/time.test.d.ts +2 -0
- package/time.test.d.ts.map +1 -0
- package/time.test.js +12 -0
- package/time.test.js.map +1 -0
- package/track.d.ts +225 -45
- package/track.d.ts.map +1 -1
- package/track.js +505 -93
- package/track.js.map +1 -1
- package/track.test.js +138 -29
- package/track.test.js.map +1 -1
- package/util/timeout.d.ts +5 -0
- package/util/timeout.d.ts.map +1 -0
- package/util/timeout.js +18 -0
- package/util/timeout.js.map +1 -0
- package/util/timeout.test.d.ts +2 -0
- package/util/timeout.test.d.ts.map +1 -0
- package/util/timeout.test.js +18 -0
- package/util/timeout.test.js.map +1 -0
- package/varint.d.ts +6 -0
- package/varint.d.ts.map +1 -1
- package/varint.js +6 -2
- package/varint.js.map +1 -1
- package/zod.d.ts +4 -4
- package/zod.d.ts.map +1 -1
- package/zod.js.map +1 -1
- package/bandwidth.d.ts +0 -11
- package/bandwidth.d.ts.map +0 -1
- package/bandwidth.js +0 -7
- package/bandwidth.js.map +0 -1
- package/util/error.d.ts +0 -3
- package/util/error.d.ts.map +0 -1
- package/util/error.js +0 -9
- package/util/error.js.map +0 -1
- package/util/index.d.ts +0 -2
- package/util/index.d.ts.map +0 -1
- package/util/index.js +0 -3
- package/util/index.js.map +0 -1
package/group.js
CHANGED
|
@@ -1,136 +1,313 @@
|
|
|
1
1
|
/* @ts-self-types="./group.d.ts" */
|
|
2
|
-
|
|
3
|
-
|
|
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
|
|
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
|
-
/**
|
|
10
|
-
|
|
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
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
*
|
|
32
|
-
*
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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() !==
|
|
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
|
|
62
|
-
* check {@link done} to tell "no frame buffered yet"
|
|
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
|
-
|
|
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
|
|
72
|
-
|
|
73
|
-
if (data === undefined)
|
|
238
|
+
const read = this.#readBufferedFrame();
|
|
239
|
+
if (!read)
|
|
74
240
|
return undefined;
|
|
75
|
-
return { sequence:
|
|
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
|
-
*
|
|
255
|
+
* Treat the returned frame bytes as read-only; they are shared with other consumers.
|
|
97
256
|
*/
|
|
98
257
|
async readFrame() {
|
|
99
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
|
113
|
-
await this.
|
|
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
|
|
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
|
|
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
|
|
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.
|
|
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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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,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AG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACpE,CAAC;IAED,2DAA2D;IAC3D,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,0EAA0E;IAC1E,KAAK,CAAC,QAAQ;QACb,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnD,CAAC;IAED,+EAA+E;IAC/E,KAAK,CAAC,KAAa;QAClB,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,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"]}
|
package/group.test.js
CHANGED
|
@@ -1,42 +1,128 @@
|
|
|
1
1
|
/* @ts-self-types="./group.test.d.ts" */
|
|
2
2
|
import { expect, test } from "bun:test";
|
|
3
|
-
import {
|
|
3
|
+
import { Lagged, MAX_GROUP_CACHE_BYTES, MAX_GROUP_FRAMES, Producer } from "./group.js";
|
|
4
|
+
import { Timestamp } from "./time.js";
|
|
4
5
|
const dec = new TextDecoder();
|
|
6
|
+
test("used reflects mirror demand and unused resolves when the last reader leaves", async () => {
|
|
7
|
+
const producer = new Producer(0);
|
|
8
|
+
// No mirror readers: no demand.
|
|
9
|
+
expect(producer.used.peek()).toBe(false);
|
|
10
|
+
const a = producer.mirror();
|
|
11
|
+
const b = producer.mirror();
|
|
12
|
+
expect(producer.used.peek()).toBe(true);
|
|
13
|
+
// Closing one of two keeps demand, so unused() stays pending.
|
|
14
|
+
a.close();
|
|
15
|
+
expect(producer.used.peek()).toBe(true);
|
|
16
|
+
// Closing the last reader drops demand; unused() resolves. Fetch coalescing awaits this to
|
|
17
|
+
// cancel a download that everyone has abandoned (a group may never end on its own).
|
|
18
|
+
b.close();
|
|
19
|
+
await producer.unused();
|
|
20
|
+
expect(producer.used.peek()).toBe(false);
|
|
21
|
+
});
|
|
22
|
+
function pair(sequence) {
|
|
23
|
+
const producer = new Producer(sequence);
|
|
24
|
+
return { producer, consumer: producer.consume() };
|
|
25
|
+
}
|
|
26
|
+
test("a group caps its frame count, dropping from the front", () => {
|
|
27
|
+
const { producer, consumer } = pair(0);
|
|
28
|
+
const extra = 100;
|
|
29
|
+
for (let i = 0; i < MAX_GROUP_FRAMES + extra; i++) {
|
|
30
|
+
producer.writeFrame({ payload: new Uint8Array([i & 0xff]), timestamp: Timestamp.now() });
|
|
31
|
+
}
|
|
32
|
+
// Drain the buffered frames: exactly MAX_GROUP_FRAMES remain after eviction.
|
|
33
|
+
const frames = [];
|
|
34
|
+
for (let f = consumer.tryReadFrameSequence(); f; f = consumer.tryReadFrameSequence())
|
|
35
|
+
frames.push(f);
|
|
36
|
+
expect(frames.length).toBe(MAX_GROUP_FRAMES);
|
|
37
|
+
// Sequence numbers count every frame ever written (evicted included), so the first surviving
|
|
38
|
+
// frame is index `extra`, not 0: indices stay consistent across eviction.
|
|
39
|
+
expect(frames[0].sequence).toBe(extra);
|
|
40
|
+
expect(frames[0].payload[0]).toBe(extra & 0xff);
|
|
41
|
+
});
|
|
42
|
+
test("a group caps its byte size, dropping from the front", () => {
|
|
43
|
+
const { producer, consumer } = pair(0);
|
|
44
|
+
// 40 x 1 MiB = 40 MiB, over the 32 MiB cap.
|
|
45
|
+
const oneMiB = 1024 * 1024;
|
|
46
|
+
for (let i = 0; i < 40; i++) {
|
|
47
|
+
producer.writeFrame({ payload: new Uint8Array(oneMiB), timestamp: Timestamp.now() });
|
|
48
|
+
}
|
|
49
|
+
// Drain the buffered frames and sum their bytes: the cache stayed under the byte cap.
|
|
50
|
+
const frames = [];
|
|
51
|
+
for (let f = consumer.tryReadFrame(); f; f = consumer.tryReadFrame())
|
|
52
|
+
frames.push(f.payload);
|
|
53
|
+
const bytes = frames.reduce((sum, f) => sum + f.byteLength, 0);
|
|
54
|
+
expect(bytes).toBeLessThanOrEqual(MAX_GROUP_CACHE_BYTES);
|
|
55
|
+
expect(frames.length).toBe(MAX_GROUP_CACHE_BYTES / oneMiB);
|
|
56
|
+
});
|
|
57
|
+
test("a caught-up reader does not trip the byte cache cap", async () => {
|
|
58
|
+
const { producer, consumer } = pair(0);
|
|
59
|
+
const oneMiB = 1024 * 1024;
|
|
60
|
+
const frames = MAX_GROUP_CACHE_BYTES / oneMiB + 8;
|
|
61
|
+
for (let i = 0; i < frames; i++) {
|
|
62
|
+
producer.writeFrame({ payload: new Uint8Array(oneMiB), timestamp: Timestamp.now() });
|
|
63
|
+
expect((await consumer.readFrame())?.payload.byteLength).toBe(oneMiB);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
test("reading a group whose frames were evicted throws Lagged", async () => {
|
|
67
|
+
const { producer, consumer } = pair(0);
|
|
68
|
+
// Overflow the frame cap without reading, so the front frames are evicted.
|
|
69
|
+
for (let i = 0; i < MAX_GROUP_FRAMES + 10; i++) {
|
|
70
|
+
producer.writeFrame({ payload: new Uint8Array([i & 0xff]), timestamp: Timestamp.now() });
|
|
71
|
+
}
|
|
72
|
+
// The reader fell behind the eviction window: it must error, not skip the gap.
|
|
73
|
+
expect(consumer.readFrame()).rejects.toBeInstanceOf(Lagged);
|
|
74
|
+
});
|
|
75
|
+
test("a group with no eviction reads every frame without error", async () => {
|
|
76
|
+
const { producer, consumer } = pair(0);
|
|
77
|
+
producer.writeFrame({ payload: new Uint8Array([1]), timestamp: Timestamp.now() });
|
|
78
|
+
producer.writeFrame({ payload: new Uint8Array([2]), timestamp: Timestamp.now() });
|
|
79
|
+
producer.close();
|
|
80
|
+
expect((await consumer.readFrame())?.payload[0]).toBe(1);
|
|
81
|
+
expect((await consumer.readFrame())?.payload[0]).toBe(2);
|
|
82
|
+
expect(await consumer.readFrame()).toBeUndefined();
|
|
83
|
+
});
|
|
5
84
|
test("tryReadFrame drains buffered frames then returns undefined", () => {
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
expect(dec.decode(
|
|
10
|
-
expect(dec.decode(
|
|
85
|
+
const { producer, consumer } = pair(0);
|
|
86
|
+
producer.writeString("a");
|
|
87
|
+
producer.writeString("b");
|
|
88
|
+
expect(dec.decode(consumer.tryReadFrame()?.payload)).toBe("a");
|
|
89
|
+
expect(dec.decode(consumer.tryReadFrame()?.payload)).toBe("b");
|
|
11
90
|
// Nothing buffered: undefined, and the group is not closed so this is not end-of-group.
|
|
12
|
-
expect(
|
|
91
|
+
expect(consumer.tryReadFrame()).toBeUndefined();
|
|
13
92
|
});
|
|
14
93
|
test("tryReadFrameSequence reports per-frame sequence numbers", () => {
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
expect(
|
|
19
|
-
expect(
|
|
20
|
-
expect(
|
|
94
|
+
const { producer, consumer } = pair(7);
|
|
95
|
+
producer.writeString("a");
|
|
96
|
+
producer.writeString("b");
|
|
97
|
+
expect(consumer.tryReadFrameSequence()).toMatchObject({ sequence: 0, payload: new TextEncoder().encode("a") });
|
|
98
|
+
expect(consumer.tryReadFrameSequence()).toMatchObject({ sequence: 1, payload: new TextEncoder().encode("b") });
|
|
99
|
+
expect(consumer.tryReadFrameSequence()).toBeUndefined();
|
|
100
|
+
});
|
|
101
|
+
test("readFrameSequence reports per-frame sequence numbers", async () => {
|
|
102
|
+
const { producer, consumer } = pair(7);
|
|
103
|
+
producer.writeString("a");
|
|
104
|
+
producer.writeString("b");
|
|
105
|
+
expect(await consumer.readFrameSequence()).toMatchObject({ sequence: 0, payload: new TextEncoder().encode("a") });
|
|
106
|
+
expect(await consumer.readFrameSequence()).toMatchObject({ sequence: 1, payload: new TextEncoder().encode("b") });
|
|
21
107
|
});
|
|
22
108
|
test("done distinguishes a finished group from one that is merely empty", () => {
|
|
23
|
-
const
|
|
109
|
+
const { producer, consumer } = pair(0);
|
|
24
110
|
// Open and empty: not done (more frames may arrive), and tryReadFrame is undefined.
|
|
25
|
-
expect(
|
|
26
|
-
expect(
|
|
27
|
-
|
|
111
|
+
expect(consumer.tryReadFrame()).toBeUndefined();
|
|
112
|
+
expect(consumer.done).toBe(false);
|
|
113
|
+
producer.writeString("a");
|
|
28
114
|
// Buffered but closed: still not done until the frame is drained.
|
|
29
|
-
|
|
30
|
-
expect(
|
|
31
|
-
|
|
115
|
+
producer.close();
|
|
116
|
+
expect(consumer.done).toBe(false);
|
|
117
|
+
consumer.tryReadFrame();
|
|
32
118
|
// Drained and closed: now done.
|
|
33
|
-
expect(
|
|
34
|
-
expect(
|
|
119
|
+
expect(consumer.tryReadFrame()).toBeUndefined();
|
|
120
|
+
expect(consumer.done).toBe(true);
|
|
35
121
|
});
|
|
36
122
|
test("readable resolves once a frame is buffered", async () => {
|
|
37
|
-
const
|
|
123
|
+
const { producer, consumer } = pair(0);
|
|
38
124
|
// No frame yet: readable() must stay pending for an empty, open group.
|
|
39
|
-
const readable =
|
|
125
|
+
const readable = consumer.readable();
|
|
40
126
|
let settled = false;
|
|
41
127
|
void readable.then(() => {
|
|
42
128
|
settled = true;
|
|
@@ -44,23 +130,23 @@ test("readable resolves once a frame is buffered", async () => {
|
|
|
44
130
|
await Promise.resolve();
|
|
45
131
|
expect(settled).toBe(false);
|
|
46
132
|
// Writing makes it resolve.
|
|
47
|
-
|
|
133
|
+
producer.writeString("hi");
|
|
48
134
|
await readable; // must not hang
|
|
49
|
-
expect(dec.decode(
|
|
135
|
+
expect(dec.decode(consumer.tryReadFrame()?.payload)).toBe("hi");
|
|
50
136
|
});
|
|
51
137
|
test("readable resolves once the group closes, even with nothing buffered", async () => {
|
|
52
|
-
const
|
|
53
|
-
const readable =
|
|
54
|
-
|
|
138
|
+
const { producer, consumer } = pair(0);
|
|
139
|
+
const readable = consumer.readable();
|
|
140
|
+
producer.close();
|
|
55
141
|
await readable; // resolves on close so callers don't wait forever
|
|
56
|
-
expect(
|
|
142
|
+
expect(consumer.tryReadFrame()).toBeUndefined();
|
|
57
143
|
});
|
|
58
144
|
test("buffered frames are still readable after the group closes", async () => {
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
145
|
+
const { producer, consumer } = pair(0);
|
|
146
|
+
producer.writeString("a");
|
|
147
|
+
producer.close();
|
|
62
148
|
// Closing doesn't discard buffered frames; the blocking reader drains them before ending.
|
|
63
|
-
expect(await
|
|
64
|
-
expect(await
|
|
149
|
+
expect(await consumer.readString()).toBe("a");
|
|
150
|
+
expect(await consumer.readFrame()).toBeUndefined();
|
|
65
151
|
});
|
|
66
152
|
//# sourceMappingURL=group.test.js.map
|