@torrent-tv/proxy 2.9.107 → 2.9.108
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/CHANGELOG.md +4 -0
- package/bin/cli.js +4 -1
- package/package.json +2 -3
- package/services/data-channel-handler.js +638 -542
- package/services/webrtc-manager.js +46 -1
|
@@ -1,542 +1,638 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file WebRTC data channel request handler (proxy side).
|
|
3
|
-
*
|
|
4
|
-
* When a browser opens a data channel to this proxy, this handler wires up
|
|
5
|
-
* message handlers that implement an HTTP-over-DataChannel protocol:
|
|
6
|
-
* each incoming `request` message triggers a local `fetch` to the Fastify
|
|
7
|
-
* server, and the response is streamed back as base64-encoded chunks.
|
|
8
|
-
*
|
|
9
|
-
* ## Wire protocol
|
|
10
|
-
*
|
|
11
|
-
* Browser → Proxy
|
|
12
|
-
* ```
|
|
13
|
-
* { type: "request", requestId, method, path, query, headers, body }
|
|
14
|
-
* { type: "ping", id }
|
|
15
|
-
* ```
|
|
16
|
-
*
|
|
17
|
-
* Proxy → Browser
|
|
18
|
-
* ```
|
|
19
|
-
* { type: "response-start", requestId, status, headers } (JSON string)
|
|
20
|
-
* { type: "response-error", requestId, error: string } (JSON string)
|
|
21
|
-
* { type: "pong", id } (JSON string)
|
|
22
|
-
* ```
|
|
23
|
-
*
|
|
24
|
-
* Response bodies are sent as BINARY data-channel messages (not JSON), to
|
|
25
|
-
* avoid the ~33% base64 overhead and the JSON encode/decode cost. Each binary
|
|
26
|
-
* frame is laid out as:
|
|
27
|
-
* ```
|
|
28
|
-
* byte 0 flags (bit 0: done)
|
|
29
|
-
* byte 1 idLen (length of the requestId in bytes)
|
|
30
|
-
* bytes 2..2+N requestId (ASCII)
|
|
31
|
-
* bytes 2+N.. payload (raw body bytes; empty on the final done frame)
|
|
32
|
-
* ```
|
|
33
|
-
* Control messages stay JSON strings so the browser can distinguish them from
|
|
34
|
-
* body frames by message type (string vs ArrayBuffer).
|
|
35
|
-
*
|
|
36
|
-
* The protocol mirrors the tunnel relay protocol so both transports share
|
|
37
|
-
* the same mental model and the same browser-side `WebRtcProxy` implementation.
|
|
38
|
-
*/
|
|
39
|
-
|
|
40
|
-
/** @import { DataChannel } from 'node-datachannel' */
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Configuration for the data channel handler.
|
|
44
|
-
*
|
|
45
|
-
* @typedef {Object} DataChannelHandlerOptions
|
|
46
|
-
* @property {number} proxyPort
|
|
47
|
-
* Local port the proxy's Fastify HTTP server is listening on.
|
|
48
|
-
* Incoming requests are forwarded to `http://127.0.0.1:{proxyPort}`.
|
|
49
|
-
* @property {(message: string) => void} [onLog]
|
|
50
|
-
* Optional log sink.
|
|
51
|
-
*/
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* An incoming request message received over the data channel.
|
|
55
|
-
*
|
|
56
|
-
* @typedef {Object} DataChannelRequest
|
|
57
|
-
* @property {string} requestId
|
|
58
|
-
* @property {string} method - HTTP method (GET, POST, …).
|
|
59
|
-
* @property {string} path - Request path (e.g. "/api/sources").
|
|
60
|
-
* @property {string} query - Raw query string without the leading "?".
|
|
61
|
-
* @property {Record<string, string>} headers - Headers to forward.
|
|
62
|
-
* @property {string | null} body - Request body string, or null.
|
|
63
|
-
*/
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* The object returned by {@link createDataChannelHandler}.
|
|
67
|
-
*
|
|
68
|
-
* @typedef {Object} DataChannelHandler
|
|
69
|
-
* @property {(sessionId: string, channel: DataChannel) => void} handleChannel
|
|
70
|
-
* Wire message handlers onto a freshly opened data channel.
|
|
71
|
-
*/
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
return
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
if (
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
if (
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @file WebRTC data channel request handler (proxy side).
|
|
3
|
+
*
|
|
4
|
+
* When a browser opens a data channel to this proxy, this handler wires up
|
|
5
|
+
* message handlers that implement an HTTP-over-DataChannel protocol:
|
|
6
|
+
* each incoming `request` message triggers a local `fetch` to the Fastify
|
|
7
|
+
* server, and the response is streamed back as base64-encoded chunks.
|
|
8
|
+
*
|
|
9
|
+
* ## Wire protocol
|
|
10
|
+
*
|
|
11
|
+
* Browser → Proxy
|
|
12
|
+
* ```
|
|
13
|
+
* { type: "request", requestId, method, path, query, headers, body }
|
|
14
|
+
* { type: "ping", id }
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Proxy → Browser
|
|
18
|
+
* ```
|
|
19
|
+
* { type: "response-start", requestId, status, headers } (JSON string)
|
|
20
|
+
* { type: "response-error", requestId, error: string } (JSON string)
|
|
21
|
+
* { type: "pong", id } (JSON string)
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* Response bodies are sent as BINARY data-channel messages (not JSON), to
|
|
25
|
+
* avoid the ~33% base64 overhead and the JSON encode/decode cost. Each binary
|
|
26
|
+
* frame is laid out as:
|
|
27
|
+
* ```
|
|
28
|
+
* byte 0 flags (bit 0: done)
|
|
29
|
+
* byte 1 idLen (length of the requestId in bytes)
|
|
30
|
+
* bytes 2..2+N requestId (ASCII)
|
|
31
|
+
* bytes 2+N.. payload (raw body bytes; empty on the final done frame)
|
|
32
|
+
* ```
|
|
33
|
+
* Control messages stay JSON strings so the browser can distinguish them from
|
|
34
|
+
* body frames by message type (string vs ArrayBuffer).
|
|
35
|
+
*
|
|
36
|
+
* The protocol mirrors the tunnel relay protocol so both transports share
|
|
37
|
+
* the same mental model and the same browser-side `WebRtcProxy` implementation.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/** @import { DataChannel } from 'node-datachannel' */
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Configuration for the data channel handler.
|
|
44
|
+
*
|
|
45
|
+
* @typedef {Object} DataChannelHandlerOptions
|
|
46
|
+
* @property {number} proxyPort
|
|
47
|
+
* Local port the proxy's Fastify HTTP server is listening on.
|
|
48
|
+
* Incoming requests are forwarded to `http://127.0.0.1:{proxyPort}`.
|
|
49
|
+
* @property {(message: string) => void} [onLog]
|
|
50
|
+
* Optional log sink.
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* An incoming request message received over the data channel.
|
|
55
|
+
*
|
|
56
|
+
* @typedef {Object} DataChannelRequest
|
|
57
|
+
* @property {string} requestId
|
|
58
|
+
* @property {string} method - HTTP method (GET, POST, …).
|
|
59
|
+
* @property {string} path - Request path (e.g. "/api/sources").
|
|
60
|
+
* @property {string} query - Raw query string without the leading "?".
|
|
61
|
+
* @property {Record<string, string>} headers - Headers to forward.
|
|
62
|
+
* @property {string | null} body - Request body string, or null.
|
|
63
|
+
*/
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The object returned by {@link createDataChannelHandler}.
|
|
67
|
+
*
|
|
68
|
+
* @typedef {Object} DataChannelHandler
|
|
69
|
+
* @property {(sessionId: string, channel: DataChannel) => void} handleChannel
|
|
70
|
+
* Wire message handlers onto a freshly opened data channel.
|
|
71
|
+
*/
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Watch one channel's send queue and, when it stops draining, say WHY.
|
|
75
|
+
*
|
|
76
|
+
* A channel that is open, keeps accepting requests and delivers nothing was
|
|
77
|
+
* seen in the field 2026-08-06: the queue grew from 214 049 to 239 731 bytes in
|
|
78
|
+
* fourteen seconds and never fell, while every layer above reported success —
|
|
79
|
+
* the route answered in 15 ms, the handler sent 378 bytes, the channel was
|
|
80
|
+
* open. The viewer sat in front of a spinner for eleven minutes.
|
|
81
|
+
*
|
|
82
|
+
* `bufferedAmount` alone cannot say why: it only proves the bytes are still
|
|
83
|
+
* OURS. The transport counters can, and this is the table the snapshot is read
|
|
84
|
+
* against — written down in advance so the answer is a reading, not an opinion:
|
|
85
|
+
*
|
|
86
|
+
* bytesSent rising, queue rising → packets leave, nothing acknowledges
|
|
87
|
+
* them: the return path is broken.
|
|
88
|
+
* bytesSent flat, queue rising → SCTP is not transmitting: the peer's
|
|
89
|
+
* receive window is shut or congestion
|
|
90
|
+
* control has collapsed.
|
|
91
|
+
* bytesReceived rising either way → the peer is alive and its packets do
|
|
92
|
+
* reach us; the failure is one-way.
|
|
93
|
+
* both flat → nothing crosses at all.
|
|
94
|
+
*
|
|
95
|
+
* Sampled every second; reported only once the queue has failed to fall for
|
|
96
|
+
* {@link SEND_QUEUE_STUCK_MS}, then every second while it lasts, so the trend
|
|
97
|
+
* of every counter is in the log rather than one snapshot of it.
|
|
98
|
+
*
|
|
99
|
+
* @param {string} sessionId
|
|
100
|
+
* @param {string} tag
|
|
101
|
+
* @param {string} label
|
|
102
|
+
* @param {DataChannel} channel
|
|
103
|
+
* @returns {() => void} Stops the watch.
|
|
104
|
+
*/
|
|
105
|
+
function makeSendQueueWatcher({ log, getTransportSnapshot }) {
|
|
106
|
+
return function watchSendQueue(sessionId, tag, label, channel) {
|
|
107
|
+
let lowestSinceDrain = Number.POSITIVE_INFINITY;
|
|
108
|
+
let stuckSince = 0;
|
|
109
|
+
let previous = null;
|
|
110
|
+
|
|
111
|
+
const timer = setInterval(() => {
|
|
112
|
+
let queued = 0;
|
|
113
|
+
try {
|
|
114
|
+
queued = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0;
|
|
115
|
+
} catch {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (queued === 0 || queued < lowestSinceDrain) {
|
|
119
|
+
lowestSinceDrain = queued;
|
|
120
|
+
stuckSince = 0;
|
|
121
|
+
previous = null;
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const now = Date.now();
|
|
125
|
+
if (stuckSince === 0) {
|
|
126
|
+
stuckSince = now;
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (now - stuckSince < SEND_QUEUE_STUCK_MS) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const snapshot = getTransportSnapshot?.(sessionId) ?? null;
|
|
133
|
+
if (!snapshot) {
|
|
134
|
+
log(`[dc] Session ${tag} "${label}": send queue stuck at ${queued}B for ` +
|
|
135
|
+
`${Math.round((now - stuckSince) / 1000)}s — no transport to ask`);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const sentDelta = previous ? snapshot.bytesSent - previous.bytesSent : null;
|
|
139
|
+
const recvDelta = previous ? snapshot.bytesReceived - previous.bytesReceived : null;
|
|
140
|
+
previous = snapshot;
|
|
141
|
+
log(
|
|
142
|
+
`[dc] Session ${tag} "${label}": send queue stuck at ${queued}B for ` +
|
|
143
|
+
`${Math.round((now - stuckSince) / 1000)}s — transport ` +
|
|
144
|
+
`sent=${snapshot.bytesSent}${sentDelta === null ? "" : ` (+${sentDelta})`} ` +
|
|
145
|
+
`received=${snapshot.bytesReceived}${recvDelta === null ? "" : ` (+${recvDelta})`} ` +
|
|
146
|
+
`rtt=${snapshot.rtt}ms pc=${snapshot.state} ice=${snapshot.iceState} pair=${snapshot.pair}`
|
|
147
|
+
);
|
|
148
|
+
}, SEND_QUEUE_SAMPLE_MS);
|
|
149
|
+
|
|
150
|
+
if (typeof timer.unref === "function") {
|
|
151
|
+
timer.unref();
|
|
152
|
+
}
|
|
153
|
+
return () => clearInterval(timer);
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Create a handler for incoming WebRTC data channels.
|
|
159
|
+
*
|
|
160
|
+
* @param {DataChannelHandlerOptions} options
|
|
161
|
+
* @returns {DataChannelHandler}
|
|
162
|
+
*/
|
|
163
|
+
import { performance } from "node:perf_hooks";
|
|
164
|
+
import { eventLoopDelay, resetEventLoopDelay } from "../utils/perf.js";
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Build one body frame: `[flags(1)][idLen(1)][requestId][payload]`.
|
|
168
|
+
*
|
|
169
|
+
* One allocation and one copy. The previous version made two of each — a copy
|
|
170
|
+
* of the chunk into a `Buffer`, then a `concat` that copied it again into the
|
|
171
|
+
* frame — which measured 75.9 ms per 13 MB segment on the field host against
|
|
172
|
+
* 40.0 ms this way, and allocated ~600 extra buffers over a segment's 208
|
|
173
|
+
* chunks. One copy is the floor: chunks arrive from a web stream that allocates
|
|
174
|
+
* them itself, so there is no buffer of ours to read them into.
|
|
175
|
+
*
|
|
176
|
+
* @param {Buffer} idBytes - The request id, already encoded.
|
|
177
|
+
* @param {Uint8Array | null} bytes - Payload, or nothing for the done frame.
|
|
178
|
+
* @param {boolean} done
|
|
179
|
+
* @returns {Buffer}
|
|
180
|
+
*/
|
|
181
|
+
export function encodeFrame(idBytes, bytes, done) {
|
|
182
|
+
const payloadLength = bytes?.length ?? 0;
|
|
183
|
+
const frame = Buffer.allocUnsafe(2 + idBytes.length + payloadLength);
|
|
184
|
+
frame[0] = done ? 1 : 0;
|
|
185
|
+
frame[1] = idBytes.length;
|
|
186
|
+
idBytes.copy(frame, 2);
|
|
187
|
+
if (payloadLength > 0) {
|
|
188
|
+
frame.set(bytes, 2 + idBytes.length);
|
|
189
|
+
}
|
|
190
|
+
return frame;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function createDataChannelHandler({ proxyPort, onLog, getTransportSnapshot }) {
|
|
194
|
+
/** Request id → its ASCII bytes; see {@link requestIdBytes}. */
|
|
195
|
+
const requestIdCache = new Map();
|
|
196
|
+
|
|
197
|
+
const watchSendQueue = makeSendQueueWatcher({ log: (message) => log(message), getTransportSnapshot });
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* @param {string} message
|
|
201
|
+
* @returns {void}
|
|
202
|
+
*/
|
|
203
|
+
function log(message) {
|
|
204
|
+
if (typeof onLog === "function") {
|
|
205
|
+
onLog(message);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Wire up the `onMessage`, `onClosed`, and `onError` handlers for a channel.
|
|
211
|
+
*
|
|
212
|
+
* @param {string} sessionId
|
|
213
|
+
* @param {DataChannel} channel
|
|
214
|
+
* @returns {void}
|
|
215
|
+
*/
|
|
216
|
+
function handleChannel(sessionId, channel) {
|
|
217
|
+
const tag = sessionId.slice(0, 8);
|
|
218
|
+
const label = typeof channel.getLabel === "function" ? channel.getLabel() : "?";
|
|
219
|
+
log(`[dc] Session ${tag}: channel open`);
|
|
220
|
+
const stopWatchdog = watchSendQueue(sessionId, tag, label, channel);
|
|
221
|
+
|
|
222
|
+
// Partial chunked-request bodies in flight on THIS channel, keyed by
|
|
223
|
+
// requestId. Each entry buffers frames until the done frame, then runs the
|
|
224
|
+
// assembled request through the same path as a single-message request.
|
|
225
|
+
/** @type {Map<string, { meta: object, chunks: Buffer[], receivedBytes: number, bodyBytes: number, timer: ReturnType<typeof setTimeout> }>} */
|
|
226
|
+
const partials = new Map();
|
|
227
|
+
|
|
228
|
+
const dropPartial = (requestId) => {
|
|
229
|
+
const entry = partials.get(requestId);
|
|
230
|
+
if (entry) {
|
|
231
|
+
clearTimeout(entry.timer);
|
|
232
|
+
partials.delete(requestId);
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Begin assembling a chunked request. Validates the path and size up front
|
|
238
|
+
* so an invalid or oversized request never buffers a body.
|
|
239
|
+
*
|
|
240
|
+
* @param {any} message - The `request-start` control message.
|
|
241
|
+
*/
|
|
242
|
+
const startPartialRequest = (message) => {
|
|
243
|
+
const { requestId, method, path, query, headers, bodyBytes } = message ?? {};
|
|
244
|
+
if (typeof requestId !== "string" || requestId.length === 0) {
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (!isValidRequestPath(path)) {
|
|
248
|
+
send(channel, { type: "response-error", requestId, error: "Invalid request path." });
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (!Number.isInteger(bodyBytes) || bodyBytes < 0 || bodyBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
|
|
252
|
+
send(channel, { type: "response-error", requestId, error: "Request body too large." });
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
dropPartial(requestId); // replace any stale entry with the same id
|
|
256
|
+
const timer = setTimeout(() => {
|
|
257
|
+
const entry = partials.get(requestId);
|
|
258
|
+
partials.delete(requestId);
|
|
259
|
+
log(`[dc] Session ${tag}: dropped stale partial request ${requestId.slice(0, 8)} (${entry?.receivedBytes ?? 0}B)`);
|
|
260
|
+
}, PARTIAL_REQUEST_TTL_MS);
|
|
261
|
+
partials.set(requestId, {
|
|
262
|
+
meta: { requestId, method, path, query, headers },
|
|
263
|
+
chunks: [],
|
|
264
|
+
receivedBytes: 0,
|
|
265
|
+
bodyBytes,
|
|
266
|
+
timer
|
|
267
|
+
});
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Handle a binary body frame for a chunked request.
|
|
272
|
+
* Layout: [flags(1)][idLen(1)][requestId(ASCII)][payload].
|
|
273
|
+
*
|
|
274
|
+
* @param {Buffer} buf
|
|
275
|
+
*/
|
|
276
|
+
const handleBodyFrame = (buf) => {
|
|
277
|
+
if (buf.length < 2) {
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const flags = buf[0];
|
|
281
|
+
const idLen = buf[1];
|
|
282
|
+
if (buf.length < 2 + idLen) {
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const requestId = buf.toString("ascii", 2, 2 + idLen);
|
|
286
|
+
const entry = partials.get(requestId);
|
|
287
|
+
if (!entry) {
|
|
288
|
+
return; // stale / already-dropped / aborted
|
|
289
|
+
}
|
|
290
|
+
if (flags & 2) {
|
|
291
|
+
// Aborted by the browser — drop silently, no reply.
|
|
292
|
+
dropPartial(requestId);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (buf.length > 2 + idLen) {
|
|
296
|
+
const payload = buf.subarray(2 + idLen);
|
|
297
|
+
entry.chunks.push(Buffer.from(payload));
|
|
298
|
+
entry.receivedBytes += payload.length;
|
|
299
|
+
}
|
|
300
|
+
if (entry.receivedBytes > entry.bodyBytes || entry.receivedBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
|
|
301
|
+
dropPartial(requestId);
|
|
302
|
+
send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (flags & 1) {
|
|
306
|
+
// Done frame — assemble and execute.
|
|
307
|
+
dropPartial(requestId);
|
|
308
|
+
if (entry.receivedBytes !== entry.bodyBytes) {
|
|
309
|
+
send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
const body = Buffer.concat(entry.chunks).toString("utf8");
|
|
313
|
+
void handleRequest(channel, { ...entry.meta, body }, true).catch((error) => {
|
|
314
|
+
log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
channel.onMessage((raw) => {
|
|
320
|
+
// Binary messages are chunked-request body frames; the proxy otherwise
|
|
321
|
+
// only ever receives JSON strings, so the type discriminates cleanly.
|
|
322
|
+
if (typeof raw !== "string") {
|
|
323
|
+
handleBodyFrame(Buffer.isBuffer(raw) ? raw : Buffer.from(raw));
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** @type {DataChannelRequest | { type: string, id?: string }} */
|
|
328
|
+
let message;
|
|
329
|
+
try {
|
|
330
|
+
message = JSON.parse(raw);
|
|
331
|
+
} catch {
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (message.type === "request") {
|
|
336
|
+
void handleRequest(channel, message).catch((error) => {
|
|
337
|
+
log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
|
|
338
|
+
});
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
if (message.type === "request-start") {
|
|
343
|
+
startPartialRequest(message);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (message.type === "ping") {
|
|
348
|
+
send(channel, { type: "pong", id: message.id });
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
channel.onClosed(() => {
|
|
353
|
+
stopWatchdog();
|
|
354
|
+
for (const entry of partials.values()) {
|
|
355
|
+
clearTimeout(entry.timer);
|
|
356
|
+
}
|
|
357
|
+
partials.clear();
|
|
358
|
+
log(`[dc] Session ${tag}: channel closed`);
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
channel.onError((err) => {
|
|
362
|
+
log(`[dc] Session ${tag}: channel error: ${err}`);
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Fetch a resource from the local proxy HTTP server and stream the response
|
|
368
|
+
* back to the browser over the data channel.
|
|
369
|
+
*
|
|
370
|
+
* The `Host` header is rewritten to `127.0.0.1:{proxyPort}` so that Fastify
|
|
371
|
+
* routes the request correctly regardless of what the browser sent.
|
|
372
|
+
*
|
|
373
|
+
* @param {DataChannel} channel
|
|
374
|
+
* @param {DataChannelRequest} req
|
|
375
|
+
* @returns {Promise<void>}
|
|
376
|
+
*/
|
|
377
|
+
async function handleRequest(channel, req, viaChunks = false) {
|
|
378
|
+
const { requestId, method, path, query, headers: forwardedHeaders, body } = req;
|
|
379
|
+
|
|
380
|
+
// Reject paths that are not absolute, contain traversal sequences, or
|
|
381
|
+
// do not start with a known proxy route prefix. All valid browser-side
|
|
382
|
+
// requests use /api/*, /stream, /transcode/*, /health, or /healthz.
|
|
383
|
+
if (!isValidRequestPath(path)) {
|
|
384
|
+
send(channel, { type: "response-error", requestId, error: "Invalid request path." });
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const queryInfo = query ? `?${query}` : "";
|
|
389
|
+
const bodyInfo =
|
|
390
|
+
body != null && typeof body === "string" && body.length > 0
|
|
391
|
+
? ` body=${body.length} bytes${viaChunks ? " (chunked)" : ""}`
|
|
392
|
+
: "";
|
|
393
|
+
log(`[dc] ${method} ${path}${queryInfo}${bodyInfo}`);
|
|
394
|
+
|
|
395
|
+
const targetUrl = `http://127.0.0.1:${proxyPort}${path}${query ? `?${query}` : ""}`;
|
|
396
|
+
const requestHeaders = { ...(forwardedHeaders ?? {}), host: `127.0.0.1:${proxyPort}` };
|
|
397
|
+
|
|
398
|
+
let response;
|
|
399
|
+
// [net-debug] TEMPORARY: time spent in the local fetch (waiting for the
|
|
400
|
+
// route to return a response — e.g. long-polling until an HLS segment is
|
|
401
|
+
// finalized by ffmpeg) vs. the body transfer over the data channel.
|
|
402
|
+
const fetchStartedAt = Date.now();
|
|
403
|
+
try {
|
|
404
|
+
response = await fetch(targetUrl, {
|
|
405
|
+
method,
|
|
406
|
+
headers: requestHeaders,
|
|
407
|
+
body: body != null ? body : undefined,
|
|
408
|
+
redirect: "manual"
|
|
409
|
+
});
|
|
410
|
+
} catch (fetchError) {
|
|
411
|
+
log(`[dc] ${method} ${path}${queryInfo} → error: ${fetchError?.message ?? String(fetchError)}`);
|
|
412
|
+
send(channel, { type: "response-error", requestId, error: fetchError?.message ?? String(fetchError) });
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
if (response.status !== 200 && response.status !== 206) {
|
|
417
|
+
log(`[dc] ${method} ${path}${queryInfo} → ${response.status}`);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** @type {Record<string, string>} */
|
|
421
|
+
const responseHeaders = {};
|
|
422
|
+
for (const [name, value] of response.headers.entries()) {
|
|
423
|
+
responseHeaders[name] = value;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
send(channel, { type: "response-start", requestId, status: response.status, headers: responseHeaders });
|
|
427
|
+
|
|
428
|
+
if (!response.body) {
|
|
429
|
+
sendChunk(channel, requestId, null, true);
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
try {
|
|
434
|
+
const reader = response.body.getReader();
|
|
435
|
+
// [net-debug] TEMPORARY: measure transfer size/time and channel buffering.
|
|
436
|
+
// fetchMs = time waiting for the route (incl. ffmpeg segment finalization).
|
|
437
|
+
// ttfbMs = time from body-read start to the first chunk with data (loopback).
|
|
438
|
+
// sendMs = total body read+send duration over the data channel.
|
|
439
|
+
const fetchMs = Date.now() - fetchStartedAt;
|
|
440
|
+
const sendStartedAt = Date.now();
|
|
441
|
+
let firstByteMs = -1;
|
|
442
|
+
let chunks = 0;
|
|
443
|
+
let totalBytes = 0;
|
|
444
|
+
let maxBuffered = 0;
|
|
445
|
+
// Attribute the transfer to the step that actually consumes the time.
|
|
446
|
+
// Without this split a slow transfer is indistinguishable between "the
|
|
447
|
+
// source is slow", "the channel is slow" and "the event loop is blocked",
|
|
448
|
+
// which is exactly the argument a field seek left unresolved.
|
|
449
|
+
let readMs = 0;
|
|
450
|
+
let sendMs2 = 0;
|
|
451
|
+
let drainMs = 0;
|
|
452
|
+
resetEventLoopDelay();
|
|
453
|
+
while (true) {
|
|
454
|
+
const readStartedAt = performance.now();
|
|
455
|
+
const { done, value } = await reader.read();
|
|
456
|
+
readMs += performance.now() - readStartedAt;
|
|
457
|
+
if (done) {
|
|
458
|
+
sendChunk(channel, requestId, null, true);
|
|
459
|
+
const elapsedMs = Date.now() - sendStartedAt;
|
|
460
|
+
let bufferedNow = 0;
|
|
461
|
+
try { bufferedNow = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0; } catch { /* ignore */ }
|
|
462
|
+
const loop = eventLoopDelay();
|
|
463
|
+
const mbps = elapsedMs > 0 ? (totalBytes * 8) / (elapsedMs * 1000) : 0;
|
|
464
|
+
log(
|
|
465
|
+
`[net-debug] sent ${path}${queryInfo} bytes=${totalBytes} fetchMs=${fetchMs} ` +
|
|
466
|
+
`ttfbMs=${firstByteMs} sendMs=${elapsedMs} chunks=${chunks} ` +
|
|
467
|
+
`maxBuffered=${maxBuffered} bufferedAtEnd=${bufferedNow} ` +
|
|
468
|
+
// Where the time went: reading the body from the local route,
|
|
469
|
+
// handing chunks to the channel, or waiting for its queue. Plus
|
|
470
|
+
// the event-loop delay over the same window — a large max here
|
|
471
|
+
// means the transfer was blocked by synchronous work, not by the
|
|
472
|
+
// network, and the three figures above will all look inflated.
|
|
473
|
+
`readMs=${readMs.toFixed(0)} chanMs=${sendMs2.toFixed(0)} drainMs=${drainMs.toFixed(0)} ` +
|
|
474
|
+
`loopMean=${loop.meanMs.toFixed(1)} loopP99=${loop.p99Ms.toFixed(1)} loopMax=${loop.maxMs.toFixed(1)} ` +
|
|
475
|
+
`rate=${mbps.toFixed(1)}Mbps`
|
|
476
|
+
);
|
|
477
|
+
break;
|
|
478
|
+
}
|
|
479
|
+
if (firstByteMs < 0) firstByteMs = Date.now() - sendStartedAt;
|
|
480
|
+
chunks += 1;
|
|
481
|
+
totalBytes += value.length;
|
|
482
|
+
try {
|
|
483
|
+
const b = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0;
|
|
484
|
+
if (b > maxBuffered) maxBuffered = b;
|
|
485
|
+
} catch { /* ignore */ }
|
|
486
|
+
const sendStepAt = performance.now();
|
|
487
|
+
sendChunk(channel, requestId, value, false);
|
|
488
|
+
sendMs2 += performance.now() - sendStepAt;
|
|
489
|
+
// Backpressure: do not keep queuing chunks once the channel's outgoing
|
|
490
|
+
// buffer is large — wait for it to drain. Prevents the SCTP send buffer
|
|
491
|
+
// from ballooning, which stalls throughput.
|
|
492
|
+
const drainStepAt = performance.now();
|
|
493
|
+
await waitForBufferDrain(channel);
|
|
494
|
+
drainMs += performance.now() - drainStepAt;
|
|
495
|
+
}
|
|
496
|
+
} catch {
|
|
497
|
+
sendChunk(channel, requestId, null, true);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* Send a response body frame as a BINARY data-channel message.
|
|
503
|
+
* Layout: [flags(1)][idLen(1)][requestId(ASCII)][payload].
|
|
504
|
+
*
|
|
505
|
+
* @param {DataChannel} channel
|
|
506
|
+
* @param {string} requestId
|
|
507
|
+
* @param {Uint8Array | null} bytes - Body bytes, or null/empty for the done frame.
|
|
508
|
+
* @param {boolean} done
|
|
509
|
+
* @returns {void}
|
|
510
|
+
*/
|
|
511
|
+
/**
|
|
512
|
+
* The request id as bytes, prepared once per request rather than per chunk.
|
|
513
|
+
*
|
|
514
|
+
* A segment is a couple of hundred chunks, and each one was re-encoding the
|
|
515
|
+
* same 32-character string. The map is bounded because request ids are
|
|
516
|
+
* short-lived and unbounded in number — dropping the whole cache when it
|
|
517
|
+
* grows costs one re-encode per live request and cannot leak.
|
|
518
|
+
*
|
|
519
|
+
* @param {string} requestId
|
|
520
|
+
* @returns {Buffer}
|
|
521
|
+
*/
|
|
522
|
+
function requestIdBytes(requestId) {
|
|
523
|
+
let bytes = requestIdCache.get(requestId);
|
|
524
|
+
if (!bytes) {
|
|
525
|
+
if (requestIdCache.size > 64) {
|
|
526
|
+
requestIdCache.clear();
|
|
527
|
+
}
|
|
528
|
+
bytes = Buffer.from(requestId, "ascii");
|
|
529
|
+
requestIdCache.set(requestId, bytes);
|
|
530
|
+
}
|
|
531
|
+
return bytes;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function sendChunk(channel, requestId, bytes, done) {
|
|
535
|
+
try {
|
|
536
|
+
channel.sendMessageBinary(encodeFrame(requestIdBytes(requestId), bytes, done));
|
|
537
|
+
} catch {
|
|
538
|
+
// Channel closed between check and send — safe to ignore.
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Resolve once the channel's outgoing buffer has drained below the low-water
|
|
544
|
+
* mark. No-op (resolves immediately) when the buffer is already small or the
|
|
545
|
+
* channel does not expose buffer APIs. A timeout fallback guards against a
|
|
546
|
+
* missed low-water event so the send loop can never deadlock.
|
|
547
|
+
*
|
|
548
|
+
* @param {DataChannel} channel
|
|
549
|
+
* @returns {Promise<void>}
|
|
550
|
+
*/
|
|
551
|
+
function waitForBufferDrain(channel) {
|
|
552
|
+
return new Promise((resolve) => {
|
|
553
|
+
try {
|
|
554
|
+
if (typeof channel.bufferedAmount !== "function" || channel.bufferedAmount() <= DC_BUFFER_HIGH_WATER) {
|
|
555
|
+
resolve();
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
let settled = false;
|
|
559
|
+
const done = () => {
|
|
560
|
+
if (settled) return;
|
|
561
|
+
settled = true;
|
|
562
|
+
resolve();
|
|
563
|
+
};
|
|
564
|
+
channel.setBufferedAmountLowThreshold(DC_BUFFER_LOW_WATER);
|
|
565
|
+
channel.onBufferedAmountLow(done);
|
|
566
|
+
// Guard against a race where the buffer drained between the check above
|
|
567
|
+
// and registering the callback (the low-water event would never fire).
|
|
568
|
+
if (channel.bufferedAmount() <= DC_BUFFER_LOW_WATER) {
|
|
569
|
+
done();
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
setTimeout(done, DC_BUFFER_DRAIN_TIMEOUT_MS);
|
|
573
|
+
} catch {
|
|
574
|
+
resolve();
|
|
575
|
+
}
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Serialise `message` to JSON and send it over the data channel.
|
|
581
|
+
* Errors are silently swallowed — the channel may have closed between
|
|
582
|
+
* the open check and the actual send.
|
|
583
|
+
*
|
|
584
|
+
* @param {DataChannel} channel
|
|
585
|
+
* @param {object} message
|
|
586
|
+
* @returns {void}
|
|
587
|
+
*/
|
|
588
|
+
function send(channel, message) {
|
|
589
|
+
try {
|
|
590
|
+
channel.sendMessage(JSON.stringify(message));
|
|
591
|
+
} catch {
|
|
592
|
+
// Channel closed between check and send — safe to ignore.
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
return { handleChannel };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Allowed path prefixes for data-channel requests.
|
|
601
|
+
* Only the known proxy API and streaming routes are accepted.
|
|
602
|
+
*/
|
|
603
|
+
const PATH_ALLOWLIST_RE = /^(?:\/api\/|\/stream(?:$|\?)|\/?transcode\/|\/health(?:z)?(?:$|\?))/;
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* True when `path` is an absolute, traversal-free path on a known proxy route.
|
|
607
|
+
* Shared by the single-message and chunked request entry points.
|
|
608
|
+
*
|
|
609
|
+
* @param {unknown} path
|
|
610
|
+
* @returns {boolean}
|
|
611
|
+
*/
|
|
612
|
+
function isValidRequestPath(path) {
|
|
613
|
+
return (
|
|
614
|
+
typeof path === "string" &&
|
|
615
|
+
path.startsWith("/") &&
|
|
616
|
+
!path.includes("..") &&
|
|
617
|
+
PATH_ALLOWLIST_RE.test(path)
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** Max assembled size of a chunked request body (guards proxy memory). */
|
|
622
|
+
const PROXY_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024;
|
|
623
|
+
/** Drop an incomplete chunked body if no further frame arrives within this window. */
|
|
624
|
+
const PARTIAL_REQUEST_TTL_MS = 60_000;
|
|
625
|
+
|
|
626
|
+
/** Pause sending body chunks once the channel buffer exceeds this many bytes. */
|
|
627
|
+
// How often the send queue is sampled, and how long it must fail to fall
|
|
628
|
+
// before the transport is asked what it is doing. Five seconds is far longer
|
|
629
|
+
// than any healthy burst drains in — measured, a 6-11 MB segment leaves in
|
|
630
|
+
// well under a second on the LAN — and short enough that a stuck channel is
|
|
631
|
+
// named while the viewer is still looking at it.
|
|
632
|
+
const SEND_QUEUE_SAMPLE_MS = 1_000;
|
|
633
|
+
const SEND_QUEUE_STUCK_MS = 5_000;
|
|
634
|
+
const DC_BUFFER_HIGH_WATER = 8 * 1024 * 1024;
|
|
635
|
+
/** Resume sending once the channel buffer drains to this many bytes. */
|
|
636
|
+
const DC_BUFFER_LOW_WATER = 1 * 1024 * 1024;
|
|
637
|
+
/** Safety fallback so the send loop cannot deadlock on a missed drain event. */
|
|
638
|
+
const DC_BUFFER_DRAIN_TIMEOUT_MS = 5000;
|