@torrent-tv/proxy 2.87.6 → 2.87.8

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.
@@ -1,1356 +1,1369 @@
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
- * { type: "probe-echo", seen: { <label>: seq }, report }
16
- * ```
17
- *
18
- * Proxy → Browser
19
- * ```
20
- * { type: "probe", seq, sentAt } (JSON string)
21
- * { type: "response-start", requestId, status, headers } (JSON string)
22
- * { type: "response-error", requestId, error: string } (JSON string)
23
- * { type: "pong", id } (JSON string)
24
- * { type: "subtitle-cues", fileIndex, trackIndex, cues, language, cursor } (JSON string)
25
- * ```
26
- * The last one is unsolicited — sent the moment new cues are read from a
27
- * file's already-downloaded pieces, to whichever channel last asked for that
28
- * file's subtitles over `/api/subtitles`. Not a response to any `requestId`.
29
- *
30
- * Response bodies are sent as BINARY data-channel messages (not JSON), to
31
- * avoid the ~33% base64 overhead and the JSON encode/decode cost. Each binary
32
- * frame is laid out as:
33
- * ```
34
- * byte 0 flags (bit 0: done)
35
- * byte 1 idLen (length of the requestId in bytes)
36
- * bytes 2..2+N requestId (ASCII)
37
- * bytes 2+N.. payload (raw body bytes; empty on the final done frame)
38
- * ```
39
- * Control messages stay JSON strings so the browser can distinguish them from
40
- * body frames by message type (string vs ArrayBuffer).
41
- *
42
- * The protocol mirrors the tunnel relay protocol so both transports share
43
- * the same mental model and the same browser-side `WebRtcProxy` implementation.
44
- */
45
-
46
- /** @import { DataChannel } from 'node-datachannel' */
47
-
48
- import { createDeliveryProbe, PROBE_INTERVAL_MS } from "./delivery-probe.js";
49
-
50
- /**
51
- * Configuration for the data channel handler.
52
- *
53
- * @typedef {Object} DataChannelHandlerOptions
54
- * @property {number} proxyPort
55
- * Local port the proxy's Fastify HTTP server is listening on.
56
- * Incoming requests are forwarded to `http://127.0.0.1:{proxyPort}`.
57
- * @property {(message: string) => void} [onLog]
58
- * Optional log sink.
59
- * @property {{ maybeCapture: (trigger: {
60
- * sessionId: string, tag: string, label: string,
61
- * remote: { address: string, port: number } | null,
62
- * queuedBytes: number, stuckForMs: number
63
- * }) => boolean }} [witness]
64
- * The packet witness (services/transport/packet-witness.js). When {@link wedgeIsCertain}
65
- * says delivery has stopped, the watcher hands it the transport snapshot's
66
- * remote endpoint: the ring's history is kept and a tail capture records what
67
- * the wire actually does. Optional; absent means no captures are taken.
68
- */
69
-
70
- /**
71
- * An incoming request message received over the data channel.
72
- *
73
- * @typedef {Object} DataChannelRequest
74
- * @property {string} requestId
75
- * @property {string} method - HTTP method (GET, POST, …).
76
- * @property {string} path - Request path (e.g. "/api/sources").
77
- * @property {string} query - Raw query string without the leading "?".
78
- * @property {Record<string, string>} headers - Headers to forward.
79
- * @property {string | null} body - Request body string, or null.
80
- */
81
-
82
- /**
83
- * The object returned by {@link createDataChannelHandler}.
84
- *
85
- * @typedef {Object} DataChannelHandler
86
- * @property {(sessionId: string, channel: DataChannel) => void} handleChannel
87
- * Wire message handlers onto a freshly opened data channel.
88
- */
89
-
90
- /**
91
- * How long a wedge must hold before the packet witness is asked for evidence.
92
- *
93
- * Derived per connection rather than chosen, because a chosen number is what
94
- * cost the two field captures their onset: the previous rule waited a flat 30 s
95
- * and the recording therefore began half a minute after the interesting part.
96
- *
97
- * Three quantities, all measured on this connection:
98
- *
99
- * the queue's own drain time — `queuedBytes / bytesPerSecond`, how long a
100
- * healthy channel would need to clear what is sitting in it, at the best rate
101
- * this very connection has been seen to move bytes at;
102
- *
103
- * the longest this connection has EVER paused while healthy — an ordinary
104
- * retransmission timeout stops the accepted-byte counter dead for as long as
105
- * it lasts, because a full send buffer accepts nothing, and a link with loss
106
- * does that routinely. The longest such pause already observed here is what
107
- * the link's own behaviour says a legitimate pause looks like;
108
- *
109
- * the interval at which we offer bytes at all — the delivery probe hands
110
- * every channel a message every {@linkcode PROBE_INTERVAL_MS}, so in health
111
- * the accepted-byte counter cannot stand still for longer than that.
112
- *
113
- * A wedge is certain once ALL of them have passed with the counter unmoved.
114
- * Without a rate there is nothing to divide by, and the function says so
115
- * instead of guessing.
116
- *
117
- * @param {{ queuedBytes: number, bytesPerSecond: number, flatForMs: number, longestHealthyFlatMs?: number }} state
118
- * @returns {{ certain: boolean, needMs: number | null }}
119
- */
120
- export function wedgeIsCertain({ queuedBytes, bytesPerSecond, flatForMs, longestHealthyFlatMs = 0 }) {
121
- if (!(bytesPerSecond > 0)) {
122
- return { certain: false, needMs: null };
123
- }
124
- const drainMs = (Math.max(queuedBytes, 0) / bytesPerSecond) * 1000;
125
- const needMs = Math.max(drainMs, longestHealthyFlatMs, PROBE_INTERVAL_MS);
126
- return { certain: flatForMs >= needMs, needMs };
127
- }
128
-
129
- /**
130
- * Watch one channel's send queue and, when it stops draining, say WHY.
131
- *
132
- * A channel that is open, keeps accepting requests and delivers nothing was
133
- * seen in the field 2026-08-06: the queue grew from 214 049 to 239 731 bytes in
134
- * fourteen seconds and never fell, while every layer above reported success —
135
- * the route answered in 15 ms, the handler sent 378 bytes, the channel was
136
- * open. The viewer sat in front of a spinner for eleven minutes.
137
- *
138
- * `bufferedAmount` alone cannot say why: it only proves the bytes are still
139
- * OURS. The transport counters can, and this is the table the snapshot is read
140
- * against — written down in advance so the answer is a reading, not an opinion:
141
- *
142
- * bytesSent rising, queue rising → packets leave, nothing acknowledges
143
- * them: the return path is broken.
144
- * bytesSent flat, queue rising → SCTP is not transmitting: the peer's
145
- * receive window is shut or congestion
146
- * control has collapsed.
147
- * bytesReceived rising either way → the peer is alive and its packets do
148
- * reach us; the failure is one-way.
149
- * both flat → nothing crosses at all.
150
- *
151
- * Sampled every second; reported only once the queue has failed to fall for
152
- * {@link SEND_QUEUE_STUCK_MS}, then every second while it lasts, so the trend
153
- * of every counter is in the log rather than one snapshot of it.
154
- *
155
- * @param {string} sessionId
156
- * @param {string} tag
157
- * @param {string} label
158
- * @param {DataChannel} channel
159
- * @returns {() => void} Stops the watch.
160
- */
161
- function makeSendQueueWatcher({ log, getTransportSnapshot, witness, usrsctpState, onConnectionGone }) {
162
- // Every channel of one connection reads the SAME transport counters — the
163
- // snapshot describes the peer connection, not the channel — so the heartbeat
164
- // belongs to the connection and is printed once for it. Printed per channel
165
- // it produced two byte-for-byte identical lines (measured 2026-08-14:
166
- // `sent=5153491` under both "proxy" and "proxy-control"), which read as two
167
- // independent readings agreeing and made the second channel invisible: the
168
- // one thing that IS per channel, its queue depth, was the only real
169
- // difference and it was buried in a line that looked like a duplicate.
170
- //
171
- // sessionId → the channels currently open on that connection, and when it was
172
- // last reported. Channels are keyed by the channel OBJECT, not by its label:
173
- // a label is whatever the peer chose and two channels can carry the same one
174
- // (or none, where `getLabel` is missing and both fall back to "?"), and a
175
- // Map keyed on that would let one channel evict the other and then, on
176
- // closing, delete the survivor's entry. `captureStarted` rides on the same
177
- // record: both channels of one wedged connection must ask the witness once,
178
- // not once per channel.
179
- /** @type {Map<string, { channels: Map<DataChannel, string>, at: number, previous: object | null, unknown: number, captureStarted: boolean }>} */
180
- const connections = new Map();
181
-
182
- /**
183
- * What each channel of a connection is holding, right now.
184
- *
185
- * @param {Map<DataChannel, string>} channels
186
- * @returns {string} `label:NB` per channel, in the order they opened.
187
- */
188
- const queueDepths = (channels) => {
189
- const parts = [];
190
- for (const [openChannel, channelLabel] of channels) {
191
- let depth = -1;
192
- try {
193
- depth = typeof openChannel.bufferedAmount === "function" ? openChannel.bufferedAmount() : 0;
194
- } catch {
195
- depth = -1;
196
- }
197
- parts.push(`${channelLabel}:${depth}B`);
198
- }
199
- return parts.join(" ");
200
- };
201
-
202
- /**
203
- * What this connection is getting away, for whoever else needs it.
204
- *
205
- * The delivery probe judges a late probe against the queue ahead of it, and
206
- * the queue's drain time needs a rate. It is measured here already, once a
207
- * second, so it is read from here rather than measured twice.
208
- *
209
- * @param {string} sessionId
210
- * @returns {{ bytesPerSecond: number, rttMs: number } | null}
211
- */
212
- const readDelivery = (sessionId) => {
213
- const connection = connections.get(sessionId);
214
- if (!connection) {
215
- return null;
216
- }
217
- return {
218
- bytesPerSecond: connection.bytesPerSecond,
219
- rttMs: Number(connection.previous?.rtt) || 0
220
- };
221
- };
222
-
223
- /**
224
- * Update the browser-side channel byte counter for a session.
225
- *
226
- * The transport's `bytesReceived` advances on SACKs (140 B/s on a wedged
227
- * association) even though every data channel is flat — so it gives a false
228
- * "peer still sending" through every other tick (field 2026-09-06: 6 h 50 min
229
- * wedge, `flowing`/`association-stopped` alternating every 500 ms). Channel
230
- * counters are in the same `probe-echo` report and are flat on a wedge.
231
- *
232
- * @param {string} sessionId
233
- * @param {object} report - The `report` object from `probe-echo`.
234
- * @returns {void}
235
- */
236
- const noteBrowserReport = (sessionId, report) => {
237
- const connection = connections.get(sessionId);
238
- if (!connection || !report || typeof report !== "object") return;
239
- const channels = report.channels;
240
- if (!channels || typeof channels !== "object") return;
241
- let total = 0;
242
- let hasBytes = false;
243
- for (const v of Object.values(channels)) {
244
- if (v && typeof v.bytes === "number" && Number.isFinite(v.bytes)) {
245
- total += v.bytes;
246
- hasBytes = true;
247
- }
248
- }
249
- if (hasBytes) {
250
- connection.browserChannelBytes = total;
251
- }
252
- };
253
-
254
- /**
255
- * @param {string} sessionId
256
- * @param {string} tag
257
- * @param {string} label
258
- * @param {DataChannel} channel
259
- * @returns {() => void} Stops the watch.
260
- */
261
- const watchSendQueue = (sessionId, tag, label, channel) => {
262
- let lowestSinceDrain = Number.POSITIVE_INFINITY;
263
- let stuckSince = 0;
264
- let previous = null;
265
- // The peer's byte count when this queue stopped falling. What separates a
266
- // wedge from an ordinary dead connection is that the far end keeps sending
267
- // throughout — measured across the whole wedge window rather than sampled
268
- // in a one-second slice, because the browser polls every 1.5 s and plenty
269
- // of individual seconds are legitimately empty.
270
- let receivedWhenStuck = -1;
271
- // Per CHANNEL, not per connection: `proxy-control` and `proxy-fast` hold an
272
- // empty queue in health and tick every second, so a flag shared with them
273
- // would be cleared a second after the wedged channel set it and the line
274
- // would print for every second of a 54-minute episode.
275
- let wedgeSaid = false;
276
- let lastStuckLogAt = 0;
277
- let connection = connections.get(sessionId);
278
- if (!connection) {
279
- connection = {
280
- channels: new Map(),
281
- at: 0,
282
- previous: null,
283
- unknown: 0,
284
- captureStarted: false,
285
- // The accepted-byte counter and when it last moved, plus the rate it
286
- // was moving at. `wedgeIsCertain` divides the queue by that rate.
287
- rateAt: 0,
288
- sentAt: 0,
289
- sentBytes: 0,
290
- bytesPerSecond: 0,
291
- longestHealthyFlatMs: 0,
292
- // Browser-side channel bytes (sum of report.channels[].bytes). Transport's
293
- // bytesReceived advances on SACKs (140 B/s on a wedge) and gives a false
294
- // "peer still sending" every other tick — channel bytes are flat on a wedge.
295
- browserChannelBytes: 0,
296
- browserChannelBytesAtStuck: -1
297
- };
298
- connections.set(sessionId, connection);
299
- }
300
- connection.channels.set(channel, label);
301
- /** @type {ReturnType<typeof setInterval> | null} */
302
- let timer = null;
303
- let stopped = false;
304
- // Record the wire for as long as this channel is open. Held here rather
305
- // than beside `onClosed`, because `onClosed` does not always come — a peer
306
- // connection can die without it — and the watch below already ends itself
307
- // when the transport stops answering. A hold that outlives its channel
308
- // would leave tcpdump writing on an idle proxy for the life of the process.
309
- witness?.holdRing?.();
310
- /**
311
- * End this channel's watch and let go of its entry.
312
- *
313
- * @returns {void}
314
- */
315
- const stop = () => {
316
- if (stopped) {
317
- return;
318
- }
319
- stopped = true;
320
- witness?.releaseRing?.();
321
- if (timer) {
322
- clearInterval(timer);
323
- }
324
- connection.channels.delete(channel);
325
- // Only if the map still holds THIS record: a late stop, after the same
326
- // session id has been reused and a new record made for it, must not evict
327
- // the live one.
328
- if (connection.channels.size === 0 && connections.get(sessionId) === connection) {
329
- connections.delete(sessionId);
330
- // Every channel of this connection is down, so the person on it is
331
- // gone. This is the SECOND way that becomes known, and it exists
332
- // because the first does not always come: a peer connection can die
333
- // without `onClosed`, which is why this watch was written in the first
334
- // place.
335
- onConnectionGone?.(sessionId, "the transport stopped answering");
336
- }
337
- };
338
- // Independent of the queue: the transport's own counters, sampled for as
339
- // long as the channel is open. The queue was the wrong thing to watch —
340
- // field 2026-08-06, a 9.26 MB segment was accepted by the transport with
341
- // `maxBuffered=0 bufferedAtEnd=0`, reported as sent at 274 Mbit/s, and
342
- // never arrived; everything the proxy sent from that moment on was lost the
343
- // same way while requests kept coming the other direction. With nothing
344
- // queued this watcher never woke, so the one question that matters — did
345
- // those bytes leave the machine — has no answer in the log. It does now.
346
- // A connection the transport no longer knows about is gone, whatever the
347
- // channel says. `onClosed` is the ordinary way this watch ends, and it does
348
- // not always come — a peer connection can die without it, leaving the timer
349
- // and this channel's entry behind for the life of the process.
350
- //
351
- // The count is kept on the CONNECTION: exactly one channel enters the
352
- // heartbeat branch per interval, so a per-channel count would advance only
353
- // on that channel's turn and the teardown would take three heartbeats per
354
- // channel rather than three in total.
355
- timer = setInterval(() => {
356
- const sampledAt = Date.now();
357
- // Whichever channel's timer arrives first past the interval reports for
358
- // the whole connection; the others find the timestamp already moved and
359
- // skip. So the line appears once however many channels are open.
360
- if (sampledAt - connection.at >= TRANSPORT_HEARTBEAT_MS) {
361
- connection.at = sampledAt;
362
- const snapshot = getTransportSnapshot?.(sessionId) ?? null;
363
- connection.unknown = snapshot ? 0 : connection.unknown + 1;
364
- if (connection.unknown >= TRANSPORT_UNKNOWN_HEARTBEATS) {
365
- // THE SECOND DETECTOR, and it is the one that has to work: `onClosed`
366
- // does not always come — a peer connection can die without it — and
367
- // presence is the connection and nothing else, so nothing else will
368
- // ever say these people have gone. Until now this ended the watch and
369
- // left them registered for the life of the process, holding the
370
- // outputs they were watching.
371
- // Named for what it is: the watcher is handed this, it does not
372
- // hold the registry. Written as a bare `connectionGone` it was a
373
- // reference to a function of the FACTORY, which is not in scope here,
374
- // so the one detector that has to work threw a `ReferenceError`
375
- // inside its own timer instead of releasing the viewer.
376
- onConnectionGone?.(sessionId, "the transport stopped answering");
377
- stop();
378
- return;
379
- }
380
- if (snapshot) {
381
- const sent = connection.previous ? snapshot.bytesSent - connection.previous.bytesSent : null;
382
- const received = connection.previous
383
- ? snapshot.bytesReceived - connection.previous.bytesReceived
384
- : null;
385
- connection.previous = snapshot;
386
- log(
387
- `[dc-transport] ${tag} sent=${snapshot.bytesSent}` +
388
- `${sent === null ? "" : ` (+${sent})`} received=${snapshot.bytesReceived}` +
389
- `${received === null ? "" : ` (+${received})`} queued[${queueDepths(connection.channels)}] ` +
390
- `rtt=${snapshot.rtt}ms pc=${snapshot.state} ice=${snapshot.iceState} pair=${snapshot.pair}`
391
- );
392
- }
393
- }
394
- // The rate this connection accepts bytes at, and how long that counter
395
- // has stood still — both measured every second, whatever the queue is
396
- // doing, because the rate has to come from the HEALTHY stretch that
397
- // precedes a wedge. One channel updates it for the whole connection.
398
- if (sampledAt - connection.rateAt >= SEND_QUEUE_SAMPLE_MS) {
399
- connection.rateAt = sampledAt;
400
- const snapshot = getTransportSnapshot?.(sessionId) ?? null;
401
- const sentNow = Number(snapshot?.bytesSent);
402
- if (Number.isFinite(sentNow) && sentNow >= 0) {
403
- if (connection.sentAt === 0 || sentNow < connection.sentBytes) {
404
- // First reading, or the counter went backwards — a fresh peer
405
- // connection reusing this session id. Either way the old baseline
406
- // describes a transport that no longer exists, so start over
407
- // rather than measure a pause against it for ever.
408
- connection.sentBytes = sentNow;
409
- connection.sentAt = sampledAt;
410
- } else if (sentNow > connection.sentBytes) {
411
- const seconds = (sampledAt - connection.sentAt) / 1000;
412
- if (seconds > 0) {
413
- // The BEST rate this connection has shown, not the latest one.
414
- // The latest is usually the quietest: with the browser's buffer
415
- // full nothing is requested for tens of seconds and the only
416
- // traffic is the probe, a few hundred bytes a second. Dividing a
417
- // queue by that gives hours, and the wedge would never be called.
418
- const rate = (sentNow - connection.sentBytes) / seconds;
419
- if (rate > connection.bytesPerSecond) {
420
- connection.bytesPerSecond = rate;
421
- }
422
- }
423
- // How long the counter stood still before this advance. While the
424
- // queue is draining that pause was legitimate, so it is the link's
425
- // own answer to "how long may a healthy pause be".
426
- const pausedMs = sampledAt - connection.sentAt;
427
- if (stuckSince === 0 && pausedMs > connection.longestHealthyFlatMs) {
428
- connection.longestHealthyFlatMs = pausedMs;
429
- }
430
- connection.sentBytes = sentNow;
431
- connection.sentAt = sampledAt;
432
- }
433
- }
434
- }
435
- let queued = 0;
436
- try {
437
- queued = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0;
438
- } catch {
439
- return;
440
- }
441
- if (queued === 0 || queued < lowestSinceDrain) {
442
- lowestSinceDrain = queued;
443
- stuckSince = 0;
444
- previous = null;
445
- receivedWhenStuck = -1;
446
- connection.browserChannelBytesAtStuck = -1;
447
- wedgeSaid = false;
448
- // The queue moved, so whatever was called a wedge has cleared. Let a
449
- // later one be recorded too: one mistaken call must not spend the
450
- // session's only capture.
451
- connection.captureStarted = false;
452
- return;
453
- }
454
- const now = Date.now();
455
- if (stuckSince === 0) {
456
- stuckSince = now;
457
- return;
458
- }
459
- const snapshot = getTransportSnapshot?.(sessionId) ?? null;
460
- if (!snapshot) {
461
- if (now - stuckSince >= SEND_QUEUE_STUCK_MS && now - lastStuckLogAt >= 30_000) {
462
- lastStuckLogAt = now;
463
- log(`[dc] Session ${tag} "${label}": send queue stuck at ${queued}B for ` +
464
- `${Math.round((now - stuckSince) / 1000)}s — no transport to ask`);
465
- }
466
- return;
467
- }
468
- const sentDelta = previous ? snapshot.bytesSent - previous.bytesSent : null;
469
- const recvDelta = previous ? snapshot.bytesReceived - previous.bytesReceived : null;
470
- previous = snapshot;
471
- if (receivedWhenStuck < 0) {
472
- receivedWhenStuck = snapshot.bytesReceived;
473
- }
474
- if (connection.browserChannelBytesAtStuck < 0) {
475
- connection.browserChannelBytesAtStuck = connection.browserChannelBytes;
476
- }
477
- // The periodic line waits for {@link SEND_QUEUE_STUCK_MS}, because a
478
- // queue that has merely not fallen for a second is ordinary and a line a
479
- // second for it is noise. The WEDGE below does not wait for it: its own
480
- // condition already says how long this queue may legitimately take, and
481
- // on a fast link that is under a second. Holding the evidence back for a
482
- // fixed five seconds would repeat, in miniature, the mistake that left
483
- // both field captures without an onset in them.
484
- // Rate-limit to 30 s — field 2026-09-06 printed 49 295 lines (31 % of log)
485
- // for one 6 h 50 min wedge, one line per second per channel.
486
- if (now - stuckSince >= SEND_QUEUE_STUCK_MS && now - lastStuckLogAt >= 30_000) {
487
- lastStuckLogAt = now;
488
- log(
489
- `[dc] Session ${tag} "${label}": send queue stuck at ${queued}B for ` +
490
- `${Math.round((now - stuckSince) / 1000)}s — transport ` +
491
- `sent=${snapshot.bytesSent}${sentDelta === null ? "" : ` (+${sentDelta})`} ` +
492
- `received=${snapshot.bytesReceived}${recvDelta === null ? "" : ` (+${recvDelta})`} ` +
493
- `rtt=${snapshot.rtt}ms pc=${snapshot.state} ice=${snapshot.iceState} pair=${snapshot.pair}`
494
- );
495
- }
496
- // Roadmap item 11: ask for the packet-level truth the moment the wedge is
497
- // CERTAIN, not after a chosen delay. The three facts below are not
498
- // ambiguous together — the queue has not fallen, the accepted-byte
499
- // counter has not moved for longer than the queue's own drain time at
500
- // this link's own speed, and the peer is still sending. The previous
501
- // rule's flat 30 s is what left both field captures with no onset in
502
- // them. One attempt per connection — the witness applies its own
503
- // single-flight and cooldown rules after that.
504
- const flatForMs = connection.sentAt === 0 ? 0 : now - connection.sentAt;
505
- const verdict = wedgeIsCertain({
506
- queuedBytes: queued,
507
- bytesPerSecond: connection.bytesPerSecond,
508
- flatForMs,
509
- longestHealthyFlatMs: connection.longestHealthyFlatMs
510
- });
511
- const hasBrowserBytes = Number.isFinite(connection.browserChannelBytes) && connection.browserChannelBytesAtStuck >= 0;
512
- const peerStillSending = hasBrowserBytes
513
- ? connection.browserChannelBytes > connection.browserChannelBytesAtStuck
514
- : snapshot.bytesReceived > receivedWhenStuck;
515
- if (verdict.certain && peerStillSending && !wedgeSaid) {
516
- wedgeSaid = true;
517
- log(
518
- `[dc] Session ${tag} "${label}": delivery has stopped — ${queued}B queued, ` +
519
- `accepted-byte counter unmoved for ${Math.round(flatForMs / 1000)}s against the ` +
520
- `${(verdict.needMs / 1000).toFixed(1)}s this queue needs at the ` +
521
- `${(connection.bytesPerSecond / 1024).toFixed(0)} KB/s last measured here, ` +
522
- "and the peer is still sending"
523
- );
524
- }
525
- if (
526
- witness &&
527
- !connection.captureStarted &&
528
- verdict.certain &&
529
- peerStillSending
530
- ) {
531
- connection.captureStarted = true;
532
- witness.maybeCapture({
533
- sessionId,
534
- tag,
535
- label,
536
- remote: snapshot.remote ?? null,
537
- queuedBytes: queued,
538
- stuckForMs: now - stuckSince
539
- });
540
- }
541
- if (usrsctpState && verdict.certain && peerStillSending) {
542
- // Its own single-flight and cooldown, independent of the witness's —
543
- // one gdb attach per wedge is enough, and a refusal here (already
544
- // read, cooling down) costs nothing to retry on the next tick.
545
- usrsctpState.maybeRead(
546
- `send queue stuck ${queued}B, accepted-byte counter unmoved ${Math.round(flatForMs / 1000)}s`
547
- );
548
- }
549
- }, SEND_QUEUE_SAMPLE_MS);
550
-
551
- if (typeof timer.unref === "function") {
552
- timer.unref();
553
- }
554
- return stop;
555
- };
556
-
557
- return { watchSendQueue, readDelivery, noteBrowserReport };
558
- }
559
-
560
- /**
561
- * Create a handler for incoming WebRTC data channels.
562
- *
563
- * @param {DataChannelHandlerOptions} options
564
- * @returns {DataChannelHandler}
565
- */
566
- import { performance } from "node:perf_hooks";
567
- import { eventLoopDelay, resetEventLoopDelay } from "../../utils/perf.js";
568
-
569
- /**
570
- * Build one body frame: `[flags(1)][idLen(1)][requestId][payload]`.
571
- *
572
- * One allocation and one copy. The previous version made two of each — a copy
573
- * of the chunk into a `Buffer`, then a `concat` that copied it again into the
574
- * frame — which measured 75.9 ms per 13 MB segment on the field host against
575
- * 40.0 ms this way, and allocated ~600 extra buffers over a segment's 208
576
- * chunks. One copy is the floor: chunks arrive from a web stream that allocates
577
- * them itself, so there is no buffer of ours to read them into.
578
- *
579
- * @param {Buffer} idBytes - The request id, already encoded.
580
- * @param {Uint8Array | null} bytes - Payload, or nothing for the done frame.
581
- * @param {boolean} done
582
- * @returns {Buffer}
583
- */
584
- export function encodeFrame(idBytes, bytes, done) {
585
- const payloadLength = bytes?.length ?? 0;
586
- const frame = Buffer.allocUnsafe(2 + idBytes.length + payloadLength);
587
- frame[0] = done ? 1 : 0;
588
- frame[1] = idBytes.length;
589
- idBytes.copy(frame, 2);
590
- if (payloadLength > 0) {
591
- frame.set(bytes, 2 + idBytes.length);
592
- }
593
- return frame;
594
- }
595
-
596
- /**
597
- * Reshapes a body into messages of `sizeBytes` each, handing every finished one
598
- * to `sendOne`. A size of zero passes each body read through untouched, which
599
- * is what the field does today — 10 657 210 bytes over 163 messages, so 65 382
600
- * each, measured 2026-09-12.
601
- *
602
- * Only the SIZE changes: the same bytes reach the far end in the same order,
603
- * over the same channel. That is what makes a comparison between two sizes a
604
- * comparison of one thing, and it is why the wedge's dependence on the size can
605
- * be measured at all — the wedge of 2026-09-12 arrived in the middle of one
606
- * message, with 63 % of a segment on the wire and then nothing.
607
- *
608
- * @param {(bytes: Uint8Array) => void} sendOne - Given each finished message.
609
- * @param {number} sizeBytes - 0 to leave reads as they are.
610
- * @returns {{ push: (bytes: Uint8Array) => number, flush: () => number }}
611
- * Both answer how many messages they sent, so a caller counting messages
612
- * counts messages rather than body reads.
613
- */
614
- export function bodySender(sendOne, sizeBytes) {
615
- if (!(sizeBytes > 0)) {
616
- return {
617
- push(bytes) {
618
- sendOne(bytes);
619
- return 1;
620
- },
621
- flush() {
622
- return 0;
623
- }
624
- };
625
- }
626
- /** @type {Uint8Array[]} */
627
- let held = [];
628
- let heldBytes = 0;
629
- const release = () => {
630
- const message = held.length === 1 ? held[0] : Buffer.concat(held);
631
- held = [];
632
- heldBytes = 0;
633
- sendOne(message);
634
- };
635
- return {
636
- push(bytes) {
637
- let sent = 0;
638
- let offset = 0;
639
- while (offset < bytes.length) {
640
- const take = Math.min(sizeBytes - heldBytes, bytes.length - offset);
641
- held.push(bytes.subarray(offset, offset + take));
642
- heldBytes += take;
643
- offset += take;
644
- if (heldBytes === sizeBytes) {
645
- release();
646
- sent += 1;
647
- }
648
- }
649
- return sent;
650
- },
651
- flush() {
652
- if (heldBytes === 0) return 0;
653
- release();
654
- return 1;
655
- }
656
- };
657
- }
658
-
659
- export function createDataChannelHandler({
660
- proxyPort,
661
- onLog,
662
- getTransportSnapshot,
663
- // Who wants pushed subtitle cues for a file, BY NAME. A plain function
664
- // returning opaque ids: this layer never learns what a viewer is, and the
665
- // subscription it used to hold against a channel — and had to sniff
666
- // `/api/subtitles` to build — now belongs to the person and outlives the
667
- // channel, a reconnect and a deliberate rotation alike.
668
- viewersWantingCues = () => [],
669
- witness,
670
- // Reads usrsctp's own association state (services/transport/usrsctp-state.js) the
671
- // moment a wedge is declared, from either detector below. Optional: a host
672
- // without gdb simply never gets a reading, same as the witness without
673
- // tcpdump.
674
- usrsctpState,
675
- // Presence, both directions. A viewer is present because their connection
676
- // is, and gone because it went — which is a fact about the PERSON and reaches
677
- // every output they were watching at once. Before this, nothing anywhere
678
- // released a viewer when their connection closed: the only exits were the
679
- // browser's own `release` and a silence long enough to be called an absence.
680
- onViewerPresent = () => {},
681
- onViewerGone = () => {},
682
- // The size of one data-channel message carrying body bytes. Zero keeps
683
- // whatever the body read hands over, which in the field is 65 382 bytes —
684
- // 10 657 210 over 163 chunks, measured 2026-09-12. It is settable because
685
- // that day's wedge arrived in the MIDDLE of one message (63 % of a segment
686
- // on the wire, then nothing), and whether the fault depends on the size is
687
- // the one branch no capture has been able to close.
688
- sendChunkBytes = 0
689
- }) {
690
- /**
691
- * Who is on each connection, by WebRTC session id.
692
- *
693
- * One connection carries one page, and a page holds one name per film it has
694
- * open — so this is normally one id, and more than one only where a page has
695
- * opened more than one.
696
- *
697
- * @type {Map<string, Set<string>>}
698
- */
699
- const viewersOnConnection = new Map();
700
-
701
- /**
702
- * Everyone on this connection has gone, because the connection has.
703
- *
704
- * Said once per connection: a second call after the set is emptied must not
705
- * announce departures a second time, and the two detectors below — the close
706
- * event and the transport's own counters — can both fire for one death.
707
- *
708
- * @param {string} sessionId
709
- * @param {string} because
710
- * @returns {void}
711
- */
712
- function connectionGone(sessionId, because) {
713
- const viewers = viewersOnConnection.get(sessionId);
714
- viewersOnConnection.delete(sessionId);
715
- if (!viewers || viewers.size === 0) {
716
- return;
717
- }
718
- for (const consumerId of viewers) {
719
- onLog?.(`[dc] Session ${sessionId.slice(0, 8)}: viewer ${consumerId} left — ${because}`);
720
- try {
721
- onViewerGone(consumerId, because);
722
- } catch {
723
- // A viewer failing to be let go must not stop the others being let go.
724
- }
725
- }
726
- }
727
- /**
728
- * The channel each viewer is reachable on right now, by the name the far end
729
- * presented when it opened.
730
- *
731
- * The transport knows a NAME and nothing else about a viewer: what it means,
732
- * who holds it and what they are watching are somebody else's facts. Keeping
733
- * only "this name is reachable here" is what lets a subscription made once
734
- * outlive the channel it was made on — a reconnect, and a rotation done on
735
- * purpose, both just rewrite this entry.
736
- *
737
- * @type {Map<string, DataChannel>}
738
- */
739
- const channelOfViewer = new Map();
740
-
741
- /**
742
- * Forget every name that was reachable on this channel.
743
- *
744
- * @param {DataChannel} channel
745
- * @returns {void}
746
- */
747
- function forgetChannel(channel) {
748
- for (const [consumerId, on] of channelOfViewer) {
749
- if (on === channel) {
750
- channelOfViewer.delete(consumerId);
751
- }
752
- }
753
- }
754
-
755
- /**
756
- * Send new cues to every channel watching this file — the push side of
757
- * subtitles arriving as they download rather than being polled for. Cues
758
- * are tiny (kilobytes at most for a whole track), so this is one message,
759
- * not a stream.
760
- *
761
- * @param {{ sourceKey: string, fileIndex: number, trackIndex: number, cues: object[],
762
- * language: string, detectedLanguage: { code: string, name: string } | null,
763
- * cursor: number }} event
764
- * @returns {void}
765
- */
766
- function publishSubtitleCues({ sourceKey, fileIndex, trackIndex, cues, language, detectedLanguage, cursor }) {
767
- const names = viewersWantingCues(sourceKey, fileIndex);
768
- if (names.length === 0) {
769
- log(
770
- `[dc] subtitle push: ${cues.length} cue(s) for ${sourceKey.slice(0, 8)}:${fileIndex} track ${trackIndex} ` +
771
- "found nobody who wants them"
772
- );
773
- return;
774
- }
775
- const message = JSON.stringify({
776
- type: "subtitle-cues", fileIndex, trackIndex, cues, language, detectedLanguage, cursor
777
- });
778
- let sent = 0;
779
- for (const consumerId of names) {
780
- const channel = channelOfViewer.get(consumerId);
781
- if (!channel) {
782
- // Subscribed but not reachable this instant — between connections, or
783
- // rotating. Nothing is dropped: they are still subscribed, and the walk
784
- // keeps a per-viewer cursor, so what they missed comes on the next ask.
785
- continue;
786
- }
787
- try {
788
- channel.sendMessage(message);
789
- sent += 1;
790
- } catch {
791
- // Closed between the lookup and the send. The subscription belongs to
792
- // the person and stays; only this delivery is lost.
793
- }
794
- }
795
- log(
796
- `[dc] subtitle push: sent ${cues.length} cue(s) for ${sourceKey.slice(0, 8)}:${fileIndex} track ${trackIndex} ` +
797
- `to ${sent}/${names.length} viewer(s)`
798
- );
799
- }
800
-
801
- /** Request id → its ASCII bytes; see {@link requestIdBytes}. */
802
- const requestIdCache = new Map();
803
-
804
- const { watchSendQueue, readDelivery, noteBrowserReport } = makeSendQueueWatcher({
805
- log: (message) => log(message),
806
- getTransportSnapshot,
807
- witness,
808
- usrsctpState,
809
- // The watcher is where a connection's death is noticed when no close event
810
- // arrives, so it is the second door presence leaves by. Given rather than
811
- // reached for: it is a module-level function and cannot see this closure.
812
- onConnectionGone: connectionGone
813
- });
814
- // Numbered probes on every channel, and the browser's echo of what it saw.
815
- // The proxy's own counters cannot say whether bytes it handed to usrsctp were
816
- // ever put on the wire; the far end can, and it keeps answering throughout a
817
- // freeze. See services/transport/delivery-probe.js.
818
- //
819
- // Also the ONLY wedge signal that does not require a nonzero channel queue —
820
- // `wedgeIsCertain` above needs `queuedBytes > 0`, which small, infrequent
821
- // traffic never produces (confirmed 2026-08-28: the 2026-08-27 episode's
822
- // ring was never saved automatically for exactly this reason). So this is
823
- // wired to the same evidence-gathering as the queue watcher.
824
- const deliveryProbe = createDeliveryProbe({
825
- log: (message) => log(message),
826
- readDelivery,
827
- getTransportSnapshot,
828
- witness,
829
- usrsctpState
830
- });
831
-
832
- /**
833
- * @param {string} message
834
- * @returns {void}
835
- */
836
- function log(message) {
837
- if (typeof onLog === "function") {
838
- onLog(message);
839
- }
840
- }
841
-
842
- /**
843
- * Wire up the `onMessage`, `onClosed`, and `onError` handlers for a channel.
844
- *
845
- * @param {string} sessionId
846
- * @param {DataChannel} channel
847
- * @returns {void}
848
- */
849
- function handleChannel(sessionId, channel) {
850
- const tag = sessionId.slice(0, 8);
851
- const label = typeof channel.getLabel === "function" ? channel.getLabel() : "?";
852
- log(`[dc] Session ${tag}: channel open`);
853
- const stopWatchdog = watchSendQueue(sessionId, tag, label, channel);
854
- deliveryProbe.attach(sessionId, tag, label, channel);
855
-
856
- // Partial chunked-request bodies in flight on THIS channel, keyed by
857
- // requestId. Each entry buffers frames until the done frame, then runs the
858
- // assembled request through the same path as a single-message request.
859
- /** @type {Map<string, { meta: object, chunks: Buffer[], receivedBytes: number, bodyBytes: number, timer: ReturnType<typeof setTimeout> }>} */
860
- const partials = new Map();
861
-
862
- const dropPartial = (requestId) => {
863
- const entry = partials.get(requestId);
864
- if (entry) {
865
- clearTimeout(entry.timer);
866
- partials.delete(requestId);
867
- }
868
- };
869
-
870
- /**
871
- * Begin assembling a chunked request. Validates the path and size up front
872
- * so an invalid or oversized request never buffers a body.
873
- *
874
- * @param {any} message - The `request-start` control message.
875
- */
876
- const startPartialRequest = (message) => {
877
- const { requestId, method, path, query, headers, bodyBytes } = message ?? {};
878
- if (typeof requestId !== "string" || requestId.length === 0) {
879
- return;
880
- }
881
- if (!isValidRequestPath(path)) {
882
- send(channel, { type: "response-error", requestId, error: "Invalid request path." });
883
- return;
884
- }
885
- if (!Number.isInteger(bodyBytes) || bodyBytes < 0 || bodyBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
886
- send(channel, { type: "response-error", requestId, error: "Request body too large." });
887
- return;
888
- }
889
- dropPartial(requestId); // replace any stale entry with the same id
890
- const timer = setTimeout(() => {
891
- const entry = partials.get(requestId);
892
- partials.delete(requestId);
893
- log(`[dc] Session ${tag}: dropped stale partial request ${requestId.slice(0, 8)} (${entry?.receivedBytes ?? 0}B)`);
894
- }, PARTIAL_REQUEST_TTL_MS);
895
- partials.set(requestId, {
896
- meta: { requestId, method, path, query, headers },
897
- chunks: [],
898
- receivedBytes: 0,
899
- bodyBytes,
900
- timer
901
- });
902
- };
903
-
904
- /**
905
- * Handle a binary body frame for a chunked request.
906
- * Layout: [flags(1)][idLen(1)][requestId(ASCII)][payload].
907
- *
908
- * @param {Buffer} buf
909
- */
910
- const handleBodyFrame = (buf) => {
911
- if (buf.length < 2) {
912
- return;
913
- }
914
- const flags = buf[0];
915
- const idLen = buf[1];
916
- if (buf.length < 2 + idLen) {
917
- return;
918
- }
919
- const requestId = buf.toString("ascii", 2, 2 + idLen);
920
- const entry = partials.get(requestId);
921
- if (!entry) {
922
- return; // stale / already-dropped / aborted
923
- }
924
- if (flags & 2) {
925
- // Aborted by the browser — drop silently, no reply.
926
- dropPartial(requestId);
927
- return;
928
- }
929
- if (buf.length > 2 + idLen) {
930
- const payload = buf.subarray(2 + idLen);
931
- entry.chunks.push(Buffer.from(payload));
932
- entry.receivedBytes += payload.length;
933
- }
934
- if (entry.receivedBytes > entry.bodyBytes || entry.receivedBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
935
- dropPartial(requestId);
936
- send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
937
- return;
938
- }
939
- if (flags & 1) {
940
- // Done frame — assemble and execute.
941
- dropPartial(requestId);
942
- if (entry.receivedBytes !== entry.bodyBytes) {
943
- send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
944
- return;
945
- }
946
- const body = Buffer.concat(entry.chunks).toString("utf8");
947
- void handleRequest(channel, { ...entry.meta, body }, true).catch((error) => {
948
- log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
949
- });
950
- }
951
- };
952
-
953
- channel.onMessage((raw) => {
954
- // Binary messages are chunked-request body frames; the proxy otherwise
955
- // only ever receives JSON strings, so the type discriminates cleanly.
956
- if (typeof raw !== "string") {
957
- handleBodyFrame(Buffer.isBuffer(raw) ? raw : Buffer.from(raw));
958
- return;
959
- }
960
-
961
- /** @type {DataChannelRequest | { type: string, id?: string }} */
962
- let message;
963
- try {
964
- message = JSON.parse(raw);
965
- } catch {
966
- return;
967
- }
968
-
969
- if (message.type === "request") {
970
- void handleRequest(channel, message).catch((error) => {
971
- log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
972
- });
973
- return;
974
- }
975
-
976
- if (message.type === "request-start") {
977
- startPartialRequest(message);
978
- return;
979
- }
980
-
981
- if (message.type === "ping") {
982
- send(channel, { type: "pong", id: message.id });
983
- return;
984
- }
985
-
986
- // WHO is on this connection. Sent once when the page opens its control
987
- // channel, and it is what lets a closed connection say that a PERSON has
988
- // gone rather than that one output lost a request.
989
- //
990
- // The name is the page's, not this connection's: it is minted once per
991
- // film opened in the tab and survives the reconnect ladder swapping the
992
- // transport underneath a running player. A name minted here would make
993
- // one person two the first time that happened, each with their own
994
- // position.
995
- if (message.type === "viewer" && typeof message.consumerId === "string" && message.consumerId) {
996
- const known = viewersOnConnection.get(sessionId) ?? new Set();
997
- const isNew = !known.has(message.consumerId);
998
- known.add(message.consumerId);
999
- viewersOnConnection.set(sessionId, known);
1000
- channelOfViewer.set(message.consumerId, channel);
1001
- if (isNew) {
1002
- log(`[dc] Session ${tag}: viewer ${message.consumerId} is on this connection`);
1003
- }
1004
- onViewerPresent(message.consumerId);
1005
- return;
1006
- }
1007
-
1008
- // The far end's answer to the numbered probes, plus what it can see of
1009
- // its own receiving. It travels browser to proxy, the direction that goes
1010
- // on working through a freeze, so it arrives when nothing else does.
1011
- if (message.type === "probe-echo") {
1012
- deliveryProbe.noteEcho(sessionId, message);
1013
- noteBrowserReport(sessionId, message.report);
1014
- if (message.report && typeof message.report === "object") {
1015
- const report = message.report;
1016
- const channels = report.channels && typeof report.channels === "object"
1017
- ? Object.entries(report.channels)
1018
- .map(([name, counters]) => `${name}=${counters?.messages ?? "?"}msg/${counters?.bytes ?? "?"}B`)
1019
- .join(" ")
1020
- : "";
1021
- log(
1022
- `[dc-far] ${tag} visibility=${report.visibility ?? "?"} ` +
1023
- `loopLag=${report.loopLagMs ?? "?"}ms handler=${report.handlerMaxMs ?? "?"}ms ` +
1024
- `transportIn=${report.transportBytesReceived ?? "?"} ${channels} ` +
1025
- `pending=${report.pending ?? "?"} at=${new Date().toISOString()}`
1026
- );
1027
- }
1028
- return;
1029
- }
1030
- });
1031
-
1032
- channel.onClosed(() => {
1033
- stopWatchdog();
1034
- deliveryProbe.detach(sessionId, channel);
1035
- for (const entry of partials.values()) {
1036
- clearTimeout(entry.timer);
1037
- }
1038
- partials.clear();
1039
- forgetChannel(channel);
1040
- log(`[dc] Session ${tag}: channel closed`);
1041
- // The ordinary way a viewer leaves, and the only one that is immediate.
1042
- // Everything else — a silence long enough to be called an absence, the
1043
- // transport's own counters going quiet — is a backstop for this event
1044
- // failing to arrive.
1045
- connectionGone(sessionId, "the connection closed");
1046
- });
1047
-
1048
- channel.onError((err) => {
1049
- log(`[dc] Session ${tag}: channel error: ${err}`);
1050
- });
1051
- }
1052
-
1053
- /**
1054
- * Fetch a resource from the local proxy HTTP server and stream the response
1055
- * back to the browser over the data channel.
1056
- *
1057
- * The `Host` header is rewritten to `127.0.0.1:{proxyPort}` so that Fastify
1058
- * routes the request correctly regardless of what the browser sent.
1059
- *
1060
- * @param {DataChannel} channel
1061
- * @param {DataChannelRequest} req
1062
- * @returns {Promise<void>}
1063
- */
1064
- async function handleRequest(channel, req, viaChunks = false) {
1065
- const { requestId, method, path, query, headers: forwardedHeaders, body } = req;
1066
-
1067
- // Reject paths that are not absolute, contain traversal sequences, or
1068
- // do not start with a known proxy route prefix. All valid browser-side
1069
- // requests use /api/*, /stream, /transcode/*, /health, or /healthz.
1070
- if (!isValidRequestPath(path)) {
1071
- send(channel, { type: "response-error", requestId, error: "Invalid request path." });
1072
- return;
1073
- }
1074
-
1075
-
1076
- const queryInfo = query ? `?${query}` : "";
1077
- const bodyInfo =
1078
- body != null && typeof body === "string" && body.length > 0
1079
- ? ` body=${body.length} bytes${viaChunks ? " (chunked)" : ""}`
1080
- : "";
1081
- log(`[dc] ${method} ${path}${queryInfo}${bodyInfo}`);
1082
-
1083
- const targetUrl = `http://127.0.0.1:${proxyPort}${path}${query ? `?${query}` : ""}`;
1084
- const requestHeaders = { ...(forwardedHeaders ?? {}), host: `127.0.0.1:${proxyPort}` };
1085
-
1086
- let response;
1087
- // [net-debug] TEMPORARY: time spent in the local fetch (waiting for the
1088
- // route to return a response — e.g. long-polling until an HLS segment is
1089
- // finalized by ffmpeg) vs. the body transfer over the data channel.
1090
- const fetchStartedAt = Date.now();
1091
- try {
1092
- response = await fetch(targetUrl, {
1093
- method,
1094
- headers: requestHeaders,
1095
- body: body != null ? body : undefined,
1096
- redirect: "manual"
1097
- });
1098
- } catch (fetchError) {
1099
- log(`[dc] ${method} ${path}${queryInfo} → error: ${fetchError?.message ?? String(fetchError)}`);
1100
- send(channel, { type: "response-error", requestId, error: fetchError?.message ?? String(fetchError) });
1101
- return;
1102
- }
1103
-
1104
- if (response.status !== 200 && response.status !== 206) {
1105
- log(`[dc] ${method} ${path}${queryInfo} → ${response.status}`);
1106
- }
1107
-
1108
- /** @type {Record<string, string>} */
1109
- const responseHeaders = {};
1110
- for (const [name, value] of response.headers.entries()) {
1111
- responseHeaders[name] = value;
1112
- }
1113
-
1114
- send(channel, { type: "response-start", requestId, status: response.status, headers: responseHeaders });
1115
-
1116
- if (!response.body) {
1117
- sendChunk(channel, requestId, null, true);
1118
- return;
1119
- }
1120
-
1121
- try {
1122
- const reader = response.body.getReader();
1123
- // [net-debug] TEMPORARY: measure transfer size/time and channel buffering.
1124
- // fetchMs = time waiting for the route (incl. ffmpeg segment finalization).
1125
- // ttfbMs = time from body-read start to the first chunk with data (loopback).
1126
- // sendMs = total body read+send duration over the data channel.
1127
- const fetchMs = Date.now() - fetchStartedAt;
1128
- const sendStartedAt = Date.now();
1129
- let firstByteMs = -1;
1130
- let chunks = 0;
1131
- let totalBytes = 0;
1132
- let maxBuffered = 0;
1133
- // Attribute the transfer to the step that actually consumes the time.
1134
- // Without this split a slow transfer is indistinguishable between "the
1135
- // source is slow", "the channel is slow" and "the event loop is blocked",
1136
- // which is exactly the argument a field seek left unresolved.
1137
- let readMs = 0;
1138
- let sendMs2 = 0;
1139
- let drainMs = 0;
1140
- const body = bodySender((bytes) => sendChunk(channel, requestId, bytes, false), sendChunkBytes);
1141
- resetEventLoopDelay();
1142
- while (true) {
1143
- const readStartedAt = performance.now();
1144
- const { done, value } = await reader.read();
1145
- readMs += performance.now() - readStartedAt;
1146
- if (done) {
1147
- chunks += body.flush();
1148
- sendChunk(channel, requestId, null, true);
1149
- const elapsedMs = Date.now() - sendStartedAt;
1150
- let bufferedNow = 0;
1151
- try { bufferedNow = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0; } catch { /* ignore */ }
1152
- const loop = eventLoopDelay();
1153
- const mbps = elapsedMs > 0 ? (totalBytes * 8) / (elapsedMs * 1000) : 0;
1154
- log(
1155
- `[net-debug] sent ${path}${queryInfo} bytes=${totalBytes} fetchMs=${fetchMs} ` +
1156
- `ttfbMs=${firstByteMs} sendMs=${elapsedMs} chunks=${chunks} ` +
1157
- // The size of one message, so a reading can be attributed to the
1158
- // size it was taken at rather than to the run it came from.
1159
- `msgBytes=${sendChunkBytes > 0 ? sendChunkBytes : "asread"} ` +
1160
- `maxBuffered=${maxBuffered} bufferedAtEnd=${bufferedNow} ` +
1161
- // Where the time went: reading the body from the local route,
1162
- // handing chunks to the channel, or waiting for its queue. Plus
1163
- // the event-loop delay over the same window — a large max here
1164
- // means the transfer was blocked by synchronous work, not by the
1165
- // network, and the three figures above will all look inflated.
1166
- `readMs=${readMs.toFixed(0)} chanMs=${sendMs2.toFixed(0)} drainMs=${drainMs.toFixed(0)} ` +
1167
- `loopMean=${loop.meanMs.toFixed(1)} loopP99=${loop.p99Ms.toFixed(1)} loopMax=${loop.maxMs.toFixed(1)} ` +
1168
- `rate=${mbps.toFixed(1)}Mbps`
1169
- );
1170
- break;
1171
- }
1172
- if (firstByteMs < 0) firstByteMs = Date.now() - sendStartedAt;
1173
- totalBytes += value.length;
1174
- try {
1175
- const b = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0;
1176
- if (b > maxBuffered) maxBuffered = b;
1177
- } catch { /* ignore */ }
1178
- const sendStepAt = performance.now();
1179
- chunks += body.push(value);
1180
- sendMs2 += performance.now() - sendStepAt;
1181
- // Backpressure: do not keep queuing chunks once the channel's outgoing
1182
- // buffer is large — wait for it to drain. Prevents the SCTP send buffer
1183
- // from ballooning, which stalls throughput.
1184
- const drainStepAt = performance.now();
1185
- await waitForBufferDrain(channel);
1186
- drainMs += performance.now() - drainStepAt;
1187
- }
1188
- } catch {
1189
- sendChunk(channel, requestId, null, true);
1190
- }
1191
- }
1192
-
1193
- /**
1194
- * Send a response body frame as a BINARY data-channel message.
1195
- * Layout: [flags(1)][idLen(1)][requestId(ASCII)][payload].
1196
- *
1197
- * @param {DataChannel} channel
1198
- * @param {string} requestId
1199
- * @param {Uint8Array | null} bytes - Body bytes, or null/empty for the done frame.
1200
- * @param {boolean} done
1201
- * @returns {void}
1202
- */
1203
- /**
1204
- * The request id as bytes, prepared once per request rather than per chunk.
1205
- *
1206
- * A segment is a couple of hundred chunks, and each one was re-encoding the
1207
- * same 32-character string. The map is bounded because request ids are
1208
- * short-lived and unbounded in number — dropping the whole cache when it
1209
- * grows costs one re-encode per live request and cannot leak.
1210
- *
1211
- * @param {string} requestId
1212
- * @returns {Buffer}
1213
- */
1214
- function requestIdBytes(requestId) {
1215
- let bytes = requestIdCache.get(requestId);
1216
- if (!bytes) {
1217
- if (requestIdCache.size > 64) {
1218
- requestIdCache.clear();
1219
- }
1220
- bytes = Buffer.from(requestId, "ascii");
1221
- requestIdCache.set(requestId, bytes);
1222
- }
1223
- return bytes;
1224
- }
1225
-
1226
- function sendChunk(channel, requestId, bytes, done) {
1227
- try {
1228
- channel.sendMessageBinary(encodeFrame(requestIdBytes(requestId), bytes, done));
1229
- } catch {
1230
- // Channel closed between check and send — safe to ignore.
1231
- }
1232
- }
1233
-
1234
- /**
1235
- * Resolve once the channel's outgoing buffer has drained below the low-water
1236
- * mark. No-op (resolves immediately) when the buffer is already small or the
1237
- * channel does not expose buffer APIs. The previous implementation resolved
1238
- * after {@link DC_BUFFER_DRAIN_TIMEOUT_MS} even though the buffer was still
1239
- * high, so the send loop kept queueing into a wedged channel and the queue
1240
- * grew to 399 MB (field 2026-09-06). This version waits until the buffer
1241
- * actually drains, polling as a fallback for a missed low-water event, and
1242
- * never resolves while the channel is still holding bytes above the low-water
1243
- * mark.
1244
- *
1245
- * @param {DataChannel} channel
1246
- * @returns {Promise<void>}
1247
- */
1248
- function waitForBufferDrain(channel) {
1249
- return new Promise((resolve) => {
1250
- try {
1251
- if (typeof channel.bufferedAmount !== "function" || channel.bufferedAmount() <= DC_BUFFER_HIGH_WATER) {
1252
- resolve();
1253
- return;
1254
- }
1255
- let poll = null;
1256
- let settled = false;
1257
- const done = () => {
1258
- if (settled) return;
1259
- settled = true;
1260
- if (poll) clearInterval(poll);
1261
- try { channel.onBufferedAmountLow(() => {}); } catch {}
1262
- resolve();
1263
- };
1264
- channel.setBufferedAmountLowThreshold(DC_BUFFER_LOW_WATER);
1265
- channel.onBufferedAmountLow(done);
1266
- // Poll as a fallback for a missed low-water event — the previous
1267
- // 5 s timeout resolved while the buffer was still high, which is the
1268
- // defect. Polling waits until the condition is actually met.
1269
- poll = setInterval(() => {
1270
- try {
1271
- if (channel.bufferedAmount() <= DC_BUFFER_LOW_WATER) {
1272
- done();
1273
- }
1274
- } catch {
1275
- done();
1276
- }
1277
- }, 50);
1278
- if (typeof poll.unref === "function") poll.unref();
1279
- // Guard against a race where the buffer drained between the check above
1280
- // and registering the callback (the low-water event would never fire).
1281
- if (channel.bufferedAmount() <= DC_BUFFER_LOW_WATER) {
1282
- done();
1283
- }
1284
- } catch {
1285
- resolve();
1286
- }
1287
- });
1288
- }
1289
-
1290
- /**
1291
- * Serialise `message` to JSON and send it over the data channel.
1292
- * Errors are silently swallowed — the channel may have closed between
1293
- * the open check and the actual send.
1294
- *
1295
- * @param {DataChannel} channel
1296
- * @param {object} message
1297
- * @returns {void}
1298
- */
1299
- function send(channel, message) {
1300
- try {
1301
- channel.sendMessage(JSON.stringify(message));
1302
- } catch {
1303
- // Channel closed between check and send — safe to ignore.
1304
- }
1305
- }
1306
-
1307
- return { handleChannel, publishSubtitleCues };
1308
- }
1309
-
1310
- /**
1311
- * Allowed path prefixes for data-channel requests.
1312
- * Only the known proxy API and streaming routes are accepted.
1313
- */
1314
- const PATH_ALLOWLIST_RE = /^(?:\/api\/|\/stream(?:$|\?)|\/?transcode\/|\/health(?:z)?(?:$|\?))/;
1315
-
1316
- /**
1317
- * True when `path` is an absolute, traversal-free path on a known proxy route.
1318
- * Shared by the single-message and chunked request entry points.
1319
- *
1320
- * @param {unknown} path
1321
- * @returns {boolean}
1322
- */
1323
- function isValidRequestPath(path) {
1324
- return (
1325
- typeof path === "string" &&
1326
- path.startsWith("/") &&
1327
- !path.includes("..") &&
1328
- PATH_ALLOWLIST_RE.test(path)
1329
- );
1330
- }
1331
-
1332
- /** Max assembled size of a chunked request body (guards proxy memory). */
1333
- const PROXY_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024;
1334
- /** Drop an incomplete chunked body if no further frame arrives within this window. */
1335
- const PARTIAL_REQUEST_TTL_MS = 60_000;
1336
-
1337
- /** Pause sending body chunks once the channel buffer exceeds this many bytes. */
1338
- // How often the send queue is sampled, and how long it must fail to fall
1339
- // before the transport is asked what it is doing. Five seconds is far longer
1340
- // than any healthy burst drains in — measured, a 6-11 MB segment leaves in
1341
- // well under a second on the LAN — and short enough that a stuck channel is
1342
- // named while the viewer is still looking at it.
1343
- const SEND_QUEUE_SAMPLE_MS = 1_000;
1344
- // How often the transport's own counters are written to the log, whatever the
1345
- // send queue is doing. Frequent enough to place a loss within a few seconds,
1346
- // sparse enough that a two-hour film costs a few hundred lines.
1347
- const TRANSPORT_HEARTBEAT_MS = 5_000;
1348
-
1349
- // How many heartbeats in a row may find no transport for this session before
1350
- // the watch gives up. Several rather than one, so a momentary gap in the
1351
- // registry does not end a healthy watch.
1352
- const TRANSPORT_UNKNOWN_HEARTBEATS = 3;
1353
- const SEND_QUEUE_STUCK_MS = 5_000;
1354
- const DC_BUFFER_HIGH_WATER = 8 * 1024 * 1024;
1355
- /** Resume sending once the channel buffer drains to this many bytes. */
1356
- const DC_BUFFER_LOW_WATER = 1 * 1024 * 1024;
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
+ * { type: "probe-echo", seen: { <label>: seq }, report }
16
+ * ```
17
+ *
18
+ * Proxy → Browser
19
+ * ```
20
+ * { type: "probe", seq, sentAt } (JSON string)
21
+ * { type: "response-start", requestId, status, headers } (JSON string)
22
+ * { type: "response-error", requestId, error: string } (JSON string)
23
+ * { type: "pong", id } (JSON string)
24
+ * { type: "subtitle-cues", fileIndex, trackIndex, cues, language, cursor } (JSON string)
25
+ * ```
26
+ * The last one is unsolicited — sent the moment new cues are read from a
27
+ * file's already-downloaded pieces, to whichever channel last asked for that
28
+ * file's subtitles over `/api/subtitles`. Not a response to any `requestId`.
29
+ *
30
+ * Response bodies are sent as BINARY data-channel messages (not JSON), to
31
+ * avoid the ~33% base64 overhead and the JSON encode/decode cost. Each binary
32
+ * frame is laid out as:
33
+ * ```
34
+ * byte 0 flags (bit 0: done)
35
+ * byte 1 idLen (length of the requestId in bytes)
36
+ * bytes 2..2+N requestId (ASCII)
37
+ * bytes 2+N.. payload (raw body bytes; empty on the final done frame)
38
+ * ```
39
+ * Control messages stay JSON strings so the browser can distinguish them from
40
+ * body frames by message type (string vs ArrayBuffer).
41
+ *
42
+ * The protocol mirrors the tunnel relay protocol so both transports share
43
+ * the same mental model and the same browser-side `WebRtcProxy` implementation.
44
+ */
45
+
46
+ /** @import { DataChannel } from 'node-datachannel' */
47
+
48
+ import { createDeliveryProbe, PROBE_INTERVAL_MS } from "./delivery-probe.js";
49
+
50
+ /**
51
+ * Configuration for the data channel handler.
52
+ *
53
+ * @typedef {Object} DataChannelHandlerOptions
54
+ * @property {number} proxyPort
55
+ * Local port the proxy's Fastify HTTP server is listening on.
56
+ * Incoming requests are forwarded to `http://127.0.0.1:{proxyPort}`.
57
+ * @property {(message: string) => void} [onLog]
58
+ * Optional log sink.
59
+ * @property {{ maybeCapture: (trigger: {
60
+ * sessionId: string, tag: string, label: string,
61
+ * remote: { address: string, port: number } | null,
62
+ * queuedBytes: number, stuckForMs: number
63
+ * }) => boolean }} [witness]
64
+ * The packet witness (services/transport/packet-witness.js). When {@link wedgeIsCertain}
65
+ * says delivery has stopped, the watcher hands it the transport snapshot's
66
+ * remote endpoint: the ring's history is kept and a tail capture records what
67
+ * the wire actually does. Optional; absent means no captures are taken.
68
+ */
69
+
70
+ /**
71
+ * An incoming request message received over the data channel.
72
+ *
73
+ * @typedef {Object} DataChannelRequest
74
+ * @property {string} requestId
75
+ * @property {string} method - HTTP method (GET, POST, …).
76
+ * @property {string} path - Request path (e.g. "/api/sources").
77
+ * @property {string} query - Raw query string without the leading "?".
78
+ * @property {Record<string, string>} headers - Headers to forward.
79
+ * @property {string | null} body - Request body string, or null.
80
+ */
81
+
82
+ /**
83
+ * The object returned by {@link createDataChannelHandler}.
84
+ *
85
+ * @typedef {Object} DataChannelHandler
86
+ * @property {(sessionId: string, channel: DataChannel) => void} handleChannel
87
+ * Wire message handlers onto a freshly opened data channel.
88
+ */
89
+
90
+ /**
91
+ * How long a wedge must hold before the packet witness is asked for evidence.
92
+ *
93
+ * Derived per connection rather than chosen, because a chosen number is what
94
+ * cost the two field captures their onset: the previous rule waited a flat 30 s
95
+ * and the recording therefore began half a minute after the interesting part.
96
+ *
97
+ * Three quantities, all measured on this connection:
98
+ *
99
+ * the queue's own drain time — `queuedBytes / bytesPerSecond`, how long a
100
+ * healthy channel would need to clear what is sitting in it, at the best rate
101
+ * this very connection has been seen to move bytes at;
102
+ *
103
+ * the longest this connection has EVER paused while healthy — an ordinary
104
+ * retransmission timeout stops the accepted-byte counter dead for as long as
105
+ * it lasts, because a full send buffer accepts nothing, and a link with loss
106
+ * does that routinely. The longest such pause already observed here is what
107
+ * the link's own behaviour says a legitimate pause looks like;
108
+ *
109
+ * the interval at which we offer bytes at all — the delivery probe hands
110
+ * every channel a message every {@linkcode PROBE_INTERVAL_MS}, so in health
111
+ * the accepted-byte counter cannot stand still for longer than that.
112
+ *
113
+ * A wedge is certain once ALL of them have passed with the counter unmoved.
114
+ * Without a rate there is nothing to divide by, and the function says so
115
+ * instead of guessing.
116
+ *
117
+ * @param {{ queuedBytes: number, bytesPerSecond: number, flatForMs: number, longestHealthyFlatMs?: number }} state
118
+ * @returns {{ certain: boolean, needMs: number | null }}
119
+ */
120
+ export function wedgeIsCertain({ queuedBytes, bytesPerSecond, flatForMs, longestHealthyFlatMs = 0 }) {
121
+ if (!(bytesPerSecond > 0)) {
122
+ return { certain: false, needMs: null };
123
+ }
124
+ const drainMs = (Math.max(queuedBytes, 0) / bytesPerSecond) * 1000;
125
+ const needMs = Math.max(drainMs, longestHealthyFlatMs, PROBE_INTERVAL_MS);
126
+ return { certain: flatForMs >= needMs, needMs };
127
+ }
128
+
129
+ /**
130
+ * Watch one channel's send queue and, when it stops draining, say WHY.
131
+ *
132
+ * A channel that is open, keeps accepting requests and delivers nothing was
133
+ * seen in the field 2026-08-06: the queue grew from 214 049 to 239 731 bytes in
134
+ * fourteen seconds and never fell, while every layer above reported success —
135
+ * the route answered in 15 ms, the handler sent 378 bytes, the channel was
136
+ * open. The viewer sat in front of a spinner for eleven minutes.
137
+ *
138
+ * `bufferedAmount` alone cannot say why: it only proves the bytes are still
139
+ * OURS. The transport counters can, and this is the table the snapshot is read
140
+ * against — written down in advance so the answer is a reading, not an opinion:
141
+ *
142
+ * bytesSent rising, queue rising → packets leave, nothing acknowledges
143
+ * them: the return path is broken.
144
+ * bytesSent flat, queue rising → SCTP is not transmitting: the peer's
145
+ * receive window is shut or congestion
146
+ * control has collapsed.
147
+ * bytesReceived rising either way → the peer is alive and its packets do
148
+ * reach us; the failure is one-way.
149
+ * both flat → nothing crosses at all.
150
+ *
151
+ * Sampled every second; reported only once the queue has failed to fall for
152
+ * {@link SEND_QUEUE_STUCK_MS}, then every second while it lasts, so the trend
153
+ * of every counter is in the log rather than one snapshot of it.
154
+ *
155
+ * @param {string} sessionId
156
+ * @param {string} tag
157
+ * @param {string} label
158
+ * @param {DataChannel} channel
159
+ * @returns {() => void} Stops the watch.
160
+ */
161
+ function makeSendQueueWatcher({ log, getTransportSnapshot, witness, usrsctpState, onConnectionGone }) {
162
+ // Every channel of one connection reads the SAME transport counters — the
163
+ // snapshot describes the peer connection, not the channel — so the heartbeat
164
+ // belongs to the connection and is printed once for it. Printed per channel
165
+ // it produced two byte-for-byte identical lines (measured 2026-08-14:
166
+ // `sent=5153491` under both "proxy" and "proxy-control"), which read as two
167
+ // independent readings agreeing and made the second channel invisible: the
168
+ // one thing that IS per channel, its queue depth, was the only real
169
+ // difference and it was buried in a line that looked like a duplicate.
170
+ //
171
+ // sessionId → the channels currently open on that connection, and when it was
172
+ // last reported. Channels are keyed by the channel OBJECT, not by its label:
173
+ // a label is whatever the peer chose and two channels can carry the same one
174
+ // (or none, where `getLabel` is missing and both fall back to "?"), and a
175
+ // Map keyed on that would let one channel evict the other and then, on
176
+ // closing, delete the survivor's entry. `captureStarted` rides on the same
177
+ // record: both channels of one wedged connection must ask the witness once,
178
+ // not once per channel.
179
+ /** @type {Map<string, { channels: Map<DataChannel, string>, at: number, previous: object | null, unknown: number, captureStarted: boolean }>} */
180
+ const connections = new Map();
181
+
182
+ /**
183
+ * What each channel of a connection is holding, right now.
184
+ *
185
+ * @param {Map<DataChannel, string>} channels
186
+ * @returns {string} `label:NB` per channel, in the order they opened.
187
+ */
188
+ const queueDepths = (channels) => {
189
+ const parts = [];
190
+ for (const [openChannel, channelLabel] of channels) {
191
+ let depth = -1;
192
+ try {
193
+ depth = typeof openChannel.bufferedAmount === "function" ? openChannel.bufferedAmount() : 0;
194
+ } catch {
195
+ depth = -1;
196
+ }
197
+ parts.push(`${channelLabel}:${depth}B`);
198
+ }
199
+ return parts.join(" ");
200
+ };
201
+
202
+ /**
203
+ * What this connection is getting away, for whoever else needs it.
204
+ *
205
+ * The delivery probe judges a late probe against the queue ahead of it, and
206
+ * the queue's drain time needs a rate. It is measured here already, once a
207
+ * second, so it is read from here rather than measured twice.
208
+ *
209
+ * @param {string} sessionId
210
+ * @returns {{ bytesPerSecond: number, rttMs: number } | null}
211
+ */
212
+ const readDelivery = (sessionId) => {
213
+ const connection = connections.get(sessionId);
214
+ if (!connection) {
215
+ return null;
216
+ }
217
+ return {
218
+ bytesPerSecond: connection.bytesPerSecond,
219
+ rttMs: Number(connection.previous?.rtt) || 0
220
+ };
221
+ };
222
+
223
+ /**
224
+ * Update the browser-side channel byte counter for a session.
225
+ *
226
+ * The transport's `bytesReceived` advances on SACKs (140 B/s on a wedged
227
+ * association) even though every data channel is flat — so it gives a false
228
+ * "peer still sending" through every other tick (field 2026-09-06: 6 h 50 min
229
+ * wedge, `flowing`/`association-stopped` alternating every 500 ms). Channel
230
+ * counters are in the same `probe-echo` report and are flat on a wedge.
231
+ *
232
+ * @param {string} sessionId
233
+ * @param {object} report - The `report` object from `probe-echo`.
234
+ * @returns {void}
235
+ */
236
+ const noteBrowserReport = (sessionId, report) => {
237
+ const connection = connections.get(sessionId);
238
+ if (!connection || !report || typeof report !== "object") return;
239
+ const channels = report.channels;
240
+ if (!channels || typeof channels !== "object") return;
241
+ let total = 0;
242
+ let hasBytes = false;
243
+ for (const v of Object.values(channels)) {
244
+ if (v && typeof v.bytes === "number" && Number.isFinite(v.bytes)) {
245
+ total += v.bytes;
246
+ hasBytes = true;
247
+ }
248
+ }
249
+ if (hasBytes) {
250
+ connection.browserChannelBytes = total;
251
+ }
252
+ };
253
+
254
+ /**
255
+ * @param {string} sessionId
256
+ * @param {string} tag
257
+ * @param {string} label
258
+ * @param {DataChannel} channel
259
+ * @returns {() => void} Stops the watch.
260
+ */
261
+ const watchSendQueue = (sessionId, tag, label, channel) => {
262
+ let lowestSinceDrain = Number.POSITIVE_INFINITY;
263
+ let stuckSince = 0;
264
+ let previous = null;
265
+ // The peer's byte count when this queue stopped falling. What separates a
266
+ // wedge from an ordinary dead connection is that the far end keeps sending
267
+ // throughout — measured across the whole wedge window rather than sampled
268
+ // in a one-second slice, because the browser polls every 1.5 s and plenty
269
+ // of individual seconds are legitimately empty.
270
+ let receivedWhenStuck = -1;
271
+ // Per CHANNEL, not per connection: `proxy-control` and `proxy-fast` hold an
272
+ // empty queue in health and tick every second, so a flag shared with them
273
+ // would be cleared a second after the wedged channel set it and the line
274
+ // would print for every second of a 54-minute episode.
275
+ let wedgeSaid = false;
276
+ let lastStuckLogAt = 0;
277
+ let connection = connections.get(sessionId);
278
+ if (!connection) {
279
+ connection = {
280
+ channels: new Map(),
281
+ at: 0,
282
+ previous: null,
283
+ unknown: 0,
284
+ captureStarted: false,
285
+ // The accepted-byte counter and when it last moved, plus the rate it
286
+ // was moving at. `wedgeIsCertain` divides the queue by that rate.
287
+ rateAt: 0,
288
+ sentAt: 0,
289
+ sentBytes: 0,
290
+ bytesPerSecond: 0,
291
+ longestHealthyFlatMs: 0,
292
+ // Browser-side channel bytes (sum of report.channels[].bytes). Transport's
293
+ // bytesReceived advances on SACKs (140 B/s on a wedge) and gives a false
294
+ // "peer still sending" every other tick — channel bytes are flat on a wedge.
295
+ browserChannelBytes: 0,
296
+ browserChannelBytesAtStuck: -1
297
+ };
298
+ connections.set(sessionId, connection);
299
+ }
300
+ connection.channels.set(channel, label);
301
+ /** @type {ReturnType<typeof setInterval> | null} */
302
+ let timer = null;
303
+ let stopped = false;
304
+ // Record the wire for as long as this channel is open. Held here rather
305
+ // than beside `onClosed`, because `onClosed` does not always come — a peer
306
+ // connection can die without it — and the watch below already ends itself
307
+ // when the transport stops answering. A hold that outlives its channel
308
+ // would leave tcpdump writing on an idle proxy for the life of the process.
309
+ witness?.holdRing?.();
310
+ /**
311
+ * End this channel's watch and let go of its entry.
312
+ *
313
+ * @returns {void}
314
+ */
315
+ const stop = (because = "the transport stopped answering") => {
316
+ if (stopped) {
317
+ return;
318
+ }
319
+ stopped = true;
320
+ witness?.releaseRing?.();
321
+ if (timer) {
322
+ clearInterval(timer);
323
+ }
324
+ connection.channels.delete(channel);
325
+ // Only if the map still holds THIS record: a late stop, after the same
326
+ // session id has been reused and a new record made for it, must not evict
327
+ // the live one.
328
+ if (connection.channels.size === 0 && connections.get(sessionId) === connection) {
329
+ connections.delete(sessionId);
330
+ // Every channel of this connection is down, so the person on it is
331
+ // gone. This is the SECOND way that becomes known, and it exists
332
+ // because the first does not always come: a peer connection can die
333
+ // without `onClosed`, which is why this watch was written in the first
334
+ // place.
335
+ onConnectionGone?.(sessionId, because);
336
+ }
337
+ };
338
+ // Independent of the queue: the transport's own counters, sampled for as
339
+ // long as the channel is open. The queue was the wrong thing to watch —
340
+ // field 2026-08-06, a 9.26 MB segment was accepted by the transport with
341
+ // `maxBuffered=0 bufferedAtEnd=0`, reported as sent at 274 Mbit/s, and
342
+ // never arrived; everything the proxy sent from that moment on was lost the
343
+ // same way while requests kept coming the other direction. With nothing
344
+ // queued this watcher never woke, so the one question that matters — did
345
+ // those bytes leave the machine — has no answer in the log. It does now.
346
+ // A connection the transport no longer knows about is gone, whatever the
347
+ // channel says. `onClosed` is the ordinary way this watch ends, and it does
348
+ // not always come — a peer connection can die without it, leaving the timer
349
+ // and this channel's entry behind for the life of the process.
350
+ //
351
+ // The count is kept on the CONNECTION: exactly one channel enters the
352
+ // heartbeat branch per interval, so a per-channel count would advance only
353
+ // on that channel's turn and the teardown would take three heartbeats per
354
+ // channel rather than three in total.
355
+ timer = setInterval(() => {
356
+ const sampledAt = Date.now();
357
+ // Whichever channel's timer arrives first past the interval reports for
358
+ // the whole connection; the others find the timestamp already moved and
359
+ // skip. So the line appears once however many channels are open.
360
+ if (sampledAt - connection.at >= TRANSPORT_HEARTBEAT_MS) {
361
+ connection.at = sampledAt;
362
+ const snapshot = getTransportSnapshot?.(sessionId) ?? null;
363
+ connection.unknown = snapshot ? 0 : connection.unknown + 1;
364
+ if (connection.unknown >= TRANSPORT_UNKNOWN_HEARTBEATS) {
365
+ // THE SECOND DETECTOR, and it is the one that has to work: `onClosed`
366
+ // does not always come — a peer connection can die without it — and
367
+ // presence is the connection and nothing else, so nothing else will
368
+ // ever say these people have gone. Until now this ended the watch and
369
+ // left them registered for the life of the process, holding the
370
+ // outputs they were watching.
371
+ // Named for what it is: the watcher is handed this, it does not
372
+ // hold the registry. Written as a bare `connectionGone` it was a
373
+ // reference to a function of the FACTORY, which is not in scope here,
374
+ // so the one detector that has to work threw a `ReferenceError`
375
+ // inside its own timer instead of releasing the viewer.
376
+ onConnectionGone?.(sessionId, "the transport stopped answering");
377
+ stop();
378
+ return;
379
+ }
380
+ if (snapshot) {
381
+ const sent = connection.previous ? snapshot.bytesSent - connection.previous.bytesSent : null;
382
+ const received = connection.previous
383
+ ? snapshot.bytesReceived - connection.previous.bytesReceived
384
+ : null;
385
+ connection.previous = snapshot;
386
+ log(
387
+ `[dc-transport] ${tag} sent=${snapshot.bytesSent}` +
388
+ `${sent === null ? "" : ` (+${sent})`} received=${snapshot.bytesReceived}` +
389
+ `${received === null ? "" : ` (+${received})`} queued[${queueDepths(connection.channels)}] ` +
390
+ `rtt=${snapshot.rtt}ms pc=${snapshot.state} ice=${snapshot.iceState} pair=${snapshot.pair}`
391
+ );
392
+ }
393
+ }
394
+ // The rate this connection accepts bytes at, and how long that counter
395
+ // has stood still — both measured every second, whatever the queue is
396
+ // doing, because the rate has to come from the HEALTHY stretch that
397
+ // precedes a wedge. One channel updates it for the whole connection.
398
+ if (sampledAt - connection.rateAt >= SEND_QUEUE_SAMPLE_MS) {
399
+ connection.rateAt = sampledAt;
400
+ const snapshot = getTransportSnapshot?.(sessionId) ?? null;
401
+ const sentNow = Number(snapshot?.bytesSent);
402
+ if (Number.isFinite(sentNow) && sentNow >= 0) {
403
+ if (connection.sentAt === 0 || sentNow < connection.sentBytes) {
404
+ // First reading, or the counter went backwards — a fresh peer
405
+ // connection reusing this session id. Either way the old baseline
406
+ // describes a transport that no longer exists, so start over
407
+ // rather than measure a pause against it for ever.
408
+ connection.sentBytes = sentNow;
409
+ connection.sentAt = sampledAt;
410
+ } else if (sentNow > connection.sentBytes) {
411
+ const seconds = (sampledAt - connection.sentAt) / 1000;
412
+ if (seconds > 0) {
413
+ // The BEST rate this connection has shown, not the latest one.
414
+ // The latest is usually the quietest: with the browser's buffer
415
+ // full nothing is requested for tens of seconds and the only
416
+ // traffic is the probe, a few hundred bytes a second. Dividing a
417
+ // queue by that gives hours, and the wedge would never be called.
418
+ const rate = (sentNow - connection.sentBytes) / seconds;
419
+ if (rate > connection.bytesPerSecond) {
420
+ connection.bytesPerSecond = rate;
421
+ }
422
+ }
423
+ // How long the counter stood still before this advance. While the
424
+ // queue is draining that pause was legitimate, so it is the link's
425
+ // own answer to "how long may a healthy pause be".
426
+ const pausedMs = sampledAt - connection.sentAt;
427
+ if (stuckSince === 0 && pausedMs > connection.longestHealthyFlatMs) {
428
+ connection.longestHealthyFlatMs = pausedMs;
429
+ }
430
+ connection.sentBytes = sentNow;
431
+ connection.sentAt = sampledAt;
432
+ }
433
+ }
434
+ }
435
+ let queued = 0;
436
+ try {
437
+ queued = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0;
438
+ } catch {
439
+ return;
440
+ }
441
+ if (queued === 0 || queued < lowestSinceDrain) {
442
+ lowestSinceDrain = queued;
443
+ stuckSince = 0;
444
+ previous = null;
445
+ receivedWhenStuck = -1;
446
+ connection.browserChannelBytesAtStuck = -1;
447
+ wedgeSaid = false;
448
+ // The queue moved, so whatever was called a wedge has cleared. Let a
449
+ // later one be recorded too: one mistaken call must not spend the
450
+ // session's only capture.
451
+ connection.captureStarted = false;
452
+ return;
453
+ }
454
+ const now = Date.now();
455
+ if (stuckSince === 0) {
456
+ stuckSince = now;
457
+ return;
458
+ }
459
+ const snapshot = getTransportSnapshot?.(sessionId) ?? null;
460
+ if (!snapshot) {
461
+ if (now - stuckSince >= SEND_QUEUE_STUCK_MS && now - lastStuckLogAt >= 30_000) {
462
+ lastStuckLogAt = now;
463
+ log(`[dc] Session ${tag} "${label}": send queue stuck at ${queued}B for ` +
464
+ `${Math.round((now - stuckSince) / 1000)}s — no transport to ask`);
465
+ }
466
+ return;
467
+ }
468
+ const sentDelta = previous ? snapshot.bytesSent - previous.bytesSent : null;
469
+ const recvDelta = previous ? snapshot.bytesReceived - previous.bytesReceived : null;
470
+ previous = snapshot;
471
+ if (receivedWhenStuck < 0) {
472
+ receivedWhenStuck = snapshot.bytesReceived;
473
+ }
474
+ if (connection.browserChannelBytesAtStuck < 0) {
475
+ connection.browserChannelBytesAtStuck = connection.browserChannelBytes;
476
+ }
477
+ // The periodic line waits for {@link SEND_QUEUE_STUCK_MS}, because a
478
+ // queue that has merely not fallen for a second is ordinary and a line a
479
+ // second for it is noise. The WEDGE below does not wait for it: its own
480
+ // condition already says how long this queue may legitimately take, and
481
+ // on a fast link that is under a second. Holding the evidence back for a
482
+ // fixed five seconds would repeat, in miniature, the mistake that left
483
+ // both field captures without an onset in them.
484
+ // Rate-limit to 30 s — field 2026-09-06 printed 49 295 lines (31 % of log)
485
+ // for one 6 h 50 min wedge, one line per second per channel.
486
+ if (now - stuckSince >= SEND_QUEUE_STUCK_MS && now - lastStuckLogAt >= 30_000) {
487
+ lastStuckLogAt = now;
488
+ log(
489
+ `[dc] Session ${tag} "${label}": send queue stuck at ${queued}B for ` +
490
+ `${Math.round((now - stuckSince) / 1000)}s — transport ` +
491
+ `sent=${snapshot.bytesSent}${sentDelta === null ? "" : ` (+${sentDelta})`} ` +
492
+ `received=${snapshot.bytesReceived}${recvDelta === null ? "" : ` (+${recvDelta})`} ` +
493
+ `rtt=${snapshot.rtt}ms pc=${snapshot.state} ice=${snapshot.iceState} pair=${snapshot.pair}`
494
+ );
495
+ }
496
+ // Roadmap item 11: ask for the packet-level truth the moment the wedge is
497
+ // CERTAIN, not after a chosen delay. The three facts below are not
498
+ // ambiguous together — the queue has not fallen, the accepted-byte
499
+ // counter has not moved for longer than the queue's own drain time at
500
+ // this link's own speed, and the peer is still sending. The previous
501
+ // rule's flat 30 s is what left both field captures with no onset in
502
+ // them. One attempt per connection — the witness applies its own
503
+ // single-flight and cooldown rules after that.
504
+ const flatForMs = connection.sentAt === 0 ? 0 : now - connection.sentAt;
505
+ const verdict = wedgeIsCertain({
506
+ queuedBytes: queued,
507
+ bytesPerSecond: connection.bytesPerSecond,
508
+ flatForMs,
509
+ longestHealthyFlatMs: connection.longestHealthyFlatMs
510
+ });
511
+ const hasBrowserBytes = Number.isFinite(connection.browserChannelBytes) && connection.browserChannelBytesAtStuck >= 0;
512
+ const peerStillSending = hasBrowserBytes
513
+ ? connection.browserChannelBytes > connection.browserChannelBytesAtStuck
514
+ : snapshot.bytesReceived > receivedWhenStuck;
515
+ if (verdict.certain && peerStillSending && !wedgeSaid) {
516
+ wedgeSaid = true;
517
+ log(
518
+ `[dc] Session ${tag} "${label}": delivery has stopped — ${queued}B queued, ` +
519
+ `accepted-byte counter unmoved for ${Math.round(flatForMs / 1000)}s against the ` +
520
+ `${(verdict.needMs / 1000).toFixed(1)}s this queue needs at the ` +
521
+ `${(connection.bytesPerSecond / 1024).toFixed(0)} KB/s last measured here, ` +
522
+ "and the peer is still sending"
523
+ );
524
+ }
525
+ if (
526
+ witness &&
527
+ !connection.captureStarted &&
528
+ verdict.certain &&
529
+ peerStillSending
530
+ ) {
531
+ connection.captureStarted = true;
532
+ witness.maybeCapture({
533
+ sessionId,
534
+ tag,
535
+ label,
536
+ remote: snapshot.remote ?? null,
537
+ queuedBytes: queued,
538
+ stuckForMs: now - stuckSince
539
+ });
540
+ }
541
+ if (usrsctpState && verdict.certain && peerStillSending) {
542
+ // Its own single-flight and cooldown, independent of the witness's —
543
+ // one gdb attach per wedge is enough, and a refusal here (already
544
+ // read, cooling down) costs nothing to retry on the next tick.
545
+ usrsctpState.maybeRead(
546
+ `send queue stuck ${queued}B, accepted-byte counter unmoved ${Math.round(flatForMs / 1000)}s`
547
+ );
548
+ }
549
+ }, SEND_QUEUE_SAMPLE_MS);
550
+
551
+ if (typeof timer.unref === "function") {
552
+ timer.unref();
553
+ }
554
+ return stop;
555
+ };
556
+
557
+ return { watchSendQueue, readDelivery, noteBrowserReport };
558
+ }
559
+
560
+ /**
561
+ * Create a handler for incoming WebRTC data channels.
562
+ *
563
+ * @param {DataChannelHandlerOptions} options
564
+ * @returns {DataChannelHandler}
565
+ */
566
+ import { performance } from "node:perf_hooks";
567
+ import { eventLoopDelay, resetEventLoopDelay } from "../../utils/perf.js";
568
+
569
+ /**
570
+ * Build one body frame: `[flags(1)][idLen(1)][requestId][payload]`.
571
+ *
572
+ * One allocation and one copy. The previous version made two of each — a copy
573
+ * of the chunk into a `Buffer`, then a `concat` that copied it again into the
574
+ * frame — which measured 75.9 ms per 13 MB segment on the field host against
575
+ * 40.0 ms this way, and allocated ~600 extra buffers over a segment's 208
576
+ * chunks. One copy is the floor: chunks arrive from a web stream that allocates
577
+ * them itself, so there is no buffer of ours to read them into.
578
+ *
579
+ * @param {Buffer} idBytes - The request id, already encoded.
580
+ * @param {Uint8Array | null} bytes - Payload, or nothing for the done frame.
581
+ * @param {boolean} done
582
+ * @returns {Buffer}
583
+ */
584
+ export function encodeFrame(idBytes, bytes, done) {
585
+ const payloadLength = bytes?.length ?? 0;
586
+ const frame = Buffer.allocUnsafe(2 + idBytes.length + payloadLength);
587
+ frame[0] = done ? 1 : 0;
588
+ frame[1] = idBytes.length;
589
+ idBytes.copy(frame, 2);
590
+ if (payloadLength > 0) {
591
+ frame.set(bytes, 2 + idBytes.length);
592
+ }
593
+ return frame;
594
+ }
595
+
596
+ /**
597
+ * Reshapes a body into messages of `sizeBytes` each, handing every finished one
598
+ * to `sendOne`. A size of zero passes each body read through untouched, which
599
+ * is what the field does today — 10 657 210 bytes over 163 messages, so 65 382
600
+ * each, measured 2026-09-12.
601
+ *
602
+ * Only the SIZE changes: the same bytes reach the far end in the same order,
603
+ * over the same channel. That is what makes a comparison between two sizes a
604
+ * comparison of one thing, and it is why the wedge's dependence on the size can
605
+ * be measured at all — the wedge of 2026-09-12 arrived in the middle of one
606
+ * message, with 63 % of a segment on the wire and then nothing.
607
+ *
608
+ * @param {(bytes: Uint8Array) => void} sendOne - Given each finished message.
609
+ * @param {number} sizeBytes - 0 to leave reads as they are.
610
+ * @returns {{ push: (bytes: Uint8Array) => number, flush: () => number }}
611
+ * Both answer how many messages they sent, so a caller counting messages
612
+ * counts messages rather than body reads.
613
+ */
614
+ export function bodySender(sendOne, sizeBytes) {
615
+ if (!(sizeBytes > 0)) {
616
+ return {
617
+ push(bytes) {
618
+ sendOne(bytes);
619
+ return 1;
620
+ },
621
+ flush() {
622
+ return 0;
623
+ }
624
+ };
625
+ }
626
+ /** @type {Uint8Array[]} */
627
+ let held = [];
628
+ let heldBytes = 0;
629
+ const release = () => {
630
+ const message = held.length === 1 ? held[0] : Buffer.concat(held);
631
+ held = [];
632
+ heldBytes = 0;
633
+ sendOne(message);
634
+ };
635
+ return {
636
+ push(bytes) {
637
+ let sent = 0;
638
+ let offset = 0;
639
+ while (offset < bytes.length) {
640
+ const take = Math.min(sizeBytes - heldBytes, bytes.length - offset);
641
+ held.push(bytes.subarray(offset, offset + take));
642
+ heldBytes += take;
643
+ offset += take;
644
+ if (heldBytes === sizeBytes) {
645
+ release();
646
+ sent += 1;
647
+ }
648
+ }
649
+ return sent;
650
+ },
651
+ flush() {
652
+ if (heldBytes === 0) return 0;
653
+ release();
654
+ return 1;
655
+ }
656
+ };
657
+ }
658
+
659
+ export function createDataChannelHandler({
660
+ proxyPort,
661
+ onLog,
662
+ getTransportSnapshot,
663
+ // Who wants pushed subtitle cues for a file, BY NAME. A plain function
664
+ // returning opaque ids: this layer never learns what a viewer is, and the
665
+ // subscription it used to hold against a channel — and had to sniff
666
+ // `/api/subtitles` to build — now belongs to the person and outlives the
667
+ // channel, a reconnect and a deliberate rotation alike.
668
+ viewersWantingCues = () => [],
669
+ witness,
670
+ // Reads usrsctp's own association state (services/transport/usrsctp-state.js) the
671
+ // moment a wedge is declared, from either detector below. Optional: a host
672
+ // without gdb simply never gets a reading, same as the witness without
673
+ // tcpdump.
674
+ usrsctpState,
675
+ // Presence, both directions. A viewer is present because their connection
676
+ // is, and gone because it went — which is a fact about the PERSON and reaches
677
+ // every output they were watching at once. Before this, nothing anywhere
678
+ // released a viewer when their connection closed: the only exits were the
679
+ // browser's own `release` and a silence long enough to be called an absence.
680
+ onViewerPresent = () => {},
681
+ onViewerGone = () => {},
682
+ // The size of one data-channel message carrying body bytes. Zero keeps
683
+ // whatever the body read hands over, which in the field is 65 382 bytes —
684
+ // 10 657 210 over 163 chunks, measured 2026-09-12. It is settable because
685
+ // that day's wedge arrived in the MIDDLE of one message (63 % of a segment
686
+ // on the wire, then nothing), and whether the fault depends on the size is
687
+ // the one branch no capture has been able to close.
688
+ sendChunkBytes = 0
689
+ }) {
690
+ /**
691
+ * Who is on each connection, by WebRTC session id.
692
+ *
693
+ * One connection carries one page, and a page holds one name per film it has
694
+ * open — so this is normally one id, and more than one only where a page has
695
+ * opened more than one.
696
+ *
697
+ * @type {Map<string, Set<string>>}
698
+ */
699
+ const viewersOnConnection = new Map();
700
+ /**
701
+ * The newest connection currently carrying each viewer's identity.
702
+ *
703
+ * A reconnect can open its channels before the old connection finishes
704
+ * closing. The old connection must not release a viewer who has already
705
+ * identified themselves on the replacement.
706
+ *
707
+ * @type {Map<string, string>}
708
+ */
709
+ const connectionOfViewer = new Map();
710
+
711
+ /**
712
+ * Everyone on this connection has gone, because the connection has.
713
+ *
714
+ * Said once per connection: a second call after the set is emptied must not
715
+ * announce departures a second time, and the two detectors below — the close
716
+ * event and the transport's own counters — can both fire for one death.
717
+ *
718
+ * @param {string} sessionId
719
+ * @param {string} because
720
+ * @returns {void}
721
+ */
722
+ function connectionGone(sessionId, because) {
723
+ const viewers = viewersOnConnection.get(sessionId);
724
+ viewersOnConnection.delete(sessionId);
725
+ if (!viewers || viewers.size === 0) {
726
+ return;
727
+ }
728
+ for (const consumerId of viewers) {
729
+ if (connectionOfViewer.get(consumerId) !== sessionId) {
730
+ continue;
731
+ }
732
+ connectionOfViewer.delete(consumerId);
733
+ onLog?.(`[dc] Session ${sessionId.slice(0, 8)}: viewer ${consumerId} left — ${because}`);
734
+ try {
735
+ onViewerGone(consumerId, because);
736
+ } catch {
737
+ // A viewer failing to be let go must not stop the others being let go.
738
+ }
739
+ }
740
+ }
741
+ /**
742
+ * The channel each viewer is reachable on right now, by the name the far end
743
+ * presented when it opened.
744
+ *
745
+ * The transport knows a NAME and nothing else about a viewer: what it means,
746
+ * who holds it and what they are watching are somebody else's facts. Keeping
747
+ * only "this name is reachable here" is what lets a subscription made once
748
+ * outlive the channel it was made on — a reconnect, and a rotation done on
749
+ * purpose, both just rewrite this entry.
750
+ *
751
+ * @type {Map<string, DataChannel>}
752
+ */
753
+ const channelOfViewer = new Map();
754
+
755
+ /**
756
+ * Forget every name that was reachable on this channel.
757
+ *
758
+ * @param {DataChannel} channel
759
+ * @returns {void}
760
+ */
761
+ function forgetChannel(channel) {
762
+ for (const [consumerId, on] of channelOfViewer) {
763
+ if (on === channel) {
764
+ channelOfViewer.delete(consumerId);
765
+ }
766
+ }
767
+ }
768
+
769
+ /**
770
+ * Send new cues to every channel watching this file — the push side of
771
+ * subtitles arriving as they download rather than being polled for. Cues
772
+ * are tiny (kilobytes at most for a whole track), so this is one message,
773
+ * not a stream.
774
+ *
775
+ * @param {{ sourceKey: string, fileIndex: number, trackIndex: number, cues: object[],
776
+ * language: string, detectedLanguage: { code: string, name: string } | null,
777
+ * cursor: number }} event
778
+ * @returns {void}
779
+ */
780
+ function publishSubtitleCues({ sourceKey, fileIndex, trackIndex, cues, language, detectedLanguage, cursor }) {
781
+ const names = viewersWantingCues(sourceKey, fileIndex);
782
+ if (names.length === 0) {
783
+ log(
784
+ `[dc] subtitle push: ${cues.length} cue(s) for ${sourceKey.slice(0, 8)}:${fileIndex} track ${trackIndex} ` +
785
+ "found nobody who wants them"
786
+ );
787
+ return;
788
+ }
789
+ const message = JSON.stringify({
790
+ type: "subtitle-cues", fileIndex, trackIndex, cues, language, detectedLanguage, cursor
791
+ });
792
+ let sent = 0;
793
+ for (const consumerId of names) {
794
+ const channel = channelOfViewer.get(consumerId);
795
+ if (!channel) {
796
+ // Subscribed but not reachable this instant — between connections, or
797
+ // rotating. Nothing is dropped: they are still subscribed, and the walk
798
+ // keeps a per-viewer cursor, so what they missed comes on the next ask.
799
+ continue;
800
+ }
801
+ try {
802
+ channel.sendMessage(message);
803
+ sent += 1;
804
+ } catch {
805
+ // Closed between the lookup and the send. The subscription belongs to
806
+ // the person and stays; only this delivery is lost.
807
+ }
808
+ }
809
+ log(
810
+ `[dc] subtitle push: sent ${cues.length} cue(s) for ${sourceKey.slice(0, 8)}:${fileIndex} track ${trackIndex} ` +
811
+ `to ${sent}/${names.length} viewer(s)`
812
+ );
813
+ }
814
+
815
+ /** Request id → its ASCII bytes; see {@link requestIdBytes}. */
816
+ const requestIdCache = new Map();
817
+
818
+ const { watchSendQueue, readDelivery, noteBrowserReport } = makeSendQueueWatcher({
819
+ log: (message) => log(message),
820
+ getTransportSnapshot,
821
+ witness,
822
+ usrsctpState,
823
+ // The watcher is where a connection's death is noticed when no close event
824
+ // arrives, so it is the second door presence leaves by. Given rather than
825
+ // reached for: it is a module-level function and cannot see this closure.
826
+ onConnectionGone: connectionGone
827
+ });
828
+ // Numbered probes on every channel, and the browser's echo of what it saw.
829
+ // The proxy's own counters cannot say whether bytes it handed to usrsctp were
830
+ // ever put on the wire; the far end can, and it keeps answering throughout a
831
+ // freeze. See services/transport/delivery-probe.js.
832
+ //
833
+ // Also the ONLY wedge signal that does not require a nonzero channel queue —
834
+ // `wedgeIsCertain` above needs `queuedBytes > 0`, which small, infrequent
835
+ // traffic never produces (confirmed 2026-08-28: the 2026-08-27 episode's
836
+ // ring was never saved automatically for exactly this reason). So this is
837
+ // wired to the same evidence-gathering as the queue watcher.
838
+ const deliveryProbe = createDeliveryProbe({
839
+ log: (message) => log(message),
840
+ readDelivery,
841
+ getTransportSnapshot,
842
+ witness,
843
+ usrsctpState
844
+ });
845
+
846
+ /**
847
+ * @param {string} message
848
+ * @returns {void}
849
+ */
850
+ function log(message) {
851
+ if (typeof onLog === "function") {
852
+ onLog(message);
853
+ }
854
+ }
855
+
856
+ /**
857
+ * Wire up the `onMessage`, `onClosed`, and `onError` handlers for a channel.
858
+ *
859
+ * @param {string} sessionId
860
+ * @param {DataChannel} channel
861
+ * @returns {void}
862
+ */
863
+ function handleChannel(sessionId, channel) {
864
+ const tag = sessionId.slice(0, 8);
865
+ const label = typeof channel.getLabel === "function" ? channel.getLabel() : "?";
866
+ log(`[dc] Session ${tag}: channel open`);
867
+ const stopWatchdog = watchSendQueue(sessionId, tag, label, channel);
868
+ deliveryProbe.attach(sessionId, tag, label, channel);
869
+
870
+ // Partial chunked-request bodies in flight on THIS channel, keyed by
871
+ // requestId. Each entry buffers frames until the done frame, then runs the
872
+ // assembled request through the same path as a single-message request.
873
+ /** @type {Map<string, { meta: object, chunks: Buffer[], receivedBytes: number, bodyBytes: number, timer: ReturnType<typeof setTimeout> }>} */
874
+ const partials = new Map();
875
+
876
+ const dropPartial = (requestId) => {
877
+ const entry = partials.get(requestId);
878
+ if (entry) {
879
+ clearTimeout(entry.timer);
880
+ partials.delete(requestId);
881
+ }
882
+ };
883
+
884
+ /**
885
+ * Begin assembling a chunked request. Validates the path and size up front
886
+ * so an invalid or oversized request never buffers a body.
887
+ *
888
+ * @param {any} message - The `request-start` control message.
889
+ */
890
+ const startPartialRequest = (message) => {
891
+ const { requestId, method, path, query, headers, bodyBytes } = message ?? {};
892
+ if (typeof requestId !== "string" || requestId.length === 0) {
893
+ return;
894
+ }
895
+ if (!isValidRequestPath(path)) {
896
+ send(channel, { type: "response-error", requestId, error: "Invalid request path." });
897
+ return;
898
+ }
899
+ if (!Number.isInteger(bodyBytes) || bodyBytes < 0 || bodyBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
900
+ send(channel, { type: "response-error", requestId, error: "Request body too large." });
901
+ return;
902
+ }
903
+ dropPartial(requestId); // replace any stale entry with the same id
904
+ const timer = setTimeout(() => {
905
+ const entry = partials.get(requestId);
906
+ partials.delete(requestId);
907
+ log(`[dc] Session ${tag}: dropped stale partial request ${requestId.slice(0, 8)} (${entry?.receivedBytes ?? 0}B)`);
908
+ }, PARTIAL_REQUEST_TTL_MS);
909
+ partials.set(requestId, {
910
+ meta: { requestId, method, path, query, headers },
911
+ chunks: [],
912
+ receivedBytes: 0,
913
+ bodyBytes,
914
+ timer
915
+ });
916
+ };
917
+
918
+ /**
919
+ * Handle a binary body frame for a chunked request.
920
+ * Layout: [flags(1)][idLen(1)][requestId(ASCII)][payload].
921
+ *
922
+ * @param {Buffer} buf
923
+ */
924
+ const handleBodyFrame = (buf) => {
925
+ if (buf.length < 2) {
926
+ return;
927
+ }
928
+ const flags = buf[0];
929
+ const idLen = buf[1];
930
+ if (buf.length < 2 + idLen) {
931
+ return;
932
+ }
933
+ const requestId = buf.toString("ascii", 2, 2 + idLen);
934
+ const entry = partials.get(requestId);
935
+ if (!entry) {
936
+ return; // stale / already-dropped / aborted
937
+ }
938
+ if (flags & 2) {
939
+ // Aborted by the browser — drop silently, no reply.
940
+ dropPartial(requestId);
941
+ return;
942
+ }
943
+ if (buf.length > 2 + idLen) {
944
+ const payload = buf.subarray(2 + idLen);
945
+ entry.chunks.push(Buffer.from(payload));
946
+ entry.receivedBytes += payload.length;
947
+ }
948
+ if (entry.receivedBytes > entry.bodyBytes || entry.receivedBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
949
+ dropPartial(requestId);
950
+ send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
951
+ return;
952
+ }
953
+ if (flags & 1) {
954
+ // Done frame — assemble and execute.
955
+ dropPartial(requestId);
956
+ if (entry.receivedBytes !== entry.bodyBytes) {
957
+ send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
958
+ return;
959
+ }
960
+ const body = Buffer.concat(entry.chunks).toString("utf8");
961
+ void handleRequest(channel, { ...entry.meta, body }, true).catch((error) => {
962
+ log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
963
+ });
964
+ }
965
+ };
966
+
967
+ channel.onMessage((raw) => {
968
+ // Binary messages are chunked-request body frames; the proxy otherwise
969
+ // only ever receives JSON strings, so the type discriminates cleanly.
970
+ if (typeof raw !== "string") {
971
+ handleBodyFrame(Buffer.isBuffer(raw) ? raw : Buffer.from(raw));
972
+ return;
973
+ }
974
+
975
+ /** @type {DataChannelRequest | { type: string, id?: string }} */
976
+ let message;
977
+ try {
978
+ message = JSON.parse(raw);
979
+ } catch {
980
+ return;
981
+ }
982
+
983
+ if (message.type === "request") {
984
+ void handleRequest(channel, message).catch((error) => {
985
+ log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
986
+ });
987
+ return;
988
+ }
989
+
990
+ if (message.type === "request-start") {
991
+ startPartialRequest(message);
992
+ return;
993
+ }
994
+
995
+ if (message.type === "ping") {
996
+ send(channel, { type: "pong", id: message.id });
997
+ return;
998
+ }
999
+
1000
+ // WHO is on this connection. Sent once when the page opens its control
1001
+ // channel, and it is what lets a closed connection say that a PERSON has
1002
+ // gone rather than that one output lost a request.
1003
+ //
1004
+ // The name is the page's, not this connection's: it is minted once per
1005
+ // film opened in the tab and survives the reconnect ladder swapping the
1006
+ // transport underneath a running player. A name minted here would make
1007
+ // one person two the first time that happened, each with their own
1008
+ // position.
1009
+ if (message.type === "viewer" && typeof message.consumerId === "string" && message.consumerId) {
1010
+ const known = viewersOnConnection.get(sessionId) ?? new Set();
1011
+ const isNew = !known.has(message.consumerId);
1012
+ known.add(message.consumerId);
1013
+ viewersOnConnection.set(sessionId, known);
1014
+ connectionOfViewer.set(message.consumerId, sessionId);
1015
+ channelOfViewer.set(message.consumerId, channel);
1016
+ if (isNew) {
1017
+ log(`[dc] Session ${tag}: viewer ${message.consumerId} is on this connection`);
1018
+ }
1019
+ onViewerPresent(message.consumerId);
1020
+ return;
1021
+ }
1022
+
1023
+ // The far end's answer to the numbered probes, plus what it can see of
1024
+ // its own receiving. It travels browser to proxy, the direction that goes
1025
+ // on working through a freeze, so it arrives when nothing else does.
1026
+ if (message.type === "probe-echo") {
1027
+ deliveryProbe.noteEcho(sessionId, message);
1028
+ noteBrowserReport(sessionId, message.report);
1029
+ if (message.report && typeof message.report === "object") {
1030
+ const report = message.report;
1031
+ const channels = report.channels && typeof report.channels === "object"
1032
+ ? Object.entries(report.channels)
1033
+ .map(([name, counters]) => `${name}=${counters?.messages ?? "?"}msg/${counters?.bytes ?? "?"}B`)
1034
+ .join(" ")
1035
+ : "";
1036
+ log(
1037
+ `[dc-far] ${tag} visibility=${report.visibility ?? "?"} ` +
1038
+ `loopLag=${report.loopLagMs ?? "?"}ms handler=${report.handlerMaxMs ?? "?"}ms ` +
1039
+ `transportIn=${report.transportBytesReceived ?? "?"} ${channels} ` +
1040
+ `pending=${report.pending ?? "?"} at=${new Date().toISOString()}`
1041
+ );
1042
+ }
1043
+ return;
1044
+ }
1045
+ });
1046
+
1047
+ channel.onClosed(() => {
1048
+ stopWatchdog("the connection closed");
1049
+ deliveryProbe.detach(sessionId, channel);
1050
+ for (const entry of partials.values()) {
1051
+ clearTimeout(entry.timer);
1052
+ }
1053
+ partials.clear();
1054
+ forgetChannel(channel);
1055
+ log(`[dc] Session ${tag}: channel closed`);
1056
+ // One closed data channel does not mean the peer connection is gone:
1057
+ // media, control and probe channels can close independently. The shared
1058
+ // transport watcher calls `connectionGone` when its last channel closes.
1059
+ });
1060
+
1061
+ channel.onError((err) => {
1062
+ log(`[dc] Session ${tag}: channel error: ${err}`);
1063
+ });
1064
+ }
1065
+
1066
+ /**
1067
+ * Fetch a resource from the local proxy HTTP server and stream the response
1068
+ * back to the browser over the data channel.
1069
+ *
1070
+ * The `Host` header is rewritten to `127.0.0.1:{proxyPort}` so that Fastify
1071
+ * routes the request correctly regardless of what the browser sent.
1072
+ *
1073
+ * @param {DataChannel} channel
1074
+ * @param {DataChannelRequest} req
1075
+ * @returns {Promise<void>}
1076
+ */
1077
+ async function handleRequest(channel, req, viaChunks = false) {
1078
+ const { requestId, method, path, query, headers: forwardedHeaders, body } = req;
1079
+
1080
+ // Reject paths that are not absolute, contain traversal sequences, or
1081
+ // do not start with a known proxy route prefix. All valid browser-side
1082
+ // requests use /api/*, /stream, /transcode/*, /health, or /healthz.
1083
+ if (!isValidRequestPath(path)) {
1084
+ send(channel, { type: "response-error", requestId, error: "Invalid request path." });
1085
+ return;
1086
+ }
1087
+
1088
+
1089
+ const queryInfo = query ? `?${query}` : "";
1090
+ const bodyInfo =
1091
+ body != null && typeof body === "string" && body.length > 0
1092
+ ? ` body=${body.length} bytes${viaChunks ? " (chunked)" : ""}`
1093
+ : "";
1094
+ log(`[dc] ${method} ${path}${queryInfo}${bodyInfo}`);
1095
+
1096
+ const targetUrl = `http://127.0.0.1:${proxyPort}${path}${query ? `?${query}` : ""}`;
1097
+ const requestHeaders = { ...(forwardedHeaders ?? {}), host: `127.0.0.1:${proxyPort}` };
1098
+
1099
+ let response;
1100
+ // [net-debug] TEMPORARY: time spent in the local fetch (waiting for the
1101
+ // route to return a response — e.g. long-polling until an HLS segment is
1102
+ // finalized by ffmpeg) vs. the body transfer over the data channel.
1103
+ const fetchStartedAt = Date.now();
1104
+ try {
1105
+ response = await fetch(targetUrl, {
1106
+ method,
1107
+ headers: requestHeaders,
1108
+ body: body != null ? body : undefined,
1109
+ redirect: "manual"
1110
+ });
1111
+ } catch (fetchError) {
1112
+ log(`[dc] ${method} ${path}${queryInfo} → error: ${fetchError?.message ?? String(fetchError)}`);
1113
+ send(channel, { type: "response-error", requestId, error: fetchError?.message ?? String(fetchError) });
1114
+ return;
1115
+ }
1116
+
1117
+ if (response.status !== 200 && response.status !== 206) {
1118
+ log(`[dc] ${method} ${path}${queryInfo} → ${response.status}`);
1119
+ }
1120
+
1121
+ /** @type {Record<string, string>} */
1122
+ const responseHeaders = {};
1123
+ for (const [name, value] of response.headers.entries()) {
1124
+ responseHeaders[name] = value;
1125
+ }
1126
+
1127
+ send(channel, { type: "response-start", requestId, status: response.status, headers: responseHeaders });
1128
+
1129
+ if (!response.body) {
1130
+ sendChunk(channel, requestId, null, true);
1131
+ return;
1132
+ }
1133
+
1134
+ try {
1135
+ const reader = response.body.getReader();
1136
+ // [net-debug] TEMPORARY: measure transfer size/time and channel buffering.
1137
+ // fetchMs = time waiting for the route (incl. ffmpeg segment finalization).
1138
+ // ttfbMs = time from body-read start to the first chunk with data (loopback).
1139
+ // sendMs = total body read+send duration over the data channel.
1140
+ const fetchMs = Date.now() - fetchStartedAt;
1141
+ const sendStartedAt = Date.now();
1142
+ let firstByteMs = -1;
1143
+ let chunks = 0;
1144
+ let totalBytes = 0;
1145
+ let maxBuffered = 0;
1146
+ // Attribute the transfer to the step that actually consumes the time.
1147
+ // Without this split a slow transfer is indistinguishable between "the
1148
+ // source is slow", "the channel is slow" and "the event loop is blocked",
1149
+ // which is exactly the argument a field seek left unresolved.
1150
+ let readMs = 0;
1151
+ let sendMs2 = 0;
1152
+ let drainMs = 0;
1153
+ const body = bodySender((bytes) => sendChunk(channel, requestId, bytes, false), sendChunkBytes);
1154
+ resetEventLoopDelay();
1155
+ while (true) {
1156
+ const readStartedAt = performance.now();
1157
+ const { done, value } = await reader.read();
1158
+ readMs += performance.now() - readStartedAt;
1159
+ if (done) {
1160
+ chunks += body.flush();
1161
+ sendChunk(channel, requestId, null, true);
1162
+ const elapsedMs = Date.now() - sendStartedAt;
1163
+ let bufferedNow = 0;
1164
+ try { bufferedNow = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0; } catch { /* ignore */ }
1165
+ const loop = eventLoopDelay();
1166
+ const mbps = elapsedMs > 0 ? (totalBytes * 8) / (elapsedMs * 1000) : 0;
1167
+ log(
1168
+ `[net-debug] sent ${path}${queryInfo} bytes=${totalBytes} fetchMs=${fetchMs} ` +
1169
+ `ttfbMs=${firstByteMs} sendMs=${elapsedMs} chunks=${chunks} ` +
1170
+ // The size of one message, so a reading can be attributed to the
1171
+ // size it was taken at rather than to the run it came from.
1172
+ `msgBytes=${sendChunkBytes > 0 ? sendChunkBytes : "asread"} ` +
1173
+ `maxBuffered=${maxBuffered} bufferedAtEnd=${bufferedNow} ` +
1174
+ // Where the time went: reading the body from the local route,
1175
+ // handing chunks to the channel, or waiting for its queue. Plus
1176
+ // the event-loop delay over the same window — a large max here
1177
+ // means the transfer was blocked by synchronous work, not by the
1178
+ // network, and the three figures above will all look inflated.
1179
+ `readMs=${readMs.toFixed(0)} chanMs=${sendMs2.toFixed(0)} drainMs=${drainMs.toFixed(0)} ` +
1180
+ `loopMean=${loop.meanMs.toFixed(1)} loopP99=${loop.p99Ms.toFixed(1)} loopMax=${loop.maxMs.toFixed(1)} ` +
1181
+ `rate=${mbps.toFixed(1)}Mbps`
1182
+ );
1183
+ break;
1184
+ }
1185
+ if (firstByteMs < 0) firstByteMs = Date.now() - sendStartedAt;
1186
+ totalBytes += value.length;
1187
+ try {
1188
+ const b = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0;
1189
+ if (b > maxBuffered) maxBuffered = b;
1190
+ } catch { /* ignore */ }
1191
+ const sendStepAt = performance.now();
1192
+ chunks += body.push(value);
1193
+ sendMs2 += performance.now() - sendStepAt;
1194
+ // Backpressure: do not keep queuing chunks once the channel's outgoing
1195
+ // buffer is large — wait for it to drain. Prevents the SCTP send buffer
1196
+ // from ballooning, which stalls throughput.
1197
+ const drainStepAt = performance.now();
1198
+ await waitForBufferDrain(channel);
1199
+ drainMs += performance.now() - drainStepAt;
1200
+ }
1201
+ } catch {
1202
+ sendChunk(channel, requestId, null, true);
1203
+ }
1204
+ }
1205
+
1206
+ /**
1207
+ * Send a response body frame as a BINARY data-channel message.
1208
+ * Layout: [flags(1)][idLen(1)][requestId(ASCII)][payload].
1209
+ *
1210
+ * @param {DataChannel} channel
1211
+ * @param {string} requestId
1212
+ * @param {Uint8Array | null} bytes - Body bytes, or null/empty for the done frame.
1213
+ * @param {boolean} done
1214
+ * @returns {void}
1215
+ */
1216
+ /**
1217
+ * The request id as bytes, prepared once per request rather than per chunk.
1218
+ *
1219
+ * A segment is a couple of hundred chunks, and each one was re-encoding the
1220
+ * same 32-character string. The map is bounded because request ids are
1221
+ * short-lived and unbounded in number — dropping the whole cache when it
1222
+ * grows costs one re-encode per live request and cannot leak.
1223
+ *
1224
+ * @param {string} requestId
1225
+ * @returns {Buffer}
1226
+ */
1227
+ function requestIdBytes(requestId) {
1228
+ let bytes = requestIdCache.get(requestId);
1229
+ if (!bytes) {
1230
+ if (requestIdCache.size > 64) {
1231
+ requestIdCache.clear();
1232
+ }
1233
+ bytes = Buffer.from(requestId, "ascii");
1234
+ requestIdCache.set(requestId, bytes);
1235
+ }
1236
+ return bytes;
1237
+ }
1238
+
1239
+ function sendChunk(channel, requestId, bytes, done) {
1240
+ try {
1241
+ channel.sendMessageBinary(encodeFrame(requestIdBytes(requestId), bytes, done));
1242
+ } catch {
1243
+ // Channel closed between check and send — safe to ignore.
1244
+ }
1245
+ }
1246
+
1247
+ /**
1248
+ * Resolve once the channel's outgoing buffer has drained below the low-water
1249
+ * mark. No-op (resolves immediately) when the buffer is already small or the
1250
+ * channel does not expose buffer APIs. The previous implementation resolved
1251
+ * after {@link DC_BUFFER_DRAIN_TIMEOUT_MS} even though the buffer was still
1252
+ * high, so the send loop kept queueing into a wedged channel and the queue
1253
+ * grew to 399 MB (field 2026-09-06). This version waits until the buffer
1254
+ * actually drains, polling as a fallback for a missed low-water event, and
1255
+ * never resolves while the channel is still holding bytes above the low-water
1256
+ * mark.
1257
+ *
1258
+ * @param {DataChannel} channel
1259
+ * @returns {Promise<void>}
1260
+ */
1261
+ function waitForBufferDrain(channel) {
1262
+ return new Promise((resolve) => {
1263
+ try {
1264
+ if (typeof channel.bufferedAmount !== "function" || channel.bufferedAmount() <= DC_BUFFER_HIGH_WATER) {
1265
+ resolve();
1266
+ return;
1267
+ }
1268
+ let poll = null;
1269
+ let settled = false;
1270
+ const done = () => {
1271
+ if (settled) return;
1272
+ settled = true;
1273
+ if (poll) clearInterval(poll);
1274
+ try { channel.onBufferedAmountLow(() => {}); } catch {}
1275
+ resolve();
1276
+ };
1277
+ channel.setBufferedAmountLowThreshold(DC_BUFFER_LOW_WATER);
1278
+ channel.onBufferedAmountLow(done);
1279
+ // Poll as a fallback for a missed low-water event — the previous
1280
+ // 5 s timeout resolved while the buffer was still high, which is the
1281
+ // defect. Polling waits until the condition is actually met.
1282
+ poll = setInterval(() => {
1283
+ try {
1284
+ if (channel.bufferedAmount() <= DC_BUFFER_LOW_WATER) {
1285
+ done();
1286
+ }
1287
+ } catch {
1288
+ done();
1289
+ }
1290
+ }, 50);
1291
+ if (typeof poll.unref === "function") poll.unref();
1292
+ // Guard against a race where the buffer drained between the check above
1293
+ // and registering the callback (the low-water event would never fire).
1294
+ if (channel.bufferedAmount() <= DC_BUFFER_LOW_WATER) {
1295
+ done();
1296
+ }
1297
+ } catch {
1298
+ resolve();
1299
+ }
1300
+ });
1301
+ }
1302
+
1303
+ /**
1304
+ * Serialise `message` to JSON and send it over the data channel.
1305
+ * Errors are silently swallowed — the channel may have closed between
1306
+ * the open check and the actual send.
1307
+ *
1308
+ * @param {DataChannel} channel
1309
+ * @param {object} message
1310
+ * @returns {void}
1311
+ */
1312
+ function send(channel, message) {
1313
+ try {
1314
+ channel.sendMessage(JSON.stringify(message));
1315
+ } catch {
1316
+ // Channel closed between check and send — safe to ignore.
1317
+ }
1318
+ }
1319
+
1320
+ return { handleChannel, publishSubtitleCues };
1321
+ }
1322
+
1323
+ /**
1324
+ * Allowed path prefixes for data-channel requests.
1325
+ * Only the known proxy API and streaming routes are accepted.
1326
+ */
1327
+ const PATH_ALLOWLIST_RE = /^(?:\/api\/|\/stream(?:$|\?)|\/?transcode\/|\/health(?:z)?(?:$|\?))/;
1328
+
1329
+ /**
1330
+ * True when `path` is an absolute, traversal-free path on a known proxy route.
1331
+ * Shared by the single-message and chunked request entry points.
1332
+ *
1333
+ * @param {unknown} path
1334
+ * @returns {boolean}
1335
+ */
1336
+ function isValidRequestPath(path) {
1337
+ return (
1338
+ typeof path === "string" &&
1339
+ path.startsWith("/") &&
1340
+ !path.includes("..") &&
1341
+ PATH_ALLOWLIST_RE.test(path)
1342
+ );
1343
+ }
1344
+
1345
+ /** Max assembled size of a chunked request body (guards proxy memory). */
1346
+ const PROXY_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024;
1347
+ /** Drop an incomplete chunked body if no further frame arrives within this window. */
1348
+ const PARTIAL_REQUEST_TTL_MS = 60_000;
1349
+
1350
+ /** Pause sending body chunks once the channel buffer exceeds this many bytes. */
1351
+ // How often the send queue is sampled, and how long it must fail to fall
1352
+ // before the transport is asked what it is doing. Five seconds is far longer
1353
+ // than any healthy burst drains in — measured, a 6-11 MB segment leaves in
1354
+ // well under a second on the LAN — and short enough that a stuck channel is
1355
+ // named while the viewer is still looking at it.
1356
+ const SEND_QUEUE_SAMPLE_MS = 1_000;
1357
+ // How often the transport's own counters are written to the log, whatever the
1358
+ // send queue is doing. Frequent enough to place a loss within a few seconds,
1359
+ // sparse enough that a two-hour film costs a few hundred lines.
1360
+ const TRANSPORT_HEARTBEAT_MS = 5_000;
1361
+
1362
+ // How many heartbeats in a row may find no transport for this session before
1363
+ // the watch gives up. Several rather than one, so a momentary gap in the
1364
+ // registry does not end a healthy watch.
1365
+ const TRANSPORT_UNKNOWN_HEARTBEATS = 3;
1366
+ const SEND_QUEUE_STUCK_MS = 5_000;
1367
+ const DC_BUFFER_HIGH_WATER = 8 * 1024 * 1024;
1368
+ /** Resume sending once the channel buffer drains to this many bytes. */
1369
+ const DC_BUFFER_LOW_WATER = 1 * 1024 * 1024;