moqtail 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/client-BzncAN14.mjs +4359 -0
- package/dist/client-DahXR3l4.cjs +4496 -0
- package/dist/client.cjs +25 -8254
- package/dist/client.d.cts +1333 -1470
- package/dist/client.d.mts +1706 -0
- package/dist/client.mjs +2 -0
- package/dist/index-C8pNnaj0.d.cts +2814 -0
- package/dist/index-C8pNnaj0.d.mts +2814 -0
- package/dist/index.cjs +284 -8975
- package/dist/index.d.cts +5 -5
- package/dist/index.d.mts +5 -0
- package/dist/index.mjs +5 -0
- package/dist/logger-ByDB8lYF.mjs +56 -0
- package/dist/logger-c2NoQqtx.cjs +85 -0
- package/dist/{logger-C6QS408Z.d.cts → logger-dEoueCj7.d.cts} +13 -12
- package/dist/{logger-C6QS408Z.d.ts → logger-dEoueCj7.d.mts} +13 -12
- package/dist/model.cjs +6173 -4883
- package/dist/model.d.cts +2 -442
- package/dist/model.d.mts +2 -0
- package/dist/model.mjs +6115 -0
- package/dist/util.cjs +123 -142
- package/dist/util.d.cts +29 -24
- package/dist/{util.d.ts → util.d.mts} +29 -24
- package/dist/util.mjs +121 -0
- package/package.json +19 -18
- package/dist/client.d.ts +0 -1843
- package/dist/client.js +0 -8233
- package/dist/index.d.ts +0 -5
- package/dist/index.js +0 -8825
- package/dist/model.d.ts +0 -442
- package/dist/model.js +0 -4951
- package/dist/setup_parameter-BgNrJRDS.d.cts +0 -2758
- package/dist/setup_parameter-BgNrJRDS.d.ts +0 -2758
- package/dist/util.js +0 -139
|
@@ -0,0 +1,4496 @@
|
|
|
1
|
+
const require_model = require("./model.cjs");
|
|
2
|
+
const require_logger = require("./logger-c2NoQqtx.cjs");
|
|
3
|
+
//#region src/client/control_stream.ts
|
|
4
|
+
/**
|
|
5
|
+
* Copyright 2025 The MOQtail Authors
|
|
6
|
+
*
|
|
7
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
* you may not use this file except in compliance with the License.
|
|
9
|
+
* You may obtain a copy of the License at
|
|
10
|
+
*
|
|
11
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
*
|
|
13
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
* See the License for the specific language governing permissions and
|
|
17
|
+
* limitations under the License.
|
|
18
|
+
*/
|
|
19
|
+
function withTimeout$1(promise, ms, errorMsg) {
|
|
20
|
+
if (ms === void 0) return promise;
|
|
21
|
+
let timeoutId;
|
|
22
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
23
|
+
timeoutId = setTimeout(() => reject(new require_model.TimeoutError(errorMsg ?? `Timeout after ${ms}ms`)), ms);
|
|
24
|
+
});
|
|
25
|
+
return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timeoutId));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Send half of the control plane: a unidirectional stream this endpoint opens and
|
|
29
|
+
* whose first message must be SETUP.
|
|
30
|
+
*/
|
|
31
|
+
var ControlSendStream = class {
|
|
32
|
+
#writer;
|
|
33
|
+
onMessageSent;
|
|
34
|
+
constructor(writeStream, onMessageSent) {
|
|
35
|
+
this.#writer = writeStream.getWriter();
|
|
36
|
+
if (onMessageSent) this.onMessageSent = onMessageSent;
|
|
37
|
+
}
|
|
38
|
+
async send(message) {
|
|
39
|
+
const msgName = message.constructor.name;
|
|
40
|
+
try {
|
|
41
|
+
const serializedMessage = require_model.ControlMessage.serialize(message);
|
|
42
|
+
require_logger.logger.debug("control_stream", `send: waiting for writer.ready — ${msgName} (${serializedMessage.length}B)`);
|
|
43
|
+
await this.#writer.ready;
|
|
44
|
+
require_logger.logger.debug("control_stream", `send: writer ready, writing — ${msgName}`);
|
|
45
|
+
await this.#writer.write(serializedMessage.toUint8Array());
|
|
46
|
+
require_logger.logger.debug("control_stream", `send: write complete — ${msgName}`);
|
|
47
|
+
if (this.onMessageSent) this.onMessageSent(message);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
50
|
+
require_logger.logger.error("control_stream", `send: failed to write ${msgName} — ${errorMessage}`);
|
|
51
|
+
await this.close();
|
|
52
|
+
throw new require_model.TerminationError(`ControlStream.send: Failed to write message: ${errorMessage}`, 1);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async close() {
|
|
56
|
+
require_logger.logger.debug("control_stream", "close: closing writer");
|
|
57
|
+
await this.#writer.close().catch(() => {});
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Receive half of the control plane: the unidirectional stream the peer opens,
|
|
62
|
+
* whose first message must be SETUP.
|
|
63
|
+
*/
|
|
64
|
+
var ControlRecvStream = class {
|
|
65
|
+
stream;
|
|
66
|
+
#receiveBuffer;
|
|
67
|
+
#expectedPayloadLength = null;
|
|
68
|
+
#partialMessageTimeoutMs;
|
|
69
|
+
#reader;
|
|
70
|
+
onMessageReceived;
|
|
71
|
+
constructor(readStream, partialMessageTimeoutMs, onMessageReceived) {
|
|
72
|
+
this.#receiveBuffer = new require_model.ByteBuffer();
|
|
73
|
+
this.#partialMessageTimeoutMs = partialMessageTimeoutMs;
|
|
74
|
+
this.#reader = readStream.getReader();
|
|
75
|
+
if (onMessageReceived) this.onMessageReceived = onMessageReceived;
|
|
76
|
+
this.stream = new ReadableStream({
|
|
77
|
+
start: (controller) => this.#ingestLoop(controller),
|
|
78
|
+
cancel: () => this.close()
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async close() {
|
|
82
|
+
require_logger.logger.debug("control_stream", "close: cancelling reader");
|
|
83
|
+
await this.#reader.cancel().catch(() => {});
|
|
84
|
+
}
|
|
85
|
+
async #ingestLoop(controller) {
|
|
86
|
+
require_logger.logger.debug("control_stream", "ingestLoop: started");
|
|
87
|
+
try {
|
|
88
|
+
while (true) {
|
|
89
|
+
if (this.#receiveBuffer.length === 0) {
|
|
90
|
+
require_logger.logger.debug("control_stream", "ingestLoop: buffer empty, awaiting reader.read()");
|
|
91
|
+
const readResult = await this.#reader.read();
|
|
92
|
+
this.#handleReadResult(readResult);
|
|
93
|
+
if (readResult.done) {
|
|
94
|
+
require_logger.logger.debug("control_stream", "ingestLoop: reader done (stream closed by peer)");
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
require_logger.logger.debug("control_stream", `ingestLoop: received ${readResult.value?.byteLength ?? 0}B chunk`);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
this.#receiveBuffer.checkpoint();
|
|
102
|
+
const startOffset = this.#receiveBuffer.offset;
|
|
103
|
+
this.#receiveBuffer.getVI();
|
|
104
|
+
const payloadLength = this.#receiveBuffer.getU16();
|
|
105
|
+
const totalMessageSize = this.#receiveBuffer.offset - startOffset + payloadLength;
|
|
106
|
+
this.#receiveBuffer.restore();
|
|
107
|
+
if (this.#receiveBuffer.length >= totalMessageSize) {
|
|
108
|
+
const messageBytes = this.#receiveBuffer.getBytes(totalMessageSize);
|
|
109
|
+
this.#receiveBuffer.commit();
|
|
110
|
+
this.#expectedPayloadLength = null;
|
|
111
|
+
const msg = require_model.ControlMessage.deserialize(new require_model.FrozenByteBuffer(messageBytes));
|
|
112
|
+
require_logger.logger.debug("control_stream", `ingestLoop: deserialized ${msg.constructor.name} (${totalMessageSize}B)`);
|
|
113
|
+
controller.enqueue(msg);
|
|
114
|
+
if (this.onMessageReceived) this.onMessageReceived(msg);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
this.#expectedPayloadLength = payloadLength;
|
|
118
|
+
require_logger.logger.debug("control_stream", `ingestLoop: partial message — have ${this.#receiveBuffer.length}B, need ${totalMessageSize}B, awaiting more data`);
|
|
119
|
+
const timeoutMessage = `ControlStream: Timeout waiting for partial message data (expected ${payloadLength} bytes)`;
|
|
120
|
+
let readResult;
|
|
121
|
+
if (this.#partialMessageTimeoutMs !== void 0) readResult = await withTimeout$1(this.#reader.read(), this.#partialMessageTimeoutMs, timeoutMessage);
|
|
122
|
+
else readResult = await this.#reader.read();
|
|
123
|
+
this.#handleReadResult(readResult);
|
|
124
|
+
if (readResult.done) {
|
|
125
|
+
require_logger.logger.debug("control_stream", "ingestLoop: reader done while waiting for partial message");
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
} catch (error) {
|
|
129
|
+
if (error instanceof require_model.NotEnoughBytesError) {
|
|
130
|
+
require_logger.logger.debug("control_stream", "ingestLoop: not enough bytes for header, awaiting more data");
|
|
131
|
+
let readResult;
|
|
132
|
+
if (this.#partialMessageTimeoutMs !== void 0) readResult = await withTimeout$1(this.#reader.read(), this.#partialMessageTimeoutMs, "ControlStream: Timeout waiting for message header");
|
|
133
|
+
else readResult = await this.#reader.read();
|
|
134
|
+
this.#handleReadResult(readResult);
|
|
135
|
+
if (readResult.done) {
|
|
136
|
+
require_logger.logger.debug("control_stream", "ingestLoop: reader done while waiting for header");
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
} else {
|
|
140
|
+
require_logger.logger.error("control_stream", `ingestLoop: deserialization error — ${error.message}`);
|
|
141
|
+
controller.error(new require_model.TerminationError(`ControlStream: Deserialization error: ${error.message}`, 3));
|
|
142
|
+
await this.close();
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
} catch (error) {
|
|
148
|
+
require_logger.logger.error("control_stream", `ingestLoop: unexpected error — ${error instanceof Error ? error.message : String(error)}`);
|
|
149
|
+
controller.error(error);
|
|
150
|
+
await this.close();
|
|
151
|
+
} finally {
|
|
152
|
+
require_logger.logger.debug("control_stream", "ingestLoop: ended, closing controller");
|
|
153
|
+
controller.close();
|
|
154
|
+
await this.close();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
#handleReadResult(readResult) {
|
|
158
|
+
if (readResult.done) {
|
|
159
|
+
if (this.#receiveBuffer.length > 0 || this.#expectedPayloadLength !== null) {
|
|
160
|
+
require_logger.logger.error("control_stream", `handleReadResult: peer closed stream with incomplete data — bufferLen=${this.#receiveBuffer.length} expectedPayload=${this.#expectedPayloadLength}`);
|
|
161
|
+
throw new require_model.TerminationError("ControlStream: Stream closed by peer with incomplete message data.", 3);
|
|
162
|
+
}
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (readResult.value) {
|
|
166
|
+
this.#receiveBuffer.putBytes(readResult.value);
|
|
167
|
+
require_logger.logger.debug("control_stream", `handleReadResult: appended ${readResult.value.byteLength}B — bufferLen=${this.#receiveBuffer.length}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* The control plane as a whole: the two independent unidirectional halves opened by
|
|
173
|
+
* each endpoint.
|
|
174
|
+
*/
|
|
175
|
+
var ControlStream = class {
|
|
176
|
+
stream;
|
|
177
|
+
#sendHalf;
|
|
178
|
+
#recvHalf;
|
|
179
|
+
constructor(sendHalf, recvHalf) {
|
|
180
|
+
this.#sendHalf = sendHalf;
|
|
181
|
+
this.#recvHalf = recvHalf;
|
|
182
|
+
this.stream = recvHalf.stream;
|
|
183
|
+
}
|
|
184
|
+
async send(message) {
|
|
185
|
+
try {
|
|
186
|
+
await this.#sendHalf.send(message);
|
|
187
|
+
} catch (error) {
|
|
188
|
+
await this.#recvHalf.close();
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async close() {
|
|
193
|
+
await Promise.allSettled([this.#sendHalf.close(), this.#recvHalf.close()]);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
//#endregion
|
|
197
|
+
//#region src/client/util/stream_reset.ts
|
|
198
|
+
/**
|
|
199
|
+
* Copyright 2026 The MOQtail Authors
|
|
200
|
+
*
|
|
201
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
202
|
+
* you may not use this file except in compliance with the License.
|
|
203
|
+
* You may obtain a copy of the License at
|
|
204
|
+
*
|
|
205
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
206
|
+
*
|
|
207
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
208
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
209
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
210
|
+
* See the License for the specific language governing permissions and
|
|
211
|
+
* limitations under the License.
|
|
212
|
+
*/
|
|
213
|
+
/**
|
|
214
|
+
* @public
|
|
215
|
+
* The peer reset this stream, or told us to stop sending on it, with a code.
|
|
216
|
+
*/
|
|
217
|
+
var PeerStreamResetError = class extends require_model.MOQtailError {
|
|
218
|
+
context;
|
|
219
|
+
code;
|
|
220
|
+
constructor(context, code) {
|
|
221
|
+
super(`[${context}] peer reset the stream with ${require_model.StreamResetCode[code]} (0x${code.toString(16)})`);
|
|
222
|
+
this.context = context;
|
|
223
|
+
this.code = code;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* Stand-in for `WebTransportError` on runtimes that do not define it. Carries the
|
|
228
|
+
* same two fields so {@link streamResetCodeOf} reads either shape.
|
|
229
|
+
*/
|
|
230
|
+
var StreamResetError = class extends Error {
|
|
231
|
+
streamErrorCode;
|
|
232
|
+
source = "stream";
|
|
233
|
+
constructor(streamErrorCode) {
|
|
234
|
+
super(`stream reset with code ${streamErrorCode}`);
|
|
235
|
+
this.streamErrorCode = streamErrorCode;
|
|
236
|
+
this.name = "StreamResetError";
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
/**
|
|
240
|
+
* @public
|
|
241
|
+
* The reason to hand `writer.abort()` or `reader.cancel()` so the stream is torn down
|
|
242
|
+
* with `code`.
|
|
243
|
+
*
|
|
244
|
+
* WebTransport carries a numeric RESET_STREAM / STOP_SENDING code only when the reason
|
|
245
|
+
* is a `WebTransportError` with `source: 'stream'`; any other value — a string, say —
|
|
246
|
+
* resets with 0, which the peer reads as INTERNAL_ERROR.
|
|
247
|
+
*/
|
|
248
|
+
function streamResetReason(code) {
|
|
249
|
+
const ctor = globalThis.WebTransportError;
|
|
250
|
+
const message = `stream reset with code ${code}`;
|
|
251
|
+
if (typeof ctor === "function") {
|
|
252
|
+
const candidates = [() => new ctor({
|
|
253
|
+
streamErrorCode: code,
|
|
254
|
+
message
|
|
255
|
+
}), () => new ctor(message, {
|
|
256
|
+
source: "stream",
|
|
257
|
+
streamErrorCode: code
|
|
258
|
+
})];
|
|
259
|
+
for (const build of candidates) try {
|
|
260
|
+
const error = build();
|
|
261
|
+
if (streamResetCodeOf(error) === code) return error;
|
|
262
|
+
} catch {}
|
|
263
|
+
}
|
|
264
|
+
return new StreamResetError(code);
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* @public
|
|
268
|
+
* The code the peer reset a stream with, or `undefined` if `error` is not a stream
|
|
269
|
+
* reset or carries a code this draft does not define.
|
|
270
|
+
*/
|
|
271
|
+
function streamResetCodeOf(error) {
|
|
272
|
+
const code = error?.streamErrorCode;
|
|
273
|
+
if (typeof code !== "number") return void 0;
|
|
274
|
+
try {
|
|
275
|
+
return require_model.StreamResetCode.tryFrom(code);
|
|
276
|
+
} catch {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* @public
|
|
282
|
+
* Re-types a failed read: a peer reset becomes a {@link PeerStreamResetError} naming
|
|
283
|
+
* the code, anything else is passed through untouched.
|
|
284
|
+
*/
|
|
285
|
+
function asStreamResetError(context, error) {
|
|
286
|
+
const code = streamResetCodeOf(error);
|
|
287
|
+
return code === void 0 ? error : new PeerStreamResetError(context, code);
|
|
288
|
+
}
|
|
289
|
+
//#endregion
|
|
290
|
+
//#region src/client/request_stream.ts
|
|
291
|
+
/**
|
|
292
|
+
* Copyright 2025 The MOQtail Authors
|
|
293
|
+
*
|
|
294
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
295
|
+
* you may not use this file except in compliance with the License.
|
|
296
|
+
* You may obtain a copy of the License at
|
|
297
|
+
*
|
|
298
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
299
|
+
*
|
|
300
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
301
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
302
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
303
|
+
* See the License for the specific language governing permissions and
|
|
304
|
+
* limitations under the License.
|
|
305
|
+
*/
|
|
306
|
+
/**
|
|
307
|
+
* Wraps a WebTransport bidirectional stream carrying one MOQT request.
|
|
308
|
+
* Because a response is correlated by the stream it arrives on, nothing here needs a
|
|
309
|
+
* request id.
|
|
310
|
+
*/
|
|
311
|
+
var RequestStream = class RequestStream {
|
|
312
|
+
stream;
|
|
313
|
+
/**
|
|
314
|
+
* The message this side opened the stream with, kept so the request can be re-issued
|
|
315
|
+
* on a fresh stream when the peer migrates it with a GOAWAY (§10.4). Undefined on a
|
|
316
|
+
* peer-opened stream, which is the peer's request to re-issue, not ours.
|
|
317
|
+
*/
|
|
318
|
+
first;
|
|
319
|
+
/**
|
|
320
|
+
* The type of the message that opened this stream, whichever side opened it. It is
|
|
321
|
+
* what the request on this stream *is*, which decides what may follow — a
|
|
322
|
+
* REQUEST_UPDATE is only valid for the types §10.9 lists.
|
|
323
|
+
*/
|
|
324
|
+
openingType;
|
|
325
|
+
/** Set when the request this stream carried has been re-issued on a new stream. */
|
|
326
|
+
migrated = false;
|
|
327
|
+
#reader;
|
|
328
|
+
#writer;
|
|
329
|
+
#receiveBuffer;
|
|
330
|
+
/** Held for the stream's lifetime once {@link next} is first called. */
|
|
331
|
+
#messageReader;
|
|
332
|
+
constructor(biStream) {
|
|
333
|
+
this.#receiveBuffer = new require_model.ByteBuffer();
|
|
334
|
+
this.#reader = biStream.readable.getReader();
|
|
335
|
+
this.#writer = biStream.writable.getWriter();
|
|
336
|
+
this.stream = new ReadableStream({
|
|
337
|
+
start: (controller) => this.#ingestLoop(controller),
|
|
338
|
+
cancel: () => this.close()
|
|
339
|
+
});
|
|
340
|
+
require_logger.logger.debug("request_stream", "opened");
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Opens a new bidi stream and writes `first` on it.
|
|
344
|
+
*
|
|
345
|
+
* @throws :{@link ProtocolViolationError} If `first` is not one of the seven types
|
|
346
|
+
* Table 5 marks `First`; those are the only ones allowed to open a request stream.
|
|
347
|
+
*/
|
|
348
|
+
static async open(webTransport, first) {
|
|
349
|
+
if (!require_model.ControlMessageType.isFirst(first.getType())) throw new require_model.ProtocolViolationError("RequestStream.open", `${first.constructor.name} may not open a request stream: only First-marked types can`);
|
|
350
|
+
const biStream = await webTransport.createBidirectionalStream();
|
|
351
|
+
const requestStream = new RequestStream(biStream);
|
|
352
|
+
requestStream.first = first;
|
|
353
|
+
requestStream.openingType = first.getType();
|
|
354
|
+
await requestStream.send(first);
|
|
355
|
+
return requestStream;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Reads the next control message off this stream, or `undefined` once the peer has
|
|
359
|
+
* closed or reset it.
|
|
360
|
+
*
|
|
361
|
+
* Takes ownership of {@link RequestStream.stream}'s reader on first use, so callers
|
|
362
|
+
* must not mix `next()` with `stream.getReader()`.
|
|
363
|
+
*/
|
|
364
|
+
async next() {
|
|
365
|
+
this.#messageReader ??= this.stream.getReader();
|
|
366
|
+
const { value, done } = await this.#messageReader.read();
|
|
367
|
+
return done ? void 0 : value;
|
|
368
|
+
}
|
|
369
|
+
async send(message) {
|
|
370
|
+
try {
|
|
371
|
+
const serialized = require_model.ControlMessage.serialize(message);
|
|
372
|
+
await this.#writer.ready;
|
|
373
|
+
await this.#writer.write(serialized.toUint8Array());
|
|
374
|
+
require_logger.logger.debug("request_stream", `sent ${message.constructor.name}`);
|
|
375
|
+
} catch (error) {
|
|
376
|
+
await this.close();
|
|
377
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
378
|
+
require_logger.logger.error("request_stream", `send failed: ${msg}`);
|
|
379
|
+
throw new require_model.TerminationError(`RequestStream.send: Failed to write message: ${msg}`, 1);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
async close() {
|
|
383
|
+
require_logger.logger.debug("request_stream", "closed");
|
|
384
|
+
await Promise.allSettled([this.#writer.close().catch(() => {}), this.#reader.cancel().catch(() => {})]);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Cancels the request by resetting its stream with `code` (§3.3.2), which is how
|
|
388
|
+
* draft-18 cancels a request now that the dedicated cancel messages are gone.
|
|
389
|
+
*/
|
|
390
|
+
async reset(code) {
|
|
391
|
+
require_logger.logger.debug("request_stream", `reset code=${code}`);
|
|
392
|
+
const reason = streamResetReason(code);
|
|
393
|
+
await Promise.allSettled([this.#writer.abort(reason).catch(() => {}), this.#reader.cancel(reason).catch(() => {})]);
|
|
394
|
+
}
|
|
395
|
+
async #ingestLoop(controller) {
|
|
396
|
+
try {
|
|
397
|
+
while (true) {
|
|
398
|
+
if (this.#receiveBuffer.length === 0) {
|
|
399
|
+
const readResult = await this.#reader.read();
|
|
400
|
+
this.#handleReadResult(readResult);
|
|
401
|
+
if (readResult.done) break;
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
this.#receiveBuffer.checkpoint();
|
|
406
|
+
const startOffset = this.#receiveBuffer.offset;
|
|
407
|
+
this.#receiveBuffer.getVI();
|
|
408
|
+
const payloadLength = this.#receiveBuffer.getU16();
|
|
409
|
+
const totalMessageSize = this.#receiveBuffer.offset - startOffset + payloadLength;
|
|
410
|
+
this.#receiveBuffer.restore();
|
|
411
|
+
if (this.#receiveBuffer.length >= totalMessageSize) {
|
|
412
|
+
const messageBytes = this.#receiveBuffer.getBytes(totalMessageSize);
|
|
413
|
+
this.#receiveBuffer.commit();
|
|
414
|
+
const msg = require_model.ControlMessage.deserialize(new require_model.FrozenByteBuffer(messageBytes));
|
|
415
|
+
controller.enqueue(msg);
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
const readResult = await this.#reader.read();
|
|
419
|
+
this.#handleReadResult(readResult);
|
|
420
|
+
if (readResult.done) break;
|
|
421
|
+
} catch (error) {
|
|
422
|
+
if (error instanceof require_model.NotEnoughBytesError) {
|
|
423
|
+
const readResult = await this.#reader.read();
|
|
424
|
+
this.#handleReadResult(readResult);
|
|
425
|
+
if (readResult.done) break;
|
|
426
|
+
} else {
|
|
427
|
+
require_logger.logger.error("request_stream", `deserialization error: ${error.message}`);
|
|
428
|
+
controller.error(new require_model.TerminationError(`RequestStream: Deserialization error: ${error.message}`, 3));
|
|
429
|
+
await this.close();
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
} catch (error) {
|
|
435
|
+
require_logger.logger.error("request_stream", "ingest loop error", error);
|
|
436
|
+
controller.error(asStreamResetError("RequestStream", error));
|
|
437
|
+
await this.close();
|
|
438
|
+
} finally {
|
|
439
|
+
controller.close();
|
|
440
|
+
await this.close();
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
#handleReadResult(readResult) {
|
|
444
|
+
if (readResult.done) return;
|
|
445
|
+
if (readResult.value) this.#receiveBuffer.putBytes(readResult.value);
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
//#endregion
|
|
449
|
+
//#region src/client/data_stream.ts
|
|
450
|
+
/**
|
|
451
|
+
* Copyright 2025 The MOQtail Authors
|
|
452
|
+
*
|
|
453
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
454
|
+
* you may not use this file except in compliance with the License.
|
|
455
|
+
* You may obtain a copy of the License at
|
|
456
|
+
*
|
|
457
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
458
|
+
*
|
|
459
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
460
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
461
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
462
|
+
* See the License for the specific language governing permissions and
|
|
463
|
+
* limitations under the License.
|
|
464
|
+
*/
|
|
465
|
+
var SendStream = class SendStream {
|
|
466
|
+
header;
|
|
467
|
+
#lastObjectId;
|
|
468
|
+
#fetchPrevCtx;
|
|
469
|
+
#writer;
|
|
470
|
+
#groupOrder;
|
|
471
|
+
onDataSent;
|
|
472
|
+
constructor(header, writer, onDataSent, groupOrder = 0) {
|
|
473
|
+
this.header = header;
|
|
474
|
+
if (onDataSent) this.onDataSent = onDataSent;
|
|
475
|
+
this.#writer = writer;
|
|
476
|
+
this.#groupOrder = groupOrder;
|
|
477
|
+
}
|
|
478
|
+
static async new(writeStream, header, onDataSent, groupOrder = 0) {
|
|
479
|
+
const writer = writeStream.getWriter();
|
|
480
|
+
const serializedHeader = header.serialize().toUint8Array();
|
|
481
|
+
await writer.write(serializedHeader);
|
|
482
|
+
if (onDataSent) onDataSent(header);
|
|
483
|
+
require_logger.logger.debug("data_stream", `SendStream opened type=${header.type}`);
|
|
484
|
+
return new SendStream(header, writer, onDataSent, groupOrder);
|
|
485
|
+
}
|
|
486
|
+
async write(object) {
|
|
487
|
+
let serializedObject;
|
|
488
|
+
if (object instanceof require_model.FetchObject) {
|
|
489
|
+
serializedObject = object.serialize(this.#fetchPrevCtx, this.#groupOrder).toUint8Array();
|
|
490
|
+
const newCtx = object.toContext();
|
|
491
|
+
if (newCtx) this.#fetchPrevCtx = newCtx;
|
|
492
|
+
} else {
|
|
493
|
+
if (this.#lastObjectId !== void 0 && object.objectId <= this.#lastObjectId) {
|
|
494
|
+
require_logger.logger.error("data_stream", `SendStream out-of-order objectId=${object.objectId} lastObjectId=${this.#lastObjectId}`);
|
|
495
|
+
throw new Error(`SendStream.write: Out-of-order object detected. Attempted to write objectId=${object.objectId}, but lastObjectId=${this.#lastObjectId}.`);
|
|
496
|
+
}
|
|
497
|
+
serializedObject = object.serialize(this.#lastObjectId).toUint8Array();
|
|
498
|
+
this.#lastObjectId = object.objectId;
|
|
499
|
+
}
|
|
500
|
+
await this.#writer.write(serializedObject);
|
|
501
|
+
if (this.onDataSent) this.onDataSent(object);
|
|
502
|
+
}
|
|
503
|
+
async close() {
|
|
504
|
+
if (this.#writer) {
|
|
505
|
+
require_logger.logger.debug("data_stream", `SendStream closed type=${this.header.type}`);
|
|
506
|
+
await this.#writer.close();
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
/** Abruptly tears the stream down, so the peer reads back `code` (§3.3.3). */
|
|
510
|
+
async reset(code) {
|
|
511
|
+
require_logger.logger.debug("data_stream", `SendStream reset type=${this.header.type} code=${code}`);
|
|
512
|
+
await this.#writer.abort(streamResetReason(code)).catch(() => {});
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
function withTimeout(promise, ms, errorMsg) {
|
|
516
|
+
if (ms === void 0) return promise;
|
|
517
|
+
let timeoutId;
|
|
518
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
519
|
+
timeoutId = setTimeout(() => reject(new require_model.TimeoutError(errorMsg ?? `Timeout after ${ms}ms`)), ms);
|
|
520
|
+
});
|
|
521
|
+
return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timeoutId));
|
|
522
|
+
}
|
|
523
|
+
var RecvStream = class RecvStream {
|
|
524
|
+
header;
|
|
525
|
+
stream;
|
|
526
|
+
#partialDataTimeout;
|
|
527
|
+
#reader;
|
|
528
|
+
#internalBuffer;
|
|
529
|
+
#groupOrder;
|
|
530
|
+
onDataReceived;
|
|
531
|
+
constructor(header, reader, internalBuffer, partialDataTimeout, onDataReceived, groupOrder = 0) {
|
|
532
|
+
this.header = header;
|
|
533
|
+
this.#reader = reader;
|
|
534
|
+
this.#internalBuffer = internalBuffer;
|
|
535
|
+
this.#partialDataTimeout = partialDataTimeout;
|
|
536
|
+
this.#groupOrder = groupOrder;
|
|
537
|
+
if (onDataReceived) this.onDataReceived = onDataReceived;
|
|
538
|
+
this.stream = new ReadableStream({
|
|
539
|
+
start: (controller) => this.#ingestLoop(controller),
|
|
540
|
+
cancel: (reason) => this.#reader.cancel(reason)
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* @param resolveGroupOrder - Consulted once the FETCH header names its request, since
|
|
545
|
+
* Group ID deltas on the stream are signed by the Group Order the request negotiated.
|
|
546
|
+
*/
|
|
547
|
+
static async new(readStream, partialDataTimeout, onDataReceived, resolveGroupOrder) {
|
|
548
|
+
const reader = readStream.getReader();
|
|
549
|
+
const internalBuffer = new require_model.ByteBuffer();
|
|
550
|
+
let headerInstance;
|
|
551
|
+
try {
|
|
552
|
+
while (true) {
|
|
553
|
+
let readResult;
|
|
554
|
+
if (partialDataTimeout !== void 0) readResult = await withTimeout(reader.read(), partialDataTimeout, `RecvStream.new: Timeout after ${partialDataTimeout}ms waiting for header data`);
|
|
555
|
+
else readResult = await reader.read();
|
|
556
|
+
const { done, value } = readResult;
|
|
557
|
+
if (done) throw new require_model.ProtocolViolationError("RecvStream.new", internalBuffer.length > 0 ? "Stream closed with incomplete header data." : "Stream closed before any header data received.");
|
|
558
|
+
if (value) internalBuffer.putBytes(value);
|
|
559
|
+
try {
|
|
560
|
+
internalBuffer.checkpoint();
|
|
561
|
+
headerInstance = require_model.Header.deserialize(internalBuffer);
|
|
562
|
+
internalBuffer.commit();
|
|
563
|
+
if (onDataReceived) onDataReceived(headerInstance);
|
|
564
|
+
break;
|
|
565
|
+
} catch (e) {
|
|
566
|
+
if (e instanceof require_model.NotEnoughBytesError) {
|
|
567
|
+
internalBuffer.restore();
|
|
568
|
+
continue;
|
|
569
|
+
} else throw e;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
} catch (error) {
|
|
573
|
+
await reader.cancel(streamResetReason(0)).catch(() => {});
|
|
574
|
+
reader.releaseLock();
|
|
575
|
+
throw asStreamResetError("RecvStream.new", error);
|
|
576
|
+
}
|
|
577
|
+
if (onDataReceived) onDataReceived(headerInstance);
|
|
578
|
+
require_logger.logger.debug("data_stream", `RecvStream opened type=${headerInstance.type}`);
|
|
579
|
+
const groupOrder = require_model.Header.isFetch(headerInstance) && resolveGroupOrder ? resolveGroupOrder(headerInstance) : 0;
|
|
580
|
+
return new RecvStream(headerInstance, reader, internalBuffer, partialDataTimeout, onDataReceived, groupOrder);
|
|
581
|
+
}
|
|
582
|
+
async #ingestLoop(controller) {
|
|
583
|
+
try {
|
|
584
|
+
let previousObjectId = void 0;
|
|
585
|
+
let fetchPrevCtx = void 0;
|
|
586
|
+
while (true) {
|
|
587
|
+
if (this.#internalBuffer.remaining > 0) try {
|
|
588
|
+
this.#internalBuffer.checkpoint();
|
|
589
|
+
let object;
|
|
590
|
+
if (require_model.Header.isFetch(this.header)) {
|
|
591
|
+
object = require_model.FetchObject.deserialize(this.#internalBuffer, fetchPrevCtx, this.#groupOrder);
|
|
592
|
+
const newCtx = object.toContext();
|
|
593
|
+
if (newCtx) fetchPrevCtx = newCtx;
|
|
594
|
+
} else {
|
|
595
|
+
object = require_model.SubgroupObject.deserialize(this.#internalBuffer, require_model.SubgroupHeaderType.hasProperties(this.header.type), previousObjectId);
|
|
596
|
+
this.header.resolveSubgroupId(object.objectId);
|
|
597
|
+
previousObjectId = object.objectId;
|
|
598
|
+
}
|
|
599
|
+
this.#internalBuffer.commit();
|
|
600
|
+
controller.enqueue(object);
|
|
601
|
+
if (this.onDataReceived) this.onDataReceived(object);
|
|
602
|
+
continue;
|
|
603
|
+
} catch (e) {
|
|
604
|
+
if (e instanceof require_model.NotEnoughBytesError) this.#internalBuffer.restore();
|
|
605
|
+
else {
|
|
606
|
+
controller.error(e);
|
|
607
|
+
break;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
let readResult;
|
|
611
|
+
if (this.#partialDataTimeout) readResult = await withTimeout(this.#reader.read(), this.#partialDataTimeout, `RecvStream: Timeout after ${this.#partialDataTimeout}ms waiting for object data`);
|
|
612
|
+
else readResult = await this.#reader.read();
|
|
613
|
+
const { done, value } = readResult;
|
|
614
|
+
if (done) {
|
|
615
|
+
if (this.#internalBuffer.remaining > 0) {
|
|
616
|
+
require_logger.logger.error("data_stream", `RecvStream closed with incomplete data remaining=${this.#internalBuffer.remaining}`);
|
|
617
|
+
controller.error(new require_model.ProtocolViolationError("RecvStream", `Stream closed with incomplete object data. Remaining: ${this.#internalBuffer.remaining} bytes.`));
|
|
618
|
+
} else {
|
|
619
|
+
require_logger.logger.debug("data_stream", `RecvStream closed type=${this.header.type}`);
|
|
620
|
+
controller.close();
|
|
621
|
+
}
|
|
622
|
+
break;
|
|
623
|
+
}
|
|
624
|
+
if (value) this.#internalBuffer.putBytes(value);
|
|
625
|
+
}
|
|
626
|
+
} catch (error) {
|
|
627
|
+
const peerReset = streamResetCodeOf(error);
|
|
628
|
+
if (peerReset !== void 0) require_logger.logger.debug("data_stream", `RecvStream reset by peer code=${require_model.StreamResetCode[peerReset]}`);
|
|
629
|
+
else {
|
|
630
|
+
require_logger.logger.error("data_stream", "RecvStream ingest loop error", error);
|
|
631
|
+
await this.#reader.cancel(streamResetReason(0)).catch(() => {});
|
|
632
|
+
}
|
|
633
|
+
controller.error(asStreamResetError("RecvStream", error));
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
/** Asks the peer to stop sending on this stream, reporting `code` (§3.3.3). */
|
|
637
|
+
async stopSending(code) {
|
|
638
|
+
require_logger.logger.debug("data_stream", `RecvStream stopSending type=${this.header.type} code=${code}`);
|
|
639
|
+
await this.#reader.cancel(streamResetReason(code)).catch(() => {});
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
//#endregion
|
|
643
|
+
//#region src/client/track/content_source.ts
|
|
644
|
+
var StaticTrackSource = class {
|
|
645
|
+
cache;
|
|
646
|
+
constructor(cache) {
|
|
647
|
+
this.cache = cache;
|
|
648
|
+
}
|
|
649
|
+
async getRange(start, end) {
|
|
650
|
+
return this.cache.getRange(start, end);
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
var LiveTrackSource = class {
|
|
654
|
+
stream;
|
|
655
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
656
|
+
#doneListeners = /* @__PURE__ */ new Set();
|
|
657
|
+
#largestLocation;
|
|
658
|
+
#ingestActive = false;
|
|
659
|
+
#reader;
|
|
660
|
+
constructor(stream) {
|
|
661
|
+
this.stream = stream;
|
|
662
|
+
this.#startIngest();
|
|
663
|
+
}
|
|
664
|
+
get largestLocation() {
|
|
665
|
+
return this.#largestLocation;
|
|
666
|
+
}
|
|
667
|
+
async #startIngest() {
|
|
668
|
+
if (this.#ingestActive) return;
|
|
669
|
+
this.#ingestActive = true;
|
|
670
|
+
try {
|
|
671
|
+
this.#reader = this.stream.getReader();
|
|
672
|
+
while (this.#ingestActive) {
|
|
673
|
+
const { value, done } = await this.#reader.read();
|
|
674
|
+
if (done) break;
|
|
675
|
+
this.#largestLocation = value.location;
|
|
676
|
+
for (const listener of this.#listeners) listener(value);
|
|
677
|
+
}
|
|
678
|
+
} catch (error) {
|
|
679
|
+
require_logger.logger.error("track/content_source", "Error during live object ingestion:", error);
|
|
680
|
+
} finally {
|
|
681
|
+
this.#ingestActive = false;
|
|
682
|
+
this.#reader?.releaseLock();
|
|
683
|
+
for (const doneListener of this.#doneListeners) Promise.resolve().then(() => doneListener());
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
onNewObject(listener) {
|
|
687
|
+
let queue = Promise.resolve();
|
|
688
|
+
const queuedListener = (obj) => {
|
|
689
|
+
queue = queue.then(() => listener(obj)).catch((err) => {
|
|
690
|
+
require_logger.logger.error("track/content_source", "Error in subscriber listener:", err);
|
|
691
|
+
});
|
|
692
|
+
};
|
|
693
|
+
this.#listeners.add(queuedListener);
|
|
694
|
+
return () => this.#listeners.delete(queuedListener);
|
|
695
|
+
}
|
|
696
|
+
onDone(listener) {
|
|
697
|
+
this.#doneListeners.add(listener);
|
|
698
|
+
return () => this.#doneListeners.delete(listener);
|
|
699
|
+
}
|
|
700
|
+
stop() {
|
|
701
|
+
this.#ingestActive = false;
|
|
702
|
+
this.#reader?.cancel();
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
var HybridTrackSource = class {
|
|
706
|
+
past;
|
|
707
|
+
live;
|
|
708
|
+
constructor(cache, stream) {
|
|
709
|
+
this.past = new StaticTrackSource(cache);
|
|
710
|
+
this.live = new LiveTrackSource(stream);
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
//#endregion
|
|
714
|
+
//#region src/client/request/publish_namespace.ts
|
|
715
|
+
/**
|
|
716
|
+
* Copyright 2026 The MOQtail Authors
|
|
717
|
+
*
|
|
718
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
719
|
+
* you may not use this file except in compliance with the License.
|
|
720
|
+
* You may obtain a copy of the License at
|
|
721
|
+
*
|
|
722
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
723
|
+
*
|
|
724
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
725
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
726
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
727
|
+
* See the License for the specific language governing permissions and
|
|
728
|
+
* limitations under the License.
|
|
729
|
+
*/
|
|
730
|
+
var PublishNamespaceRequest = class {
|
|
731
|
+
requestId;
|
|
732
|
+
message;
|
|
733
|
+
_resolve;
|
|
734
|
+
_reject;
|
|
735
|
+
promise;
|
|
736
|
+
constructor(requestId, message) {
|
|
737
|
+
this.requestId = requestId;
|
|
738
|
+
this.message = message;
|
|
739
|
+
this.promise = new Promise((resolve, reject) => {
|
|
740
|
+
this._resolve = resolve;
|
|
741
|
+
this._reject = reject;
|
|
742
|
+
});
|
|
743
|
+
require_logger.logger.debug("request/publish_namespace", `created requestId=${this.requestId} namespace="${message.trackNamespace}"`);
|
|
744
|
+
}
|
|
745
|
+
resolve(value) {
|
|
746
|
+
if (value instanceof require_model.RequestError) require_logger.logger.error("request/publish_namespace", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
|
|
747
|
+
else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/publish_namespace", `resolved with OK requestId=${this.requestId}`);
|
|
748
|
+
this._resolve(value);
|
|
749
|
+
}
|
|
750
|
+
reject(reason) {
|
|
751
|
+
require_logger.logger.error("request/publish_namespace", `rejected requestId=${this.requestId}`, reason);
|
|
752
|
+
this._reject(reason);
|
|
753
|
+
}
|
|
754
|
+
then(onfulfilled, onrejected) {
|
|
755
|
+
return this.promise.then(onfulfilled, onrejected);
|
|
756
|
+
}
|
|
757
|
+
catch(onrejected) {
|
|
758
|
+
return this.promise.catch(onrejected);
|
|
759
|
+
}
|
|
760
|
+
finally(onfinally) {
|
|
761
|
+
return this.promise.finally(onfinally);
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
//#endregion
|
|
765
|
+
//#region src/client/request/fetch.ts
|
|
766
|
+
/**
|
|
767
|
+
* Copyright 2025 The MOQtail Authors
|
|
768
|
+
*
|
|
769
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
770
|
+
* you may not use this file except in compliance with the License.
|
|
771
|
+
* You may obtain a copy of the License at
|
|
772
|
+
*
|
|
773
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
774
|
+
*
|
|
775
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
776
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
777
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
778
|
+
* See the License for the specific language governing permissions and
|
|
779
|
+
* limitations under the License.
|
|
780
|
+
*/
|
|
781
|
+
var FetchRequest = class {
|
|
782
|
+
requestId;
|
|
783
|
+
message;
|
|
784
|
+
_resolve;
|
|
785
|
+
_reject;
|
|
786
|
+
promise;
|
|
787
|
+
controller;
|
|
788
|
+
stream;
|
|
789
|
+
isActive = true;
|
|
790
|
+
isResolved = false;
|
|
791
|
+
constructor(message) {
|
|
792
|
+
this.requestId = message.requestId;
|
|
793
|
+
this.message = message;
|
|
794
|
+
this.stream = new ReadableStream({ start: (controller) => {
|
|
795
|
+
this.controller = controller;
|
|
796
|
+
} });
|
|
797
|
+
this.promise = new Promise((resolve, reject) => {
|
|
798
|
+
this._resolve = resolve;
|
|
799
|
+
this._reject = reject;
|
|
800
|
+
});
|
|
801
|
+
require_logger.logger.debug("request/fetch", `created requestId=${this.requestId}`);
|
|
802
|
+
}
|
|
803
|
+
resolve(value) {
|
|
804
|
+
if (value instanceof require_model.RequestError) require_logger.logger.error("request/fetch", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
|
|
805
|
+
else if (value instanceof require_model.FetchOk) require_logger.logger.debug("request/fetch", `resolved with OK requestId=${this.requestId}`);
|
|
806
|
+
this._resolve(value);
|
|
807
|
+
}
|
|
808
|
+
reject(reason) {
|
|
809
|
+
require_logger.logger.error("request/fetch", `rejected requestId=${this.requestId}`, reason);
|
|
810
|
+
this._reject(reason);
|
|
811
|
+
}
|
|
812
|
+
then(onfulfilled, onrejected) {
|
|
813
|
+
return this.promise.then(onfulfilled, onrejected);
|
|
814
|
+
}
|
|
815
|
+
catch(onrejected) {
|
|
816
|
+
return this.promise.catch(onrejected);
|
|
817
|
+
}
|
|
818
|
+
finally(onfinally) {
|
|
819
|
+
return this.promise.finally(onfinally);
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
//#endregion
|
|
823
|
+
//#region src/client/request/subscribe.ts
|
|
824
|
+
/**
|
|
825
|
+
* Copyright 2025 The MOQtail Authors
|
|
826
|
+
*
|
|
827
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
828
|
+
* you may not use this file except in compliance with the License.
|
|
829
|
+
* You may obtain a copy of the License at
|
|
830
|
+
*
|
|
831
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
832
|
+
*
|
|
833
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
834
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
835
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
836
|
+
* See the License for the specific language governing permissions and
|
|
837
|
+
* limitations under the License.
|
|
838
|
+
*/
|
|
839
|
+
var SubscribeRequest = class {
|
|
840
|
+
requestId;
|
|
841
|
+
fullTrackName;
|
|
842
|
+
isCanceled = false;
|
|
843
|
+
startLocation;
|
|
844
|
+
endGroup;
|
|
845
|
+
priority;
|
|
846
|
+
forward;
|
|
847
|
+
subscribeParameters;
|
|
848
|
+
earlyDiscardPolicy;
|
|
849
|
+
largestLocation;
|
|
850
|
+
streamsAccepted = 0n;
|
|
851
|
+
expectedStreams;
|
|
852
|
+
controller;
|
|
853
|
+
stream;
|
|
854
|
+
#promise;
|
|
855
|
+
#resolve;
|
|
856
|
+
#reject;
|
|
857
|
+
constructor(msg) {
|
|
858
|
+
this.requestId = msg.requestId;
|
|
859
|
+
this.fullTrackName = msg.fullTrackName;
|
|
860
|
+
const filter = msg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
|
|
861
|
+
this.startLocation = filter?.startLocation;
|
|
862
|
+
this.endGroup = filter?.endGroup;
|
|
863
|
+
const subPriority = msg.parameters.find(require_model.MessageParameter.isSubscriberPriority);
|
|
864
|
+
this.priority = subPriority?.priority ?? 128;
|
|
865
|
+
const fwd = msg.parameters.find(require_model.MessageParameter.isForward);
|
|
866
|
+
this.forward = fwd?.forward ?? true;
|
|
867
|
+
this.subscribeParameters = msg.parameters;
|
|
868
|
+
this.stream = new ReadableStream({ start: (controller) => {
|
|
869
|
+
this.controller = controller;
|
|
870
|
+
} });
|
|
871
|
+
this.#promise = new Promise((resolve, reject) => {
|
|
872
|
+
this.#resolve = resolve;
|
|
873
|
+
this.#reject = reject;
|
|
874
|
+
});
|
|
875
|
+
require_logger.logger.debug("request/subscribe", `created requestId=${this.requestId} ftn="${this.fullTrackName}" priority=${this.priority} forward=${this.forward}`);
|
|
876
|
+
}
|
|
877
|
+
update(msg) {
|
|
878
|
+
const filter = msg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
|
|
879
|
+
if (filter?.startLocation !== void 0) this.startLocation = filter.startLocation;
|
|
880
|
+
if (filter?.endGroup !== void 0) this.endGroup = filter.endGroup;
|
|
881
|
+
for (const param of msg.parameters) if (require_model.MessageParameter.isSubscriberPriority?.(param)) this.priority = param.priority;
|
|
882
|
+
else if (require_model.MessageParameter.isForward?.(param)) this.forward = param.forward;
|
|
883
|
+
if (typeof require_model.applyMessageParameterUpdate === "function") require_model.applyMessageParameterUpdate(this.subscribeParameters, msg.parameters);
|
|
884
|
+
}
|
|
885
|
+
switch(newTrackName, newParameters) {
|
|
886
|
+
this.fullTrackName = newTrackName;
|
|
887
|
+
this.subscribeParameters = newParameters;
|
|
888
|
+
this.#promise = new Promise((resolve, reject) => {
|
|
889
|
+
this.#resolve = resolve;
|
|
890
|
+
this.#reject = reject;
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
unsubscribe() {
|
|
894
|
+
this.isCanceled = true;
|
|
895
|
+
}
|
|
896
|
+
resolve(value) {
|
|
897
|
+
if (value instanceof require_model.RequestError) require_logger.logger.error("request/subscribe", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
|
|
898
|
+
else if (value instanceof require_model.SubscribeOk) require_logger.logger.debug("request/subscribe", `resolved with OK requestId=${this.requestId} trackAlias=${value.trackAlias}`);
|
|
899
|
+
this.#resolve(value);
|
|
900
|
+
}
|
|
901
|
+
reject(reason) {
|
|
902
|
+
require_logger.logger.error("request/subscribe", `rejected requestId=${this.requestId}`, reason);
|
|
903
|
+
this.#reject(reason);
|
|
904
|
+
}
|
|
905
|
+
then(onfulfilled, onrejected) {
|
|
906
|
+
return this.#promise.then(onfulfilled, onrejected);
|
|
907
|
+
}
|
|
908
|
+
catch(onrejected) {
|
|
909
|
+
return this.#promise.catch(onrejected);
|
|
910
|
+
}
|
|
911
|
+
finally(onfinally) {
|
|
912
|
+
return this.#promise.finally(onfinally);
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
//#endregion
|
|
916
|
+
//#region src/client/request/publish.ts
|
|
917
|
+
/**
|
|
918
|
+
* Copyright 2025 The MOQtail Authors
|
|
919
|
+
*
|
|
920
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
921
|
+
* you may not use this file except in compliance with the License.
|
|
922
|
+
* You may obtain a copy of the License at
|
|
923
|
+
*
|
|
924
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
925
|
+
*
|
|
926
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
927
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
928
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
929
|
+
* See the License for the specific language governing permissions and
|
|
930
|
+
* limitations under the License.
|
|
931
|
+
*/
|
|
932
|
+
var PublishRequest = class {
|
|
933
|
+
requestId;
|
|
934
|
+
message;
|
|
935
|
+
_resolve;
|
|
936
|
+
_reject;
|
|
937
|
+
promise;
|
|
938
|
+
constructor(msg) {
|
|
939
|
+
this.requestId = msg.requestId;
|
|
940
|
+
this.message = msg;
|
|
941
|
+
this.promise = new Promise((resolve, reject) => {
|
|
942
|
+
this._resolve = resolve;
|
|
943
|
+
this._reject = reject;
|
|
944
|
+
});
|
|
945
|
+
require_logger.logger.debug("request/publish", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
|
|
946
|
+
}
|
|
947
|
+
resolve(value) {
|
|
948
|
+
if (value instanceof require_model.RequestError) require_logger.logger.error("request/publish", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
|
|
949
|
+
else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/publish", `resolved with OK requestId=${this.requestId}`);
|
|
950
|
+
this._resolve(value);
|
|
951
|
+
}
|
|
952
|
+
reject(reason) {
|
|
953
|
+
require_logger.logger.error("request/publish", `rejected requestId=${this.requestId}`, reason);
|
|
954
|
+
this._reject(reason);
|
|
955
|
+
}
|
|
956
|
+
then(onfulfilled, onrejected) {
|
|
957
|
+
return this.promise.then(onfulfilled, onrejected);
|
|
958
|
+
}
|
|
959
|
+
catch(onrejected) {
|
|
960
|
+
return this.promise.catch(onrejected);
|
|
961
|
+
}
|
|
962
|
+
finally(onfinally) {
|
|
963
|
+
return this.promise.finally(onfinally);
|
|
964
|
+
}
|
|
965
|
+
};
|
|
966
|
+
//#endregion
|
|
967
|
+
//#region src/client/request/track_status.ts
|
|
968
|
+
/**
|
|
969
|
+
* Copyright 2026 The MOQtail Authors
|
|
970
|
+
*
|
|
971
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
972
|
+
* you may not use this file except in compliance with the License.
|
|
973
|
+
* You may obtain a copy of the License at
|
|
974
|
+
*
|
|
975
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
976
|
+
*
|
|
977
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
978
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
979
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
980
|
+
* See the License for the specific language governing permissions and
|
|
981
|
+
* limitations under the License.
|
|
982
|
+
*/
|
|
983
|
+
var TrackStatusRequest = class {
|
|
984
|
+
requestId;
|
|
985
|
+
message;
|
|
986
|
+
_resolve;
|
|
987
|
+
_reject;
|
|
988
|
+
promise;
|
|
989
|
+
constructor(msg) {
|
|
990
|
+
this.requestId = msg.requestId;
|
|
991
|
+
this.message = msg;
|
|
992
|
+
this.promise = new Promise((resolve, reject) => {
|
|
993
|
+
this._resolve = resolve;
|
|
994
|
+
this._reject = reject;
|
|
995
|
+
});
|
|
996
|
+
require_logger.logger.debug("request/track_status", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
|
|
997
|
+
}
|
|
998
|
+
resolve(value) {
|
|
999
|
+
if (value instanceof require_model.RequestError) require_logger.logger.error("request/track_status", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
|
|
1000
|
+
else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/track_status", `resolved with OK requestId=${this.requestId}`);
|
|
1001
|
+
this._resolve(value);
|
|
1002
|
+
}
|
|
1003
|
+
reject(reason) {
|
|
1004
|
+
require_logger.logger.error("request/track_status", `rejected requestId=${this.requestId}`, reason);
|
|
1005
|
+
this._reject(reason);
|
|
1006
|
+
}
|
|
1007
|
+
then(onfulfilled, onrejected) {
|
|
1008
|
+
return this.promise.then(onfulfilled, onrejected);
|
|
1009
|
+
}
|
|
1010
|
+
catch(onrejected) {
|
|
1011
|
+
return this.promise.catch(onrejected);
|
|
1012
|
+
}
|
|
1013
|
+
finally(onfinally) {
|
|
1014
|
+
return this.promise.finally(onfinally);
|
|
1015
|
+
}
|
|
1016
|
+
};
|
|
1017
|
+
//#endregion
|
|
1018
|
+
//#region src/client/handler/publish.ts
|
|
1019
|
+
/**
|
|
1020
|
+
* Copyright 2025 The MOQtail Authors
|
|
1021
|
+
*
|
|
1022
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1023
|
+
* you may not use this file except in compliance with the License.
|
|
1024
|
+
* You may obtain a copy of the License at
|
|
1025
|
+
*
|
|
1026
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1027
|
+
*
|
|
1028
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1029
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1030
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1031
|
+
* See the License for the specific language governing permissions and
|
|
1032
|
+
* limitations under the License.
|
|
1033
|
+
*/
|
|
1034
|
+
const handlerPublish = async (client, msg, stream) => {
|
|
1035
|
+
require_logger.logger.log("handler/publish", "track: %s alias: %d", msg.fullTrackName.toString(), msg.trackAlias);
|
|
1036
|
+
let streamController;
|
|
1037
|
+
const objects = new ReadableStream({ start(c) {
|
|
1038
|
+
streamController = c;
|
|
1039
|
+
} });
|
|
1040
|
+
const localPseudoRequestId = client.allocatePseudoRequestId();
|
|
1041
|
+
client.requestIdMap.addMapping(localPseudoRequestId, msg.fullTrackName);
|
|
1042
|
+
client.subscriptionAliasMap.set(localPseudoRequestId, msg.trackAlias);
|
|
1043
|
+
client.aliasFullTrackNameMap.set(msg.trackAlias, msg.fullTrackName);
|
|
1044
|
+
const receiver = {
|
|
1045
|
+
requestId: localPseudoRequestId,
|
|
1046
|
+
streamsAccepted: 0,
|
|
1047
|
+
largestLocation: void 0,
|
|
1048
|
+
controller: streamController
|
|
1049
|
+
};
|
|
1050
|
+
client.subscriptions.set(msg.trackAlias, receiver);
|
|
1051
|
+
if (client.onPeerPublish) client.onPeerPublish(msg, objects);
|
|
1052
|
+
await stream.send(new require_model.RequestOk());
|
|
1053
|
+
};
|
|
1054
|
+
//#endregion
|
|
1055
|
+
//#region src/client/handler/publish_blocked.ts
|
|
1056
|
+
/**
|
|
1057
|
+
* Copyright 2026 The MOQtail Authors
|
|
1058
|
+
*
|
|
1059
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1060
|
+
* you may not use this file except in compliance with the License.
|
|
1061
|
+
* You may obtain a copy of the License at
|
|
1062
|
+
*
|
|
1063
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1064
|
+
*
|
|
1065
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1066
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1067
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1068
|
+
* See the License for the specific language governing permissions and
|
|
1069
|
+
* limitations under the License.
|
|
1070
|
+
*/
|
|
1071
|
+
const handlerPublishBlocked = async (client, msg, stream) => {
|
|
1072
|
+
const first = stream.first;
|
|
1073
|
+
if (!(first instanceof require_model.SubscribeTracks)) throw new require_model.ProtocolViolationError("handlerPublishBlocked", "PUBLISH_BLOCKED on a stream this side did not open with SUBSCRIBE_TRACKS");
|
|
1074
|
+
require_logger.logger.log("handler/publish_blocked", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
|
|
1075
|
+
client.onPeerPublishBlocked?.(first.trackNamespacePrefix, msg);
|
|
1076
|
+
};
|
|
1077
|
+
//#endregion
|
|
1078
|
+
//#region src/client/handler/publish_namespace.ts
|
|
1079
|
+
/**
|
|
1080
|
+
* Copyright 2025 The MOQtail Authors
|
|
1081
|
+
*
|
|
1082
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1083
|
+
* you may not use this file except in compliance with the License.
|
|
1084
|
+
* You may obtain a copy of the License at
|
|
1085
|
+
*
|
|
1086
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1087
|
+
*
|
|
1088
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1089
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1090
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1091
|
+
* See the License for the specific language governing permissions and
|
|
1092
|
+
* limitations under the License.
|
|
1093
|
+
*/
|
|
1094
|
+
const handlerPublishNamespace = async (client, msg, stream) => {
|
|
1095
|
+
require_logger.logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
|
|
1096
|
+
if (client.onNamespacePublished) client.onNamespacePublished(msg);
|
|
1097
|
+
await stream.send(new require_model.RequestOk());
|
|
1098
|
+
};
|
|
1099
|
+
//#endregion
|
|
1100
|
+
//#region src/util/simple_lock.ts
|
|
1101
|
+
var SimpleLock = class {
|
|
1102
|
+
acquiredLock = false;
|
|
1103
|
+
contQueue = [];
|
|
1104
|
+
/**
|
|
1105
|
+
* Acquires the lock. If the lock is already held, waits until it is released.
|
|
1106
|
+
*/
|
|
1107
|
+
async acquire() {
|
|
1108
|
+
if (!this.acquiredLock) this.acquiredLock = true;
|
|
1109
|
+
else return new Promise((resolve, _) => {
|
|
1110
|
+
this.contQueue.push(resolve);
|
|
1111
|
+
});
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Releases the lock. If there are queued waiters, resumes the next one.
|
|
1115
|
+
*/
|
|
1116
|
+
async release() {
|
|
1117
|
+
if (this.contQueue.length === 0 && this.acquiredLock) {
|
|
1118
|
+
this.acquiredLock = false;
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
const continuation = this.contQueue.shift();
|
|
1122
|
+
return new Promise((res) => {
|
|
1123
|
+
continuation();
|
|
1124
|
+
res();
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
};
|
|
1128
|
+
//#endregion
|
|
1129
|
+
//#region src/client/util/priority.ts
|
|
1130
|
+
/**
|
|
1131
|
+
* Copyright 2025 The MOQtail Authors
|
|
1132
|
+
*
|
|
1133
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1134
|
+
* you may not use this file except in compliance with the License.
|
|
1135
|
+
* You may obtain a copy of the License at
|
|
1136
|
+
*
|
|
1137
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1138
|
+
*
|
|
1139
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1140
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1141
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1142
|
+
* See the License for the specific language governing permissions and
|
|
1143
|
+
* limitations under the License.
|
|
1144
|
+
*/
|
|
1145
|
+
function getTransportPriority(priority) {
|
|
1146
|
+
priority = Math.max(0, Math.min(255, Math.round(priority)));
|
|
1147
|
+
if (priority === 0) return Number.MAX_SAFE_INTEGER;
|
|
1148
|
+
if (priority === 255) return 0;
|
|
1149
|
+
return Math.round((255 - priority) * (Number.MAX_SAFE_INTEGER / 255));
|
|
1150
|
+
}
|
|
1151
|
+
//#endregion
|
|
1152
|
+
//#region src/client/publication/subscribe.ts
|
|
1153
|
+
/**
|
|
1154
|
+
* Copyright 2025 The MOQtail Authors
|
|
1155
|
+
*
|
|
1156
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1157
|
+
* you may not use this file except in compliance with the License.
|
|
1158
|
+
* You may obtain a copy of the License at
|
|
1159
|
+
*
|
|
1160
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1161
|
+
*
|
|
1162
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1163
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1164
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1165
|
+
* See the License for the specific language governing permissions and
|
|
1166
|
+
* limitations under the License.
|
|
1167
|
+
*/
|
|
1168
|
+
/**
|
|
1169
|
+
* @public
|
|
1170
|
+
* Manages the publication of MOQT objects to a subscriber for a specific track.
|
|
1171
|
+
* Handles live object streaming, subscription lifecycle, and stream management.
|
|
1172
|
+
*/
|
|
1173
|
+
var SubscribePublication = class {
|
|
1174
|
+
client;
|
|
1175
|
+
track;
|
|
1176
|
+
subscribeMsg;
|
|
1177
|
+
requestStream;
|
|
1178
|
+
/**
|
|
1179
|
+
* The latest location that was published to the subscriber.
|
|
1180
|
+
*/
|
|
1181
|
+
latestLocation;
|
|
1182
|
+
/**
|
|
1183
|
+
* The alias for the track being published.
|
|
1184
|
+
*/
|
|
1185
|
+
#trackAlias;
|
|
1186
|
+
/**
|
|
1187
|
+
* The starting location for the subscription.
|
|
1188
|
+
*/
|
|
1189
|
+
#startLocation;
|
|
1190
|
+
/**
|
|
1191
|
+
* The end group for AbsoluteRange subscriptions, if specified.
|
|
1192
|
+
*/
|
|
1193
|
+
#endGroup;
|
|
1194
|
+
/**
|
|
1195
|
+
* The priority of the subscriber.
|
|
1196
|
+
*/
|
|
1197
|
+
#subscriberPriority;
|
|
1198
|
+
/**
|
|
1199
|
+
* The priority of the publisher.
|
|
1200
|
+
*/
|
|
1201
|
+
#publisherPriority;
|
|
1202
|
+
/**
|
|
1203
|
+
* Whether objects should be forwarded to the subscriber.
|
|
1204
|
+
*/
|
|
1205
|
+
#forward;
|
|
1206
|
+
/**
|
|
1207
|
+
* The subscription parameters for this publication.
|
|
1208
|
+
*/
|
|
1209
|
+
#parameters;
|
|
1210
|
+
/**
|
|
1211
|
+
* The number of streams opened for this subscription.
|
|
1212
|
+
*/
|
|
1213
|
+
#streamsOpened = 0n;
|
|
1214
|
+
/**
|
|
1215
|
+
* Function to cancel publishing, if set.
|
|
1216
|
+
*/
|
|
1217
|
+
#cancelPublishing;
|
|
1218
|
+
/**
|
|
1219
|
+
* Whether publishing has started.
|
|
1220
|
+
*/
|
|
1221
|
+
#isStarted = false;
|
|
1222
|
+
/**
|
|
1223
|
+
* Whether publishing is completed.
|
|
1224
|
+
*/
|
|
1225
|
+
#isCompleted = false;
|
|
1226
|
+
/**
|
|
1227
|
+
* Lock for synchronizing stream operations.
|
|
1228
|
+
*/
|
|
1229
|
+
#lock = new SimpleLock();
|
|
1230
|
+
/**
|
|
1231
|
+
* Map of group IDs to their corresponding send streams.
|
|
1232
|
+
*/
|
|
1233
|
+
#streams = /* @__PURE__ */ new Map();
|
|
1234
|
+
/**
|
|
1235
|
+
* Unique identifier for this publication instance.
|
|
1236
|
+
*/
|
|
1237
|
+
#id = Math.floor(Math.random() * 1e6);
|
|
1238
|
+
/**
|
|
1239
|
+
* Highest group this publication has already opened a stream for or skipped objects of.
|
|
1240
|
+
* A stream for a group at or below it either reopens a subgroup or starts past the
|
|
1241
|
+
* subgroup's first object, so it cannot claim FIRST_OBJECT.
|
|
1242
|
+
*/
|
|
1243
|
+
#highestGroupSeen;
|
|
1244
|
+
/**
|
|
1245
|
+
* Creates a new SubscribePublication instance.
|
|
1246
|
+
* @param client - The MOQT client managing the subscription.
|
|
1247
|
+
* @param track - The track being published.
|
|
1248
|
+
* @param subscribeMsg - The subscribe message containing subscription details.
|
|
1249
|
+
* @param requestStream - The bidi request stream the SUBSCRIBE arrived on. Every
|
|
1250
|
+
* message this publication sends back to the subscriber goes on it.
|
|
1251
|
+
* @param largestLocation - The largest location seen so far, used for determining start location.
|
|
1252
|
+
*/
|
|
1253
|
+
constructor(client, track, subscribeMsg, requestStream, largestLocation) {
|
|
1254
|
+
this.client = client;
|
|
1255
|
+
this.track = track;
|
|
1256
|
+
this.subscribeMsg = subscribeMsg;
|
|
1257
|
+
this.requestStream = requestStream;
|
|
1258
|
+
this.#trackAlias = track.trackAlias;
|
|
1259
|
+
this.#publisherPriority = track.publisherPriority;
|
|
1260
|
+
const subPriority = subscribeMsg.parameters.find(require_model.MessageParameter.isSubscriberPriority);
|
|
1261
|
+
const fwd = subscribeMsg.parameters.find(require_model.MessageParameter.isForward);
|
|
1262
|
+
const filter = subscribeMsg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
|
|
1263
|
+
this.#subscriberPriority = subPriority?.priority ?? 128;
|
|
1264
|
+
this.#forward = fwd?.forward ?? true;
|
|
1265
|
+
this.#parameters = [...subscribeMsg.parameters];
|
|
1266
|
+
this.#startLocation = new require_model.Location(0n, 0n);
|
|
1267
|
+
switch (filter?.filterType ?? 2) {
|
|
1268
|
+
case 2:
|
|
1269
|
+
if (largestLocation) this.#startLocation = new require_model.Location(largestLocation.group, largestLocation.object + 1n);
|
|
1270
|
+
else this.#startLocation = new require_model.Location(0n, 0n);
|
|
1271
|
+
break;
|
|
1272
|
+
case 1:
|
|
1273
|
+
if (largestLocation) this.#startLocation = new require_model.Location(largestLocation.group + 1n, 0n);
|
|
1274
|
+
else this.#startLocation = new require_model.Location(0n, 0n);
|
|
1275
|
+
break;
|
|
1276
|
+
case 3:
|
|
1277
|
+
this.#startLocation = filter?.startLocation ?? new require_model.Location(0n, 0n);
|
|
1278
|
+
break;
|
|
1279
|
+
case 4:
|
|
1280
|
+
this.#startLocation = filter?.startLocation ?? new require_model.Location(0n, 0n);
|
|
1281
|
+
this.#endGroup = filter?.endGroup;
|
|
1282
|
+
break;
|
|
1283
|
+
}
|
|
1284
|
+
this.publish();
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* Calculates the stream priority based on publisher and subscriber priorities.
|
|
1288
|
+
*/
|
|
1289
|
+
get #streamPriority() {
|
|
1290
|
+
return .4 * getTransportPriority(this.#publisherPriority) + .6 * getTransportPriority(this.#subscriberPriority);
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Cancels the publication and cleans up resources.
|
|
1294
|
+
* Removes the publication from the client's publication map.
|
|
1295
|
+
*/
|
|
1296
|
+
cancel() {
|
|
1297
|
+
if (this.#cancelPublishing) {
|
|
1298
|
+
this.#cancelPublishing();
|
|
1299
|
+
this.client.publications.delete(this.subscribeMsg.requestId);
|
|
1300
|
+
}
|
|
1301
|
+
this.#isCompleted = true;
|
|
1302
|
+
}
|
|
1303
|
+
/**
|
|
1304
|
+
* Marks the publication as done and sends a PublishDone message to the client.
|
|
1305
|
+
* @param statusCode - The status code indicating why the publication ended.
|
|
1306
|
+
* @throws :{@link InternalError} If sending the message fails.
|
|
1307
|
+
*/
|
|
1308
|
+
async done(statusCode) {
|
|
1309
|
+
this.#isCompleted = true;
|
|
1310
|
+
const publishDone = new require_model.PublishDone(statusCode, BigInt(this.#streamsOpened), new require_model.ReasonPhrase("Subscription ended"));
|
|
1311
|
+
await this.requestStream.send(publishDone);
|
|
1312
|
+
}
|
|
1313
|
+
/**
|
|
1314
|
+
* Updates the subscription parameters and locations based on a RequestUpdate message.
|
|
1315
|
+
* @param msg - The update message containing new request details.
|
|
1316
|
+
*/
|
|
1317
|
+
update(msg) {
|
|
1318
|
+
const filter = msg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
|
|
1319
|
+
if (filter?.startLocation !== void 0) this.#startLocation = filter.startLocation;
|
|
1320
|
+
if (filter?.endGroup !== void 0) this.#endGroup = filter.endGroup;
|
|
1321
|
+
for (const param of msg.parameters) if (require_model.MessageParameter.isSubscriberPriority?.(param)) this.#subscriberPriority = param.priority;
|
|
1322
|
+
else if (require_model.MessageParameter.isForward?.(param)) this.#forward = param.forward;
|
|
1323
|
+
require_model.applyMessageParameterUpdate(this.#parameters, msg.parameters);
|
|
1324
|
+
}
|
|
1325
|
+
#markGroupSeen(group) {
|
|
1326
|
+
if (this.#highestGroupSeen === void 0 || group > this.#highestGroupSeen) this.#highestGroupSeen = group;
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* Publishes MOQT objects to the subscriber as they become available.
|
|
1330
|
+
* Handles stream creation, object writing, and stream closure based on subscription parameters.
|
|
1331
|
+
* @throws :{@link InternalError} If the track does not support live content.
|
|
1332
|
+
*/
|
|
1333
|
+
async publish() {
|
|
1334
|
+
if (!this.track.trackSource.live) throw new require_model.InternalError("SubscribePublication.publish", "Track does not support live content");
|
|
1335
|
+
this.track.trackSource.live.onDone(() => {
|
|
1336
|
+
this.done(2);
|
|
1337
|
+
});
|
|
1338
|
+
this.#highestGroupSeen = this.track.trackSource.live.largestLocation?.group;
|
|
1339
|
+
this.#cancelPublishing = this.track.trackSource.live.onNewObject(async (obj) => {
|
|
1340
|
+
if (this.#isCompleted) return;
|
|
1341
|
+
if (!this.#forward) {
|
|
1342
|
+
this.#markGroupSeen(obj.location.group);
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
if (!this.#isStarted && this.#startLocation.compare(obj.location) <= 0) this.#isStarted = true;
|
|
1346
|
+
if (!this.#isStarted) this.#markGroupSeen(obj.location.group);
|
|
1347
|
+
if (this.#isStarted) try {
|
|
1348
|
+
if (!this.#streams.has(obj.location.group)) {
|
|
1349
|
+
await this.#lock.acquire();
|
|
1350
|
+
if (!this.#streams.has(obj.location.group)) {
|
|
1351
|
+
const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
|
|
1352
|
+
const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
|
|
1353
|
+
const headerType = obj.getSubgroupHeaderType(true, false, firstObject);
|
|
1354
|
+
let subgroupId;
|
|
1355
|
+
if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType)) subgroupId = obj.subgroupId;
|
|
1356
|
+
const header = new require_model.SubgroupHeader(headerType, this.#trackAlias, obj.location.group, subgroupId, this.#publisherPriority);
|
|
1357
|
+
const sendStream = await SendStream.new(writeStream, header);
|
|
1358
|
+
this.#streams.set(obj.location.group, sendStream);
|
|
1359
|
+
this.#streamsOpened++;
|
|
1360
|
+
this.#markGroupSeen(obj.location.group);
|
|
1361
|
+
}
|
|
1362
|
+
await this.#lock.release();
|
|
1363
|
+
}
|
|
1364
|
+
const sendStream = this.#streams.get(obj.location.group);
|
|
1365
|
+
await this.#lock.acquire();
|
|
1366
|
+
await sendStream.write(obj.tryIntoSubgroupObject());
|
|
1367
|
+
await this.#lock.release();
|
|
1368
|
+
if (this.#endGroup && obj.location.group === this.#endGroup) {
|
|
1369
|
+
try {
|
|
1370
|
+
await this.#lock.acquire();
|
|
1371
|
+
if (this.#streams.has(obj.location.group)) {
|
|
1372
|
+
await sendStream.close();
|
|
1373
|
+
this.#streams.delete(obj.location.group);
|
|
1374
|
+
}
|
|
1375
|
+
await this.#lock.release();
|
|
1376
|
+
} catch (err) {
|
|
1377
|
+
require_logger.logger.warn("publication/subscribe", "error in closing stream: id, endGroup, err", this.#id, this.#endGroup, err);
|
|
1378
|
+
}
|
|
1379
|
+
await this.done(3);
|
|
1380
|
+
this.cancel();
|
|
1381
|
+
} else if (this.latestLocation && this.latestLocation.group !== obj.location.group) {
|
|
1382
|
+
const prevGroup = this.latestLocation.group;
|
|
1383
|
+
try {
|
|
1384
|
+
await this.#lock.acquire();
|
|
1385
|
+
const prevStream = this.#streams.get(prevGroup);
|
|
1386
|
+
if (prevStream) {
|
|
1387
|
+
try {
|
|
1388
|
+
await prevStream.close();
|
|
1389
|
+
} catch (err) {
|
|
1390
|
+
require_logger.logger.warn("publication/subscribe", "error in closing stream", prevGroup, err);
|
|
1391
|
+
}
|
|
1392
|
+
this.#streams.delete(prevGroup);
|
|
1393
|
+
}
|
|
1394
|
+
await this.#lock.release();
|
|
1395
|
+
} catch (err) {
|
|
1396
|
+
require_logger.logger.warn("publication/subscribe", "error in closing stream: id, latestLocation.group, err", this.#id, this.latestLocation.group, err);
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
await this.#lock.acquire();
|
|
1400
|
+
this.latestLocation = obj.location;
|
|
1401
|
+
await this.#lock.release();
|
|
1402
|
+
} catch (err) {
|
|
1403
|
+
this.cancel();
|
|
1404
|
+
throw err;
|
|
1405
|
+
}
|
|
1406
|
+
});
|
|
1407
|
+
}
|
|
1408
|
+
};
|
|
1409
|
+
//#endregion
|
|
1410
|
+
//#region src/client/publication/fetch.ts
|
|
1411
|
+
/**
|
|
1412
|
+
* Copyright 2025 The MOQtail Authors
|
|
1413
|
+
*
|
|
1414
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1415
|
+
* you may not use this file except in compliance with the License.
|
|
1416
|
+
* You may obtain a copy of the License at
|
|
1417
|
+
*
|
|
1418
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1419
|
+
*
|
|
1420
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1421
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1422
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1423
|
+
* See the License for the specific language governing permissions and
|
|
1424
|
+
* limitations under the License.
|
|
1425
|
+
*/
|
|
1426
|
+
var FetchPublication = class {
|
|
1427
|
+
#requestId;
|
|
1428
|
+
#track;
|
|
1429
|
+
#startLocation;
|
|
1430
|
+
#endLocation;
|
|
1431
|
+
#msg;
|
|
1432
|
+
#client;
|
|
1433
|
+
#stream;
|
|
1434
|
+
#writer;
|
|
1435
|
+
#objects;
|
|
1436
|
+
#isCanceled = false;
|
|
1437
|
+
constructor(client, track, fetchRequest) {
|
|
1438
|
+
this.#client = client;
|
|
1439
|
+
this.#requestId = fetchRequest.requestId;
|
|
1440
|
+
this.#track = track;
|
|
1441
|
+
this.#msg = fetchRequest;
|
|
1442
|
+
let joiningRequest;
|
|
1443
|
+
switch (this.#msg.typeAndProps.type) {
|
|
1444
|
+
case 1:
|
|
1445
|
+
this.#startLocation = this.#msg.typeAndProps.props.startLocation;
|
|
1446
|
+
this.#endLocation = this.#msg.typeAndProps.props.endLocation;
|
|
1447
|
+
break;
|
|
1448
|
+
case 2:
|
|
1449
|
+
joiningRequest = client.publications.get(this.#msg.typeAndProps.props.joiningRequestId);
|
|
1450
|
+
if (!(joiningRequest instanceof SubscribePublication)) throw new require_model.InternalError("FetchPublication.constructor", "No subscription for the joining request id");
|
|
1451
|
+
if (!joiningRequest.latestLocation) throw new require_model.InternalError("FetchPublication.constructor", "joiningRequest.largestLocation does not exist");
|
|
1452
|
+
this.#startLocation = new require_model.Location(joiningRequest.latestLocation.group - this.#msg.typeAndProps.props.joiningStart, 0n);
|
|
1453
|
+
this.#endLocation = joiningRequest.latestLocation;
|
|
1454
|
+
break;
|
|
1455
|
+
case 3:
|
|
1456
|
+
joiningRequest = client.publications.get(this.#msg.typeAndProps.props.joiningRequestId);
|
|
1457
|
+
if (!(joiningRequest instanceof SubscribePublication)) throw new require_model.InternalError("FetchPublication.constructor", "No subscription for the joining request id");
|
|
1458
|
+
if (!joiningRequest.latestLocation) throw new require_model.InternalError("FetchPublication.constructor", "joiningRequest.largestLocation does not exist");
|
|
1459
|
+
this.#startLocation = new require_model.Location(this.#msg.typeAndProps.props.joiningStart, 0n);
|
|
1460
|
+
this.#endLocation = joiningRequest.latestLocation;
|
|
1461
|
+
break;
|
|
1462
|
+
}
|
|
1463
|
+
require_logger.logger.debug("publication/fetch", `created requestId=${this.#requestId} type=${this.#msg.typeAndProps.type}`);
|
|
1464
|
+
this.publish();
|
|
1465
|
+
}
|
|
1466
|
+
cancel() {
|
|
1467
|
+
require_logger.logger.debug("publication/fetch", `canceled requestId=${this.#requestId}`);
|
|
1468
|
+
this.#isCanceled = true;
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Resets the data stream this fetch is being delivered on, which §10.9.1 requires when
|
|
1472
|
+
* a REQUEST_UPDATE for a FETCH fails.
|
|
1473
|
+
*/
|
|
1474
|
+
async resetDataStream(code) {
|
|
1475
|
+
require_logger.logger.debug("publication/fetch", `reset data stream requestId=${this.#requestId} code=${code}`);
|
|
1476
|
+
this.#isCanceled = true;
|
|
1477
|
+
await this.#writer?.abort(streamResetReason(code)).catch(() => {});
|
|
1478
|
+
}
|
|
1479
|
+
async publish() {
|
|
1480
|
+
if (this.#isCanceled) return;
|
|
1481
|
+
if (!this.#track.trackSource.past) throw new require_model.MOQtailError("FetchPublication.publish, Track does not support fetch");
|
|
1482
|
+
require_logger.logger.debug("publication/fetch", `publishing requestId=${this.#requestId} start=${this.#startLocation} end=${this.#endLocation}`);
|
|
1483
|
+
try {
|
|
1484
|
+
this.#objects = await this.#track.trackSource.past.getRange(this.#startLocation, this.#endLocation);
|
|
1485
|
+
this.#stream = await this.#client.webTransport.createUnidirectionalStream();
|
|
1486
|
+
this.#writer = this.#stream.getWriter();
|
|
1487
|
+
const header = new require_model.FetchHeader(5, this.#requestId);
|
|
1488
|
+
await this.#writer.write(header);
|
|
1489
|
+
const groupOrder = require_model.MessageParameter.groupOrderOf(this.#msg.parameters);
|
|
1490
|
+
let fetchPrevCtx = void 0;
|
|
1491
|
+
for (const obj of this.#objects) {
|
|
1492
|
+
if (this.#isCanceled) {
|
|
1493
|
+
require_logger.logger.debug("publication/fetch", `aborted during publish requestId=${this.#requestId}`);
|
|
1494
|
+
await this.#writer.abort(streamResetReason(1));
|
|
1495
|
+
this.#client.publications.delete(this.#requestId);
|
|
1496
|
+
return;
|
|
1497
|
+
}
|
|
1498
|
+
const fetchObj = obj.tryIntoFetchObject();
|
|
1499
|
+
await this.#writer.write(fetchObj.serialize(fetchPrevCtx, groupOrder).toUint8Array());
|
|
1500
|
+
const newCtx = fetchObj.toContext();
|
|
1501
|
+
if (newCtx) fetchPrevCtx = newCtx;
|
|
1502
|
+
}
|
|
1503
|
+
await this.#writer.close();
|
|
1504
|
+
require_logger.logger.debug("publication/fetch", `published requestId=${this.#requestId} objects=${this.#objects.length}`);
|
|
1505
|
+
this.#client.publications.delete(this.#requestId);
|
|
1506
|
+
} catch (error) {
|
|
1507
|
+
if (this.#isCanceled) return;
|
|
1508
|
+
await this.#writer?.abort(streamResetReason(0));
|
|
1509
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1510
|
+
require_logger.logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
|
|
1511
|
+
throw new require_model.InternalError("FetchPublication.publish", `Failed to publish: ${message}`);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
};
|
|
1515
|
+
//#endregion
|
|
1516
|
+
//#region src/client/handler/fetch.ts
|
|
1517
|
+
/**
|
|
1518
|
+
* Copyright 2025 The MOQtail Authors
|
|
1519
|
+
*
|
|
1520
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1521
|
+
* you may not use this file except in compliance with the License.
|
|
1522
|
+
* You may obtain a copy of the License at
|
|
1523
|
+
*
|
|
1524
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1525
|
+
*
|
|
1526
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1527
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1528
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1529
|
+
* See the License for the specific language governing permissions and
|
|
1530
|
+
* limitations under the License.
|
|
1531
|
+
*/
|
|
1532
|
+
const handlerFetch = async (client, msg, stream) => {
|
|
1533
|
+
require_logger.logger.log("handler/fetch", "requestId, type", msg.requestId, msg.typeAndProps.type);
|
|
1534
|
+
let fullTrackName;
|
|
1535
|
+
let joiningRequest;
|
|
1536
|
+
switch (msg.typeAndProps.type) {
|
|
1537
|
+
case 1:
|
|
1538
|
+
fullTrackName = msg.typeAndProps.props.fullTrackName;
|
|
1539
|
+
break;
|
|
1540
|
+
case 2:
|
|
1541
|
+
case 3:
|
|
1542
|
+
joiningRequest = client.publications.get(msg.typeAndProps.props.joiningRequestId);
|
|
1543
|
+
if (!(joiningRequest instanceof SubscribePublication)) throw new require_model.InternalError("handlerFetch", "No subscription for the joining request id");
|
|
1544
|
+
fullTrackName = joiningRequest.track.fullTrackName;
|
|
1545
|
+
break;
|
|
1546
|
+
}
|
|
1547
|
+
const track = client.trackSources.get(fullTrackName.toString());
|
|
1548
|
+
if (!track) {
|
|
1549
|
+
const response = new require_model.RequestError(16, 0n, new require_model.ReasonPhrase("Track does not exists"));
|
|
1550
|
+
await stream.send(response);
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
if (!track.trackSource.past) {
|
|
1554
|
+
const response = new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("Requested track does not support fetch"));
|
|
1555
|
+
await stream.send(response);
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
const publication = new FetchPublication(client, track, msg);
|
|
1559
|
+
client.publications.set(msg.requestId, publication);
|
|
1560
|
+
const response = new require_model.FetchOk(false, new require_model.Location(0n, 0n), msg.parameters, track.trackProperties ?? []);
|
|
1561
|
+
await stream.send(response);
|
|
1562
|
+
};
|
|
1563
|
+
//#endregion
|
|
1564
|
+
//#region src/client/handler/fetch_ok.ts
|
|
1565
|
+
/**
|
|
1566
|
+
* Copyright 2025 The MOQtail Authors
|
|
1567
|
+
*
|
|
1568
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1569
|
+
* you may not use this file except in compliance with the License.
|
|
1570
|
+
* You may obtain a copy of the License at
|
|
1571
|
+
*
|
|
1572
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1573
|
+
*
|
|
1574
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1575
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1576
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1577
|
+
* See the License for the specific language governing permissions and
|
|
1578
|
+
* limitations under the License.
|
|
1579
|
+
*/
|
|
1580
|
+
const handlerFetchOk = async (client, msg, _stream, requestId) => {
|
|
1581
|
+
require_logger.logger.log("handler/fetch_ok", "requestId", requestId);
|
|
1582
|
+
const request = client.requests.get(requestId);
|
|
1583
|
+
if (request instanceof FetchRequest) {
|
|
1584
|
+
if (msg.trackProperties.length > 0) {
|
|
1585
|
+
const fetchMsg = request.message;
|
|
1586
|
+
let fullTrackName = fetchMsg.typeAndProps.type === 1 ? fetchMsg.typeAndProps.props.fullTrackName : (() => {
|
|
1587
|
+
const joiningReq = client.requests.get(fetchMsg.typeAndProps.props.joiningRequestId);
|
|
1588
|
+
return joiningReq instanceof SubscribeRequest ? joiningReq.fullTrackName : void 0;
|
|
1589
|
+
})();
|
|
1590
|
+
if (fullTrackName !== void 0) {
|
|
1591
|
+
const track = client.trackSources.get(fullTrackName.toString());
|
|
1592
|
+
if (track !== void 0) track.trackProperties = msg.trackProperties;
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
request.resolve(msg);
|
|
1596
|
+
} else throw new require_model.ProtocolViolationError("handlerFetchOk", `FETCH_OK on a stream with no pending fetch request (request id ${requestId})`);
|
|
1597
|
+
};
|
|
1598
|
+
//#endregion
|
|
1599
|
+
//#region src/client/handler/goaway.ts
|
|
1600
|
+
const handlerGoAway = async (client, msg) => {
|
|
1601
|
+
require_logger.logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout, "requestId", msg.requestId);
|
|
1602
|
+
if (client.goawayReceived) {
|
|
1603
|
+
await client.disconnect(new require_model.ProtocolViolationError("handler/goaway", "A second GOAWAY arrived on the control stream"));
|
|
1604
|
+
return;
|
|
1605
|
+
}
|
|
1606
|
+
client.goawayReceived = true;
|
|
1607
|
+
if (client.onGoaway) client.onGoaway(msg);
|
|
1608
|
+
};
|
|
1609
|
+
/**
|
|
1610
|
+
* GOAWAY on a request stream: the peer is migrating that one request (§10.4). The
|
|
1611
|
+
* request is re-issued on a fresh stream and the session, along with every other request
|
|
1612
|
+
* on it, carries on.
|
|
1613
|
+
*/
|
|
1614
|
+
const handlerGoAwayOnRequestStream = async (client, msg, _stream, requestId) => {
|
|
1615
|
+
require_logger.logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
|
|
1616
|
+
await client.migrateRequest(requestId, msg);
|
|
1617
|
+
};
|
|
1618
|
+
//#endregion
|
|
1619
|
+
//#region src/client/util/validators.ts
|
|
1620
|
+
/**
|
|
1621
|
+
* Copyright 2026 The MOQtail Authors
|
|
1622
|
+
*
|
|
1623
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1624
|
+
* you may not use this file except in compliance with the License.
|
|
1625
|
+
* You may obtain a copy of the License at
|
|
1626
|
+
*
|
|
1627
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1628
|
+
*
|
|
1629
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1630
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1631
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1632
|
+
* See the License for the specific language governing permissions and
|
|
1633
|
+
* limitations under the License.
|
|
1634
|
+
*/
|
|
1635
|
+
/** Returns true when `trackAlias` is a valid (non-negative) track alias. Zero is a legal value. */
|
|
1636
|
+
function isValidTrackAlias(trackAlias) {
|
|
1637
|
+
return trackAlias !== void 0 && trackAlias >= 0n;
|
|
1638
|
+
}
|
|
1639
|
+
//#endregion
|
|
1640
|
+
//#region src/client/handler/subscribe.ts
|
|
1641
|
+
/**
|
|
1642
|
+
* Copyright 2025 The MOQtail Authors
|
|
1643
|
+
*
|
|
1644
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1645
|
+
* you may not use this file except in compliance with the License.
|
|
1646
|
+
* You may obtain a copy of the License at
|
|
1647
|
+
*
|
|
1648
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1649
|
+
*
|
|
1650
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1651
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1652
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1653
|
+
* See the License for the specific language governing permissions and
|
|
1654
|
+
* limitations under the License.
|
|
1655
|
+
*/
|
|
1656
|
+
const handlerSubscribe = async (client, msg, stream) => {
|
|
1657
|
+
require_logger.logger.debug("handler/subscribe", `received requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
|
|
1658
|
+
const track = client.trackSources.get(msg.fullTrackName.toString());
|
|
1659
|
+
if (!track) {
|
|
1660
|
+
require_logger.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track not found, sending REQUEST_ERROR`);
|
|
1661
|
+
const subscribeError = new require_model.RequestError(16, 0n, new require_model.ReasonPhrase("Track does not exist"));
|
|
1662
|
+
await stream.send(subscribeError);
|
|
1663
|
+
return;
|
|
1664
|
+
}
|
|
1665
|
+
if (!track.trackSource.live) {
|
|
1666
|
+
require_logger.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track has no live source, sending REQUEST_ERROR`);
|
|
1667
|
+
const response = new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("Requested track does not support subscribe"));
|
|
1668
|
+
await stream.send(response);
|
|
1669
|
+
return;
|
|
1670
|
+
}
|
|
1671
|
+
if (!isValidTrackAlias(track.trackAlias)) throw new Error("Expected track alias to be set");
|
|
1672
|
+
const largestLocation = track.trackSource.live.largestLocation;
|
|
1673
|
+
const parameters = [...msg.parameters];
|
|
1674
|
+
if (largestLocation) parameters.push(new require_model.LargestObject(largestLocation));
|
|
1675
|
+
require_logger.logger.debug("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" trackAlias=${track.trackAlias} largestLocation=${largestLocation ? `${largestLocation.group}:${largestLocation.object}` : "none"} — sending SUBSCRIBE_OK`);
|
|
1676
|
+
const subscribeOk = require_model.SubscribeOk.create(track.trackAlias, parameters, track.trackProperties ?? []);
|
|
1677
|
+
const publication = new SubscribePublication(client, track, msg, stream, largestLocation);
|
|
1678
|
+
client.publications.set(msg.requestId, publication);
|
|
1679
|
+
await stream.send(subscribeOk);
|
|
1680
|
+
require_logger.logger.debug("handler/subscribe", `requestId=${msg.requestId} — SUBSCRIBE_OK sent, publication registered`);
|
|
1681
|
+
};
|
|
1682
|
+
//#endregion
|
|
1683
|
+
//#region src/client/handler/subscribe_namespace.ts
|
|
1684
|
+
/**
|
|
1685
|
+
* Copyright 2025 The MOQtail Authors
|
|
1686
|
+
*
|
|
1687
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1688
|
+
* you may not use this file except in compliance with the License.
|
|
1689
|
+
* You may obtain a copy of the License at
|
|
1690
|
+
*
|
|
1691
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1692
|
+
*
|
|
1693
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1694
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1695
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1696
|
+
* See the License for the specific language governing permissions and
|
|
1697
|
+
* limitations under the License.
|
|
1698
|
+
*/
|
|
1699
|
+
const handlerSubscribeNamespace = async (client, msg, stream) => {
|
|
1700
|
+
require_logger.logger.log("handler/subscribe_namespace", "namespace", msg.trackNamespacePrefix.toUtf8Path());
|
|
1701
|
+
if (client.onPeerSubscribeNamespace) client.onPeerSubscribeNamespace(msg);
|
|
1702
|
+
await stream.send(new require_model.RequestOk());
|
|
1703
|
+
};
|
|
1704
|
+
//#endregion
|
|
1705
|
+
//#region src/client/handler/subscribe_tracks.ts
|
|
1706
|
+
/**
|
|
1707
|
+
* Copyright 2026 The MOQtail Authors
|
|
1708
|
+
*
|
|
1709
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1710
|
+
* you may not use this file except in compliance with the License.
|
|
1711
|
+
* You may obtain a copy of the License at
|
|
1712
|
+
*
|
|
1713
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1714
|
+
*
|
|
1715
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1716
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1717
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1718
|
+
* See the License for the specific language governing permissions and
|
|
1719
|
+
* limitations under the License.
|
|
1720
|
+
*/
|
|
1721
|
+
const handlerSubscribeTracks = async (client, msg, stream) => {
|
|
1722
|
+
require_logger.logger.log("handler/subscribe_tracks", "prefix", msg.trackNamespacePrefix.toUtf8Path());
|
|
1723
|
+
if (client.onPeerSubscribeTracks) client.onPeerSubscribeTracks(msg);
|
|
1724
|
+
await stream.send(new require_model.RequestOk());
|
|
1725
|
+
};
|
|
1726
|
+
//#endregion
|
|
1727
|
+
//#region src/client/request/subscribe_namespace.ts
|
|
1728
|
+
/**
|
|
1729
|
+
* Copyright 2026 The MOQtail Authors
|
|
1730
|
+
*
|
|
1731
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1732
|
+
* you may not use this file except in compliance with the License.
|
|
1733
|
+
* You may obtain a copy of the License at
|
|
1734
|
+
*
|
|
1735
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1736
|
+
*
|
|
1737
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1738
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1739
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1740
|
+
* See the License for the specific language governing permissions and
|
|
1741
|
+
* limitations under the License.
|
|
1742
|
+
*/
|
|
1743
|
+
var SubscribeNamespaceRequest = class {
|
|
1744
|
+
requestId;
|
|
1745
|
+
message;
|
|
1746
|
+
_resolve;
|
|
1747
|
+
_reject;
|
|
1748
|
+
promise;
|
|
1749
|
+
constructor(msg) {
|
|
1750
|
+
this.requestId = msg.requestId;
|
|
1751
|
+
this.message = msg;
|
|
1752
|
+
this.promise = new Promise((resolve, reject) => {
|
|
1753
|
+
this._resolve = resolve;
|
|
1754
|
+
this._reject = reject;
|
|
1755
|
+
});
|
|
1756
|
+
require_logger.logger.debug("request/subscribe_namespace", `created requestId=${this.requestId} namespace="${msg.trackNamespacePrefix}"`);
|
|
1757
|
+
}
|
|
1758
|
+
resolve(value) {
|
|
1759
|
+
if (value instanceof require_model.RequestError) require_logger.logger.error("request/subscribe_namespace", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
|
|
1760
|
+
else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/subscribe_namespace", `resolved with OK requestId=${this.requestId}`);
|
|
1761
|
+
this._resolve(value);
|
|
1762
|
+
}
|
|
1763
|
+
reject(reason) {
|
|
1764
|
+
require_logger.logger.error("request/subscribe_namespace", `rejected requestId=${this.requestId}`, reason);
|
|
1765
|
+
this._reject(reason);
|
|
1766
|
+
}
|
|
1767
|
+
then(onfulfilled, onrejected) {
|
|
1768
|
+
return this.promise.then(onfulfilled, onrejected);
|
|
1769
|
+
}
|
|
1770
|
+
catch(onrejected) {
|
|
1771
|
+
return this.promise.catch(onrejected);
|
|
1772
|
+
}
|
|
1773
|
+
finally(onfinally) {
|
|
1774
|
+
return this.promise.finally(onfinally);
|
|
1775
|
+
}
|
|
1776
|
+
};
|
|
1777
|
+
//#endregion
|
|
1778
|
+
//#region src/client/publication/publish.ts
|
|
1779
|
+
/**
|
|
1780
|
+
* @public
|
|
1781
|
+
* Manages the proactive publication of MOQT objects from a publisher to the relay.
|
|
1782
|
+
* Handles live object streaming and stream management.
|
|
1783
|
+
*/
|
|
1784
|
+
var PublishPublication = class {
|
|
1785
|
+
client;
|
|
1786
|
+
track;
|
|
1787
|
+
publishMsg;
|
|
1788
|
+
/**
|
|
1789
|
+
* The latest location that was published to the relay.
|
|
1790
|
+
*/
|
|
1791
|
+
latestLocation;
|
|
1792
|
+
/**
|
|
1793
|
+
* The alias for the track being published.
|
|
1794
|
+
*/
|
|
1795
|
+
#trackAlias;
|
|
1796
|
+
/**
|
|
1797
|
+
* The priority of the publisher.
|
|
1798
|
+
*/
|
|
1799
|
+
#publisherPriority;
|
|
1800
|
+
/**
|
|
1801
|
+
* The number of streams opened for this publication.
|
|
1802
|
+
*/
|
|
1803
|
+
#streamsOpened = 0n;
|
|
1804
|
+
/**
|
|
1805
|
+
* Function to cancel publishing, if set.
|
|
1806
|
+
*/
|
|
1807
|
+
#cancelPublishing;
|
|
1808
|
+
/**
|
|
1809
|
+
* Whether publishing is completed/cancelled.
|
|
1810
|
+
*/
|
|
1811
|
+
#isCompleted = false;
|
|
1812
|
+
/**
|
|
1813
|
+
* Lock for synchronizing stream operations.
|
|
1814
|
+
*/
|
|
1815
|
+
#lock = new SimpleLock();
|
|
1816
|
+
/**
|
|
1817
|
+
* Map of group IDs to their corresponding send streams.
|
|
1818
|
+
*/
|
|
1819
|
+
#streams = /* @__PURE__ */ new Map();
|
|
1820
|
+
/**
|
|
1821
|
+
* Unique identifier for this publication instance.
|
|
1822
|
+
*/
|
|
1823
|
+
#id = Math.floor(Math.random() * 1e6);
|
|
1824
|
+
/**
|
|
1825
|
+
* Whether the peer is taking Objects right now. A PUBLISH may declare FORWARD=0, and
|
|
1826
|
+
* then nothing is sent until the peer raises it -- in its PUBLISH_OK, or later with a
|
|
1827
|
+
* REQUEST_UPDATE on this publication's own request stream.
|
|
1828
|
+
*/
|
|
1829
|
+
#forward;
|
|
1830
|
+
/**
|
|
1831
|
+
* The parameters this publication currently holds. An update amends them rather than
|
|
1832
|
+
* replacing them, so a parameter the update leaves out keeps the value it had.
|
|
1833
|
+
*/
|
|
1834
|
+
#parameters;
|
|
1835
|
+
/**
|
|
1836
|
+
* Highest group this publication has already opened a stream for or skipped objects of.
|
|
1837
|
+
* A stream for a group at or below it reopens a subgroup, so it cannot claim FIRST_OBJECT.
|
|
1838
|
+
*/
|
|
1839
|
+
#highestGroupSeen;
|
|
1840
|
+
/**
|
|
1841
|
+
* Creates a new PublishPublication instance.
|
|
1842
|
+
* @param client - The MOQT client managing the connection.
|
|
1843
|
+
* @param track - The track being proactively published.
|
|
1844
|
+
* @param publishMsg - The publish message that initiated this session.
|
|
1845
|
+
*/
|
|
1846
|
+
constructor(client, track, publishMsg) {
|
|
1847
|
+
this.client = client;
|
|
1848
|
+
this.track = track;
|
|
1849
|
+
this.publishMsg = publishMsg;
|
|
1850
|
+
this.#trackAlias = track.trackAlias;
|
|
1851
|
+
this.#publisherPriority = track.publisherPriority;
|
|
1852
|
+
this.#parameters = [...publishMsg.parameters];
|
|
1853
|
+
this.#forward = publishMsg.parameters.find(require_model.MessageParameter.isForward)?.forward ?? true;
|
|
1854
|
+
this.publishToRelay();
|
|
1855
|
+
}
|
|
1856
|
+
/**
|
|
1857
|
+
* How many data streams this publication has opened, which is what a PUBLISH_DONE
|
|
1858
|
+
* reports to the subscriber.
|
|
1859
|
+
*/
|
|
1860
|
+
get streamsOpened() {
|
|
1861
|
+
return this.#streamsOpened;
|
|
1862
|
+
}
|
|
1863
|
+
/**
|
|
1864
|
+
* Whether Objects are being sent right now. False while the peer holds this
|
|
1865
|
+
* publication at FORWARD=0.
|
|
1866
|
+
*/
|
|
1867
|
+
get forwarding() {
|
|
1868
|
+
return this.#forward;
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* Moves the Forward State: false parks the publication, true resumes it. The
|
|
1872
|
+
* application hears about the move through {@link MOQtailClient.onForwardStateChange},
|
|
1873
|
+
* which is where a publisher starts or stops the work behind the track -- a camera
|
|
1874
|
+
* and an encoder cost the same whether or not anything is listening.
|
|
1875
|
+
*/
|
|
1876
|
+
setForwardState(forward) {
|
|
1877
|
+
if (this.#forward === forward) return;
|
|
1878
|
+
this.#forward = forward;
|
|
1879
|
+
this.client.onForwardStateChange?.(this.publishMsg.requestId, forward);
|
|
1880
|
+
}
|
|
1881
|
+
/**
|
|
1882
|
+
* Applies a REQUEST_UPDATE the peer sent on this publication's request stream. The
|
|
1883
|
+
* Forward State is the one thing it can move; what a publisher sends, and when,
|
|
1884
|
+
* is otherwise its own to decide.
|
|
1885
|
+
*/
|
|
1886
|
+
update(msg) {
|
|
1887
|
+
const forward = msg.parameters.find(require_model.MessageParameter.isForward);
|
|
1888
|
+
if (forward) this.setForwardState(forward.forward);
|
|
1889
|
+
require_model.applyMessageParameterUpdate(this.#parameters, msg.parameters);
|
|
1890
|
+
}
|
|
1891
|
+
/**
|
|
1892
|
+
* Calculates the stream priority based on publisher priority.
|
|
1893
|
+
* (Since this is a proactive push, there is no subscriber priority to average with).
|
|
1894
|
+
*/
|
|
1895
|
+
get #streamPriority() {
|
|
1896
|
+
return getTransportPriority(this.#publisherPriority);
|
|
1897
|
+
}
|
|
1898
|
+
/**
|
|
1899
|
+
* Cancels the publication and cleans up resources.
|
|
1900
|
+
* Removes the publication from the client's publication map.
|
|
1901
|
+
*/
|
|
1902
|
+
cancel() {
|
|
1903
|
+
if (this.#cancelPublishing) {
|
|
1904
|
+
this.#cancelPublishing();
|
|
1905
|
+
this.client.publications.delete(this.publishMsg.requestId);
|
|
1906
|
+
}
|
|
1907
|
+
this.#isCompleted = true;
|
|
1908
|
+
this.#lock.acquire().then(() => {
|
|
1909
|
+
for (const [groupId, stream] of this.#streams.entries()) stream.close().catch((e) => require_logger.logger.warn("publication/publish", `Failed to close stream for group ${groupId}:`, e));
|
|
1910
|
+
this.#streams.clear();
|
|
1911
|
+
this.#lock.release();
|
|
1912
|
+
});
|
|
1913
|
+
}
|
|
1914
|
+
#markGroupSeen(group) {
|
|
1915
|
+
if (this.#highestGroupSeen === void 0 || group > this.#highestGroupSeen) this.#highestGroupSeen = group;
|
|
1916
|
+
}
|
|
1917
|
+
/**
|
|
1918
|
+
* Publishes MOQT objects to the relay as they become available.
|
|
1919
|
+
* Handles stream creation, object writing, and stream closure.
|
|
1920
|
+
* @throws :{@link InternalError} If the track does not support live content.
|
|
1921
|
+
*/
|
|
1922
|
+
async publishToRelay() {
|
|
1923
|
+
if (!this.track.trackSource.live) throw new require_model.InternalError("PublishPublication.publishToRelay", "Track does not support live content");
|
|
1924
|
+
this.track.trackSource.live.onDone(() => {
|
|
1925
|
+
this.cancel();
|
|
1926
|
+
});
|
|
1927
|
+
this.#highestGroupSeen = this.track.trackSource.live.largestLocation?.group;
|
|
1928
|
+
this.#cancelPublishing = this.track.trackSource.live.onNewObject(async (obj) => {
|
|
1929
|
+
if (this.#isCompleted) return;
|
|
1930
|
+
if (!this.#forward) {
|
|
1931
|
+
this.#markGroupSeen(obj.location.group);
|
|
1932
|
+
return;
|
|
1933
|
+
}
|
|
1934
|
+
try {
|
|
1935
|
+
if (!this.#streams.has(obj.location.group)) {
|
|
1936
|
+
await this.#lock.acquire();
|
|
1937
|
+
if (!this.#streams.has(obj.location.group)) {
|
|
1938
|
+
const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
|
|
1939
|
+
const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
|
|
1940
|
+
const headerType = obj.getSubgroupHeaderType(true, false, firstObject);
|
|
1941
|
+
let subgroupId;
|
|
1942
|
+
if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType)) subgroupId = obj.subgroupId;
|
|
1943
|
+
const header = new require_model.SubgroupHeader(headerType, this.#trackAlias, obj.location.group, subgroupId, this.#publisherPriority);
|
|
1944
|
+
const sendStream = await SendStream.new(writeStream, header);
|
|
1945
|
+
this.#streams.set(obj.location.group, sendStream);
|
|
1946
|
+
this.#streamsOpened++;
|
|
1947
|
+
this.#markGroupSeen(obj.location.group);
|
|
1948
|
+
}
|
|
1949
|
+
await this.#lock.release();
|
|
1950
|
+
}
|
|
1951
|
+
const sendStream = this.#streams.get(obj.location.group);
|
|
1952
|
+
await this.#lock.acquire();
|
|
1953
|
+
await sendStream.write(obj.tryIntoSubgroupObject());
|
|
1954
|
+
await this.#lock.release();
|
|
1955
|
+
if (this.latestLocation && this.latestLocation.group !== obj.location.group) {
|
|
1956
|
+
const prevGroup = this.latestLocation.group;
|
|
1957
|
+
try {
|
|
1958
|
+
await this.#lock.acquire();
|
|
1959
|
+
const prevStream = this.#streams.get(prevGroup);
|
|
1960
|
+
if (prevStream) {
|
|
1961
|
+
try {
|
|
1962
|
+
await prevStream.close();
|
|
1963
|
+
} catch (err) {
|
|
1964
|
+
require_logger.logger.warn("publication/publish", "error in closing stream", prevGroup, err);
|
|
1965
|
+
}
|
|
1966
|
+
this.#streams.delete(prevGroup);
|
|
1967
|
+
}
|
|
1968
|
+
await this.#lock.release();
|
|
1969
|
+
} catch (err) {
|
|
1970
|
+
require_logger.logger.warn("publication/publish", "error in closing stream: id, latestLocation.group, err", this.#id, this.latestLocation.group, err);
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
await this.#lock.acquire();
|
|
1974
|
+
this.latestLocation = obj.location;
|
|
1975
|
+
await this.#lock.release();
|
|
1976
|
+
} catch (err) {
|
|
1977
|
+
this.cancel();
|
|
1978
|
+
throw err;
|
|
1979
|
+
}
|
|
1980
|
+
});
|
|
1981
|
+
}
|
|
1982
|
+
};
|
|
1983
|
+
//#endregion
|
|
1984
|
+
//#region src/client/handler/request_ok.ts
|
|
1985
|
+
const handlerRequestOk = async (client, msg, _stream, requestId) => {
|
|
1986
|
+
require_logger.logger.log("handler/request_ok", "received RequestOk for requestId:", requestId);
|
|
1987
|
+
const request = client.requests.get(requestId);
|
|
1988
|
+
if (!request) {
|
|
1989
|
+
require_logger.logger.warn("handler/request_ok", `Received RequestOk for unknown or already-resolved request id: ${requestId}`);
|
|
1990
|
+
return;
|
|
1991
|
+
}
|
|
1992
|
+
msg.validateTrackProperties(request instanceof TrackStatusRequest);
|
|
1993
|
+
if (request instanceof PublishRequest) {
|
|
1994
|
+
request.resolve(msg);
|
|
1995
|
+
const fullTrackName = client.requestIdMap.getNameByRequestId(requestId);
|
|
1996
|
+
if (!fullTrackName) {
|
|
1997
|
+
require_logger.logger.warn("handler/request_ok", `No track mapped for PublishRequest requestId: ${requestId}`);
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
const track = client.trackSources.get(fullTrackName.toString());
|
|
2001
|
+
if (!track || !track.trackSource.live) {
|
|
2002
|
+
require_logger.logger.warn("handler/request_ok", `Live track source not found for ${fullTrackName.toString()}`);
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
2005
|
+
const publication = new PublishPublication(client, track, request.message);
|
|
2006
|
+
client.publications.set(requestId, publication);
|
|
2007
|
+
const forward = msg.parameters.find(require_model.MessageParameter.isForward);
|
|
2008
|
+
if (forward) publication.setForwardState(forward.forward);
|
|
2009
|
+
return;
|
|
2010
|
+
}
|
|
2011
|
+
if (request instanceof PublishNamespaceRequest || request instanceof SubscribeNamespaceRequest || request instanceof TrackStatusRequest) {
|
|
2012
|
+
request.resolve(msg);
|
|
2013
|
+
client.requests.delete(requestId);
|
|
2014
|
+
} else throw new require_model.ProtocolViolationError("handlerRequestOk", `Request ID ${requestId} matched a pending request, but it does not expect a RequestOk response.`);
|
|
2015
|
+
};
|
|
2016
|
+
//#endregion
|
|
2017
|
+
//#region src/client/handler/request_error.ts
|
|
2018
|
+
const handlerRequestError = async (client, msg, _stream, requestId) => {
|
|
2019
|
+
require_logger.logger.error("handler/request_error", `received requestId=${requestId} code=${msg.errorCode} reason="${msg.reasonPhrase.phrase}"`);
|
|
2020
|
+
const request = client.requests.get(requestId);
|
|
2021
|
+
if (!request) {
|
|
2022
|
+
require_logger.logger.warn("handler/request_error", `requestId=${requestId} — no pending request found (already resolved or unknown)`);
|
|
2023
|
+
return;
|
|
2024
|
+
}
|
|
2025
|
+
require_logger.logger.debug("handler/request_error", `requestId=${requestId} — resolving ${request.constructor.name} with error`);
|
|
2026
|
+
if (request instanceof SubscribeRequest || request instanceof PublishRequest || request instanceof PublishNamespaceRequest || request instanceof SubscribeNamespaceRequest || request instanceof TrackStatusRequest || request instanceof FetchRequest) {
|
|
2027
|
+
request.resolve(msg);
|
|
2028
|
+
client.requests.delete(requestId);
|
|
2029
|
+
}
|
|
2030
|
+
};
|
|
2031
|
+
//#endregion
|
|
2032
|
+
//#region src/client/handler/publish_done.ts
|
|
2033
|
+
const handlerPublishDone = async (client, msg, _stream, openingRequestId) => {
|
|
2034
|
+
if (client.onPeerPublishDone) client.onPeerPublishDone(msg, openingRequestId);
|
|
2035
|
+
const request = client.requests.get(openingRequestId);
|
|
2036
|
+
if (request instanceof SubscribeRequest) request.expectedStreams = msg.streamCount;
|
|
2037
|
+
};
|
|
2038
|
+
//#endregion
|
|
2039
|
+
//#region src/client/handler/subscribe_ok.ts
|
|
2040
|
+
/**
|
|
2041
|
+
* Copyright 2025 The MOQtail Authors
|
|
2042
|
+
*
|
|
2043
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2044
|
+
* you may not use this file except in compliance with the License.
|
|
2045
|
+
* You may obtain a copy of the License at
|
|
2046
|
+
*
|
|
2047
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2048
|
+
*
|
|
2049
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2050
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2051
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2052
|
+
* See the License for the specific language governing permissions and
|
|
2053
|
+
* limitations under the License.
|
|
2054
|
+
*/
|
|
2055
|
+
const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
|
|
2056
|
+
require_logger.logger.debug("handler/subscribe_ok", `received requestId=${requestId} trackAlias=${msg.trackAlias}`);
|
|
2057
|
+
const request = client.requests.get(requestId);
|
|
2058
|
+
if (request instanceof SubscribeRequest) {
|
|
2059
|
+
if (msg.trackProperties.length > 0) {
|
|
2060
|
+
require_logger.logger.debug("handler/subscribe_ok", `requestId=${requestId} — applying ${msg.trackProperties.length} track propert(ies)`);
|
|
2061
|
+
const track = client.trackSources.get(request.fullTrackName.toString());
|
|
2062
|
+
if (track !== void 0) track.trackProperties = msg.trackProperties;
|
|
2063
|
+
}
|
|
2064
|
+
require_logger.logger.debug("handler/subscribe_ok", `requestId=${requestId} — resolving SubscribeRequest ftn="${request.fullTrackName}"`);
|
|
2065
|
+
request.resolve(msg);
|
|
2066
|
+
} else {
|
|
2067
|
+
require_logger.logger.error("handler/subscribe_ok", `requestId=${requestId} — no pending SubscribeRequest found (got ${request?.constructor.name ?? "undefined"})`);
|
|
2068
|
+
throw new require_model.ProtocolViolationError("handlerSubscribeOk", "SUBSCRIBE_OK on a stream with no pending subscribe request");
|
|
2069
|
+
}
|
|
2070
|
+
};
|
|
2071
|
+
//#endregion
|
|
2072
|
+
//#region src/client/handler/request_update.ts
|
|
2073
|
+
/**
|
|
2074
|
+
* Copyright 2025 The MOQtail Authors
|
|
2075
|
+
*
|
|
2076
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2077
|
+
* you may not use this file except in compliance with the License.
|
|
2078
|
+
* You may obtain a copy of the License at
|
|
2079
|
+
*
|
|
2080
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2081
|
+
*
|
|
2082
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2083
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2084
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2085
|
+
* See the License for the specific language governing permissions and
|
|
2086
|
+
* limitations under the License.
|
|
2087
|
+
*/
|
|
2088
|
+
/**
|
|
2089
|
+
* A REQUEST_UPDATE modifies the request whose stream it arrived on, and §10.9 requires
|
|
2090
|
+
* exactly one REQUEST_OK or REQUEST_ERROR back on that stream. TRACK_STATUS is no longer
|
|
2091
|
+
* one of the updatable request types, so an update naming one is refused.
|
|
2092
|
+
*/
|
|
2093
|
+
const handlerRequestUpdate = async (client, msg, stream, requestId) => {
|
|
2094
|
+
require_logger.logger.log("handler/request_update", "requestId", requestId);
|
|
2095
|
+
const openingType = stream.openingType;
|
|
2096
|
+
if (openingType !== void 0 && !require_model.ControlMessageType.isUpdatable(openingType)) {
|
|
2097
|
+
await stream.send(new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("request does not support REQUEST_UPDATE")));
|
|
2098
|
+
return;
|
|
2099
|
+
}
|
|
2100
|
+
const publication = client.publications.get(requestId);
|
|
2101
|
+
if (publication instanceof SubscribePublication) {
|
|
2102
|
+
try {
|
|
2103
|
+
publication.update(msg);
|
|
2104
|
+
} catch (error) {
|
|
2105
|
+
require_logger.logger.error("handler/request_update", `update failed for requestId=${requestId}`, error);
|
|
2106
|
+
await failUpdate(client, stream, requestId, 0, "REQUEST_UPDATE failed");
|
|
2107
|
+
return;
|
|
2108
|
+
}
|
|
2109
|
+
await stream.send(new require_model.RequestOk());
|
|
2110
|
+
return;
|
|
2111
|
+
}
|
|
2112
|
+
if (publication instanceof PublishPublication) {
|
|
2113
|
+
publication.update(msg);
|
|
2114
|
+
await stream.send(new require_model.RequestOk());
|
|
2115
|
+
return;
|
|
2116
|
+
}
|
|
2117
|
+
require_logger.logger.warn("handler/request_update", `no updatable request for requestId=${requestId}`);
|
|
2118
|
+
await failUpdate(client, stream, requestId, 3, "REQUEST_UPDATE cannot be applied");
|
|
2119
|
+
};
|
|
2120
|
+
/**
|
|
2121
|
+
* Refuses the update, then ends the request the way §10.9.1 requires for its type: a
|
|
2122
|
+
* subscription is terminated with PUBLISH_DONE(UPDATE_FAILED), a FETCH has its data
|
|
2123
|
+
* stream reset, and a namespace request has its bidi stream closed.
|
|
2124
|
+
*/
|
|
2125
|
+
async function failUpdate(client, stream, requestId, errorCode, reason) {
|
|
2126
|
+
await stream.send(new require_model.RequestError(errorCode, 0n, new require_model.ReasonPhrase(reason)));
|
|
2127
|
+
const publication = client.publications.get(requestId);
|
|
2128
|
+
switch (stream.openingType) {
|
|
2129
|
+
case 3:
|
|
2130
|
+
case 29:
|
|
2131
|
+
if (publication instanceof SubscribePublication) await publication.done(8);
|
|
2132
|
+
else {
|
|
2133
|
+
const streamCount = publication instanceof PublishPublication ? publication.streamsOpened : 0n;
|
|
2134
|
+
await stream.send(new require_model.PublishDone(8, streamCount, new require_model.ReasonPhrase("REQUEST_UPDATE failed")));
|
|
2135
|
+
}
|
|
2136
|
+
publication?.cancel();
|
|
2137
|
+
client.publications.delete(requestId);
|
|
2138
|
+
break;
|
|
2139
|
+
case 22:
|
|
2140
|
+
if (publication instanceof FetchPublication) await publication.resetDataStream(1);
|
|
2141
|
+
client.publications.delete(requestId);
|
|
2142
|
+
break;
|
|
2143
|
+
case 6:
|
|
2144
|
+
case 80:
|
|
2145
|
+
case 81:
|
|
2146
|
+
await stream.close();
|
|
2147
|
+
break;
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
//#endregion
|
|
2151
|
+
//#region src/client/handler/track_status.ts
|
|
2152
|
+
/**
|
|
2153
|
+
* Copyright 2025 The MOQtail Authors
|
|
2154
|
+
*
|
|
2155
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2156
|
+
* you may not use this file except in compliance with the License.
|
|
2157
|
+
* You may obtain a copy of the License at
|
|
2158
|
+
*
|
|
2159
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2160
|
+
*
|
|
2161
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2162
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2163
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2164
|
+
* See the License for the specific language governing permissions and
|
|
2165
|
+
* limitations under the License.
|
|
2166
|
+
*/
|
|
2167
|
+
const handlerTrackStatus = async (_client, msg, stream) => {
|
|
2168
|
+
require_logger.logger.debug("handler/track_status", `requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
|
|
2169
|
+
await stream.send(new require_model.RequestOk());
|
|
2170
|
+
};
|
|
2171
|
+
//#endregion
|
|
2172
|
+
//#region src/client/handler/handler.ts
|
|
2173
|
+
/**
|
|
2174
|
+
* Copyright 2025 The MOQtail Authors
|
|
2175
|
+
*
|
|
2176
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2177
|
+
* you may not use this file except in compliance with the License.
|
|
2178
|
+
* You may obtain a copy of the License at
|
|
2179
|
+
*
|
|
2180
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2181
|
+
*
|
|
2182
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2183
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2184
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2185
|
+
* See the License for the specific language governing permissions and
|
|
2186
|
+
* limitations under the License.
|
|
2187
|
+
*/
|
|
2188
|
+
/**
|
|
2189
|
+
* Draft-18 §3.3: the control stream carries SETUP and GOAWAY, nothing else. SETUP is
|
|
2190
|
+
* consumed by the handshake in {@link MOQtailClient.new}, so GOAWAY is all that reaches
|
|
2191
|
+
* the read loop. Every request type has moved to its own bidi stream — see
|
|
2192
|
+
* {@link getHandlerForRequestStreamMessage}.
|
|
2193
|
+
*/
|
|
2194
|
+
function getHandlerForControlMessage(msg) {
|
|
2195
|
+
if (msg instanceof require_model.GoAway) return handlerGoAway;
|
|
2196
|
+
}
|
|
2197
|
+
/**
|
|
2198
|
+
* Handlers for everything that travels on a bidirectional request stream: the seven
|
|
2199
|
+
* `First`-marked types that open one, the responses that come back on it, and the
|
|
2200
|
+
* follow-ups either side may send while it is open.
|
|
2201
|
+
*/
|
|
2202
|
+
function getHandlerForRequestStreamMessage(msg) {
|
|
2203
|
+
if (msg instanceof require_model.Subscribe) return handlerSubscribe;
|
|
2204
|
+
if (msg instanceof require_model.Fetch) return handlerFetch;
|
|
2205
|
+
if (msg instanceof require_model.Publish) return handlerPublish;
|
|
2206
|
+
if (msg instanceof require_model.PublishNamespace) return handlerPublishNamespace;
|
|
2207
|
+
if (msg instanceof require_model.TrackStatus) return handlerTrackStatus;
|
|
2208
|
+
if (msg instanceof require_model.SubscribeNamespace) return handlerSubscribeNamespace;
|
|
2209
|
+
if (msg instanceof require_model.SubscribeTracks) return handlerSubscribeTracks;
|
|
2210
|
+
if (msg instanceof require_model.SubscribeOk) return handlerSubscribeOk;
|
|
2211
|
+
if (msg instanceof require_model.FetchOk) return handlerFetchOk;
|
|
2212
|
+
if (msg instanceof require_model.RequestOk) return handlerRequestOk;
|
|
2213
|
+
if (msg instanceof require_model.RequestError) return handlerRequestError;
|
|
2214
|
+
if (msg instanceof require_model.GoAway) return handlerGoAwayOnRequestStream;
|
|
2215
|
+
if (msg instanceof require_model.RequestUpdate) return handlerRequestUpdate;
|
|
2216
|
+
if (msg instanceof require_model.PublishDone) return handlerPublishDone;
|
|
2217
|
+
if (msg instanceof require_model.PublishBlocked) return handlerPublishBlocked;
|
|
2218
|
+
}
|
|
2219
|
+
//#endregion
|
|
2220
|
+
//#region src/client/util/random_id.ts
|
|
2221
|
+
/**
|
|
2222
|
+
* Copyright 2025 The MOQtail Authors
|
|
2223
|
+
*
|
|
2224
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2225
|
+
* you may not use this file except in compliance with the License.
|
|
2226
|
+
* You may obtain a copy of the License at
|
|
2227
|
+
*
|
|
2228
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2229
|
+
*
|
|
2230
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2231
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2232
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2233
|
+
* See the License for the specific language governing permissions and
|
|
2234
|
+
* limitations under the License.
|
|
2235
|
+
*/
|
|
2236
|
+
function random60bitId() {
|
|
2237
|
+
const buf = /* @__PURE__ */ new Uint8Array(8);
|
|
2238
|
+
crypto.getRandomValues(buf);
|
|
2239
|
+
buf[0] = buf[0] & 15;
|
|
2240
|
+
let id = 0n;
|
|
2241
|
+
for (const b of buf) id = id << 8n | BigInt(b);
|
|
2242
|
+
return id;
|
|
2243
|
+
}
|
|
2244
|
+
//#endregion
|
|
2245
|
+
//#region src/client/datagram_stream.ts
|
|
2246
|
+
/**
|
|
2247
|
+
* Copyright 2025 The MOQtail Authors
|
|
2248
|
+
*
|
|
2249
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2250
|
+
* you may not use this file except in compliance with the License.
|
|
2251
|
+
* You may obtain a copy of the License at
|
|
2252
|
+
*
|
|
2253
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2254
|
+
*
|
|
2255
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2256
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2257
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2258
|
+
* See the License for the specific language governing permissions and
|
|
2259
|
+
* limitations under the License.
|
|
2260
|
+
*/
|
|
2261
|
+
/**
|
|
2262
|
+
* Sends MoqtObjects as WebTransport datagrams.
|
|
2263
|
+
* Parallel to SendStream but for datagram-based delivery.
|
|
2264
|
+
*
|
|
2265
|
+
* @example
|
|
2266
|
+
* ```ts
|
|
2267
|
+
* const sender = new SendDatagramStream(client.webTransport.datagrams.writable, trackAlias);
|
|
2268
|
+
* await sender.write(moqtObject);
|
|
2269
|
+
* ```
|
|
2270
|
+
*/
|
|
2271
|
+
var SendDatagramStream = class SendDatagramStream {
|
|
2272
|
+
#writer;
|
|
2273
|
+
#trackAlias;
|
|
2274
|
+
onDataSent;
|
|
2275
|
+
constructor(writer, trackAlias, onDataSent) {
|
|
2276
|
+
this.#writer = writer;
|
|
2277
|
+
this.#trackAlias = trackAlias;
|
|
2278
|
+
if (onDataSent) this.onDataSent = onDataSent;
|
|
2279
|
+
}
|
|
2280
|
+
/**
|
|
2281
|
+
* Create a new datagram sender for a specific track.
|
|
2282
|
+
*
|
|
2283
|
+
* @param writeStream - WebTransport datagram writable stream
|
|
2284
|
+
* @param trackAlias - Track alias for this datagram stream
|
|
2285
|
+
* @param onDataSent - Optional callback fired when datagram is sent
|
|
2286
|
+
* @returns SendDatagramStream instance
|
|
2287
|
+
*/
|
|
2288
|
+
static async new(writeStream, trackAlias, onDataSent) {
|
|
2289
|
+
const writer = writeStream.getWriter();
|
|
2290
|
+
return new SendDatagramStream(writer, trackAlias, onDataSent);
|
|
2291
|
+
}
|
|
2292
|
+
/**
|
|
2293
|
+
* Create a datagram sender using an existing shared writer.
|
|
2294
|
+
* Use this when multiple senders need to share a single writer.
|
|
2295
|
+
*
|
|
2296
|
+
* @param writer - Existing WritableStreamDefaultWriter
|
|
2297
|
+
* @param trackAlias - Track alias for this datagram stream
|
|
2298
|
+
* @param onDataSent - Optional callback fired when datagram is sent
|
|
2299
|
+
* @returns SendDatagramStream instance
|
|
2300
|
+
*/
|
|
2301
|
+
static fromWriter(writer, trackAlias, onDataSent) {
|
|
2302
|
+
return new SendDatagramStream(writer, trackAlias, onDataSent);
|
|
2303
|
+
}
|
|
2304
|
+
/**
|
|
2305
|
+
* Write a MoqtObject as a datagram.
|
|
2306
|
+
* Converts to Datagram automatically based on object state.
|
|
2307
|
+
*
|
|
2308
|
+
* @param object - MoqtObject to send (must have Datagram forwarding preference)
|
|
2309
|
+
*/
|
|
2310
|
+
async write(object) {
|
|
2311
|
+
const datagram = object.tryIntoDatagram(this.#trackAlias);
|
|
2312
|
+
const serialized = datagram.serialize().toUint8Array();
|
|
2313
|
+
require_logger.logger.log("datagram_stream", `Writing datagram: trackAlias=${this.#trackAlias}, group=${object.location?.group}, obj=${object.location?.object}, size=${serialized.byteLength}`);
|
|
2314
|
+
if (this.onDataSent) this.onDataSent(datagram);
|
|
2315
|
+
try {
|
|
2316
|
+
await this.#writer.write(serialized);
|
|
2317
|
+
require_logger.logger.log("datagram_stream", `Successfully wrote ${serialized.byteLength} bytes to WebTransport datagram`);
|
|
2318
|
+
} catch (err) {
|
|
2319
|
+
require_logger.logger.error("datagram_stream", `ERROR writing datagram:`, err);
|
|
2320
|
+
throw err;
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
/**
|
|
2324
|
+
* Close the datagram writer.
|
|
2325
|
+
*/
|
|
2326
|
+
async close() {
|
|
2327
|
+
if (this.#writer) await this.#writer.close();
|
|
2328
|
+
}
|
|
2329
|
+
/**
|
|
2330
|
+
* Release the writer lock without closing.
|
|
2331
|
+
*/
|
|
2332
|
+
releaseLock() {
|
|
2333
|
+
this.#writer.releaseLock();
|
|
2334
|
+
}
|
|
2335
|
+
};
|
|
2336
|
+
/**
|
|
2337
|
+
* Receives and parses WebTransport datagrams as MoqtObjects.
|
|
2338
|
+
* Parallel to RecvStream but for datagram-based delivery.
|
|
2339
|
+
*
|
|
2340
|
+
* Automatically handles:
|
|
2341
|
+
* - Datagram parsing (both payload and status datagrams)
|
|
2342
|
+
* - Track alias to full track name resolution
|
|
2343
|
+
*
|
|
2344
|
+
* @example
|
|
2345
|
+
* ```ts
|
|
2346
|
+
* const receiver = new RecvDatagramStream(
|
|
2347
|
+
* client.webTransport.datagrams.readable,
|
|
2348
|
+
* (trackAlias) => client.requestIdMap.getNameByTrackAlias(trackAlias)
|
|
2349
|
+
* );
|
|
2350
|
+
*
|
|
2351
|
+
* for await (const object of receiver.stream) {
|
|
2352
|
+
* console.log('Received:', object);
|
|
2353
|
+
* }
|
|
2354
|
+
* ```
|
|
2355
|
+
*/
|
|
2356
|
+
var RecvDatagramStream = class RecvDatagramStream {
|
|
2357
|
+
stream;
|
|
2358
|
+
#reader;
|
|
2359
|
+
#trackAliasResolver;
|
|
2360
|
+
onDataReceived;
|
|
2361
|
+
constructor(reader, trackAliasResolver, onDataReceived) {
|
|
2362
|
+
this.#reader = reader;
|
|
2363
|
+
this.#trackAliasResolver = trackAliasResolver;
|
|
2364
|
+
if (onDataReceived) this.onDataReceived = onDataReceived;
|
|
2365
|
+
this.stream = new ReadableStream({
|
|
2366
|
+
start: (controller) => this.#ingestLoop(controller),
|
|
2367
|
+
cancel: () => this.#reader.cancel()
|
|
2368
|
+
});
|
|
2369
|
+
}
|
|
2370
|
+
/**
|
|
2371
|
+
* Create a new datagram receiver.
|
|
2372
|
+
*
|
|
2373
|
+
* @param readStream - WebTransport datagram readable stream
|
|
2374
|
+
* @param trackAliasResolver - Function to resolve track alias to full track name
|
|
2375
|
+
* @param onDataReceived - Optional callback fired when datagram is received
|
|
2376
|
+
* @returns RecvDatagramStream instance
|
|
2377
|
+
*/
|
|
2378
|
+
static async new(readStream, trackAliasResolver, onDataReceived) {
|
|
2379
|
+
const reader = readStream.getReader();
|
|
2380
|
+
return new RecvDatagramStream(reader, trackAliasResolver, onDataReceived);
|
|
2381
|
+
}
|
|
2382
|
+
async #ingestLoop(controller) {
|
|
2383
|
+
try {
|
|
2384
|
+
while (true) {
|
|
2385
|
+
const { done, value: datagramBytes } = await this.#reader.read();
|
|
2386
|
+
if (done) {
|
|
2387
|
+
controller.close();
|
|
2388
|
+
break;
|
|
2389
|
+
}
|
|
2390
|
+
if (!datagramBytes || datagramBytes.length === 0) continue;
|
|
2391
|
+
try {
|
|
2392
|
+
const datagram = require_model.Datagram.deserialize(new require_model.FrozenByteBuffer(datagramBytes));
|
|
2393
|
+
if (this.onDataReceived) this.onDataReceived(datagram);
|
|
2394
|
+
const fullTrackName = this.#trackAliasResolver(datagram.trackAlias);
|
|
2395
|
+
const moqtObject = require_model.MoqtObject.fromDatagram(datagram, fullTrackName);
|
|
2396
|
+
controller.enqueue(moqtObject);
|
|
2397
|
+
} catch (error) {
|
|
2398
|
+
require_logger.logger.warn("datagram_stream", "Failed to parse datagram:", error);
|
|
2399
|
+
continue;
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
} catch (error) {
|
|
2403
|
+
controller.error(error);
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
/**
|
|
2407
|
+
* Cancel the datagram reader.
|
|
2408
|
+
*/
|
|
2409
|
+
async cancel() {
|
|
2410
|
+
await this.#reader.cancel();
|
|
2411
|
+
}
|
|
2412
|
+
/**
|
|
2413
|
+
* Release the reader lock without canceling.
|
|
2414
|
+
*/
|
|
2415
|
+
releaseLock() {
|
|
2416
|
+
this.#reader.releaseLock();
|
|
2417
|
+
}
|
|
2418
|
+
};
|
|
2419
|
+
//#endregion
|
|
2420
|
+
//#region src/client/client.ts
|
|
2421
|
+
/**
|
|
2422
|
+
* Copyright 2025 The MOQtail Authors
|
|
2423
|
+
*
|
|
2424
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
2425
|
+
* you may not use this file except in compliance with the License.
|
|
2426
|
+
* You may obtain a copy of the License at
|
|
2427
|
+
*
|
|
2428
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
2429
|
+
*
|
|
2430
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
2431
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
2432
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
2433
|
+
* See the License for the specific language governing permissions and
|
|
2434
|
+
* limitations under the License.
|
|
2435
|
+
*/
|
|
2436
|
+
/**
|
|
2437
|
+
* @public
|
|
2438
|
+
* Represents a Media Over QUIC Transport (MOQT) client session.
|
|
2439
|
+
*
|
|
2440
|
+
* Use {@link MOQtailClient.new} to establish a connection and perform MOQT operations such as subscribing to tracks,
|
|
2441
|
+
* fetching historical data, announcing tracks for publication, and managing session lifecycle.
|
|
2442
|
+
*
|
|
2443
|
+
* Once initialized, the client provides high-level methods for MOQT requests and publishing. If a protocol violation
|
|
2444
|
+
* occurs, the client will terminate and must be re-initialized.
|
|
2445
|
+
*
|
|
2446
|
+
* ## Usage
|
|
2447
|
+
*
|
|
2448
|
+
* ### Connect and Subscribe to a Track
|
|
2449
|
+
* ```ts
|
|
2450
|
+
* const client = await MOQtailClient.new({ url });
|
|
2451
|
+
* const result = await client.subscribe({
|
|
2452
|
+
* fullTrackName,
|
|
2453
|
+
* filterType: FilterType.LatestObject,
|
|
2454
|
+
* forward: true,
|
|
2455
|
+
* groupOrder: GroupOrder.Original,
|
|
2456
|
+
* priority: 0
|
|
2457
|
+
* });
|
|
2458
|
+
* if (!(result instanceof RequestError)) {
|
|
2459
|
+
* for await (const object of result.stream) {
|
|
2460
|
+
* // Consume MOQT objects
|
|
2461
|
+
* }
|
|
2462
|
+
* }
|
|
2463
|
+
* ```
|
|
2464
|
+
*
|
|
2465
|
+
* ### Publish a namespace for Publishing
|
|
2466
|
+
* ```ts
|
|
2467
|
+
* const client = await MOQtailClient.new({ url });
|
|
2468
|
+
* const publishNamespaceResult = await client.publishNamespace(["camera", "main"]);
|
|
2469
|
+
* if (!(publishNamespaceResult instanceof RequestError)) {
|
|
2470
|
+
* // Ready to publish objects under this namespace
|
|
2471
|
+
* }
|
|
2472
|
+
* ```
|
|
2473
|
+
*
|
|
2474
|
+
* ### Graceful Shutdown
|
|
2475
|
+
* ```ts
|
|
2476
|
+
* await client.disconnect();
|
|
2477
|
+
* ```
|
|
2478
|
+
*/
|
|
2479
|
+
var MOQtailClient = class MOQtailClient {
|
|
2480
|
+
/**
|
|
2481
|
+
* Namespace prefixes (tuples) the peer has requested announce notifications for via SUBSCRIBE_NAMESPACE.
|
|
2482
|
+
* Used to decide which locally issued ANNOUNCE messages should be forwarded (future optimization: prefix trie).
|
|
2483
|
+
*/
|
|
2484
|
+
peerSubscribeNamespace = /* @__PURE__ */ new Set();
|
|
2485
|
+
/**
|
|
2486
|
+
* Namespace prefixes this client has subscribed to (issued SUBSCRIBE_NAMESPACE). Enables automatic filtering
|
|
2487
|
+
* of incoming NAMESPACE / NAMESPACE_DONE. Maintained locally; no dedupe of overlapping / shadowing prefixes yet.
|
|
2488
|
+
*/
|
|
2489
|
+
subscribedNamespaces = /* @__PURE__ */ new Set();
|
|
2490
|
+
subscribedTracks = /* @__PURE__ */ new Set();
|
|
2491
|
+
/**
|
|
2492
|
+
* Track namespaces this client has successfully published (received REQUEST_OK). Source of truth for
|
|
2493
|
+
* deciding what to withdraw on teardown or targeted removal (future optimization: prefix trie).
|
|
2494
|
+
*/
|
|
2495
|
+
publishedNamespaces = /* @__PURE__ */ new Set();
|
|
2496
|
+
/**
|
|
2497
|
+
* Locally registered track definitions keyed by full track name string. Populated via addOrUpdateTrack.
|
|
2498
|
+
* Does not imply the track has been announced or has active publications.
|
|
2499
|
+
*/
|
|
2500
|
+
trackSources = /* @__PURE__ */ new Map();
|
|
2501
|
+
/**
|
|
2502
|
+
* All in‑flight request objects keyed by requestId (SUBSCRIBE, FETCH, ANNOUNCE, etc). Facilitates lookup
|
|
2503
|
+
* when responses / data arrive. Entries are removed on completion or error.
|
|
2504
|
+
*/
|
|
2505
|
+
requests = /* @__PURE__ */ new Map();
|
|
2506
|
+
/**
|
|
2507
|
+
* Active publications (SUBSCRIBE or FETCH) keyed by requestId to manage object stream controllers and lifecycle.
|
|
2508
|
+
* Subset / specialization view of `requests`.
|
|
2509
|
+
*/
|
|
2510
|
+
publications = /* @__PURE__ */ new Map();
|
|
2511
|
+
/**
|
|
2512
|
+
* Active SUBSCRIBE request wrappers keyed by track alias for rapid alias -\> subscription resolution during
|
|
2513
|
+
* incoming unidirectional data handling.
|
|
2514
|
+
*/
|
|
2515
|
+
subscriptions = /* @__PURE__ */ new Map();
|
|
2516
|
+
/**
|
|
2517
|
+
* Bidirectional track alias \<-\> subscription requestId mapping
|
|
2518
|
+
*/
|
|
2519
|
+
subscriptionAliasMap = /* @__PURE__ */ new Map();
|
|
2520
|
+
/**
|
|
2521
|
+
* Bidirectional requestId \<-\> full track name mapping to reconstruct metadata for incoming objects.
|
|
2522
|
+
*/
|
|
2523
|
+
requestIdMap = new require_model.RequestIdMap();
|
|
2524
|
+
/**
|
|
2525
|
+
* Maps track aliases to full track names for quick resolution during data handling.
|
|
2526
|
+
*/
|
|
2527
|
+
aliasFullTrackNameMap = /* @__PURE__ */ new Map();
|
|
2528
|
+
/**
|
|
2529
|
+
* Pending state updates keyed by requestId and applied once a new track alias is seen.
|
|
2530
|
+
* Used to avoid premature state updates.
|
|
2531
|
+
*/
|
|
2532
|
+
pendingStateUpdates = /* @__PURE__ */ new Map();
|
|
2533
|
+
/**
|
|
2534
|
+
* The bidirectional request stream each locally issued request runs on, keyed by the
|
|
2535
|
+
* requestId of the message that opened it (draft-18 §3.3.2). The stream stays open for
|
|
2536
|
+
* the request's lifetime: responses and follow-ups arrive on it, updates are written to
|
|
2537
|
+
* it, and closing it is how the request is cancelled.
|
|
2538
|
+
*/
|
|
2539
|
+
#requestStreams = /* @__PURE__ */ new Map();
|
|
2540
|
+
/**
|
|
2541
|
+
* Request ids of requests re-issued after a per-request GOAWAY (§10.4), which consumes
|
|
2542
|
+
* a fresh Request ID each time (§10.1). The id the caller was given stays the client's
|
|
2543
|
+
* key for the request; these two maps translate it to and from the id now on the wire.
|
|
2544
|
+
*/
|
|
2545
|
+
#wireRequestIds = /* @__PURE__ */ new Map();
|
|
2546
|
+
#clientRequestIds = /* @__PURE__ */ new Map();
|
|
2547
|
+
/**
|
|
2548
|
+
* Namespace path -\> the requestId that announced or subscribed to it, so the
|
|
2549
|
+
* namespace-keyed APIs ({@link MOQtailClient.unpublishNamespace}) can find the
|
|
2550
|
+
* stream to close.
|
|
2551
|
+
*/
|
|
2552
|
+
#namespaceRequestIds = /* @__PURE__ */ new Map();
|
|
2553
|
+
/** Underlying WebTransport session (set after successful construction in MOQtailClient.new). */
|
|
2554
|
+
webTransport;
|
|
2555
|
+
/** Validated Setup message the server sent back during handshake (protocol parameters negotiated). */
|
|
2556
|
+
#serverSetup;
|
|
2557
|
+
/** Outgoing / incoming control message stream pair. */
|
|
2558
|
+
controlStream;
|
|
2559
|
+
/** Reader over incoming uni streams: the control recv half first, data streams after. */
|
|
2560
|
+
#incomingUniStreams;
|
|
2561
|
+
/** Timeout (ms) applied to reading incoming data streams; undefined =\> no explicit timeout. */
|
|
2562
|
+
dataStreamTimeoutMs;
|
|
2563
|
+
/** Timeout (ms) for control stream read operations; undefined =\> no explicit timeout. */
|
|
2564
|
+
controlStreamTimeoutMs;
|
|
2565
|
+
/** Flag indicating the client has been disconnected/destroyed and cannot accept further API calls. */
|
|
2566
|
+
#isDestroyed = false;
|
|
2567
|
+
/** Internal monotonically increasing client-assigned request id counter (even/odd parity scheme advances by 2). */
|
|
2568
|
+
#dontUseRequestId = 0n;
|
|
2569
|
+
/** Active early discard policy; undefined means no per-stream deadline is applied. */
|
|
2570
|
+
#earlyDiscardPolicy;
|
|
2571
|
+
/**
|
|
2572
|
+
* TODO: onNamespaceAnnounced may be a better name
|
|
2573
|
+
* Fired when an PUBLISH_NAMESPACE control message is processed for a track namespace.
|
|
2574
|
+
* Use to update UI or trigger discovery logic.
|
|
2575
|
+
* Discovery event.
|
|
2576
|
+
*/
|
|
2577
|
+
onNamespacePublished;
|
|
2578
|
+
/**
|
|
2579
|
+
* Fired on GOAWAY reception signaling graceful session wind-down.
|
|
2580
|
+
* Use to prepare for disconnect or cleanup.
|
|
2581
|
+
* Lifecycle handler.
|
|
2582
|
+
*/
|
|
2583
|
+
onGoaway;
|
|
2584
|
+
/**
|
|
2585
|
+
* Whether the peer has sent a GOAWAY on the control stream. Once it has, this side
|
|
2586
|
+
* should not start new requests (§10.4); a second one closes the session with
|
|
2587
|
+
* PROTOCOL_VIOLATION.
|
|
2588
|
+
*/
|
|
2589
|
+
goawayReceived = false;
|
|
2590
|
+
/**
|
|
2591
|
+
* Fired if the underlying WebTransport session fails (ready -\> closed prematurely).
|
|
2592
|
+
* Use to log or alert on transport errors.
|
|
2593
|
+
* Lifecycle/error handler.
|
|
2594
|
+
*/
|
|
2595
|
+
onWebTransportFail;
|
|
2596
|
+
/**
|
|
2597
|
+
* Fired exactly once when the client transitions to terminated (disconnect).
|
|
2598
|
+
* Use to clean up resources or notify user.
|
|
2599
|
+
* Lifecycle handler.
|
|
2600
|
+
*/
|
|
2601
|
+
onSessionTerminated;
|
|
2602
|
+
/**
|
|
2603
|
+
* Invoked after each outbound control message is sent.
|
|
2604
|
+
* Use for logging or analytics.
|
|
2605
|
+
* Informational event.
|
|
2606
|
+
*/
|
|
2607
|
+
onMessageSent;
|
|
2608
|
+
/**
|
|
2609
|
+
* Invoked upon receiving each inbound control message before handling.
|
|
2610
|
+
* Use for logging or debugging.
|
|
2611
|
+
* Informational event.
|
|
2612
|
+
*/
|
|
2613
|
+
onMessageReceived;
|
|
2614
|
+
/**
|
|
2615
|
+
* Invoked for each decoded data object/header arriving on a uni stream (fetch or subgroup).
|
|
2616
|
+
* Use to process or display incoming media/data.
|
|
2617
|
+
* Informational event.
|
|
2618
|
+
*/
|
|
2619
|
+
onDataReceived;
|
|
2620
|
+
/**
|
|
2621
|
+
* Invoked after enqueuing each outbound data object/header.
|
|
2622
|
+
* Reserved for future use.
|
|
2623
|
+
* Informational event.
|
|
2624
|
+
*/
|
|
2625
|
+
onDataSent;
|
|
2626
|
+
/**
|
|
2627
|
+
* General-purpose error callback for surfaced exceptions not thrown to caller synchronously.
|
|
2628
|
+
* Use to log or display errors.
|
|
2629
|
+
* Error handler.
|
|
2630
|
+
*/
|
|
2631
|
+
onError;
|
|
2632
|
+
/** Invoked for each decoded datagram object/status arriving. */
|
|
2633
|
+
onDatagramReceived;
|
|
2634
|
+
/** Invoked after enqueuing each outbound datagram object/status. */
|
|
2635
|
+
onDatagramSent;
|
|
2636
|
+
/** Fired when an inbound PUBLISH control message is received. */
|
|
2637
|
+
onPeerPublish;
|
|
2638
|
+
/**
|
|
2639
|
+
* Fired when an inbound PUBLISH_DONE control message is received. The message names
|
|
2640
|
+
* no request of its own, so `requestId` is the request the stream it arrived on
|
|
2641
|
+
* opened: for a track the peer pushed, the `requestId` of the {@link Publish} handed
|
|
2642
|
+
* to {@link MOQtailClient.onPeerPublish}. It is what says which track just ended.
|
|
2643
|
+
*/
|
|
2644
|
+
onPeerPublishDone;
|
|
2645
|
+
/**
|
|
2646
|
+
* Fired when the peer moves the Forward State of a track this side is publishing,
|
|
2647
|
+
* either in its PUBLISH_OK or in a later REQUEST_UPDATE. `requestId` is the one
|
|
2648
|
+
* {@link MOQtailClient.publish} returned.
|
|
2649
|
+
*
|
|
2650
|
+
* A publication that declared FORWARD=0 sends nothing until this reports `true`, so
|
|
2651
|
+
* this is where the work behind the track starts and stops -- leaving a camera and
|
|
2652
|
+
* an encoder running for a track nobody is taking costs the same as publishing it.
|
|
2653
|
+
*/
|
|
2654
|
+
onForwardStateChange;
|
|
2655
|
+
/** Fired when an inbound SUBSCRIBE_NAMESPACE control message is received. */
|
|
2656
|
+
onPeerSubscribeNamespace;
|
|
2657
|
+
/** Fired when an inbound SUBSCRIBE_TRACKS control message is received. */
|
|
2658
|
+
onPeerSubscribeTracks;
|
|
2659
|
+
/**
|
|
2660
|
+
* Fired when a PUBLISH_BLOCKED arrives on a {@link MOQtailClient.subscribeTracks}
|
|
2661
|
+
* stream: the peer has a matching track but no bidi stream to send its PUBLISH on
|
|
2662
|
+
* until its stream limit lifts (§10.20). `prefix` is the prefix this side subscribed
|
|
2663
|
+
* with, which is what the message's suffix hangs off.
|
|
2664
|
+
*/
|
|
2665
|
+
onPeerPublishBlocked;
|
|
2666
|
+
/** Fired when a NAMESPACE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
|
|
2667
|
+
onPeerNamespace;
|
|
2668
|
+
/** Fired when a NAMESPACE_DONE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
|
|
2669
|
+
onPeerNamespaceDone;
|
|
2670
|
+
/** Datagram writer for sending datagrams. */
|
|
2671
|
+
#datagramWriter;
|
|
2672
|
+
/** Datagram reader for receiving datagrams. */
|
|
2673
|
+
#datagramReader;
|
|
2674
|
+
/** Flag indicating if datagram reception loop is active. */
|
|
2675
|
+
#isReceivingDatagrams = false;
|
|
2676
|
+
/** Controller for the received objects stream. */
|
|
2677
|
+
#receivedDatagramObjectController;
|
|
2678
|
+
/** Per-track handlers for received datagrams. */
|
|
2679
|
+
#datagramTrackHandlers = /* @__PURE__ */ new Map();
|
|
2680
|
+
/**
|
|
2681
|
+
* Stream of all received MoqtObjects from datagrams across all tracks
|
|
2682
|
+
* Consumer should filter by fullTrackName as needed
|
|
2683
|
+
*
|
|
2684
|
+
* WARNING: Only one reader should be active. For multiple subscribers,
|
|
2685
|
+
* use subscribeToTrackDatagrams() instead
|
|
2686
|
+
*/
|
|
2687
|
+
receivedDatagramObjects;
|
|
2688
|
+
/**
|
|
2689
|
+
* Allocate the next client-originated request id using the even/odd stride pattern (increments by 2).
|
|
2690
|
+
* Ensures uniqueness within the session and leaves space for peer-assigned ids if parity strategy is employed.
|
|
2691
|
+
*/
|
|
2692
|
+
get #nextClientRequestId() {
|
|
2693
|
+
const id = this.#dontUseRequestId;
|
|
2694
|
+
this.#dontUseRequestId += 2n;
|
|
2695
|
+
return id;
|
|
2696
|
+
}
|
|
2697
|
+
/**
|
|
2698
|
+
* Generates a safe, sequential local request ID for tracking pushed/incoming tracks.
|
|
2699
|
+
*/
|
|
2700
|
+
allocatePseudoRequestId() {
|
|
2701
|
+
return this.#nextClientRequestId;
|
|
2702
|
+
}
|
|
2703
|
+
/**
|
|
2704
|
+
* Gets the current server setup configuration.
|
|
2705
|
+
*
|
|
2706
|
+
* @returns The {@link Setup} instance the server sent back during handshake.
|
|
2707
|
+
*/
|
|
2708
|
+
get serverSetup() {
|
|
2709
|
+
return this.#serverSetup;
|
|
2710
|
+
}
|
|
2711
|
+
/**
|
|
2712
|
+
* Returns true if datagram support is currently active
|
|
2713
|
+
*/
|
|
2714
|
+
get isDatagramsEnabled() {
|
|
2715
|
+
return this.#isReceivingDatagrams;
|
|
2716
|
+
}
|
|
2717
|
+
/**
|
|
2718
|
+
* Sets the global log level for all moqtail-ts loggers.
|
|
2719
|
+
* @param level - The minimum {@link LogLevel} to output. Use `LogLevel.NONE` to silence all logs.
|
|
2720
|
+
*/
|
|
2721
|
+
static setLogLevel(level) {
|
|
2722
|
+
require_logger.setLogLevel(level);
|
|
2723
|
+
}
|
|
2724
|
+
/**
|
|
2725
|
+
* Restricts log output to the specified module names. Pass `null` to allow all modules.
|
|
2726
|
+
* @param modules - Array of module name strings, or `null` to enable all modules.
|
|
2727
|
+
*/
|
|
2728
|
+
static setLogEnabledModules(modules) {
|
|
2729
|
+
require_logger.setLogEnabledModules(modules);
|
|
2730
|
+
}
|
|
2731
|
+
/**
|
|
2732
|
+
* Guard that throws if the client has been destroyed (disconnect already called). Used at start of public APIs
|
|
2733
|
+
* to fail fast rather than perform partial operations on a torn-down session.
|
|
2734
|
+
* @throws MOQtailError when #isDestroyed is true.
|
|
2735
|
+
*/
|
|
2736
|
+
#ensureActive() {
|
|
2737
|
+
if (this.#isDestroyed) throw new require_model.MOQtailError("MOQtailClient is destroyed and cannot be used.");
|
|
2738
|
+
}
|
|
2739
|
+
constructor() {
|
|
2740
|
+
this.receivedDatagramObjects = new ReadableStream({
|
|
2741
|
+
start: (controller) => {
|
|
2742
|
+
this.#receivedDatagramObjectController = controller;
|
|
2743
|
+
},
|
|
2744
|
+
cancel: () => this.stopDatagrams()
|
|
2745
|
+
});
|
|
2746
|
+
}
|
|
2747
|
+
/**
|
|
2748
|
+
* Establishes a new {@link MOQtailClient} session over WebTransport and performs the MOQT setup handshake.
|
|
2749
|
+
*
|
|
2750
|
+
* @param args - {@link MOQtailClientOptions}
|
|
2751
|
+
*
|
|
2752
|
+
* @returns Promise resolving to a ready {@link MOQtailClient} instance.
|
|
2753
|
+
*
|
|
2754
|
+
* @throws :{@link ProtocolViolationError} If the server sends an unexpected or invalid message during setup.
|
|
2755
|
+
*
|
|
2756
|
+
* @example Minimal connection
|
|
2757
|
+
* ```ts
|
|
2758
|
+
* const client = await MOQtailClient.new({
|
|
2759
|
+
* url: 'https://relay.example.com/transport'
|
|
2760
|
+
* });
|
|
2761
|
+
* ```
|
|
2762
|
+
*
|
|
2763
|
+
* @example With callbacks and options
|
|
2764
|
+
* ```ts
|
|
2765
|
+
* const client = await MOQtailClient.new({
|
|
2766
|
+
* url,
|
|
2767
|
+
* setupOptions: new SetupOptions().addPath('/live'),
|
|
2768
|
+
* transportOptions: { congestionControl: 'default' },
|
|
2769
|
+
* dataStreamTimeoutMs: 5000,
|
|
2770
|
+
* controlStreamTimeoutMs: 2000,
|
|
2771
|
+
* enableDatagrams: true,
|
|
2772
|
+
* callbacks: {
|
|
2773
|
+
* onMessageSent: msg => console.log('Sent:', msg),
|
|
2774
|
+
* onMessageReceived: msg => console.log('Received:', msg),
|
|
2775
|
+
* onSessionTerminated: reason => console.warn('Session ended:', reason),
|
|
2776
|
+
* onDatagramReceived: data => console.log('Datagram:', data),
|
|
2777
|
+
* }
|
|
2778
|
+
* });
|
|
2779
|
+
* ```
|
|
2780
|
+
*/
|
|
2781
|
+
static async new(args) {
|
|
2782
|
+
let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, enableDatagrams, callbacks } = args;
|
|
2783
|
+
const client = new MOQtailClient();
|
|
2784
|
+
if (!transportOptions) transportOptions = { protocols: [] };
|
|
2785
|
+
if (!transportOptions.protocols) transportOptions = {
|
|
2786
|
+
...transportOptions,
|
|
2787
|
+
protocols: [...require_model.SUPPORTED_VERSIONS]
|
|
2788
|
+
};
|
|
2789
|
+
else transportOptions.protocols.push(...require_model.SUPPORTED_VERSIONS);
|
|
2790
|
+
require_logger.logger.log("MOQtailClient", "transportOptions", transportOptions);
|
|
2791
|
+
const { transportUrl, moqtUrl } = require_model.resolveTransportUrl(url);
|
|
2792
|
+
if (moqtUrl) {
|
|
2793
|
+
require_logger.logger.log("MOQtailClient", `moqt:// resolved to ${transportUrl}`);
|
|
2794
|
+
if (moqtUrl.fragment) require_logger.logger.log("MOQtailClient", `moqt:// fragment (local-only): ${moqtUrl.fragment.kind}:${moqtUrl.fragment.value}`);
|
|
2795
|
+
}
|
|
2796
|
+
client.webTransport = new WebTransport(transportUrl, transportOptions);
|
|
2797
|
+
await client.webTransport.ready;
|
|
2798
|
+
try {
|
|
2799
|
+
if (callbacks?.onMessageSent) client.onMessageSent = callbacks.onMessageSent;
|
|
2800
|
+
if (callbacks?.onMessageReceived) client.onMessageReceived = callbacks.onMessageReceived;
|
|
2801
|
+
if (callbacks?.onSessionTerminated) client.onSessionTerminated = callbacks.onSessionTerminated;
|
|
2802
|
+
if (callbacks?.onDatagramReceived) client.onDatagramReceived = callbacks.onDatagramReceived;
|
|
2803
|
+
if (callbacks?.onDatagramSent) client.onDatagramSent = callbacks.onDatagramSent;
|
|
2804
|
+
if (dataStreamTimeoutMs) client.dataStreamTimeoutMs = dataStreamTimeoutMs;
|
|
2805
|
+
if (controlStreamTimeoutMs) client.controlStreamTimeoutMs = controlStreamTimeoutMs;
|
|
2806
|
+
const sendHalf = new ControlSendStream(await client.webTransport.createUnidirectionalStream({ sendOrder: Number.MAX_SAFE_INTEGER }), client.onMessageSent);
|
|
2807
|
+
const params = setupOptions ? setupOptions.build() : new require_model.SetupOptions().build();
|
|
2808
|
+
require_model.assertNoAuthorityOverWebTransport(params);
|
|
2809
|
+
await sendHalf.send(new require_model.Setup(params));
|
|
2810
|
+
client.#incomingUniStreams = client.webTransport.incomingUnidirectionalStreams.getReader();
|
|
2811
|
+
const { value: recvStream, done: recvStreamDone } = await client.#incomingUniStreams.read();
|
|
2812
|
+
if (recvStreamDone || !recvStream) throw new require_model.ProtocolViolationError("MOQtailClient.new", "Session closed before the server control stream");
|
|
2813
|
+
client.controlStream = new ControlStream(sendHalf, new ControlRecvStream(recvStream, client.controlStreamTimeoutMs, client.onMessageReceived));
|
|
2814
|
+
const reader = client.controlStream.stream.getReader();
|
|
2815
|
+
const { value: response, done } = await reader.read();
|
|
2816
|
+
if (done) throw new require_model.ProtocolViolationError("MOQtailClient.new", "Stream closed after client setup");
|
|
2817
|
+
if (!(response instanceof require_model.Setup)) throw new require_model.ProtocolViolationError("MOQtailClient.new", "Expected setup as the first control message");
|
|
2818
|
+
client.#serverSetup = response;
|
|
2819
|
+
reader.releaseLock();
|
|
2820
|
+
client.#handleIncomingControlMessages();
|
|
2821
|
+
client.#acceptIncomingUniStreams();
|
|
2822
|
+
client.#acceptIncomingBiStreams();
|
|
2823
|
+
if (enableDatagrams) await client.startDatagrams();
|
|
2824
|
+
return client;
|
|
2825
|
+
} catch (error) {
|
|
2826
|
+
await client.disconnect(new require_model.InternalError("MOQtailClient.new", error instanceof Error ? error.message : String(error)));
|
|
2827
|
+
throw error;
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2830
|
+
/**
|
|
2831
|
+
* Start receiving datagrams from the WebTransport connection.
|
|
2832
|
+
* Must be called before datagrams can be received (unless enableDatagrams: true was set in options).
|
|
2833
|
+
*
|
|
2834
|
+
* @throws MOQtailError if client is destroyed or datagrams already started
|
|
2835
|
+
*/
|
|
2836
|
+
async startDatagrams() {
|
|
2837
|
+
this.#ensureActive();
|
|
2838
|
+
if (this.#isReceivingDatagrams) {
|
|
2839
|
+
require_logger.logger.warn("MOQtailClient", "Datagrams already started");
|
|
2840
|
+
return;
|
|
2841
|
+
}
|
|
2842
|
+
require_logger.logger.log("MOQtailClient", "Starting datagram support...");
|
|
2843
|
+
this.#datagramReader = this.webTransport.datagrams.readable.getReader();
|
|
2844
|
+
this.#datagramWriter = this.webTransport.datagrams.writable.getWriter();
|
|
2845
|
+
this.#isReceivingDatagrams = true;
|
|
2846
|
+
this.#acceptIncomingDatagrams();
|
|
2847
|
+
require_logger.logger.log("MOQtailClient", "Datagram support started");
|
|
2848
|
+
}
|
|
2849
|
+
/**
|
|
2850
|
+
* Stop receiving datagrams and release resources.
|
|
2851
|
+
* Idempotent - safe to call multiple times.
|
|
2852
|
+
*/
|
|
2853
|
+
async stopDatagrams() {
|
|
2854
|
+
if (!this.#isReceivingDatagrams) return;
|
|
2855
|
+
require_logger.logger.log("MOQtailClient", "Stopping datagram support...");
|
|
2856
|
+
this.#isReceivingDatagrams = false;
|
|
2857
|
+
this.#datagramTrackHandlers.clear();
|
|
2858
|
+
if (this.#datagramReader) {
|
|
2859
|
+
await this.#datagramReader.cancel().catch(() => {});
|
|
2860
|
+
this.#datagramReader.releaseLock();
|
|
2861
|
+
this.#datagramReader = void 0;
|
|
2862
|
+
}
|
|
2863
|
+
if (this.#datagramWriter) {
|
|
2864
|
+
await this.#datagramWriter.close().catch(() => {});
|
|
2865
|
+
this.#datagramWriter = void 0;
|
|
2866
|
+
}
|
|
2867
|
+
if (this.#receivedDatagramObjectController) try {
|
|
2868
|
+
this.#receivedDatagramObjectController.close();
|
|
2869
|
+
} catch {}
|
|
2870
|
+
}
|
|
2871
|
+
/**
|
|
2872
|
+
* Subscribe to receive datagrams for a specific track.
|
|
2873
|
+
* Multiple tracks can have separate handlers that run concurrently.
|
|
2874
|
+
*
|
|
2875
|
+
* @param trackAlias - Track alias to subscribe to
|
|
2876
|
+
* @param handler - Function called for each received MoqtObject on this track
|
|
2877
|
+
* @returns Unsubscribe function to remove the handler
|
|
2878
|
+
*
|
|
2879
|
+
* @example
|
|
2880
|
+
* ```ts
|
|
2881
|
+
* const unsubscribe = client.subscribeToTrackDatagrams(trackAlias, (obj) => {
|
|
2882
|
+
* console.log('Received datagram:', obj.payload);
|
|
2883
|
+
* });
|
|
2884
|
+
* // Later: unsubscribe();
|
|
2885
|
+
* ```
|
|
2886
|
+
*/
|
|
2887
|
+
subscribeToTrackDatagrams(trackAlias, handler) {
|
|
2888
|
+
const key = trackAlias.toString();
|
|
2889
|
+
require_logger.logger.log("MOQtailClient", `Registering datagram handler for trackAlias=${trackAlias}`);
|
|
2890
|
+
this.#datagramTrackHandlers.set(key, handler);
|
|
2891
|
+
return () => {
|
|
2892
|
+
require_logger.logger.log("MOQtailClient", `Unregistering datagram handler for trackAlias=${trackAlias}`);
|
|
2893
|
+
this.#datagramTrackHandlers.delete(key);
|
|
2894
|
+
};
|
|
2895
|
+
}
|
|
2896
|
+
/**
|
|
2897
|
+
* Unsubscribe from datagram delivery for a specific track.
|
|
2898
|
+
*
|
|
2899
|
+
* @param trackAlias - Track alias to unsubscribe from
|
|
2900
|
+
*/
|
|
2901
|
+
unsubscribeFromTrackDatagrams(trackAlias) {
|
|
2902
|
+
const key = trackAlias.toString();
|
|
2903
|
+
this.#datagramTrackHandlers.delete(key);
|
|
2904
|
+
}
|
|
2905
|
+
/**
|
|
2906
|
+
* Create a datagram sender for a specific track.
|
|
2907
|
+
*
|
|
2908
|
+
* @param trackAlias - Track alias for outgoing datagrams
|
|
2909
|
+
* @returns SendDatagramStream for writing MoqtObjects as datagrams
|
|
2910
|
+
* @throws MOQtailError if datagram writer not initialized (call startDatagrams() first)
|
|
2911
|
+
*
|
|
2912
|
+
* @example
|
|
2913
|
+
* ```ts
|
|
2914
|
+
* const sender = client.createDatagramSender(trackAlias);
|
|
2915
|
+
* await sender.write(moqtObject);
|
|
2916
|
+
* ```
|
|
2917
|
+
*/
|
|
2918
|
+
createDatagramSender(trackAlias) {
|
|
2919
|
+
this.#ensureActive();
|
|
2920
|
+
if (!this.#datagramWriter) throw new require_model.MOQtailError("Datagrams not started. Call startDatagrams() first or set enableDatagrams: true in options.");
|
|
2921
|
+
require_logger.logger.log("MOQtailClient", `Creating datagram sender for trackAlias=${trackAlias}`);
|
|
2922
|
+
return SendDatagramStream.fromWriter(this.#datagramWriter, trackAlias, this.onDatagramSent);
|
|
2923
|
+
}
|
|
2924
|
+
/**
|
|
2925
|
+
* Send a single MoqtObject as a datagram.
|
|
2926
|
+
* Convenience method for one-off datagram sends.
|
|
2927
|
+
*
|
|
2928
|
+
* @param trackAlias - Track alias for this object
|
|
2929
|
+
* @param object - MoqtObject to send
|
|
2930
|
+
* @throws MOQtailError if datagram writer not initialized
|
|
2931
|
+
*
|
|
2932
|
+
* @example
|
|
2933
|
+
* ```ts
|
|
2934
|
+
* await client.sendDatagram(trackAlias, moqtObject);
|
|
2935
|
+
* ```
|
|
2936
|
+
*/
|
|
2937
|
+
async sendDatagram(trackAlias, object) {
|
|
2938
|
+
this.#ensureActive();
|
|
2939
|
+
if (!this.#datagramWriter) throw new require_model.MOQtailError("Datagrams not started. Call startDatagrams() first or set enableDatagrams: true in options.");
|
|
2940
|
+
const datagram = object.tryIntoDatagram(trackAlias);
|
|
2941
|
+
const serialized = datagram.serialize().toUint8Array();
|
|
2942
|
+
if (this.onDatagramSent) this.onDatagramSent(datagram);
|
|
2943
|
+
await this.#datagramWriter.write(serialized);
|
|
2944
|
+
}
|
|
2945
|
+
/**
|
|
2946
|
+
* Background loop that receives and parses incoming datagrams.
|
|
2947
|
+
*/
|
|
2948
|
+
async #acceptIncomingDatagrams() {
|
|
2949
|
+
require_logger.logger.log("MOQtailClient", "Starting datagram reception loop...");
|
|
2950
|
+
try {
|
|
2951
|
+
while (this.#isReceivingDatagrams && this.#datagramReader) {
|
|
2952
|
+
const { done, value: datagramBytes } = await this.#datagramReader.read();
|
|
2953
|
+
if (done) {
|
|
2954
|
+
require_logger.logger.log("MOQtailClient", "Datagram reader done, stopping reception");
|
|
2955
|
+
this.#isReceivingDatagrams = false;
|
|
2956
|
+
if (this.#receivedDatagramObjectController) try {
|
|
2957
|
+
this.#receivedDatagramObjectController.close();
|
|
2958
|
+
} catch {}
|
|
2959
|
+
break;
|
|
2960
|
+
}
|
|
2961
|
+
if (!datagramBytes || datagramBytes.length === 0) continue;
|
|
2962
|
+
try {
|
|
2963
|
+
const datagram = require_model.Datagram.deserialize(new require_model.FrozenByteBuffer(datagramBytes));
|
|
2964
|
+
const trackAlias = datagram.trackAlias;
|
|
2965
|
+
if (this.onDatagramReceived) this.onDatagramReceived(datagram);
|
|
2966
|
+
const fullTrackName = this.#resolveTrackAlias(trackAlias);
|
|
2967
|
+
const moqtObject = require_model.MoqtObject.fromDatagram(datagram, fullTrackName);
|
|
2968
|
+
const trackKey = trackAlias.toString();
|
|
2969
|
+
const handler = this.#datagramTrackHandlers.get(trackKey);
|
|
2970
|
+
if (handler) try {
|
|
2971
|
+
handler(moqtObject);
|
|
2972
|
+
} catch (handlerError) {
|
|
2973
|
+
require_logger.logger.warn("MOQtailClient", "Datagram track handler error:", handlerError);
|
|
2974
|
+
}
|
|
2975
|
+
if (this.#receivedDatagramObjectController) try {
|
|
2976
|
+
this.#receivedDatagramObjectController.enqueue(moqtObject);
|
|
2977
|
+
} catch {}
|
|
2978
|
+
} catch (error) {
|
|
2979
|
+
require_logger.logger.warn("MOQtailClient", "Failed to parse datagram:", error);
|
|
2980
|
+
continue;
|
|
2981
|
+
}
|
|
2982
|
+
}
|
|
2983
|
+
} catch (error) {
|
|
2984
|
+
require_logger.logger.error("MOQtailClient", "Datagram reception error:", error);
|
|
2985
|
+
if (this.#receivedDatagramObjectController) try {
|
|
2986
|
+
this.#receivedDatagramObjectController.error(error);
|
|
2987
|
+
} catch {}
|
|
2988
|
+
this.#isReceivingDatagrams = false;
|
|
2989
|
+
}
|
|
2990
|
+
}
|
|
2991
|
+
/**
|
|
2992
|
+
* Resolve track alias to full track name using client's request ID map.
|
|
2993
|
+
* Falls back to a placeholder if not found.
|
|
2994
|
+
*/
|
|
2995
|
+
#resolveTrackAlias(trackAlias) {
|
|
2996
|
+
try {
|
|
2997
|
+
const requestId = this.subscriptionAliasMap.get(trackAlias);
|
|
2998
|
+
if (requestId !== void 0) return this.requestIdMap.getNameByRequestId(requestId);
|
|
2999
|
+
return require_model.FullTrackName.tryNew("unknown", `track-${trackAlias}`);
|
|
3000
|
+
} catch {
|
|
3001
|
+
return require_model.FullTrackName.tryNew("unknown", `track-${trackAlias}`);
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
/**
|
|
3005
|
+
* Sets (or replaces) the client-level default early discard policy for incoming subgroup streams.
|
|
3006
|
+
*
|
|
3007
|
+
* When set, each incoming subgroup QUIC stream is given a deadline of `subgroupReceiveTimeout` ms to
|
|
3008
|
+
* complete. If the stream has not finished within that window it is cancelled — objects already
|
|
3009
|
+
* delivered to the subscription are kept, but no further objects arrive from that stream.
|
|
3010
|
+
*
|
|
3011
|
+
* This is a client-wide default. Individual subscriptions can override it via the `earlyDiscardPolicy`
|
|
3012
|
+
* field in {@link SubscribeOptions}, which takes precedence over this setting.
|
|
3013
|
+
*
|
|
3014
|
+
* The policy takes effect on the next stream accepted after this call. Passing a new config
|
|
3015
|
+
* replaces the previous one. Pass `undefined` to remove the default.
|
|
3016
|
+
*
|
|
3017
|
+
* @example
|
|
3018
|
+
* ```ts
|
|
3019
|
+
* client.setEarlyDiscardPolicy({ subgroupReceiveTimeout: 2000 })
|
|
3020
|
+
* ```
|
|
3021
|
+
*/
|
|
3022
|
+
setEarlyDiscardPolicy(config) {
|
|
3023
|
+
this.#ensureActive();
|
|
3024
|
+
this.#earlyDiscardPolicy = config;
|
|
3025
|
+
}
|
|
3026
|
+
/**
|
|
3027
|
+
* Gracefully terminates this {@link MOQtailClient} session and releases underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} resources.
|
|
3028
|
+
*
|
|
3029
|
+
* @param reason - Optional application-level reason (string or error) recorded and wrapped in an {@link InternalError}
|
|
3030
|
+
* passed to the {@link MOQtailClient.onSessionTerminated | onSessionTerminated} callback.
|
|
3031
|
+
*
|
|
3032
|
+
* @returns Promise that resolves once shutdown logic completes. Subsequent calls are safe no-ops.
|
|
3033
|
+
*
|
|
3034
|
+
* @example Basic usage
|
|
3035
|
+
* ```ts
|
|
3036
|
+
* await client.disconnect();
|
|
3037
|
+
* ```
|
|
3038
|
+
*
|
|
3039
|
+
* @example With reason
|
|
3040
|
+
* ```ts
|
|
3041
|
+
* await client.disconnect('user logout');
|
|
3042
|
+
* ```
|
|
3043
|
+
*
|
|
3044
|
+
* @example Idempotent double call
|
|
3045
|
+
* ```ts
|
|
3046
|
+
* await client.disconnect();
|
|
3047
|
+
* await client.disconnect(); // no error
|
|
3048
|
+
* ```
|
|
3049
|
+
*
|
|
3050
|
+
* @example Page unload safety
|
|
3051
|
+
* ```ts
|
|
3052
|
+
* window.addEventListener('beforeunload', () => {
|
|
3053
|
+
* client.disconnect('page unload');
|
|
3054
|
+
* });
|
|
3055
|
+
* ```
|
|
3056
|
+
*/
|
|
3057
|
+
async disconnect(reason) {
|
|
3058
|
+
require_logger.logger.log("MOQtailClient", "disconnect", reason);
|
|
3059
|
+
if (this.#isDestroyed) return;
|
|
3060
|
+
this.#isDestroyed = true;
|
|
3061
|
+
await this.stopDatagrams();
|
|
3062
|
+
const openStreams = [...this.#requestStreams.values()];
|
|
3063
|
+
this.#requestStreams.clear();
|
|
3064
|
+
this.#namespaceRequestIds.clear();
|
|
3065
|
+
await Promise.allSettled(openStreams.map((requestStream) => requestStream.close()));
|
|
3066
|
+
if (!this.webTransport.closed) this.webTransport.close();
|
|
3067
|
+
if (this.onSessionTerminated) this.onSessionTerminated(new require_model.InternalError("MOQtailClient.disconnect", reason instanceof Error ? reason.message : String(reason)));
|
|
3068
|
+
}
|
|
3069
|
+
/**
|
|
3070
|
+
* Registers or updates a {@link Track} definition for local publishing or serving.
|
|
3071
|
+
*
|
|
3072
|
+
* A {@link Track} describes a logical media/data stream, identified by a unique name and namespace.
|
|
3073
|
+
* - If `trackSource.live` is present, the track can be served to subscribers in real-time.
|
|
3074
|
+
* - If `trackSource.past` is present, the track can be fetched for historical data.
|
|
3075
|
+
* - If both are present, the track supports both live and historical access.
|
|
3076
|
+
*
|
|
3077
|
+
* @param track - The {@link Track} instance to add or update. See {@link TrackSource} for live/past source options.
|
|
3078
|
+
* @returns void
|
|
3079
|
+
* @throws : {@link MOQtailError} If the client has been destroyed.
|
|
3080
|
+
*
|
|
3081
|
+
* @example Create a live video track from getUserMedia
|
|
3082
|
+
* ```ts
|
|
3083
|
+
* const stream = await navigator.mediaDevices.getUserMedia({ video: true });
|
|
3084
|
+
* const videoTrack = stream.getVideoTracks()[0];
|
|
3085
|
+
*
|
|
3086
|
+
* // Convert video frames to MoqtObject instances using your chosen scheme (e.g. MSF, CMAF, etc.)
|
|
3087
|
+
* // This part is application-specific and not provided by MOQtail:
|
|
3088
|
+
* const liveReadableStream: ReadableStream<MoqtObject> = ...
|
|
3089
|
+
*
|
|
3090
|
+
* // Register the track for live subscription
|
|
3091
|
+
* client.addOrUpdateTrack({
|
|
3092
|
+
* fullTrackName: { namespace: ["camera"], name: "main" },
|
|
3093
|
+
* trackSource: { live: liveReadableStream },
|
|
3094
|
+
* publisherPriority: 0 // highest priority
|
|
3095
|
+
* });
|
|
3096
|
+
*
|
|
3097
|
+
* // For a hybrid track (live + past):
|
|
3098
|
+
* import { MemoryObjectCache } from './track/object_cache';
|
|
3099
|
+
* const cache = new MemoryObjectCache(); // Caches are not yet fully supported
|
|
3100
|
+
* client.addOrUpdateTrack({
|
|
3101
|
+
* fullTrackName: { namespace: ["camera"], name: "main" },
|
|
3102
|
+
* trackSource: { live: liveReadableStream, past: cache },
|
|
3103
|
+
* publisherPriority: 8
|
|
3104
|
+
* });
|
|
3105
|
+
* ```
|
|
3106
|
+
*/
|
|
3107
|
+
addOrUpdateTrack(track) {
|
|
3108
|
+
this.#ensureActive();
|
|
3109
|
+
if (!isValidTrackAlias(track.trackAlias)) track.trackAlias = random60bitId();
|
|
3110
|
+
this.trackSources.set(track.fullTrackName.toString(), track);
|
|
3111
|
+
}
|
|
3112
|
+
/**
|
|
3113
|
+
* Removes a previously registered {@link Track} from this client's local catalog.
|
|
3114
|
+
*
|
|
3115
|
+
* This deletes the in-memory entry inserted via {@link MOQtailClient.addOrUpdateTrack}, so future lookups by its {@link Track.fullTrackName} will fail.
|
|
3116
|
+
* Does **not** automatically:
|
|
3117
|
+
* - Withdraw the namespace announcement (call {@link MOQtailClient.unpublishNamespace} separately if you want to inform peers)
|
|
3118
|
+
* - Cancel active subscriptions or fetches (they continue until normal completion)
|
|
3119
|
+
* - Affect already-sent objects.
|
|
3120
|
+
*
|
|
3121
|
+
* If the track was not present, the call is a silent no-op (idempotent removal).
|
|
3122
|
+
*
|
|
3123
|
+
* @param track - The exact {@link Track} instance (its canonical name is used as the key).
|
|
3124
|
+
* @throws : {@link MOQtailError} If the client has been destroyed.
|
|
3125
|
+
*
|
|
3126
|
+
* @example
|
|
3127
|
+
* ```ts
|
|
3128
|
+
* // Register a track
|
|
3129
|
+
* client.addOrUpdateTrack(track);
|
|
3130
|
+
*
|
|
3131
|
+
* // Later, when no longer publishing:
|
|
3132
|
+
* client.removeTrack(track);
|
|
3133
|
+
*
|
|
3134
|
+
* // Optionally, inform peers that the namespace is no longer available:
|
|
3135
|
+
* await client.unpublishNamespace(track.fullTrackName.namespace);
|
|
3136
|
+
* ```
|
|
3137
|
+
*/
|
|
3138
|
+
removeTrack(track) {
|
|
3139
|
+
this.#ensureActive();
|
|
3140
|
+
this.trackSources.delete(track.fullTrackName.toString());
|
|
3141
|
+
}
|
|
3142
|
+
/**
|
|
3143
|
+
* Subscribes to a track and returns a stream of {@link MoqtObject}s matching the requested window and relay forwarding mode.
|
|
3144
|
+
*
|
|
3145
|
+
* - `forward: true` tells the relay to forward objects to this subscriber as they arrive.
|
|
3146
|
+
* - `forward: false` means the relay subscribes upstream but buffers objects locally, not forwarding them to you.
|
|
3147
|
+
* - `filterType: AbsoluteStart` lets you specify a start position in the future; the stream waits for that object. If the start location is \< the latest object
|
|
3148
|
+
* observed at the publisher then it behaves as `filterType: LatestObject`
|
|
3149
|
+
* - `filterType: AbsoluteRange` lets you specify a start and end group, both of should be in the future; the stream waits for those objects. If the start location is \< the latest object
|
|
3150
|
+
* observed at the publisher then it behaves as `filterType: LatestObject`.
|
|
3151
|
+
*
|
|
3152
|
+
* The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId` and a `ReadableStream` of {@link MoqtObject}s.
|
|
3153
|
+
* Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
|
|
3154
|
+
*
|
|
3155
|
+
* @param args - {@link SubscribeOptions} describing the subscription window and relay forwarding behavior.
|
|
3156
|
+
* @returns Either a {@link RequestError} or `{ requestId, stream }` for consuming objects.
|
|
3157
|
+
* @throws : {@link MOQtailError} If the client is destroyed.
|
|
3158
|
+
* @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
|
|
3159
|
+
* @throws : {@link InternalError} On transport/protocol failure (disconnect is triggered before rethrow).
|
|
3160
|
+
*
|
|
3161
|
+
* @example Subscribe to the latest object and receive future objects as they arrive
|
|
3162
|
+
* ```ts
|
|
3163
|
+
* const result = await client.subscribe({
|
|
3164
|
+
* fullTrackName,
|
|
3165
|
+
* filterType: FilterType.LatestObject,
|
|
3166
|
+
* forward: true,
|
|
3167
|
+
* groupOrder: GroupOrder.Original,
|
|
3168
|
+
* priority: 32
|
|
3169
|
+
* });
|
|
3170
|
+
* if (!(result instanceof RequestError)) {
|
|
3171
|
+
* for await (const obj of result.stream) {
|
|
3172
|
+
* // decode and display obj
|
|
3173
|
+
* }
|
|
3174
|
+
* }
|
|
3175
|
+
* ```
|
|
3176
|
+
*
|
|
3177
|
+
* @example Subscribe to a future range (waits for those objects to arrive)
|
|
3178
|
+
* ```ts
|
|
3179
|
+
* const result = await client.subscribe({
|
|
3180
|
+
* fullTrackName,
|
|
3181
|
+
* filterType: FilterType.AbsoluteRange,
|
|
3182
|
+
* startLocation: futureStart,
|
|
3183
|
+
* endGroup: futureEnd,
|
|
3184
|
+
* forward: true,
|
|
3185
|
+
* groupOrder: GroupOrder.Original,
|
|
3186
|
+
* priority: 128
|
|
3187
|
+
* });
|
|
3188
|
+
* ```
|
|
3189
|
+
*/
|
|
3190
|
+
async subscribe(args) {
|
|
3191
|
+
this.#ensureActive();
|
|
3192
|
+
try {
|
|
3193
|
+
let { fullTrackName, priority, groupOrder, forward, filterType, parameters, startLocation, endGroup } = args;
|
|
3194
|
+
require_logger.logger.debug("MOQtailClient", `subscribe: ftn="${fullTrackName}" filterType=${filterType} priority=${priority} forward=${forward} groupOrder=${groupOrder}`);
|
|
3195
|
+
let msg;
|
|
3196
|
+
if (typeof endGroup === "number") endGroup = BigInt(endGroup);
|
|
3197
|
+
const baseParams = [
|
|
3198
|
+
new require_model.SubscriberPriority(priority),
|
|
3199
|
+
new require_model.Forward(forward),
|
|
3200
|
+
...groupOrder !== 0 ? [new require_model.GroupOrderParam(groupOrder)] : [],
|
|
3201
|
+
...parameters ?? []
|
|
3202
|
+
];
|
|
3203
|
+
switch (filterType) {
|
|
3204
|
+
case 2:
|
|
3205
|
+
msg = require_model.Subscribe.newLatestObject(this.#nextClientRequestId, fullTrackName, baseParams);
|
|
3206
|
+
break;
|
|
3207
|
+
case 1:
|
|
3208
|
+
msg = require_model.Subscribe.newNextGroupStart(this.#nextClientRequestId, fullTrackName, baseParams);
|
|
3209
|
+
break;
|
|
3210
|
+
case 3:
|
|
3211
|
+
if (!startLocation) throw new require_model.ProtocolViolationError("MOQtailClient.subscribe", "FilterType.AbsoluteStart must have a start location");
|
|
3212
|
+
msg = require_model.Subscribe.newAbsoluteStart(this.#nextClientRequestId, fullTrackName, startLocation, baseParams);
|
|
3213
|
+
break;
|
|
3214
|
+
case 4:
|
|
3215
|
+
if (startLocation === void 0 || endGroup === void 0) throw new require_model.ProtocolViolationError("MOQtailClient.subscribe", "FilterType.AbsoluteRange must have a start location and an end group");
|
|
3216
|
+
if (endGroup > 0 && startLocation.group >= endGroup) throw new require_model.ProtocolViolationError("MOQtailClient.subscribe", "End group must be greater than start group");
|
|
3217
|
+
msg = require_model.Subscribe.newAbsoluteRange(this.#nextClientRequestId, fullTrackName, startLocation, endGroup, baseParams);
|
|
3218
|
+
break;
|
|
3219
|
+
}
|
|
3220
|
+
const request = new SubscribeRequest(msg);
|
|
3221
|
+
request.earlyDiscardPolicy = args.earlyDiscardPolicy;
|
|
3222
|
+
this.requests.set(request.requestId, request);
|
|
3223
|
+
this.requestIdMap.addMapping(request.requestId, request.fullTrackName);
|
|
3224
|
+
require_logger.logger.debug("MOQtailClient", `subscribe: sending SUBSCRIBE requestId=${msg.requestId} ftn="${fullTrackName}"`);
|
|
3225
|
+
await this.#openRequestStream(request.requestId, msg);
|
|
3226
|
+
require_logger.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE sent, awaiting SUBSCRIBE_OK/REQUEST_ERROR requestId=${msg.requestId}`);
|
|
3227
|
+
const response = await request;
|
|
3228
|
+
if (response instanceof require_model.RequestError) {
|
|
3229
|
+
require_logger.logger.error("MOQtailClient", `subscribe: SUBSCRIBE_ERROR requestId=${request.requestId} code=${response.errorCode} reason="${response.reasonPhrase.phrase}"`);
|
|
3230
|
+
this.requests.delete(request.requestId);
|
|
3231
|
+
this.requestIdMap.removeMappingByRequestId(request.requestId);
|
|
3232
|
+
return response;
|
|
3233
|
+
} else {
|
|
3234
|
+
require_logger.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE_OK requestId=${request.requestId} trackAlias=${response.trackAlias}`);
|
|
3235
|
+
this.subscriptions.set(response.trackAlias, request);
|
|
3236
|
+
this.subscriptionAliasMap.set(request.requestId, response.trackAlias);
|
|
3237
|
+
this.aliasFullTrackNameMap.set(response.trackAlias, fullTrackName);
|
|
3238
|
+
return {
|
|
3239
|
+
requestId: msg.requestId,
|
|
3240
|
+
stream: request.stream
|
|
3241
|
+
};
|
|
3242
|
+
}
|
|
3243
|
+
} catch (error) {
|
|
3244
|
+
require_logger.logger.error("MOQtailClient", `subscribe: unexpected error — ${error instanceof Error ? error.message : String(error)}`);
|
|
3245
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.subscribe", error instanceof Error ? error.message : String(error)));
|
|
3246
|
+
throw error;
|
|
3247
|
+
}
|
|
3248
|
+
}
|
|
3249
|
+
/**
|
|
3250
|
+
* Stops an active subscription identified by its original SUBSCRIBE `requestId`.
|
|
3251
|
+
*
|
|
3252
|
+
* Resets the subscription's request stream with `CANCELLED` if it is still active. If the id is unknown or already
|
|
3253
|
+
* cleaned up, the call is a silent no-op (hence multiple calls are idempotent).
|
|
3254
|
+
*
|
|
3255
|
+
* Use this when you no longer want incoming objects for a track (e.g. user navigated away, switching quality).
|
|
3256
|
+
* Canceling the consumer stream reader does **not** auto-unsubscribe; call this explicitly for prompt cleanup.
|
|
3257
|
+
*
|
|
3258
|
+
* @param requestId - The id returned from {@link MOQtailClient.subscribe}.
|
|
3259
|
+
* @returns Promise that resolves once the request stream has been reset.
|
|
3260
|
+
* @throws :{@link MOQtailError} If the client is destroyed.
|
|
3261
|
+
* @throws :{@link InternalError} Wrapped lower-level failure while attempting to send (session will be disconnected first).
|
|
3262
|
+
*
|
|
3263
|
+
* @remarks
|
|
3264
|
+
* - Only targets SUBSCRIBE requests, not fetches. Passing a fetch request id is ignored (no-op).
|
|
3265
|
+
* - Safe to call multiple times; extra calls have no effect.
|
|
3266
|
+
*
|
|
3267
|
+
* @example Subscribe and later unsubscribe
|
|
3268
|
+
* ```ts
|
|
3269
|
+
* const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 });
|
|
3270
|
+
* if (!(sub instanceof RequestError)) {
|
|
3271
|
+
* // ...consume objects...
|
|
3272
|
+
* await client.unsubscribe(sub.requestId);
|
|
3273
|
+
* }
|
|
3274
|
+
* ```
|
|
3275
|
+
*
|
|
3276
|
+
* @example Idempotent usage
|
|
3277
|
+
* ```ts
|
|
3278
|
+
* await client.unsubscribe(123n);
|
|
3279
|
+
* await client.unsubscribe(123n); // no error
|
|
3280
|
+
* ```
|
|
3281
|
+
*/
|
|
3282
|
+
async unsubscribe(requestId) {
|
|
3283
|
+
this.#ensureActive();
|
|
3284
|
+
if (typeof requestId === "number") requestId = BigInt(requestId);
|
|
3285
|
+
let cleanupData = null;
|
|
3286
|
+
try {
|
|
3287
|
+
if (this.requests.has(requestId)) {
|
|
3288
|
+
const subscription = this.requests.get(requestId);
|
|
3289
|
+
if (subscription instanceof SubscribeRequest) {
|
|
3290
|
+
const trackAlias = this.subscriptionAliasMap.get(requestId);
|
|
3291
|
+
cleanupData = {
|
|
3292
|
+
requestId,
|
|
3293
|
+
trackAlias,
|
|
3294
|
+
subscription
|
|
3295
|
+
};
|
|
3296
|
+
await this.#resetRequestStream(requestId, 1);
|
|
3297
|
+
subscription.unsubscribe();
|
|
3298
|
+
}
|
|
3299
|
+
}
|
|
3300
|
+
} catch (error) {
|
|
3301
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribe", error instanceof Error ? error.message : String(error)));
|
|
3302
|
+
throw error;
|
|
3303
|
+
} finally {
|
|
3304
|
+
if (cleanupData) {
|
|
3305
|
+
this.requests.delete(cleanupData.requestId);
|
|
3306
|
+
this.subscriptions.delete(cleanupData.trackAlias);
|
|
3307
|
+
this.aliasFullTrackNameMap.delete(cleanupData.trackAlias);
|
|
3308
|
+
this.requestIdMap.removeMappingByRequestId(cleanupData.requestId);
|
|
3309
|
+
}
|
|
3310
|
+
}
|
|
3311
|
+
}
|
|
3312
|
+
/**
|
|
3313
|
+
* Narrows or updates an active subscription window and/or relay forwarding behavior.
|
|
3314
|
+
*
|
|
3315
|
+
* Use this to:
|
|
3316
|
+
* - Move the start of the subscription forward (trim history or future window).
|
|
3317
|
+
* - Move the end group earlier (shorten the window).
|
|
3318
|
+
* - Change relay forwarding (`forward: false` stops forwarding new objects, `true` resumes).
|
|
3319
|
+
* - Adjust subscriber priority.
|
|
3320
|
+
*
|
|
3321
|
+
* Only narrowing is allowed: you cannot move the start earlier or the end group later than the original subscription.
|
|
3322
|
+
* Forwarding and priority can be changed at any time.
|
|
3323
|
+
*
|
|
3324
|
+
* @param args - {@link SubscribeUpdateOptions} referencing the original subscription `requestId` and new bounds.
|
|
3325
|
+
* @returns Promise that resolves when the update control frame is sent.
|
|
3326
|
+
* @throws :{@link MOQtailError} If the client is destroyed.
|
|
3327
|
+
* @throws :{@link ProtocolViolationError} If the update would widen the window (earlier start, later end group, or invalid ordering).
|
|
3328
|
+
* @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
|
|
3329
|
+
*
|
|
3330
|
+
* @remarks
|
|
3331
|
+
* - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
|
|
3332
|
+
* - Omitting a parameter (e.g. `priority`) leaves the previous value unchanged.
|
|
3333
|
+
* - Setting `forward: false` stops relay forwarding new objects after the current window drains.
|
|
3334
|
+
* - Safe to call multiple times; extra calls with unchanged bounds have no effect.
|
|
3335
|
+
*
|
|
3336
|
+
* @example Trim start forward
|
|
3337
|
+
* ```ts
|
|
3338
|
+
* await client.subscribeUpdate({ requestId, startLocation: laterLoc, endGroup, forward: true, priority });
|
|
3339
|
+
* ```
|
|
3340
|
+
*
|
|
3341
|
+
* @example Convert tailing subscription into bounded slice
|
|
3342
|
+
* ```ts
|
|
3343
|
+
* await client.subscribeUpdate({ requestId, startLocation: origStart, endGroup: cutoffGroup, forward: false, priority });
|
|
3344
|
+
* ```
|
|
3345
|
+
*
|
|
3346
|
+
* @example Lower priority only
|
|
3347
|
+
* ```ts
|
|
3348
|
+
* await client.subscribeUpdate({ requestId, startLocation: currentStart, endGroup: currentEnd, forward: true, priority: 200 });
|
|
3349
|
+
* ```
|
|
3350
|
+
*/
|
|
3351
|
+
async subscribeUpdate(args) {
|
|
3352
|
+
this.#ensureActive();
|
|
3353
|
+
let { subscriptionRequestId, priority, forward, parameters, startLocation, endGroup } = args;
|
|
3354
|
+
if (endGroup && startLocation.group >= endGroup) throw new require_model.ProtocolViolationError("MOQtailClient.subscribeUpdate", "End group must be greater than start group");
|
|
3355
|
+
try {
|
|
3356
|
+
if (this.requests.has(subscriptionRequestId)) {
|
|
3357
|
+
if (this.requests.get(subscriptionRequestId) instanceof SubscribeRequest) {
|
|
3358
|
+
const trackAlias = this.subscriptionAliasMap.get(subscriptionRequestId);
|
|
3359
|
+
if (!isValidTrackAlias(trackAlias)) throw new require_model.InternalError("MOQtailClient.subscribeUpdate", "Request exists but track alias mapping does not");
|
|
3360
|
+
const subscription = this.subscriptions.get(trackAlias);
|
|
3361
|
+
if (!subscription) throw new require_model.InternalError("MOQtailClient.subscribeUpdate", "Request exists but subscription does not");
|
|
3362
|
+
const requestId = this.#nextClientRequestId;
|
|
3363
|
+
const msg = new require_model.RequestUpdate(requestId, [
|
|
3364
|
+
new require_model.SubscriberPriority(priority),
|
|
3365
|
+
new require_model.Forward(forward),
|
|
3366
|
+
new require_model.SubscriptionFilter(4, startLocation, endGroup),
|
|
3367
|
+
...parameters ?? []
|
|
3368
|
+
]);
|
|
3369
|
+
subscription.update(msg);
|
|
3370
|
+
await this.#requestStreamFor(subscriptionRequestId, "MOQtailClient.subscribeUpdate").send(msg);
|
|
3371
|
+
}
|
|
3372
|
+
}
|
|
3373
|
+
} catch (error) {
|
|
3374
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeUpdate", error instanceof Error ? error.message : String(error)));
|
|
3375
|
+
throw error;
|
|
3376
|
+
}
|
|
3377
|
+
}
|
|
3378
|
+
/**
|
|
3379
|
+
* Switches an active subscription to a different track while retaining the same subscription parameters.
|
|
3380
|
+
*
|
|
3381
|
+
* Use this to change the subscribed track without tearing down and re-establishing a new subscription.
|
|
3382
|
+
*
|
|
3383
|
+
* @param args - {@link SwitchOptions} referencing the original subscription `requestId` and new track name.
|
|
3384
|
+
* @returns Promise that resolves when the switch control frame is sent.
|
|
3385
|
+
* @throws :{@link MOQtailError} If the client is destroyed.
|
|
3386
|
+
* @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
|
|
3387
|
+
*
|
|
3388
|
+
* @remarks
|
|
3389
|
+
* - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
|
|
3390
|
+
* - All other subscription parameters (window, forwarding, priority) remain unchanged.
|
|
3391
|
+
*
|
|
3392
|
+
* @example Switch to a different track
|
|
3393
|
+
* ```ts
|
|
3394
|
+
* await client.switch({ subscriptionRequestId, fullTrackName: newTrackName });
|
|
3395
|
+
* ```
|
|
3396
|
+
*/
|
|
3397
|
+
async switch(args) {
|
|
3398
|
+
this.#ensureActive();
|
|
3399
|
+
let { fullTrackName, subscriptionRequestId, parameters } = args;
|
|
3400
|
+
try {
|
|
3401
|
+
if (!this.requests.has(subscriptionRequestId)) throw new require_model.ProtocolViolationError("MOQtailClient.switch", "Unknown subscription request id");
|
|
3402
|
+
if (!(this.requests.get(subscriptionRequestId) instanceof SubscribeRequest)) throw new require_model.ProtocolViolationError("MOQtailClient.switch", "Request id is not a subscription");
|
|
3403
|
+
const trackAlias = this.subscriptionAliasMap.get(subscriptionRequestId);
|
|
3404
|
+
if (!isValidTrackAlias(trackAlias)) throw new require_model.InternalError("MOQtailClient.switch", "Request exists but track alias mapping does not");
|
|
3405
|
+
const subscription = this.subscriptions.get(trackAlias);
|
|
3406
|
+
if (!subscription) throw new require_model.InternalError("MOQtailClient.switch", "Request exists but subscription does not");
|
|
3407
|
+
const requestId = this.#nextClientRequestId;
|
|
3408
|
+
this.requests.set(requestId, subscription);
|
|
3409
|
+
const switchParams = parameters ?? [];
|
|
3410
|
+
const msg = new require_model.Switch(requestId, fullTrackName, subscriptionRequestId, switchParams.map((p) => p.toKeyValuePair()));
|
|
3411
|
+
subscription.switch(fullTrackName, switchParams);
|
|
3412
|
+
const requestStream = this.#requestStreamFor(subscriptionRequestId, "MOQtailClient.switch");
|
|
3413
|
+
await requestStream.send(msg);
|
|
3414
|
+
this.#requestStreams.set(requestId, requestStream);
|
|
3415
|
+
const response = await subscription;
|
|
3416
|
+
if (response instanceof require_model.SubscribeOk) {
|
|
3417
|
+
this.aliasFullTrackNameMap.set(response.trackAlias, fullTrackName);
|
|
3418
|
+
this.pendingStateUpdates.set(subscriptionRequestId, (newTrackAlias) => {
|
|
3419
|
+
if (newTrackAlias !== response.trackAlias) return false;
|
|
3420
|
+
this.subscriptions.set(response.trackAlias, subscription);
|
|
3421
|
+
this.subscriptionAliasMap.set(requestId, response.trackAlias);
|
|
3422
|
+
subscription.requestId = requestId;
|
|
3423
|
+
this.requestIdMap.removeMappingByRequestId(subscriptionRequestId);
|
|
3424
|
+
this.requestIdMap.addMapping(subscriptionRequestId, fullTrackName);
|
|
3425
|
+
this.subscriptions.delete(trackAlias);
|
|
3426
|
+
return true;
|
|
3427
|
+
});
|
|
3428
|
+
return {
|
|
3429
|
+
requestId,
|
|
3430
|
+
stream: subscription.stream
|
|
3431
|
+
};
|
|
3432
|
+
} else {
|
|
3433
|
+
this.requestIdMap.removeMappingByRequestId(requestId);
|
|
3434
|
+
this.requests.delete(requestId);
|
|
3435
|
+
return response;
|
|
3436
|
+
}
|
|
3437
|
+
} catch (error) {
|
|
3438
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.switch", error instanceof Error ? error.message : String(error)));
|
|
3439
|
+
throw error;
|
|
3440
|
+
}
|
|
3441
|
+
}
|
|
3442
|
+
/**
|
|
3443
|
+
* One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
|
|
3444
|
+
*
|
|
3445
|
+
* Choose a fetch type via `typeAndProps.type`:
|
|
3446
|
+
* - Standalone: Historical slice of a specific {@link FullTrackName} independent of active subscriptions.
|
|
3447
|
+
* - Relative: Range relative to the JOINING subscription's current (largest) location; use when you want "N groups back" from live.
|
|
3448
|
+
* - Absolute: Absolute group/object offsets tied to an existing subscription (stable anchor) even if that subscription keeps forwarding.
|
|
3449
|
+
*
|
|
3450
|
+
* Field highlights (in {@link FetchOptions}):
|
|
3451
|
+
* - priority: 0 (highest) .. 255 (lowest); out-of-range rejected; non-integers rounded by caller expectation.
|
|
3452
|
+
* - groupOrder: {@link (GroupOrder:enum).Original} to preserve publisher order; or reorder ascending/descending if supported by server.
|
|
3453
|
+
* - typeAndProps: Discriminated union carrying parameters specific to each fetch mode (see examples).
|
|
3454
|
+
* - parameters: Optional version-specific extension block.
|
|
3455
|
+
*
|
|
3456
|
+
* Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, stream }` whose `stream`
|
|
3457
|
+
* ends naturally after the bounded range completes (no explicit cancel needed for normal completion).
|
|
3458
|
+
*
|
|
3459
|
+
* Use cases:
|
|
3460
|
+
* - Grab a historical window for scrubbing UI while a separate live subscription tails.
|
|
3461
|
+
* - Late joiner fetching a short back-buffer then discarding the stream.
|
|
3462
|
+
* - Analytics batch job pulling a fixed slice without subscribing long-term.
|
|
3463
|
+
*
|
|
3464
|
+
* @throws MOQtailError If client is destroyed.
|
|
3465
|
+
* @throws ProtocolViolationError Priority out of [0-255] or missing/invalid joining subscription id for Relative/Absolute.
|
|
3466
|
+
* @throws InternalError Transport/control failure (the client disconnects first) then rethrows original error.
|
|
3467
|
+
*
|
|
3468
|
+
* @remarks
|
|
3469
|
+
* - Relative / Absolute require an existing active SUBSCRIBE `joiningRequestId`; if not found a {@link ProtocolViolationError} is thrown.
|
|
3470
|
+
* - Result stream is finite; reader close occurs automatically when last object delivered.
|
|
3471
|
+
* - Use {@link MOQtailClient.fetchCancel} only for early termination (not yet fully implemented: see TODO in code).
|
|
3472
|
+
*
|
|
3473
|
+
* @example Standalone window
|
|
3474
|
+
* ```ts
|
|
3475
|
+
* const r = await client.fetch({
|
|
3476
|
+
* priority: 64,
|
|
3477
|
+
* groupOrder: GroupOrder.Original,
|
|
3478
|
+
* typeAndProps: {
|
|
3479
|
+
* type: FetchType.Standalone,
|
|
3480
|
+
* props: { fullTrackName, startLocation, endLocation }
|
|
3481
|
+
* }
|
|
3482
|
+
* })
|
|
3483
|
+
* if (!(r instanceof RequestError)) {
|
|
3484
|
+
* for await (const obj of r.stream as any) {
|
|
3485
|
+
* // consume objects then stream ends automatically
|
|
3486
|
+
* }
|
|
3487
|
+
* }
|
|
3488
|
+
* ```
|
|
3489
|
+
*
|
|
3490
|
+
* @example Relative to live subscription (e.g. last 5 groups)
|
|
3491
|
+
* ```ts
|
|
3492
|
+
* const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 })
|
|
3493
|
+
* if (!(sub instanceof RequestError)) {
|
|
3494
|
+
* const slice = await client.fetch({
|
|
3495
|
+
* priority: 32,
|
|
3496
|
+
* groupOrder: GroupOrder.Original,
|
|
3497
|
+
* typeAndProps: { type: FetchType.Relative, props: { joiningRequestId: sub.requestId, joiningStart: 0n } }
|
|
3498
|
+
* })
|
|
3499
|
+
* }
|
|
3500
|
+
* ```
|
|
3501
|
+
*/
|
|
3502
|
+
async fetch(args) {
|
|
3503
|
+
this.#ensureActive();
|
|
3504
|
+
try {
|
|
3505
|
+
const { priority, groupOrder, typeAndProps, parameters } = args;
|
|
3506
|
+
if (priority < 0 || priority > 255) throw new require_model.ProtocolViolationError("MOQtailClient.fetch", `subscriberPriority: ${priority} must be in range of [0-255]`);
|
|
3507
|
+
const params = [
|
|
3508
|
+
new require_model.SubscriberPriority(priority),
|
|
3509
|
+
...groupOrder !== 0 ? [new require_model.GroupOrderParam(groupOrder)] : [],
|
|
3510
|
+
...parameters ?? []
|
|
3511
|
+
];
|
|
3512
|
+
let msg;
|
|
3513
|
+
let joiningRequest;
|
|
3514
|
+
const requestId = this.#nextClientRequestId;
|
|
3515
|
+
require_logger.logger.log("MOQtailClient", "fetch: generated requestId:", requestId, "for fetch type:", typeAndProps.type, "current #dontUseRequestId:", this.#dontUseRequestId);
|
|
3516
|
+
switch (typeAndProps.type) {
|
|
3517
|
+
case 1:
|
|
3518
|
+
msg = new require_model.Fetch(requestId, {
|
|
3519
|
+
type: typeAndProps.type,
|
|
3520
|
+
props: typeAndProps.props
|
|
3521
|
+
}, params);
|
|
3522
|
+
break;
|
|
3523
|
+
case 2:
|
|
3524
|
+
joiningRequest = this.requests.get(typeAndProps.props.joiningRequestId);
|
|
3525
|
+
if (!(joiningRequest instanceof SubscribeRequest)) throw new require_model.ProtocolViolationError("MOQtailClient.fetch", `No subscribe request for the given joiningRequestId: ${typeAndProps.props.joiningRequestId}`);
|
|
3526
|
+
msg = new require_model.Fetch(requestId, {
|
|
3527
|
+
type: typeAndProps.type,
|
|
3528
|
+
props: {
|
|
3529
|
+
...typeAndProps.props,
|
|
3530
|
+
joiningRequestId: this.#wireRequestId(typeAndProps.props.joiningRequestId)
|
|
3531
|
+
}
|
|
3532
|
+
}, params);
|
|
3533
|
+
break;
|
|
3534
|
+
case 3:
|
|
3535
|
+
joiningRequest = this.requests.get(typeAndProps.props.joiningRequestId);
|
|
3536
|
+
if (!(joiningRequest instanceof SubscribeRequest)) throw new require_model.ProtocolViolationError("MOQtailClient.fetch", `No subscribe request for the given joiningRequestId: ${typeAndProps.props.joiningRequestId}`);
|
|
3537
|
+
msg = new require_model.Fetch(requestId, {
|
|
3538
|
+
type: typeAndProps.type,
|
|
3539
|
+
props: {
|
|
3540
|
+
...typeAndProps.props,
|
|
3541
|
+
joiningRequestId: this.#wireRequestId(typeAndProps.props.joiningRequestId)
|
|
3542
|
+
}
|
|
3543
|
+
}, params);
|
|
3544
|
+
break;
|
|
3545
|
+
}
|
|
3546
|
+
const request = new FetchRequest(msg);
|
|
3547
|
+
require_logger.logger.log("MOQtailClient", "fetch: storing FetchRequest with requestId:", msg.requestId, "for fetch type:", typeAndProps.type);
|
|
3548
|
+
require_logger.logger.log("MOQtailClient", "fetch: full fetch message:", {
|
|
3549
|
+
requestId: msg.requestId,
|
|
3550
|
+
fetchType: typeAndProps.type,
|
|
3551
|
+
joiningRequestId: typeAndProps.type !== 1 ? typeAndProps.props.joiningRequestId : "N/A"
|
|
3552
|
+
});
|
|
3553
|
+
this.requests.set(msg.requestId, request);
|
|
3554
|
+
require_logger.logger.log("MOQtailClient", "fetch: about to send fetch message to server");
|
|
3555
|
+
await this.#openRequestStream(msg.requestId, msg);
|
|
3556
|
+
require_logger.logger.log("MOQtailClient", "fetch: fetch message sent successfully, waiting for response");
|
|
3557
|
+
const response = await request;
|
|
3558
|
+
if (response instanceof require_model.RequestError) {
|
|
3559
|
+
this.requests.delete(msg.requestId);
|
|
3560
|
+
return response;
|
|
3561
|
+
} else {
|
|
3562
|
+
const stream = request.stream;
|
|
3563
|
+
return {
|
|
3564
|
+
requestId: msg.requestId,
|
|
3565
|
+
stream
|
|
3566
|
+
};
|
|
3567
|
+
}
|
|
3568
|
+
} catch (error) {
|
|
3569
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.fetch", error instanceof Error ? error.message : String(error)));
|
|
3570
|
+
throw error;
|
|
3571
|
+
}
|
|
3572
|
+
}
|
|
3573
|
+
/**
|
|
3574
|
+
* Request early termination of an in‑flight FETCH identified by its `requestId`.
|
|
3575
|
+
*
|
|
3576
|
+
* Use when the consumer no longer needs the remaining objects (user scrubbed away, UI panel closed, replaced by a new fetch).
|
|
3577
|
+
* Resets the fetch's request stream with `CANCELLED` if the id currently maps to an active fetch; otherwise silent no-op (idempotent).
|
|
3578
|
+
*
|
|
3579
|
+
* Parameter semantics:
|
|
3580
|
+
* - requestId: bigint returned from {@link MOQtailClient.fetch}. Numbers auto-converted to bigint.
|
|
3581
|
+
*
|
|
3582
|
+
* Current behavior / limitations:
|
|
3583
|
+
* - Data stream closure after cancel is TODO (objects may still arrive briefly).
|
|
3584
|
+
* - Unknown / already finished request: ignored without error.
|
|
3585
|
+
* - Only targets FETCH requests (not subscriptions).
|
|
3586
|
+
*
|
|
3587
|
+
* @throws MOQtailError If client is destroyed.
|
|
3588
|
+
* @throws InternalError Failure while sending the cancel (client disconnects first).
|
|
3589
|
+
*
|
|
3590
|
+
* @remarks
|
|
3591
|
+
* Follow-up improvement planned: actively close associated readable stream controller immediately upon acknowledgment.
|
|
3592
|
+
*
|
|
3593
|
+
* @example Cancel shortly after starting
|
|
3594
|
+
* ```ts
|
|
3595
|
+
* const r = await client.fetch({ priority: 32, groupOrder: GroupOrder.Original, typeAndProps: { type: FetchType.Standalone, props: { fullTrackName, startLocation, endLocation } } })
|
|
3596
|
+
* if (!(r instanceof RequestError)) {
|
|
3597
|
+
* // user navigated away
|
|
3598
|
+
* await client.fetchCancel(r.requestId)
|
|
3599
|
+
* }
|
|
3600
|
+
* ```
|
|
3601
|
+
*
|
|
3602
|
+
* @example Idempotent double cancel
|
|
3603
|
+
* ```ts
|
|
3604
|
+
* await client.fetchCancel(456n)
|
|
3605
|
+
* await client.fetchCancel(456n) // no error
|
|
3606
|
+
* ```
|
|
3607
|
+
*/
|
|
3608
|
+
async fetchCancel(requestId) {
|
|
3609
|
+
this.#ensureActive();
|
|
3610
|
+
try {
|
|
3611
|
+
if (typeof requestId === "number") requestId = BigInt(requestId);
|
|
3612
|
+
if (this.requests.get(requestId) instanceof FetchRequest) await this.#resetRequestStream(requestId, 1);
|
|
3613
|
+
} catch (error) {
|
|
3614
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.fetchCancel", error instanceof Error ? error.message : String(error)));
|
|
3615
|
+
throw error;
|
|
3616
|
+
}
|
|
3617
|
+
}
|
|
3618
|
+
/**
|
|
3619
|
+
* Proactively push a track to the relay/peer.
|
|
3620
|
+
*/
|
|
3621
|
+
async publish(fullTrackName, forward, trackAlias, parameters, trackProperties) {
|
|
3622
|
+
this.#ensureActive();
|
|
3623
|
+
try {
|
|
3624
|
+
const requestId = this.#nextClientRequestId;
|
|
3625
|
+
const msg = new require_model.Publish(requestId, fullTrackName, trackAlias, [new require_model.Forward(forward), ...parameters ?? []], trackProperties ?? []);
|
|
3626
|
+
const request = new PublishRequest(msg);
|
|
3627
|
+
this.requests.set(msg.requestId, request);
|
|
3628
|
+
this.requestIdMap.addMapping(msg.requestId, fullTrackName);
|
|
3629
|
+
this.subscriptionAliasMap.set(msg.requestId, trackAlias);
|
|
3630
|
+
await this.#openRequestStream(msg.requestId, msg);
|
|
3631
|
+
const response = await request;
|
|
3632
|
+
if (response instanceof require_model.RequestError) {
|
|
3633
|
+
this.requests.delete(msg.requestId);
|
|
3634
|
+
this.requestIdMap.removeMappingByRequestId(msg.requestId);
|
|
3635
|
+
this.subscriptionAliasMap.delete(msg.requestId);
|
|
3636
|
+
return response;
|
|
3637
|
+
} else return {
|
|
3638
|
+
requestId: msg.requestId,
|
|
3639
|
+
trackAlias
|
|
3640
|
+
};
|
|
3641
|
+
} catch (error) {
|
|
3642
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.publish", error instanceof Error ? error.message : String(error)));
|
|
3643
|
+
throw error;
|
|
3644
|
+
}
|
|
3645
|
+
}
|
|
3646
|
+
/**
|
|
3647
|
+
* Signals the end of a published track to the peer/relay.
|
|
3648
|
+
* * @param publishRequestId - The original requestId used when `publish()` was called.
|
|
3649
|
+
*/
|
|
3650
|
+
async publishDone(publishRequestId, statusCode = 0, reasonPhrase = "Track Ended") {
|
|
3651
|
+
this.#ensureActive();
|
|
3652
|
+
try {
|
|
3653
|
+
if (typeof publishRequestId === "number") publishRequestId = BigInt(publishRequestId);
|
|
3654
|
+
const msg = new require_model.PublishDone(statusCode, 0n, new require_model.ReasonPhrase(reasonPhrase));
|
|
3655
|
+
const requestStream = this.#requestStreams.get(publishRequestId);
|
|
3656
|
+
if (requestStream) {
|
|
3657
|
+
await requestStream.send(msg);
|
|
3658
|
+
await this.#closeRequestStream(publishRequestId);
|
|
3659
|
+
} else require_logger.logger.warn("MOQtailClient", `publishDone: no request stream for requestId=${publishRequestId}`);
|
|
3660
|
+
this.requests.delete(publishRequestId);
|
|
3661
|
+
this.requestIdMap.removeMappingByRequestId(publishRequestId);
|
|
3662
|
+
this.subscriptionAliasMap.delete(publishRequestId);
|
|
3663
|
+
} catch (error) {
|
|
3664
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.publishDone", error instanceof Error ? error.message : String(error)));
|
|
3665
|
+
throw error;
|
|
3666
|
+
}
|
|
3667
|
+
}
|
|
3668
|
+
/**
|
|
3669
|
+
* Registers an incoming PUBLISH announcement as a valid data receiver.
|
|
3670
|
+
* This prepares the client to ingest pushed data streams matching the published alias.
|
|
3671
|
+
* * @param msg - The incoming Publish control message
|
|
3672
|
+
* @returns - A stream of MoqtObjects being pushed by the publisher
|
|
3673
|
+
*/
|
|
3674
|
+
acceptPushedTrack(msg) {
|
|
3675
|
+
this.#ensureActive();
|
|
3676
|
+
let streamController;
|
|
3677
|
+
const stream = new ReadableStream({ start(c) {
|
|
3678
|
+
streamController = c;
|
|
3679
|
+
} });
|
|
3680
|
+
this.requestIdMap.addMapping(msg.requestId, msg.fullTrackName);
|
|
3681
|
+
this.subscriptionAliasMap.set(msg.requestId, msg.trackAlias);
|
|
3682
|
+
this.aliasFullTrackNameMap.set(msg.trackAlias, msg.fullTrackName);
|
|
3683
|
+
const receiver = {
|
|
3684
|
+
requestId: msg.requestId,
|
|
3685
|
+
streamsAccepted: 0,
|
|
3686
|
+
largestLocation: void 0,
|
|
3687
|
+
controller: streamController
|
|
3688
|
+
};
|
|
3689
|
+
this.subscriptions.set(msg.trackAlias, receiver);
|
|
3690
|
+
return stream;
|
|
3691
|
+
}
|
|
3692
|
+
/**
|
|
3693
|
+
* Declare (publish) a track namespace to the peer so subscribers using matching prefixes (via {@link MOQtailClient.subscribeNamespace})
|
|
3694
|
+
* can discover and begin subscribing/fetching its tracks.
|
|
3695
|
+
*
|
|
3696
|
+
* Typical flow (publisher side):
|
|
3697
|
+
* 1. Prepare / register one or more {@link Track} objects locally (see {@link MOQtailClient.addOrUpdateTrack}).
|
|
3698
|
+
* 2. Call `publishNamespace(namespace)` once per namespace prefix to expose those tracks.
|
|
3699
|
+
* 3. Later, call {@link MOQtailClient.unpublishNamespace} when no longer publishing under that namespace.
|
|
3700
|
+
*
|
|
3701
|
+
* Parameter semantics:
|
|
3702
|
+
* - trackNamespace: Tuple representing the namespace prefix (e.g. ["camera","main"]). All tracks whose full names start with this tuple are considered within the announce scope.
|
|
3703
|
+
* - parameters: Optional {@link MessageParameters}; omitted =\> default instance.
|
|
3704
|
+
*
|
|
3705
|
+
* Returns: {@link RequestOk} on success (namespace added to `publishedNamespaces`) or {@link RequestError} explaining refusal.
|
|
3706
|
+
*
|
|
3707
|
+
* Use cases:
|
|
3708
|
+
* - Make a camera or sensor namespace available before any objects are pushed.
|
|
3709
|
+
* - Dynamically expose a newly created room / session namespace.
|
|
3710
|
+
* - Re-announce after reconnect to repopulate discovery state.
|
|
3711
|
+
*
|
|
3712
|
+
* @throws MOQtailError If client is destroyed.
|
|
3713
|
+
* @throws InternalError Transport/control failure while sending or awaiting response (client disconnects first).
|
|
3714
|
+
*
|
|
3715
|
+
* @remarks
|
|
3716
|
+
* - Duplicate announce detection is TODO (currently a second call will still send another PUBLISH_NAMESPACE; receiver behavior may vary).
|
|
3717
|
+
* - Successful announces are tracked in `publishedNamespaces`; manual removal occurs via {@link MOQtailClient.unpublishNamespace}.
|
|
3718
|
+
* - Discovery subscribers (those who issued {@link MOQtailClient.subscribeNamespace}) will receive the resulting {@link PublishNamespace} message.
|
|
3719
|
+
*
|
|
3720
|
+
* @example Minimal announce
|
|
3721
|
+
* ```ts
|
|
3722
|
+
* const res = await client.publishNamespace(["camera","main"])
|
|
3723
|
+
* if (res instanceof RequestOk) {
|
|
3724
|
+
* // ready to publish objects under tracks with this namespace prefix
|
|
3725
|
+
* }
|
|
3726
|
+
* ```
|
|
3727
|
+
*
|
|
3728
|
+
* @example PublishNamespace with parameters block
|
|
3729
|
+
* ```ts
|
|
3730
|
+
* const params = new MessageParameters().setSomeExtensionFlag(true)
|
|
3731
|
+
* const resp = await client.publishNamespace(["room","1234"], params)
|
|
3732
|
+
* ```
|
|
3733
|
+
*/
|
|
3734
|
+
async publishNamespace(trackNamespace, parameters) {
|
|
3735
|
+
this.#ensureActive();
|
|
3736
|
+
try {
|
|
3737
|
+
const params = parameters ?? [];
|
|
3738
|
+
const msg = new require_model.PublishNamespace(this.#nextClientRequestId, trackNamespace, params);
|
|
3739
|
+
const request = new PublishNamespaceRequest(msg.requestId, msg);
|
|
3740
|
+
this.requests.set(msg.requestId, request);
|
|
3741
|
+
await this.#openRequestStream(msg.requestId, msg);
|
|
3742
|
+
const response = await request;
|
|
3743
|
+
if (response instanceof require_model.RequestOk) {
|
|
3744
|
+
this.publishedNamespaces.add(msg.trackNamespace);
|
|
3745
|
+
this.#namespaceRequestIds.set(msg.trackNamespace.toUtf8Path(), msg.requestId);
|
|
3746
|
+
} else await this.#closeRequestStream(msg.requestId);
|
|
3747
|
+
this.requests.delete(msg.requestId);
|
|
3748
|
+
return response;
|
|
3749
|
+
} catch (error) {
|
|
3750
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.publishNamespace", error instanceof Error ? error.message : String(error)));
|
|
3751
|
+
throw error;
|
|
3752
|
+
}
|
|
3753
|
+
}
|
|
3754
|
+
/**
|
|
3755
|
+
* Withdraw a previously announced namespace so new subscribers no longer discover its tracks.
|
|
3756
|
+
*
|
|
3757
|
+
* Use when shutting down publishing for a logical scope (camera offline, room closed, session ended).
|
|
3758
|
+
* Removes the namespace from `publishedNamespaces` locally and closes the stream its PUBLISH_NAMESPACE opened,
|
|
3759
|
+
* which is what withdraws the announcement (§3.3.2). This is also how an announce is retracted before the peer
|
|
3760
|
+
* has finished processing it.
|
|
3761
|
+
*
|
|
3762
|
+
* Parameter semantics:
|
|
3763
|
+
* - trackNamespace: Exact tuple used during {@link MOQtailClient.publishNamespace}. Must match to be removed from internal set.
|
|
3764
|
+
*
|
|
3765
|
+
* Behavior:
|
|
3766
|
+
* - Does not delete locally registered {@link Track} objects (they remain in `trackSources`).
|
|
3767
|
+
* - Does not forcibly end active subscriptions that were already established; peers simply stop discovering it for new ones.
|
|
3768
|
+
* - Silent if the namespace was not currently recorded (idempotent style).
|
|
3769
|
+
*
|
|
3770
|
+
* @throws MOQtailError If client is destroyed before sending.
|
|
3771
|
+
* @throws (rethrows original error) Any lower-level failure while sending results in a disconnect (unwrapped TODO: future wrap with InternalError for consistency).
|
|
3772
|
+
*
|
|
3773
|
+
* @remarks
|
|
3774
|
+
* Peers that issued {@link MOQtailClient.subscribeNamespace} for a matching prefix should receive the resulting NAMESPACE_DONE.
|
|
3775
|
+
* Consider calling this before {@link MOQtailClient.disconnect} to give consumers prompt notice.
|
|
3776
|
+
*
|
|
3777
|
+
* @example Basic usage
|
|
3778
|
+
* ```ts
|
|
3779
|
+
* await client.unpublishNamespace(["camera","main"])
|
|
3780
|
+
* ```
|
|
3781
|
+
*
|
|
3782
|
+
* @example Idempotent
|
|
3783
|
+
* ```ts
|
|
3784
|
+
* await client.unpublishNamespace(["camera","main"]) // first time
|
|
3785
|
+
* await client.unpublishNamespace(["camera","main"]) // no error, already removed
|
|
3786
|
+
* ```
|
|
3787
|
+
*/
|
|
3788
|
+
async unpublishNamespace(trackNamespace) {
|
|
3789
|
+
this.#ensureActive();
|
|
3790
|
+
try {
|
|
3791
|
+
this.publishedNamespaces.delete(trackNamespace);
|
|
3792
|
+
await this.#closeNamespaceRequestStream(trackNamespace);
|
|
3793
|
+
} catch (err) {
|
|
3794
|
+
await this.disconnect();
|
|
3795
|
+
throw err;
|
|
3796
|
+
}
|
|
3797
|
+
}
|
|
3798
|
+
/**
|
|
3799
|
+
* Subscribes to namespace announcements under a prefix (§10.18). Discovery only: the
|
|
3800
|
+
* peer answers NAMESPACE and NAMESPACE_DONE for matching namespaces, and nothing is
|
|
3801
|
+
* subscribed to. To be sent the tracks themselves, use
|
|
3802
|
+
* {@link MOQtailClient.subscribeTracks}.
|
|
3803
|
+
*/
|
|
3804
|
+
async subscribeNamespace(trackNamespacePrefix, parameters) {
|
|
3805
|
+
this.#ensureActive();
|
|
3806
|
+
try {
|
|
3807
|
+
const params = parameters ?? [];
|
|
3808
|
+
const msg = new require_model.SubscribeNamespace(this.#nextClientRequestId, trackNamespacePrefix, params);
|
|
3809
|
+
const requestStream = await RequestStream.open(this.webTransport, msg);
|
|
3810
|
+
this.#requestStreams.set(msg.requestId, requestStream);
|
|
3811
|
+
require_logger.logger.log("MOQtailClient", "subscribeNamespace | sent msg", msg, msg.trackNamespacePrefix.toUtf8Path(), msg.requestId);
|
|
3812
|
+
const response = await requestStream.next();
|
|
3813
|
+
if (!response) throw new require_model.InternalError("MOQtailClient.subscribeNamespace", "Stream closed before response");
|
|
3814
|
+
if (!(response instanceof require_model.RequestOk || response instanceof require_model.RequestError)) throw new require_model.ProtocolViolationError("MOQtailClient.subscribeNamespace", "Unexpected response message type");
|
|
3815
|
+
require_logger.logger.log("MOQtailClient", "subscribeNamespace | got response", response);
|
|
3816
|
+
if (response instanceof require_model.RequestOk) {
|
|
3817
|
+
this.subscribedNamespaces.add(trackNamespacePrefix);
|
|
3818
|
+
this.#namespaceRequestIds.set(trackNamespacePrefix.toUtf8Path(), msg.requestId);
|
|
3819
|
+
this.#drainNamespaceStream(requestStream, msg.requestId, trackNamespacePrefix);
|
|
3820
|
+
} else await this.#closeRequestStream(msg.requestId);
|
|
3821
|
+
return {
|
|
3822
|
+
response,
|
|
3823
|
+
cancel: async () => {
|
|
3824
|
+
this.subscribedNamespaces.delete(trackNamespacePrefix);
|
|
3825
|
+
this.#namespaceRequestIds.delete(trackNamespacePrefix.toUtf8Path());
|
|
3826
|
+
await this.#closeRequestStream(msg.requestId);
|
|
3827
|
+
}
|
|
3828
|
+
};
|
|
3829
|
+
} catch (error) {
|
|
3830
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeNamespace", error instanceof Error ? error.message : String(error)));
|
|
3831
|
+
throw error;
|
|
3832
|
+
}
|
|
3833
|
+
}
|
|
3834
|
+
async subscribeTracks(trackNamespacePrefix, parameters) {
|
|
3835
|
+
this.#ensureActive();
|
|
3836
|
+
try {
|
|
3837
|
+
const msg = new require_model.SubscribeTracks(this.#nextClientRequestId, trackNamespacePrefix, parameters ?? []);
|
|
3838
|
+
const requestStream = await RequestStream.open(this.webTransport, msg);
|
|
3839
|
+
this.#requestStreams.set(msg.requestId, requestStream);
|
|
3840
|
+
const response = await requestStream.next();
|
|
3841
|
+
if (!response) throw new require_model.InternalError("MOQtailClient.subscribeTracks", "Stream closed before response");
|
|
3842
|
+
if (!(response instanceof require_model.RequestOk || response instanceof require_model.RequestError)) throw new require_model.ProtocolViolationError("MOQtailClient.subscribeTracks", "Unexpected response message type");
|
|
3843
|
+
if (response instanceof require_model.RequestOk) {
|
|
3844
|
+
this.subscribedTracks.add(trackNamespacePrefix);
|
|
3845
|
+
this.#pumpRequestStream(msg.requestId, requestStream);
|
|
3846
|
+
} else await this.#closeRequestStream(msg.requestId);
|
|
3847
|
+
return {
|
|
3848
|
+
response,
|
|
3849
|
+
cancel: async () => {
|
|
3850
|
+
this.subscribedTracks.delete(trackNamespacePrefix);
|
|
3851
|
+
await this.#closeRequestStream(msg.requestId);
|
|
3852
|
+
}
|
|
3853
|
+
};
|
|
3854
|
+
} catch (error) {
|
|
3855
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeTracks", error instanceof Error ? error.message : String(error)));
|
|
3856
|
+
throw error;
|
|
3857
|
+
}
|
|
3858
|
+
}
|
|
3859
|
+
async #drainNamespaceStream(requestStream, requestId, prefix) {
|
|
3860
|
+
try {
|
|
3861
|
+
while (true) {
|
|
3862
|
+
const msg = await requestStream.next();
|
|
3863
|
+
if (!msg) break;
|
|
3864
|
+
if (msg instanceof require_model.Namespace && this.onPeerNamespace) this.onPeerNamespace(prefix, msg.trackNamespaceSuffix);
|
|
3865
|
+
else if (msg instanceof require_model.NamespaceDone && this.onPeerNamespaceDone) this.onPeerNamespaceDone(prefix, msg.trackNamespaceSuffix);
|
|
3866
|
+
}
|
|
3867
|
+
} finally {
|
|
3868
|
+
this.#requestStreams.delete(requestId);
|
|
3869
|
+
this.#namespaceRequestIds.delete(prefix.toUtf8Path());
|
|
3870
|
+
}
|
|
3871
|
+
}
|
|
3872
|
+
/**
|
|
3873
|
+
* Ends a prefix subscription started with {@link MOQtailClient.subscribeNamespace}.
|
|
3874
|
+
*
|
|
3875
|
+
* @param trackNamespacePrefix - The prefix that subscription was opened with.
|
|
3876
|
+
*/
|
|
3877
|
+
async unsubscribeNamespace(trackNamespacePrefix) {
|
|
3878
|
+
this.#ensureActive();
|
|
3879
|
+
try {
|
|
3880
|
+
this.subscribedNamespaces.delete(trackNamespacePrefix);
|
|
3881
|
+
await this.#closeNamespaceRequestStream(trackNamespacePrefix);
|
|
3882
|
+
} catch (error) {
|
|
3883
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribeNamespace", error instanceof Error ? error.message : String(error)));
|
|
3884
|
+
throw error;
|
|
3885
|
+
}
|
|
3886
|
+
}
|
|
3887
|
+
/**
|
|
3888
|
+
* Asks the peer for the current status of a track.
|
|
3889
|
+
*
|
|
3890
|
+
* TRACK_STATUS is the seventh `First`-marked type: it opens its own bidi stream and
|
|
3891
|
+
* the REQUEST_OK answering it comes back there, after which the stream is closed.
|
|
3892
|
+
*
|
|
3893
|
+
* @param fullTrackName - The track to report on.
|
|
3894
|
+
* @param trackAlias - Alias to carry in the request.
|
|
3895
|
+
* @param parameters - Optional message parameters.
|
|
3896
|
+
* @returns A {@link RequestOk} on success or a {@link RequestError} on refusal.
|
|
3897
|
+
*
|
|
3898
|
+
* @example
|
|
3899
|
+
* ```ts
|
|
3900
|
+
* const status = await client.trackStatus(fullTrackName, trackAlias)
|
|
3901
|
+
* if (!(status instanceof RequestError)) {
|
|
3902
|
+
* // track exists
|
|
3903
|
+
* }
|
|
3904
|
+
* ```
|
|
3905
|
+
*/
|
|
3906
|
+
async trackStatus(fullTrackName, trackAlias, parameters) {
|
|
3907
|
+
this.#ensureActive();
|
|
3908
|
+
try {
|
|
3909
|
+
const msg = require_model.TrackStatus.newLatestObject(this.#nextClientRequestId, trackAlias, fullTrackName, 128, 0, false, parameters ?? []);
|
|
3910
|
+
const request = new TrackStatusRequest(msg);
|
|
3911
|
+
this.requests.set(msg.requestId, request);
|
|
3912
|
+
await this.#openRequestStream(msg.requestId, msg);
|
|
3913
|
+
const response = await request;
|
|
3914
|
+
await this.#closeRequestStream(msg.requestId);
|
|
3915
|
+
this.requests.delete(msg.requestId);
|
|
3916
|
+
return response;
|
|
3917
|
+
} catch (error) {
|
|
3918
|
+
await this.disconnect(new require_model.InternalError("MOQtailClient.trackStatus", error instanceof Error ? error.message : String(error)));
|
|
3919
|
+
throw error;
|
|
3920
|
+
}
|
|
3921
|
+
}
|
|
3922
|
+
/**
|
|
3923
|
+
* Opens a bidi request stream for `first` and starts reading responses off it.
|
|
3924
|
+
*
|
|
3925
|
+
* @param requestId - The requestId carried by `first`; the key the stream is filed under.
|
|
3926
|
+
*/
|
|
3927
|
+
async #openRequestStream(requestId, first) {
|
|
3928
|
+
const requestStream = await RequestStream.open(this.webTransport, first);
|
|
3929
|
+
this.#requestStreams.set(requestId, requestStream);
|
|
3930
|
+
this.#pumpRequestStream(requestId, requestStream);
|
|
3931
|
+
return requestStream;
|
|
3932
|
+
}
|
|
3933
|
+
/**
|
|
3934
|
+
* Re-issues one request on a fresh stream after the peer sent a GOAWAY on its request
|
|
3935
|
+
* stream (§10.4). Only that request moves: the session, and every other request on it,
|
|
3936
|
+
* are left alone.
|
|
3937
|
+
*
|
|
3938
|
+
* The re-issued request consumes a new Request ID (§10.1), so the opening message is
|
|
3939
|
+
* re-stamped with it. The id the caller holds keeps naming the request; only the id on
|
|
3940
|
+
* the wire changes.
|
|
3941
|
+
*
|
|
3942
|
+
* @returns True if the request was re-issued here. A GOAWAY naming a new session URI
|
|
3943
|
+
* is not: opening a session is the application's call, so it is surfaced through
|
|
3944
|
+
* {@link MOQtailClient.onGoaway} and the request stream is closed.
|
|
3945
|
+
*
|
|
3946
|
+
* @internal
|
|
3947
|
+
*/
|
|
3948
|
+
async migrateRequest(requestId, goAway) {
|
|
3949
|
+
const oldStream = this.#requestStreams.get(requestId);
|
|
3950
|
+
const first = oldStream?.first;
|
|
3951
|
+
if (!oldStream || !first) {
|
|
3952
|
+
require_logger.logger.warn("MOQtailClient", `GOAWAY on a request stream this side did not open (request id ${requestId})`);
|
|
3953
|
+
return false;
|
|
3954
|
+
}
|
|
3955
|
+
if (goAway.newSessionUri) {
|
|
3956
|
+
require_logger.logger.log("MOQtailClient", `GOAWAY migrates request ${requestId} to ${goAway.newSessionUri}`);
|
|
3957
|
+
this.onGoaway?.(goAway);
|
|
3958
|
+
await this.#closeRequestStream(requestId);
|
|
3959
|
+
return false;
|
|
3960
|
+
}
|
|
3961
|
+
const wireRequestId = this.#nextClientRequestId;
|
|
3962
|
+
const reissued = require_model.ControlMessage.deserialize(require_model.ControlMessage.serialize(first));
|
|
3963
|
+
reissued.requestId = wireRequestId;
|
|
3964
|
+
this.#wireRequestIds.set(requestId, wireRequestId);
|
|
3965
|
+
this.#clientRequestIds.set(wireRequestId, requestId);
|
|
3966
|
+
oldStream.migrated = true;
|
|
3967
|
+
await oldStream.close();
|
|
3968
|
+
await this.#openRequestStream(requestId, reissued);
|
|
3969
|
+
require_logger.logger.log("MOQtailClient", `re-issued request ${requestId} as request id ${wireRequestId}`);
|
|
3970
|
+
return true;
|
|
3971
|
+
}
|
|
3972
|
+
/** The Request ID `requestId` currently travels under, which a migration has moved on. */
|
|
3973
|
+
#wireRequestId(requestId) {
|
|
3974
|
+
return this.#wireRequestIds.get(requestId) ?? requestId;
|
|
3975
|
+
}
|
|
3976
|
+
/** The request a peer-supplied Request ID belongs to, undoing any migration. */
|
|
3977
|
+
#clientRequestId(wireRequestId) {
|
|
3978
|
+
return this.#clientRequestIds.get(wireRequestId) ?? wireRequestId;
|
|
3979
|
+
}
|
|
3980
|
+
/**
|
|
3981
|
+
* The stream a previously issued request runs on.
|
|
3982
|
+
*
|
|
3983
|
+
* @throws :{@link InternalError} If the request has no open stream — it was never
|
|
3984
|
+
* issued, or it has already completed or been cancelled.
|
|
3985
|
+
*/
|
|
3986
|
+
#requestStreamFor(requestId, context) {
|
|
3987
|
+
const requestStream = this.#requestStreams.get(requestId);
|
|
3988
|
+
if (!requestStream) throw new require_model.InternalError(context, `No open request stream for request id ${requestId}`);
|
|
3989
|
+
return requestStream;
|
|
3990
|
+
}
|
|
3991
|
+
/**
|
|
3992
|
+
* Reads responses and follow-ups off a locally opened request stream until the peer
|
|
3993
|
+
* closes it. Each message belongs to this request by virtue of the stream it arrived
|
|
3994
|
+
* on, so no request id is consulted to route it.
|
|
3995
|
+
*/
|
|
3996
|
+
async #pumpRequestStream(requestId, requestStream) {
|
|
3997
|
+
let answered = false;
|
|
3998
|
+
try {
|
|
3999
|
+
while (true) {
|
|
4000
|
+
const msg = await requestStream.next();
|
|
4001
|
+
if (!msg) break;
|
|
4002
|
+
const handler = getHandlerForRequestStreamMessage(msg);
|
|
4003
|
+
if (!handler) throw new require_model.ProtocolViolationError("MOQtailClient", `${msg.constructor.name} is not valid on a request stream (request id ${requestId})`);
|
|
4004
|
+
await handler(this, msg, requestStream, requestId);
|
|
4005
|
+
answered = true;
|
|
4006
|
+
}
|
|
4007
|
+
require_logger.logger.debug("MOQtailClient", `request stream for requestId=${requestId} closed by peer`);
|
|
4008
|
+
} catch (error) {
|
|
4009
|
+
require_logger.logger.error("MOQtailClient", `request stream for requestId=${requestId} failed`, error);
|
|
4010
|
+
} finally {
|
|
4011
|
+
if (!requestStream.migrated) {
|
|
4012
|
+
this.#requestStreams.delete(requestId);
|
|
4013
|
+
if (!answered) this.requests.get(requestId)?.reject(new require_model.InternalError("MOQtailClient", `Request stream closed before answering request ${requestId}`));
|
|
4014
|
+
}
|
|
4015
|
+
}
|
|
4016
|
+
}
|
|
4017
|
+
/** Closes the request stream filed under `requestId`, if it is still open. */
|
|
4018
|
+
async #closeRequestStream(requestId) {
|
|
4019
|
+
const requestStream = this.#requestStreams.get(requestId);
|
|
4020
|
+
if (!requestStream) return;
|
|
4021
|
+
this.#requestStreams.delete(requestId);
|
|
4022
|
+
await requestStream.close();
|
|
4023
|
+
}
|
|
4024
|
+
/**
|
|
4025
|
+
* Resets the request stream filed under `requestId` with `code`, if it is still open.
|
|
4026
|
+
* §3.3.2: this is how draft-18 cancels a request now that the cancel messages are
|
|
4027
|
+
* gone — the peer reads the code back off the RESET_STREAM.
|
|
4028
|
+
*/
|
|
4029
|
+
async #resetRequestStream(requestId, code) {
|
|
4030
|
+
const requestStream = this.#requestStreams.get(requestId);
|
|
4031
|
+
if (!requestStream) return;
|
|
4032
|
+
this.#requestStreams.delete(requestId);
|
|
4033
|
+
await requestStream.reset(code);
|
|
4034
|
+
}
|
|
4035
|
+
/** Closes the request stream opened for `namespace`, if there is one. */
|
|
4036
|
+
async #closeNamespaceRequestStream(namespace) {
|
|
4037
|
+
const path = namespace.toUtf8Path();
|
|
4038
|
+
const requestId = this.#namespaceRequestIds.get(path);
|
|
4039
|
+
if (requestId === void 0) return;
|
|
4040
|
+
this.#namespaceRequestIds.delete(path);
|
|
4041
|
+
await this.#closeRequestStream(requestId);
|
|
4042
|
+
}
|
|
4043
|
+
/**
|
|
4044
|
+
* Reads the shared control stream, which after draft-18 §3.3 carries only SETUP and
|
|
4045
|
+
* GOAWAY. SETUP is consumed by the handshake, so GOAWAY is all that is handled here;
|
|
4046
|
+
* every request type has its own bidi stream.
|
|
4047
|
+
*/
|
|
4048
|
+
async #handleIncomingControlMessages() {
|
|
4049
|
+
this.#ensureActive();
|
|
4050
|
+
try {
|
|
4051
|
+
const reader = this.controlStream.stream.getReader();
|
|
4052
|
+
while (true) {
|
|
4053
|
+
const { done, value: msg } = await reader.read();
|
|
4054
|
+
if (done) throw new require_model.MOQtailError("WebTransport session is terminated");
|
|
4055
|
+
const handler = getHandlerForControlMessage(msg);
|
|
4056
|
+
if (!handler) {
|
|
4057
|
+
require_logger.logger.warn("MOQtailClient", `${msg.constructor.name} on the control stream; draft-18 allows only SETUP and GOAWAY there`);
|
|
4058
|
+
continue;
|
|
4059
|
+
}
|
|
4060
|
+
await handler(this, msg);
|
|
4061
|
+
}
|
|
4062
|
+
} catch (error) {
|
|
4063
|
+
this.disconnect();
|
|
4064
|
+
throw error;
|
|
4065
|
+
}
|
|
4066
|
+
}
|
|
4067
|
+
async #acceptIncomingUniStreams() {
|
|
4068
|
+
this.#ensureActive();
|
|
4069
|
+
const reader = this.#incomingUniStreams;
|
|
4070
|
+
let isDone = false;
|
|
4071
|
+
while (!isDone) try {
|
|
4072
|
+
const { done, value: stream } = await reader.read();
|
|
4073
|
+
if (done) {
|
|
4074
|
+
isDone = true;
|
|
4075
|
+
throw new require_model.MOQtailError("WebTransport session is terminated");
|
|
4076
|
+
}
|
|
4077
|
+
this.#handleRecvStreams(stream).catch((error) => {
|
|
4078
|
+
if (error instanceof PeerStreamResetError) {
|
|
4079
|
+
require_logger.logger.debug("MOQtailClient", `data stream ended: ${error.message}`);
|
|
4080
|
+
return;
|
|
4081
|
+
}
|
|
4082
|
+
require_logger.logger.error("MOQtailClient", "handleRecvStreams error", error);
|
|
4083
|
+
});
|
|
4084
|
+
} catch (error) {
|
|
4085
|
+
require_logger.logger.error("MOQtailClient", "acceptIncomingUniStreams error", error);
|
|
4086
|
+
if (this.#isDestroyed) break;
|
|
4087
|
+
}
|
|
4088
|
+
}
|
|
4089
|
+
#acceptIncomingBiStreams() {
|
|
4090
|
+
(async () => {
|
|
4091
|
+
const reader = this.webTransport.incomingBidirectionalStreams.getReader();
|
|
4092
|
+
while (true) {
|
|
4093
|
+
const { value: biStream, done } = await reader.read();
|
|
4094
|
+
if (done) break;
|
|
4095
|
+
this.#dispatchIncomingRequestStream(new RequestStream(biStream));
|
|
4096
|
+
}
|
|
4097
|
+
})();
|
|
4098
|
+
}
|
|
4099
|
+
/**
|
|
4100
|
+
* Serves one peer-opened request stream: the first message must be a `First`-marked
|
|
4101
|
+
* type, its handler answers on this same stream, and follow-ups are read until the
|
|
4102
|
+
* peer closes it. That close is the peer's cancellation, so it tears down whatever
|
|
4103
|
+
* the first message started.
|
|
4104
|
+
*/
|
|
4105
|
+
async #dispatchIncomingRequestStream(requestStream) {
|
|
4106
|
+
const first = await requestStream.next();
|
|
4107
|
+
if (!first) return;
|
|
4108
|
+
if (!require_model.ControlMessageType.isFirst(first.getType())) {
|
|
4109
|
+
require_logger.logger.warn("MOQtailClient", `${first.constructor.name} may not open a request stream; resetting it`);
|
|
4110
|
+
await requestStream.reset(0);
|
|
4111
|
+
return;
|
|
4112
|
+
}
|
|
4113
|
+
const openingRequestId = first.requestId;
|
|
4114
|
+
requestStream.openingType = first.getType();
|
|
4115
|
+
try {
|
|
4116
|
+
let msg = first;
|
|
4117
|
+
while (msg) {
|
|
4118
|
+
const handler = getHandlerForRequestStreamMessage(msg);
|
|
4119
|
+
if (!handler) throw new require_model.ProtocolViolationError("MOQtailClient", `No handler for ${msg.constructor.name} on a request stream`);
|
|
4120
|
+
await handler(this, msg, requestStream, openingRequestId);
|
|
4121
|
+
msg = await requestStream.next();
|
|
4122
|
+
}
|
|
4123
|
+
} catch (error) {
|
|
4124
|
+
require_logger.logger.error("MOQtailClient", "incoming request stream failed", error);
|
|
4125
|
+
} finally {
|
|
4126
|
+
const requestId = "requestId" in first ? first.requestId : void 0;
|
|
4127
|
+
if (requestId !== void 0) {
|
|
4128
|
+
this.publications.get(requestId)?.cancel();
|
|
4129
|
+
this.publications.delete(requestId);
|
|
4130
|
+
}
|
|
4131
|
+
await requestStream.close();
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
async #handleRecvStreams(incomingUniStream) {
|
|
4135
|
+
this.#ensureActive();
|
|
4136
|
+
try {
|
|
4137
|
+
const recvStream = await RecvStream.new(incomingUniStream, this.dataStreamTimeoutMs, this.onDataReceived, (header) => {
|
|
4138
|
+
if (!(header instanceof require_model.FetchHeader)) return 0;
|
|
4139
|
+
const request = this.requests.get(this.#clientRequestId(header.requestId));
|
|
4140
|
+
if (!(request instanceof FetchRequest)) return 0;
|
|
4141
|
+
return require_model.MessageParameter.groupOrderOf(request.message.parameters);
|
|
4142
|
+
});
|
|
4143
|
+
const header = recvStream.header;
|
|
4144
|
+
const reader = recvStream.stream.getReader();
|
|
4145
|
+
if (header instanceof require_model.FetchHeader) {
|
|
4146
|
+
const request = this.requests.get(this.#clientRequestId(header.requestId));
|
|
4147
|
+
if (request && request instanceof FetchRequest) {
|
|
4148
|
+
let fullTrackName;
|
|
4149
|
+
switch (request.message.typeAndProps.type) {
|
|
4150
|
+
case 1:
|
|
4151
|
+
fullTrackName = request.message.typeAndProps.props.fullTrackName;
|
|
4152
|
+
break;
|
|
4153
|
+
case 2:
|
|
4154
|
+
case 3: {
|
|
4155
|
+
const joiningSubscription = this.requests.get(request.message.typeAndProps.props.joiningRequestId);
|
|
4156
|
+
if (joiningSubscription instanceof SubscribeRequest) {
|
|
4157
|
+
fullTrackName = joiningSubscription.fullTrackName;
|
|
4158
|
+
break;
|
|
4159
|
+
}
|
|
4160
|
+
throw new require_model.ProtocolViolationError("_handleRecvStreams", "No active subscription for given joining request id");
|
|
4161
|
+
}
|
|
4162
|
+
default: throw new require_model.ProtocolViolationError("_handleRecvStreams", "Unknown fetchType");
|
|
4163
|
+
}
|
|
4164
|
+
try {
|
|
4165
|
+
while (true) {
|
|
4166
|
+
const { done, value: nextObject } = await reader.read();
|
|
4167
|
+
if (done) {
|
|
4168
|
+
request.controller?.close();
|
|
4169
|
+
break;
|
|
4170
|
+
}
|
|
4171
|
+
if (nextObject) {
|
|
4172
|
+
if (nextObject instanceof require_model.FetchObject) {
|
|
4173
|
+
if (nextObject.kind === "end_of_range") continue;
|
|
4174
|
+
const moqtObject = require_model.MoqtObject.fromFetchObject(nextObject, fullTrackName);
|
|
4175
|
+
request.controller?.enqueue(moqtObject);
|
|
4176
|
+
continue;
|
|
4177
|
+
}
|
|
4178
|
+
throw new require_model.ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
|
|
4179
|
+
}
|
|
4180
|
+
}
|
|
4181
|
+
} finally {
|
|
4182
|
+
reader.releaseLock();
|
|
4183
|
+
}
|
|
4184
|
+
return;
|
|
4185
|
+
}
|
|
4186
|
+
throw new require_model.ProtocolViolationError("MOQtailClient", "No request for received request id");
|
|
4187
|
+
} else {
|
|
4188
|
+
let subscription = this.subscriptions.get(header.trackAlias);
|
|
4189
|
+
if (!subscription) {
|
|
4190
|
+
for (const [subscriptionId, callback] of this.pendingStateUpdates) if (callback(header.trackAlias)) {
|
|
4191
|
+
subscription = this.subscriptions.get(header.trackAlias);
|
|
4192
|
+
this.pendingStateUpdates.delete(subscriptionId);
|
|
4193
|
+
break;
|
|
4194
|
+
}
|
|
4195
|
+
}
|
|
4196
|
+
if (subscription) {
|
|
4197
|
+
subscription.streamsAccepted++;
|
|
4198
|
+
let firstObjectId = null;
|
|
4199
|
+
let subgroupTimeoutId;
|
|
4200
|
+
const effectiveDiscardPolicy = subscription.earlyDiscardPolicy ?? this.#earlyDiscardPolicy;
|
|
4201
|
+
if (effectiveDiscardPolicy?.subgroupReceiveTimeout !== void 0) subgroupTimeoutId = setTimeout(() => {
|
|
4202
|
+
reader.cancel(streamResetReason(2)).catch(() => {});
|
|
4203
|
+
}, effectiveDiscardPolicy.subgroupReceiveTimeout);
|
|
4204
|
+
try {
|
|
4205
|
+
while (true) {
|
|
4206
|
+
const { done, value: nextObject } = await reader.read();
|
|
4207
|
+
if (done) break;
|
|
4208
|
+
if (nextObject) {
|
|
4209
|
+
if (nextObject instanceof require_model.SubgroupObject) {
|
|
4210
|
+
if (!firstObjectId) firstObjectId = nextObject.objectId;
|
|
4211
|
+
let subgroupId = null;
|
|
4212
|
+
if (require_model.SubgroupHeaderType.isSubgroupIdZero(header.type)) subgroupId = 0n;
|
|
4213
|
+
else if (require_model.SubgroupHeaderType.isSubgroupIdFirstObjectId(header.type)) subgroupId = firstObjectId ?? null;
|
|
4214
|
+
else if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(header.type)) subgroupId = header.subgroupId ?? null;
|
|
4215
|
+
const fullTrackName = this.aliasFullTrackNameMap.get(header.trackAlias);
|
|
4216
|
+
if (!fullTrackName) throw new require_model.ProtocolViolationError("MOQtailClient", "No full track name for received track alias");
|
|
4217
|
+
const moqtObject = require_model.MoqtObject.fromSubgroupObject(nextObject, header.groupId, header.publisherPriority, subgroupId, fullTrackName);
|
|
4218
|
+
if (!subscription.largestLocation) subscription.largestLocation = moqtObject.location;
|
|
4219
|
+
if (subscription.largestLocation.compare(moqtObject.location) == -1) subscription.largestLocation = moqtObject.location;
|
|
4220
|
+
subscription.controller?.enqueue(moqtObject);
|
|
4221
|
+
continue;
|
|
4222
|
+
}
|
|
4223
|
+
throw new require_model.ProtocolViolationError("MOQtailClient", "Received fetch object after subgroup header");
|
|
4224
|
+
}
|
|
4225
|
+
}
|
|
4226
|
+
} finally {
|
|
4227
|
+
if (subgroupTimeoutId !== void 0) clearTimeout(subgroupTimeoutId);
|
|
4228
|
+
}
|
|
4229
|
+
if (subscription.expectedStreams && subscription.expectedStreams === subscription.streamsAccepted) {
|
|
4230
|
+
subscription.controller?.close();
|
|
4231
|
+
this.subscriptions.delete(header.trackAlias);
|
|
4232
|
+
this.requests.delete(subscription.requestId);
|
|
4233
|
+
}
|
|
4234
|
+
return;
|
|
4235
|
+
}
|
|
4236
|
+
throw new require_model.ProtocolViolationError("MOQtailClient", "No subscription for received track alias");
|
|
4237
|
+
}
|
|
4238
|
+
} catch (error) {
|
|
4239
|
+
throw error;
|
|
4240
|
+
}
|
|
4241
|
+
}
|
|
4242
|
+
};
|
|
4243
|
+
//#endregion
|
|
4244
|
+
//#region src/client/track/object_cache.ts
|
|
4245
|
+
/**
|
|
4246
|
+
* Copyright 2025 The MOQtail Authors
|
|
4247
|
+
*
|
|
4248
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
4249
|
+
* you may not use this file except in compliance with the License.
|
|
4250
|
+
* You may obtain a copy of the License at
|
|
4251
|
+
*
|
|
4252
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
4253
|
+
*
|
|
4254
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
4255
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
4256
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
4257
|
+
* See the License for the specific language governing permissions and
|
|
4258
|
+
* limitations under the License.
|
|
4259
|
+
*/
|
|
4260
|
+
var MemoryObjectCache = class {
|
|
4261
|
+
objects = [];
|
|
4262
|
+
add(obj) {
|
|
4263
|
+
const idx = this._findInsertIndex(obj);
|
|
4264
|
+
this.objects.splice(idx, 0, obj);
|
|
4265
|
+
}
|
|
4266
|
+
getRange(start, end) {
|
|
4267
|
+
const startIdx = start ? this._findIndex(start, false) : 0;
|
|
4268
|
+
const endIdx = end ? this._findIndex(end, true) : this.objects.length;
|
|
4269
|
+
return this.objects.slice(startIdx, endIdx);
|
|
4270
|
+
}
|
|
4271
|
+
getByLocation(location) {
|
|
4272
|
+
const idx = this._findIndex(location, false);
|
|
4273
|
+
const obj = this.objects[idx];
|
|
4274
|
+
if (obj && obj.groupId === location.group && obj.objectId === location.object) return obj;
|
|
4275
|
+
}
|
|
4276
|
+
size() {
|
|
4277
|
+
return this.objects.length;
|
|
4278
|
+
}
|
|
4279
|
+
clear() {
|
|
4280
|
+
this.objects = [];
|
|
4281
|
+
}
|
|
4282
|
+
_findInsertIndex(obj) {
|
|
4283
|
+
let low = 0, high = this.objects.length;
|
|
4284
|
+
while (low < high) {
|
|
4285
|
+
const mid = low + high >> 1;
|
|
4286
|
+
const midObj = this.objects[mid];
|
|
4287
|
+
if (!midObj) break;
|
|
4288
|
+
if (new require_model.Location(midObj.groupId, midObj.objectId).compare(new require_model.Location(obj.groupId, obj.objectId)) < 0) low = mid + 1;
|
|
4289
|
+
else high = mid;
|
|
4290
|
+
}
|
|
4291
|
+
return low;
|
|
4292
|
+
}
|
|
4293
|
+
_findIndex(location, exclusive) {
|
|
4294
|
+
let low = 0, high = this.objects.length;
|
|
4295
|
+
while (low < high) {
|
|
4296
|
+
const mid = low + high >> 1;
|
|
4297
|
+
const midObj = this.objects[mid];
|
|
4298
|
+
if (!midObj) break;
|
|
4299
|
+
const cmp = new require_model.Location(midObj.groupId, midObj.objectId).compare(location);
|
|
4300
|
+
if (cmp < 0 || exclusive && cmp === 0) low = mid + 1;
|
|
4301
|
+
else high = mid;
|
|
4302
|
+
}
|
|
4303
|
+
return low;
|
|
4304
|
+
}
|
|
4305
|
+
};
|
|
4306
|
+
var RingBufferObjectCache = class {
|
|
4307
|
+
buffer;
|
|
4308
|
+
maxSize;
|
|
4309
|
+
constructor(maxSize = 100) {
|
|
4310
|
+
this.buffer = [];
|
|
4311
|
+
this.maxSize = maxSize;
|
|
4312
|
+
}
|
|
4313
|
+
add(obj) {
|
|
4314
|
+
const idx = this._findInsertIndex(obj);
|
|
4315
|
+
this.buffer.splice(idx, 0, obj);
|
|
4316
|
+
if (this.buffer.length > this.maxSize) this.buffer.shift();
|
|
4317
|
+
}
|
|
4318
|
+
getRange(start, end) {
|
|
4319
|
+
const startIdx = start ? this._findIndex(start, false) : 0;
|
|
4320
|
+
const endIdx = end ? this._findIndex(end, true) : this.buffer.length;
|
|
4321
|
+
return this.buffer.slice(startIdx, endIdx);
|
|
4322
|
+
}
|
|
4323
|
+
getByLocation(location) {
|
|
4324
|
+
const idx = this._findIndex(location, false);
|
|
4325
|
+
const obj = this.buffer[idx];
|
|
4326
|
+
if (obj && obj.groupId === location.group && obj.objectId === location.object) return obj;
|
|
4327
|
+
}
|
|
4328
|
+
size() {
|
|
4329
|
+
return this.buffer.length;
|
|
4330
|
+
}
|
|
4331
|
+
clear() {
|
|
4332
|
+
this.buffer = [];
|
|
4333
|
+
}
|
|
4334
|
+
_findInsertIndex(obj) {
|
|
4335
|
+
let low = 0, high = this.buffer.length;
|
|
4336
|
+
while (low < high) {
|
|
4337
|
+
const mid = low + high >> 1;
|
|
4338
|
+
const midObj = this.buffer[mid];
|
|
4339
|
+
if (!midObj) break;
|
|
4340
|
+
if (new require_model.Location(midObj.groupId, midObj.objectId).compare(new require_model.Location(obj.groupId, obj.objectId)) < 0) low = mid + 1;
|
|
4341
|
+
else high = mid;
|
|
4342
|
+
}
|
|
4343
|
+
return low;
|
|
4344
|
+
}
|
|
4345
|
+
_findIndex(location, exclusive) {
|
|
4346
|
+
let low = 0, high = this.buffer.length;
|
|
4347
|
+
while (low < high) {
|
|
4348
|
+
const mid = low + high >> 1;
|
|
4349
|
+
const midObj = this.buffer[mid];
|
|
4350
|
+
if (!midObj) break;
|
|
4351
|
+
const cmp = new require_model.Location(midObj.groupId, midObj.objectId).compare(location);
|
|
4352
|
+
if (cmp < 0 || exclusive && cmp === 0) low = mid + 1;
|
|
4353
|
+
else high = mid;
|
|
4354
|
+
}
|
|
4355
|
+
return low;
|
|
4356
|
+
}
|
|
4357
|
+
};
|
|
4358
|
+
//#endregion
|
|
4359
|
+
Object.defineProperty(exports, "ControlRecvStream", {
|
|
4360
|
+
enumerable: true,
|
|
4361
|
+
get: function() {
|
|
4362
|
+
return ControlRecvStream;
|
|
4363
|
+
}
|
|
4364
|
+
});
|
|
4365
|
+
Object.defineProperty(exports, "ControlSendStream", {
|
|
4366
|
+
enumerable: true,
|
|
4367
|
+
get: function() {
|
|
4368
|
+
return ControlSendStream;
|
|
4369
|
+
}
|
|
4370
|
+
});
|
|
4371
|
+
Object.defineProperty(exports, "ControlStream", {
|
|
4372
|
+
enumerable: true,
|
|
4373
|
+
get: function() {
|
|
4374
|
+
return ControlStream;
|
|
4375
|
+
}
|
|
4376
|
+
});
|
|
4377
|
+
Object.defineProperty(exports, "FetchPublication", {
|
|
4378
|
+
enumerable: true,
|
|
4379
|
+
get: function() {
|
|
4380
|
+
return FetchPublication;
|
|
4381
|
+
}
|
|
4382
|
+
});
|
|
4383
|
+
Object.defineProperty(exports, "FetchRequest", {
|
|
4384
|
+
enumerable: true,
|
|
4385
|
+
get: function() {
|
|
4386
|
+
return FetchRequest;
|
|
4387
|
+
}
|
|
4388
|
+
});
|
|
4389
|
+
Object.defineProperty(exports, "HybridTrackSource", {
|
|
4390
|
+
enumerable: true,
|
|
4391
|
+
get: function() {
|
|
4392
|
+
return HybridTrackSource;
|
|
4393
|
+
}
|
|
4394
|
+
});
|
|
4395
|
+
Object.defineProperty(exports, "LiveTrackSource", {
|
|
4396
|
+
enumerable: true,
|
|
4397
|
+
get: function() {
|
|
4398
|
+
return LiveTrackSource;
|
|
4399
|
+
}
|
|
4400
|
+
});
|
|
4401
|
+
Object.defineProperty(exports, "MOQtailClient", {
|
|
4402
|
+
enumerable: true,
|
|
4403
|
+
get: function() {
|
|
4404
|
+
return MOQtailClient;
|
|
4405
|
+
}
|
|
4406
|
+
});
|
|
4407
|
+
Object.defineProperty(exports, "MemoryObjectCache", {
|
|
4408
|
+
enumerable: true,
|
|
4409
|
+
get: function() {
|
|
4410
|
+
return MemoryObjectCache;
|
|
4411
|
+
}
|
|
4412
|
+
});
|
|
4413
|
+
Object.defineProperty(exports, "PublishNamespaceRequest", {
|
|
4414
|
+
enumerable: true,
|
|
4415
|
+
get: function() {
|
|
4416
|
+
return PublishNamespaceRequest;
|
|
4417
|
+
}
|
|
4418
|
+
});
|
|
4419
|
+
Object.defineProperty(exports, "PublishPublication", {
|
|
4420
|
+
enumerable: true,
|
|
4421
|
+
get: function() {
|
|
4422
|
+
return PublishPublication;
|
|
4423
|
+
}
|
|
4424
|
+
});
|
|
4425
|
+
Object.defineProperty(exports, "PublishRequest", {
|
|
4426
|
+
enumerable: true,
|
|
4427
|
+
get: function() {
|
|
4428
|
+
return PublishRequest;
|
|
4429
|
+
}
|
|
4430
|
+
});
|
|
4431
|
+
Object.defineProperty(exports, "RecvDatagramStream", {
|
|
4432
|
+
enumerable: true,
|
|
4433
|
+
get: function() {
|
|
4434
|
+
return RecvDatagramStream;
|
|
4435
|
+
}
|
|
4436
|
+
});
|
|
4437
|
+
Object.defineProperty(exports, "RecvStream", {
|
|
4438
|
+
enumerable: true,
|
|
4439
|
+
get: function() {
|
|
4440
|
+
return RecvStream;
|
|
4441
|
+
}
|
|
4442
|
+
});
|
|
4443
|
+
Object.defineProperty(exports, "RequestStream", {
|
|
4444
|
+
enumerable: true,
|
|
4445
|
+
get: function() {
|
|
4446
|
+
return RequestStream;
|
|
4447
|
+
}
|
|
4448
|
+
});
|
|
4449
|
+
Object.defineProperty(exports, "RingBufferObjectCache", {
|
|
4450
|
+
enumerable: true,
|
|
4451
|
+
get: function() {
|
|
4452
|
+
return RingBufferObjectCache;
|
|
4453
|
+
}
|
|
4454
|
+
});
|
|
4455
|
+
Object.defineProperty(exports, "SendDatagramStream", {
|
|
4456
|
+
enumerable: true,
|
|
4457
|
+
get: function() {
|
|
4458
|
+
return SendDatagramStream;
|
|
4459
|
+
}
|
|
4460
|
+
});
|
|
4461
|
+
Object.defineProperty(exports, "SendStream", {
|
|
4462
|
+
enumerable: true,
|
|
4463
|
+
get: function() {
|
|
4464
|
+
return SendStream;
|
|
4465
|
+
}
|
|
4466
|
+
});
|
|
4467
|
+
Object.defineProperty(exports, "StaticTrackSource", {
|
|
4468
|
+
enumerable: true,
|
|
4469
|
+
get: function() {
|
|
4470
|
+
return StaticTrackSource;
|
|
4471
|
+
}
|
|
4472
|
+
});
|
|
4473
|
+
Object.defineProperty(exports, "SubscribeNamespaceRequest", {
|
|
4474
|
+
enumerable: true,
|
|
4475
|
+
get: function() {
|
|
4476
|
+
return SubscribeNamespaceRequest;
|
|
4477
|
+
}
|
|
4478
|
+
});
|
|
4479
|
+
Object.defineProperty(exports, "SubscribePublication", {
|
|
4480
|
+
enumerable: true,
|
|
4481
|
+
get: function() {
|
|
4482
|
+
return SubscribePublication;
|
|
4483
|
+
}
|
|
4484
|
+
});
|
|
4485
|
+
Object.defineProperty(exports, "SubscribeRequest", {
|
|
4486
|
+
enumerable: true,
|
|
4487
|
+
get: function() {
|
|
4488
|
+
return SubscribeRequest;
|
|
4489
|
+
}
|
|
4490
|
+
});
|
|
4491
|
+
Object.defineProperty(exports, "TrackStatusRequest", {
|
|
4492
|
+
enumerable: true,
|
|
4493
|
+
get: function() {
|
|
4494
|
+
return TrackStatusRequest;
|
|
4495
|
+
}
|
|
4496
|
+
});
|