@torrent-tv/proxy 2.57.0 → 2.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,646 +1,701 @@
1
- /**
2
- * @file The torrent thread: WebTorrent and nothing else.
3
- *
4
- * Everything that made the main thread unresponsive lives here now — peer
5
- * connections, buffer concatenation, piece bookkeeping, garbage collection from
6
- * all of it. The main thread keeps only what owes a viewer a prompt answer.
7
- *
8
- * This file deliberately holds no HTTP, no session logic and no knowledge of
9
- * HLS: it answers the commands in `protocol.js` and streams bytes back. That
10
- * boundary is what keeps the split honest — anything added here will compete
11
- * with the torrent for this thread, which is exactly the problem being solved.
12
- *
13
- * The existing `TorrentPool` is reused wholesale rather than reimplemented. It
14
- * already carries the parts that took field failures to get right — refcounted
15
- * file claims, idle removal, the global disk cap with LRU eviction, seek-aware
16
- * piece prioritisation, adaptive upload — and none of that changes by moving
17
- * threads.
18
- */
19
-
20
- // MUST stay first: it redirects `webrtc-polyfill` to a JavaScript WebRTC stack
21
- // before WebTorrent can reach the native one. Two isolates using
22
- // node-datachannel at once abort the process, and the torrent's wss trackers
23
- // create peer connections of their own.
24
- import { isUsableTorrentHandle } from "./handle-state.js";
25
- import "./install-webrtc-shim.js";
26
- import { parentPort, workerData } from "node:worker_threads";
27
- import { createSendStream } from "./channel.js";
28
- import { createFileClaims } from "./file-claims.js";
29
- import { readFragments, supplyFiguresFor } from "./piece-reader.js";
30
- import { cuesHeldFor, declaredSubtitleTracksOf, subtitleTracksOf, warmSubtitleCues } from "./subtitle-cues.js";
31
- import { Command, Event } from "./protocol.js";
32
-
33
- // Imported dynamically, and that is load-bearing: static imports are RESOLVED
34
- // during linking, before any module body runs, so a statically imported pool
35
- // would drag in WebTorrent — and with it the real `webrtc-polyfill` — before
36
- // the hook above had a chance to register. Verified the hard way: with a static
37
- // import the process still aborted, and the stack named the genuine polyfill.
38
- const { TorrentPool, resolveDhtBootstrap } = await import("../torrent-pool.js");
39
- const { collectStoreStats, findSharedStore } = await import("../piece-store/shared-piece-store.js");
40
-
41
- // Resolved before the client exists, because the client builds its DHT in its
42
- // own constructor and the addresses have to be in hand by then. Awaiting here
43
- // costs the few milliseconds of a DNS answer, once, on a thread that has not
44
- // been asked for anything yet.
45
- const dhtBootstrap = await resolveDhtBootstrap();
46
-
47
- const pool = new TorrentPool({
48
- maxDiskBytes: workerData?.maxDiskBytes,
49
- memoryBytes: workerData?.memoryBytes,
50
- dhtBootstrap
51
- });
52
-
53
- /** Torrents by sourceKey — the main thread names them, this thread owns them. */
54
- const torrentsByKey = new Map();
55
-
56
- /**
57
- * How each source was named when it was added, so a torrent that has since been
58
- * destroyed can be added again. Kept separately from {@link torrentsByKey}
59
- * because that map holds the promise, not the recipe.
60
- *
61
- * @type {Map<string, { sourceType: string, source: string }>}
62
- */
63
- const sourceRecipes = new Map();
64
- /** File claims, each with its own identity — see `file-claims.js`. */
65
- const fileClaims = createFileClaims();
66
- /** In-flight reads, so a cancel can stop one mid-body. */
67
- const readsById = new Map();
68
-
69
- /**
70
- * Forward a log line to the main thread, so worker output is not lost or
71
- * interleaved separately from everything else.
72
- *
73
- * @param {string} message
74
- * @returns {void}
75
- */
76
- function log(message) {
77
- parentPort.postMessage({ type: Event.LOG, message });
78
- }
79
-
80
- /**
81
- * The torrent for a sourceKey, waiting for it if it is still being added.
82
- *
83
- * The map holds a PROMISE, registered the moment the add begins rather than
84
- * when it finishes. That distinction is the whole fix: adding a magnet takes as
85
- * long as its metadata does — seconds to tens of seconds — and until 2.9.77
86
- * everything naming that source in the meantime was told `Unknown source`,
87
- * which is false. The source exists; it is not ready. Reproduced with a magnet
88
- * nobody seeds: stats, the file listing and a read all failed instantly while
89
- * the add was still in flight, which on the loading screen shows up as no
90
- * peers, no progress, and a plan request that fails before the torrent has had
91
- * a chance to start.
92
- *
93
- * A source that was never added still throws, which is the honest answer.
94
- *
95
- * @param {string} sourceKey
96
- * @returns {Promise<import("webtorrent").Torrent>}
97
- */
98
- async function requireTorrent(sourceKey) {
99
- const pending = torrentsByKey.get(sourceKey);
100
- if (!pending) {
101
- throw new Error(`Unknown source ${sourceKey}.`);
102
- }
103
- const torrent = await pending;
104
- if (isUsableTorrentHandle(torrent)) {
105
- return torrent;
106
- }
107
- // The pool destroys a torrent that has gone unread for a quarter of an hour,
108
- // and under disk pressure. It clears its OWN map when it does; this one it
109
- // knows nothing about, so the promise here went on resolving to a corpse: a
110
- // destroyed torrent keeps its object but loses its files. Every later session
111
- // for that source then failed the same way — the plan and the codec probe
112
- // answered from cache in milliseconds, nothing waited for metadata because
113
- // everything believed the torrent was known, and ffmpeg's first read died on
114
- // `File N not found` 130 ms in, after which the session answered 500 for
115
- // ever. Measured 2026-08-06 on two sessions in a row, both from a phone,
116
- // which is what made it look like a mobile problem.
117
- const recipe = sourceRecipes.get(sourceKey);
118
- if (!recipe) {
119
- torrentsByKey.delete(sourceKey);
120
- throw new Error(`Source ${sourceKey} is gone and cannot be re-added.`);
121
- }
122
- const revived = pool.getTorrent(recipe.sourceType, recipe.source);
123
- torrentsByKey.set(sourceKey, revived);
124
- revived.catch(() => {
125
- if (torrentsByKey.get(sourceKey) === revived) {
126
- torrentsByKey.delete(sourceKey);
127
- }
128
- });
129
- return revived;
130
- }
131
-
132
-
133
- /**
134
- * Fragments waiting for the main thread to say it has finished reading them,
135
- * keyed by request id. One per read, because only one fragment is in flight.
136
- *
137
- * @type {Map<number, () => void>}
138
- */
139
- const fragmentWaiters = new Map();
140
-
141
- /**
142
- * Wake a read that is waiting for a fragment to be confirmed.
143
- *
144
- * Used both by the confirmation itself and by cancellation — a cancelled read
145
- * will never be confirmed, and without this it would wait forever holding a pin.
146
- *
147
- * @param {number} id
148
- * @returns {void}
149
- */
150
- function settleFragment(id) {
151
- const done = fragmentWaiters.get(id);
152
- if (done) {
153
- fragmentWaiters.delete(id);
154
- done();
155
- }
156
- }
157
-
158
- /**
159
- * Send one fragment's position and wait until the main thread is done with it.
160
- *
161
- * The pin is dropped only after the confirmation, because until then the other
162
- * thread may still be reading those exact bytes.
163
- *
164
- * @param {number} id
165
- * @param {import("./piece-reader.js").PieceFragment} fragment
166
- * @returns {Promise<void>}
167
- */
168
- function sendFragment(id, fragment) {
169
- return new Promise((resolve) => {
170
- fragmentWaiters.set(id, () => {
171
- fragment.release();
172
- resolve();
173
- });
174
- parentPort.postMessage({
175
- type: Event.FRAGMENT,
176
- id,
177
- pieceIndex: fragment.pieceIndex,
178
- offset: fragment.offset,
179
- length: fragment.length
180
- });
181
- });
182
- }
183
-
184
- /**
185
- * Stream a byte range back as CHUNK messages.
186
- *
187
- * Reads through WebTorrent's own read stream — which serves already-downloaded
188
- * pieces from disk and waits for the rest — and forwards it in
189
- * {@link STREAM_CHUNK_BYTES} pieces, transferring ownership of each so nothing
190
- * is copied across the boundary. `createSendStream` applies the backpressure,
191
- * so a fast disk cannot outrun the main thread and rebuild the queue in memory.
192
- *
193
- * @param {object} params
194
- * @param {number} params.id - Request id; CHUNK/READ_END carry it.
195
- * @param {string} params.sourceKey
196
- * @param {number} params.fileIndex
197
- * @param {number | null} params.start - Inclusive, or null for the whole file.
198
- * @param {number | null} params.end - Inclusive.
199
- * @returns {Promise<void>}
200
- */
201
- async function streamRange({ id, sourceKey, fileIndex, start, end, windowBytes }) {
202
- const torrent = await requireTorrent(sourceKey);
203
- const file = torrent.files?.[fileIndex];
204
- if (!file) {
205
- throw new Error(`File ${fileIndex} not found in ${sourceKey}.`);
206
- }
207
-
208
- const sender = createSendStream({ port: parentPort, requestId: id });
209
- readsById.set(id, sender);
210
-
211
- // Hold the file for as long as this read runs. The caller also acquires it,
212
- // but that acquire and its release are separate messages from another thread
213
- // and can be reordered; this one cannot, because it lives entirely inside the
214
- // read. Without it the idle sweep saw a zero reader count and removed the
215
- // torrent AND its store mid-read — field 2026-08-02: "removed idle torrent
216
- // ... and its store", after which every subsequent read hung and ffmpeg got
217
- // an empty input.
218
- const releaseRead = pool.acquireFile(torrent, fileIndex);
219
-
220
- const rangeStart = start ?? 0;
221
- const rangeEnd = end ?? file.length - 1;
222
-
223
- let failed = false;
224
- try {
225
- // Positions in shared memory, not bytes: the main thread maps the same pool
226
- // and reads each fragment in place, so nothing is copied and nothing is
227
- // transferred. See `piece-reader.js`.
228
- for await (const fragment of readFragments({
229
- torrent,
230
- fileIndex,
231
- start: rangeStart,
232
- end: rangeEnd,
233
- cancellation: sender,
234
- windowBytes
235
- })) {
236
- if (sender.isCancelled()) {
237
- fragment.release();
238
- break;
239
- }
240
- // One fragment in flight at a time. Each one holds a piece pinned, and
241
- // the store guarantees only two resident pieces at its smallest budget —
242
- // holding two pins while asking for a third would deadlock it against
243
- // itself. The round trip costs ~100 µs against a piece worth megabytes,
244
- // so there is nothing to win by overlapping them.
245
- await sendFragment(id, fragment);
246
- }
247
- } catch (error) {
248
- // The end-of-read marker means "the body is complete". Sending it after a
249
- // failure told the reader the file simply ended — a truncated segment that
250
- // ffmpeg reported as `Stream ends prematurely`, with the real cause thrown
251
- // away. Let the error propagate instead; the command handler reports it and
252
- // the main thread fails the stream.
253
- failed = true;
254
- throw error;
255
- } finally {
256
- readsById.delete(id);
257
- // Any fragment still awaiting confirmation will never get one now; settling
258
- // it here releases its pin rather than leaking a held slot.
259
- settleFragment(id);
260
- releaseRead();
261
- if (!failed) {
262
- sender.end();
263
- }
264
- // Nothing else to tear down: the reader owns no stream of its own, and a
265
- // cancelled read stops at its next fragment boundary because it polls the
266
- // same `sender` for cancellation.
267
- }
268
- }
269
-
270
- /**
271
- * Run one command and return its result.
272
- *
273
- * @param {string} command
274
- * @param {object} params
275
- * @param {number} id
276
- * @returns {Promise<unknown>}
277
- */
278
- async function runCommand(command, params, id) {
279
- switch (command) {
280
- case Command.ADD_SOURCE: {
281
- // Registered before it resolves, so anything naming this source while it
282
- // is being added waits for it instead of being told it does not exist.
283
- // Reusing the same promise for a repeated add also collapses two callers
284
- // racing to open the same torrent into one.
285
- sourceRecipes.set(params.sourceKey, {
286
- sourceType: params.sourceType,
287
- source: params.source
288
- });
289
- let pending = torrentsByKey.get(params.sourceKey);
290
- if (!pending) {
291
- pending = pool.getTorrent(params.sourceType, params.source);
292
- torrentsByKey.set(params.sourceKey, pending);
293
- // A failed add must not be remembered, or every later attempt at this
294
- // source replays the same failure. The handler also marks the rejection
295
- // as observed, so it cannot surface as an unhandled one.
296
- pending.catch(() => {
297
- if (torrentsByKey.get(params.sourceKey) === pending) {
298
- torrentsByKey.delete(params.sourceKey);
299
- }
300
- });
301
- }
302
- const torrent = await pending;
303
- return {
304
- infoHash: torrent.infoHash,
305
- name: torrent.name,
306
- // The piece pool itself. A `SharedArrayBuffer` crosses as a reference to
307
- // the same memory rather than a copy, which is what lets the main thread
308
- // read a piece where it already lies instead of being sent its bytes.
309
- sharedBuffer: findSharedStore(torrent)?.sharedBuffer ?? null,
310
- // Files cross as plain data; the objects stay here.
311
- files: (torrent.files ?? []).map((file, index) => ({
312
- index,
313
- name: file.name,
314
- path: file.path,
315
- length: file.length
316
- }))
317
- };
318
- }
319
-
320
- case Command.LIST_FILES: {
321
- const torrent = await requireTorrent(params.sourceKey);
322
- return (torrent.files ?? []).map((file, index) => ({
323
- index,
324
- name: file.name,
325
- path: file.path,
326
- length: file.length
327
- }));
328
- }
329
-
330
- case Command.ACQUIRE_FILE: {
331
- const torrent = await requireTorrent(params.sourceKey);
332
- // Every acquire is its own claim. Sharing one per file meant the first
333
- // reader to finish released the hold while others were still reading.
334
- return fileClaims.open(
335
- params.sourceKey,
336
- params.fileIndex,
337
- pool.acquireFile(torrent, params.fileIndex)
338
- );
339
- }
340
-
341
- case Command.RELEASE_FILE: {
342
- const released = fileClaims.close(params.claimId);
343
- if (!released) {
344
- // Not fatal — but it means a release arrived twice or after teardown,
345
- // and silence here is what let the previous scheme look healthy.
346
- log(`release for unknown file claim ${params.claimId}`);
347
- }
348
- return released;
349
- }
350
-
351
- case Command.TORRENT_TOTALS: {
352
- // Downloaded and uploaded are counted apart: hashing every downloaded
353
- // byte is work of a different order from sending one back to the swarm,
354
- // and adding them would price both at whatever the mixture happened to
355
- // be.
356
- let downloaded = 0;
357
- let uploaded = 0;
358
- for (const torrent of pool.client?.torrents ?? []) {
359
- const gotBytes = Number(torrent?.downloaded);
360
- const sentBytes = Number(torrent?.uploaded);
361
- downloaded += Number.isFinite(gotBytes) ? gotBytes : 0;
362
- uploaded += Number.isFinite(sentBytes) ? sentBytes : 0;
363
- }
364
- return { downloaded, uploaded };
365
- }
366
-
367
- case Command.SUBTITLE_TRACKS: {
368
- const torrent = await requireTorrent(params.sourceKey);
369
- return {
370
- tracks: await subtitleTracksOf(torrent, params.fileIndex, params.sourceKey),
371
- declared: await declaredSubtitleTracksOf(torrent, params.fileIndex, params.sourceKey)
372
- };
373
- }
374
-
375
- case Command.SUBTITLE_CUES: {
376
- const torrent = await requireTorrent(params.sourceKey);
377
- const held = await cuesHeldFor(torrent, params.fileIndex, params.sourceKey, params.trackNumber);
378
- return {
379
- cues: held.cues,
380
- coveredClusters: held.coveredClusters,
381
- indexedClusters: held.indexedClusters,
382
- codecId: held.track?.codecId ?? "",
383
- codecPrivate: held.track?.codecPrivate ?? "",
384
- language: held.track?.language ?? ""
385
- };
386
- }
387
-
388
- case Command.FILE_STATS: {
389
- const torrent = await requireTorrent(params.sourceKey);
390
- const stats = pool.getFileStats(torrent, params.fileIndex, {
391
- resumeAnchorByteStart: params.resumeAnchorByteStart ?? null
392
- });
393
- // What this file's own interruptions demand, measured by the reader in
394
- // this thread. It travels with the stats because the caller asking for
395
- // them is the one that has to decide with them — the browser's smallest
396
- // safe buffer, and the speed a quality step must sustain. Null until a
397
- // second interruption has been seen: one wait shows no interval, and an
398
- // interval invented from one point is exactly what this work removes.
399
- const file = Array.isArray(torrent?.files) ? torrent.files[params.fileIndex] : null;
400
- return {
401
- ...stats,
402
- supply: supplyFiguresFor(torrent?.infoHash, file?.name, params.segmentSeconds ?? 4)
403
- };
404
- }
405
-
406
- case Command.PRIORITIZE: {
407
- const torrent = await requireTorrent(params.sourceKey);
408
- pool.prioritizeByteRange(torrent, params.fileIndex, params.byteStart, params.windowBytes, {
409
- wholeFileRead: params.wholeFileRead === true
410
- });
411
- return true;
412
- }
413
-
414
- case Command.PREFETCH_EDGES: {
415
- const torrent = await requireTorrent(params.sourceKey);
416
- return pool.prefetchFileEdges(torrent, params.fileIndex, params.options ?? {});
417
- }
418
-
419
- case Command.READ_RANGE: {
420
- // Streams its own reply; the caller's promise resolves once the body has
421
- // been fully sent, which is what lets the client await completion.
422
- await streamRange({
423
- id,
424
- sourceKey: params.sourceKey,
425
- fileIndex: params.fileIndex,
426
- start: params.start ?? null,
427
- end: params.end ?? null,
428
- windowBytes: params.windowBytes
429
- });
430
- return true;
431
- }
432
-
433
- case Command.CANCEL_READ: {
434
- readsById.get(params.readId)?.cancel();
435
- // A cancelled read will never have its outstanding fragment confirmed, so
436
- // wake it here — otherwise it waits forever with a piece pinned.
437
- settleFragment(params.readId);
438
- return true;
439
- }
440
-
441
- case Command.DESTROY_ALL: {
442
- fileClaims.closeAll();
443
- torrentsByKey.clear();
444
- sourceRecipes.clear();
445
- await pool.destroyAll();
446
- return true;
447
- }
448
-
449
- default:
450
- throw new Error(`Unknown torrent-worker command: ${command}`);
451
- }
452
- }
453
-
454
- parentPort.on("message", async (message) => {
455
- // Chunk acknowledgements are not commands — they release backpressure on an
456
- // in-flight read.
457
- if (message?.type === Event.CHUNK_ACK) {
458
- readsById.get(message.id)?.ack();
459
- return;
460
- }
461
-
462
- // The main thread has finished reading a fragment out of shared memory, so
463
- // its piece may be unpinned and the read may continue.
464
- if (message?.type === Event.FRAGMENT_DONE) {
465
- settleFragment(message.id);
466
- return;
467
- }
468
-
469
- const { command, id, params } = message ?? {};
470
- try {
471
- const result = await runCommand(command, params ?? {}, id);
472
- parentPort.postMessage({ type: Event.RESULT, id, result });
473
- } catch (error) {
474
- parentPort.postMessage({ type: Event.ERROR, id, error: error?.message ?? String(error) });
475
- }
476
- });
477
-
478
- /**
479
- * How often the piece store reports what it has been doing.
480
- *
481
- * The store decides whether a read costs nothing or costs a disk trip, and
482
- * until 2.9.75 nothing about it reached the log — a field oddity would have had
483
- * no evidence to work from. Reported only when something changed, so an idle
484
- * proxy stays quiet.
485
- */
486
- const STORE_REPORT_INTERVAL_MS = 60_000;
487
-
488
- /** Last reported figures per store, so unchanged ones stay silent. */
489
- const lastReported = new Map();
490
-
491
- setInterval(() => {
492
- for (const stats of collectStoreStats()) {
493
- const signature = `${stats.fromMemory}/${stats.fromDisk}/${stats.spills}/${stats.revivals}/${stats.blockedByPins}`;
494
- if (lastReported.get(stats.name) === signature) {
495
- continue;
496
- }
497
- lastReported.set(stats.name, signature);
498
-
499
- const reads = stats.fromMemory + stats.fromDisk;
500
- const fromMemoryShare = reads > 0 ? ((stats.fromMemory / reads) * 100).toFixed(1) : "—";
501
- log(
502
- `piece-store "${stats.name.slice(0, 40)}": resident=${stats.resident}/${stats.capacity} ` +
503
- `pinned=${stats.pinned} spilled=${stats.spilled} reads=${reads} (${fromMemoryShare}% from memory) ` +
504
- `spills=${stats.spills} revivals=${stats.revivals}` +
505
- (stats.blockedByPins > 0 ? ` blocked-by-pins=${stats.blockedByPins}` : "")
506
- );
507
- }
508
- }, STORE_REPORT_INTERVAL_MS).unref();
509
-
510
- /**
511
- * Walk subtitle cues for every actively-read file of one torrent, and PUSH
512
- * whatever came out new to the main thread — which is what makes a browser's
513
- * copy current without it having asked.
514
- *
515
- * @param {string} sourceKey
516
- * @param {object} torrent
517
- * @returns {void}
518
- */
519
- function warmActiveFiles(sourceKey, torrent) {
520
- const usage = pool.fileUsageByTorrent.get(torrent);
521
- if (!usage) {
522
- return;
523
- }
524
- for (const fileIndex of usage.keys()) {
525
- const key = `${sourceKey}:${fileIndex}`;
526
- // A trigger that arrives while the previous pass is still walking is
527
- // dropped, not queued. `verified` fires per piece, so on a fast download
528
- // these arrive many times a second; the walk is serialized per file anyway,
529
- // and a queue of identical passes would only postpone the one that has
530
- // something new to find.
531
- if (warmupInFlight.has(key)) {
532
- continue;
533
- }
534
- warmupInFlight.add(key);
535
- warmSubtitleCues(torrent, fileIndex, sourceKey)
536
- .then((fresh) => {
537
- for (const entry of fresh) {
538
- const span = entry.spanStartSeconds === null
539
- ? "empty"
540
- : `${entry.spanStartSeconds.toFixed(1)}-${entry.spanEndSeconds.toFixed(1)}s`;
541
- log(
542
- `subtitle push ${sourceKey.slice(0, 8)}:${fileIndex} track ${entry.trackIndex}: ` +
543
- `${entry.cues.length} new cue(s) covering ${span}, ` +
544
- `clusters walked ${entry.walkedClusters}/${entry.indexedClusters}, cursor ${entry.cursor}, ` +
545
- "posting to main thread"
546
- );
547
- parentPort.postMessage({
548
- type: Event.SUBTITLE_CUES_READY,
549
- sourceKey,
550
- fileIndex,
551
- trackIndex: entry.trackIndex,
552
- cues: entry.cues,
553
- language: entry.language,
554
- cursor: entry.cursor
555
- });
556
- }
557
- })
558
- .catch((error) => {
559
- log(`subtitle warmup ${sourceKey}:${fileIndex} failed: ${error instanceof Error ? error.message : error}`);
560
- })
561
- .finally(() => {
562
- warmupInFlight.delete(key);
563
- });
564
- }
565
- }
566
-
567
- /**
568
- * Files whose warmup pass has not finished yet, by `sourceKey:fileIndex`.
569
- *
570
- * @type {Set<string>}
571
- */
572
- const warmupInFlight = new Set();
573
-
574
- /**
575
- * Torrents already wired to warm their subtitle cues the moment a piece
576
- * verifies, so the same torrent is not listened to twice.
577
- *
578
- * @type {WeakSet<object>}
579
- */
580
- const subtitleWarmupWired = new WeakSet();
581
-
582
- /**
583
- * A piece becoming readable is the actual event a cue can be pulled from —
584
- * "downloaded", not "about to be encoded or copied": what a viewer reaches is
585
- * decided by the read window ahead of the playhead, not by which of the two
586
- * paths a segment takes, and the piece exists (and is worth reading for
587
- * subtitles) whichever one that is. `verified` is WebTorrent's own signal for
588
- * exactly that instant, set at the same place the bitfield itself is (`
589
- * _markVerified`), so nothing here is guessing at readiness a different way.
590
- *
591
- * @param {string} sourceKey
592
- * @param {object} torrent
593
- * @returns {void}
594
- */
595
- function ensureSubtitleWarmupWired(sourceKey, torrent) {
596
- if (subtitleWarmupWired.has(torrent)) {
597
- return;
598
- }
599
- subtitleWarmupWired.add(torrent);
600
- torrent.on("verified", () => warmActiveFiles(sourceKey, torrent));
601
- }
602
-
603
- /**
604
- * How often an actively-read file's subtitle cues are walked ahead of being
605
- * asked for, as a fallback beside the per-piece `verified` listener above —
606
- * catches a listener attached after pieces already verified, and anything the
607
- * event path might otherwise miss. Cheap once caught up (`warmSubtitleCues`
608
- * skips clusters it has already read).
609
- */
610
- const SUBTITLE_WARMUP_INTERVAL_MS = 3_000;
611
-
612
- setInterval(() => {
613
- for (const [sourceKey, torrent] of pool.torrents) {
614
- ensureSubtitleWarmupWired(sourceKey, torrent);
615
- warmActiveFiles(sourceKey, torrent);
616
- }
617
- }, SUBTITLE_WARMUP_INTERVAL_MS).unref();
618
-
619
- /**
620
- * Keeps this thread alive ON PURPOSE — the one interval left accounted for
621
- * (no `.unref()`).
622
- *
623
- * Every other recurring handle here is unref'd, upload is disabled by
624
- * default, and idle peer connections close about half a minute after the
625
- * traffic stops — so once nothing is being read, every handle can be gone
626
- * at once, the event loop drains, and this thread ends BY ITSELF. Node then
627
- * tears the isolate down, that teardown touches memory some native module
628
- * has already freed, and the fault (SIGSEGV inside `uv_timer_stop`, reached
629
- * through `PerIsolatePlatformData::Shutdown`) kills the whole process at
630
- * once — HTTP server, tunnel, data channels — before any JS handler runs.
631
- * Field evidence: two deaths on 2026-08-22 (15:50:12 and 16:12:21 UTC),
632
- * each ~35 s after the last byte of traffic, identical core dumps;
633
- * same crash family as the utp-native faults of 2026-08-18..21
634
- * (`research/worker-thread-drain-crash-2026-08-22.md`).
635
- *
636
- * An empty repeating interval costs nothing, keeps the loop from draining
637
- * while the process lives, and thereby keeps that teardown path — and the
638
- * corrupted structure inside it — unreachable, whichever module is guilty.
639
- */
640
- const WORKER_KEEPALIVE_INTERVAL_MS = 5_000;
641
-
642
- setInterval(() => {
643
- void process.uptime();
644
- }, WORKER_KEEPALIVE_INTERVAL_MS);
645
-
646
- log("torrent worker started");
1
+ /**
2
+ * @file The torrent thread: WebTorrent and nothing else.
3
+ *
4
+ * Everything that made the main thread unresponsive lives here now — peer
5
+ * connections, buffer concatenation, piece bookkeeping, garbage collection from
6
+ * all of it. The main thread keeps only what owes a viewer a prompt answer.
7
+ *
8
+ * This file deliberately holds no HTTP, no session logic and no knowledge of
9
+ * HLS: it answers the commands in `protocol.js` and streams bytes back. That
10
+ * boundary is what keeps the split honest — anything added here will compete
11
+ * with the torrent for this thread, which is exactly the problem being solved.
12
+ *
13
+ * The existing `TorrentPool` is reused wholesale rather than reimplemented. It
14
+ * already carries the parts that took field failures to get right — refcounted
15
+ * file claims, idle removal, the global disk cap with LRU eviction, seek-aware
16
+ * piece prioritisation, adaptive upload — and none of that changes by moving
17
+ * threads.
18
+ */
19
+
20
+ // MUST stay first: it redirects `webrtc-polyfill` to a JavaScript WebRTC stack
21
+ // before WebTorrent can reach the native one. Two isolates using
22
+ // node-datachannel at once abort the process, and the torrent's wss trackers
23
+ // create peer connections of their own.
24
+ import { isUsableTorrentHandle } from "./handle-state.js";
25
+ import "./install-webrtc-shim.js";
26
+ import { parentPort, workerData } from "node:worker_threads";
27
+ import { createSendStream } from "./channel.js";
28
+ import { createFileClaims } from "./file-claims.js";
29
+ import { readFragments, supplyFiguresFor } from "./piece-reader.js";
30
+ import { cuesHeldFor, declaredSubtitleTracksOf, subtitleTracksOf, warmSubtitleCues } from "./subtitle-cues.js";
31
+ import { Command, Event } from "./protocol.js";
32
+
33
+ // Imported dynamically, and that is load-bearing: static imports are RESOLVED
34
+ // during linking, before any module body runs, so a statically imported pool
35
+ // would drag in WebTorrent — and with it the real `webrtc-polyfill` — before
36
+ // the hook above had a chance to register. Verified the hard way: with a static
37
+ // import the process still aborted, and the stack named the genuine polyfill.
38
+ const { TorrentPool, resolveDhtBootstrap } = await import("../torrent-pool.js");
39
+ const { collectStoreStats, findSharedStore } = await import("../piece-store/shared-piece-store.js");
40
+
41
+ // Resolved before the client exists, because the client builds its DHT in its
42
+ // own constructor and the addresses have to be in hand by then. Awaiting here
43
+ // costs the few milliseconds of a DNS answer, once, on a thread that has not
44
+ // been asked for anything yet.
45
+ const dhtBootstrap = await resolveDhtBootstrap();
46
+
47
+ const pool = new TorrentPool({
48
+ maxDiskBytes: workerData?.maxDiskBytes,
49
+ memoryBytes: workerData?.memoryBytes,
50
+ dhtBootstrap
51
+ });
52
+
53
+ /** Torrents by sourceKey — the main thread names them, this thread owns them. */
54
+ const torrentsByKey = new Map();
55
+
56
+ /**
57
+ * How each source was named when it was added, so a torrent that has since been
58
+ * destroyed can be added again. Kept separately from {@link torrentsByKey}
59
+ * because that map holds the promise, not the recipe.
60
+ *
61
+ * @type {Map<string, { sourceType: string, source: string }>}
62
+ */
63
+ const sourceRecipes = new Map();
64
+ /** File claims, each with its own identity — see `file-claims.js`. */
65
+ const fileClaims = createFileClaims();
66
+ /** In-flight reads, so a cancel can stop one mid-body. */
67
+ const readsById = new Map();
68
+
69
+ /**
70
+ * Forward a log line to the main thread, so worker output is not lost or
71
+ * interleaved separately from everything else.
72
+ *
73
+ * @param {string} message
74
+ * @returns {void}
75
+ */
76
+ function log(message) {
77
+ parentPort.postMessage({ type: Event.LOG, message });
78
+ }
79
+
80
+ /**
81
+ * The torrent for a sourceKey, waiting for it if it is still being added.
82
+ *
83
+ * The map holds a PROMISE, registered the moment the add begins rather than
84
+ * when it finishes. That distinction is the whole fix: adding a magnet takes as
85
+ * long as its metadata does — seconds to tens of seconds — and until 2.9.77
86
+ * everything naming that source in the meantime was told `Unknown source`,
87
+ * which is false. The source exists; it is not ready. Reproduced with a magnet
88
+ * nobody seeds: stats, the file listing and a read all failed instantly while
89
+ * the add was still in flight, which on the loading screen shows up as no
90
+ * peers, no progress, and a plan request that fails before the torrent has had
91
+ * a chance to start.
92
+ *
93
+ * A source that was never added still throws, which is the honest answer.
94
+ *
95
+ * @param {string} sourceKey
96
+ * @returns {Promise<import("webtorrent").Torrent>}
97
+ */
98
+ async function requireTorrent(sourceKey) {
99
+ const pending = torrentsByKey.get(sourceKey);
100
+ if (!pending) {
101
+ throw new Error(`Unknown source ${sourceKey}.`);
102
+ }
103
+ const torrent = await pending;
104
+ if (isUsableTorrentHandle(torrent)) {
105
+ return torrent;
106
+ }
107
+ // The pool destroys a torrent that has gone unread for a quarter of an hour,
108
+ // and under disk pressure. It clears its OWN map when it does; this one it
109
+ // knows nothing about, so the promise here went on resolving to a corpse: a
110
+ // destroyed torrent keeps its object but loses its files. Every later session
111
+ // for that source then failed the same way — the plan and the codec probe
112
+ // answered from cache in milliseconds, nothing waited for metadata because
113
+ // everything believed the torrent was known, and ffmpeg's first read died on
114
+ // `File N not found` 130 ms in, after which the session answered 500 for
115
+ // ever. Measured 2026-08-06 on two sessions in a row, both from a phone,
116
+ // which is what made it look like a mobile problem.
117
+ const recipe = sourceRecipes.get(sourceKey);
118
+ if (!recipe) {
119
+ torrentsByKey.delete(sourceKey);
120
+ throw new Error(`Source ${sourceKey} is gone and cannot be re-added.`);
121
+ }
122
+ const revived = pool.getTorrent(recipe.sourceType, recipe.source);
123
+ torrentsByKey.set(sourceKey, revived);
124
+ revived.catch(() => {
125
+ if (torrentsByKey.get(sourceKey) === revived) {
126
+ torrentsByKey.delete(sourceKey);
127
+ }
128
+ });
129
+ return revived;
130
+ }
131
+
132
+
133
+ /**
134
+ * Fragments waiting for the main thread to say it has finished reading them,
135
+ * keyed by request id. One per read, because only one fragment is in flight.
136
+ *
137
+ * @type {Map<number, () => void>}
138
+ */
139
+ const fragmentWaiters = new Map();
140
+
141
+ /**
142
+ * Wake a read that is waiting for a fragment to be confirmed.
143
+ *
144
+ * Used both by the confirmation itself and by cancellation — a cancelled read
145
+ * will never be confirmed, and without this it would wait forever holding a pin.
146
+ *
147
+ * @param {number} id
148
+ * @returns {void}
149
+ */
150
+ function settleFragment(id) {
151
+ const done = fragmentWaiters.get(id);
152
+ if (done) {
153
+ fragmentWaiters.delete(id);
154
+ done();
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Send one fragment's position and wait until the main thread is done with it.
160
+ *
161
+ * The pin is dropped only after the confirmation, because until then the other
162
+ * thread may still be reading those exact bytes.
163
+ *
164
+ * @param {number} id
165
+ * @param {import("./piece-reader.js").PieceFragment} fragment
166
+ * @returns {Promise<void>}
167
+ */
168
+ function sendFragment(id, fragment) {
169
+ return new Promise((resolve) => {
170
+ fragmentWaiters.set(id, () => {
171
+ fragment.release();
172
+ resolve();
173
+ });
174
+ parentPort.postMessage({
175
+ type: Event.FRAGMENT,
176
+ id,
177
+ pieceIndex: fragment.pieceIndex,
178
+ offset: fragment.offset,
179
+ length: fragment.length
180
+ });
181
+ });
182
+ }
183
+
184
+ /**
185
+ * Stream a byte range back as CHUNK messages.
186
+ *
187
+ * Reads through WebTorrent's own read stream — which serves already-downloaded
188
+ * pieces from disk and waits for the rest — and forwards it in
189
+ * {@link STREAM_CHUNK_BYTES} pieces, transferring ownership of each so nothing
190
+ * is copied across the boundary. `createSendStream` applies the backpressure,
191
+ * so a fast disk cannot outrun the main thread and rebuild the queue in memory.
192
+ *
193
+ * @param {object} params
194
+ * @param {number} params.id - Request id; CHUNK/READ_END carry it.
195
+ * @param {string} params.sourceKey
196
+ * @param {number} params.fileIndex
197
+ * @param {number | null} params.start - Inclusive, or null for the whole file.
198
+ * @param {number | null} params.end - Inclusive.
199
+ * @returns {Promise<void>}
200
+ */
201
+ async function streamRange({ id, sourceKey, fileIndex, start, end, windowBytes }) {
202
+ const torrent = await requireTorrent(sourceKey);
203
+ const file = torrent.files?.[fileIndex];
204
+ if (!file) {
205
+ throw new Error(`File ${fileIndex} not found in ${sourceKey}.`);
206
+ }
207
+
208
+ const sender = createSendStream({ port: parentPort, requestId: id });
209
+ readsById.set(id, sender);
210
+
211
+ // Hold the file for as long as this read runs. The caller also acquires it,
212
+ // but that acquire and its release are separate messages from another thread
213
+ // and can be reordered; this one cannot, because it lives entirely inside the
214
+ // read. Without it the idle sweep saw a zero reader count and removed the
215
+ // torrent AND its store mid-read — field 2026-08-02: "removed idle torrent
216
+ // ... and its store", after which every subsequent read hung and ffmpeg got
217
+ // an empty input.
218
+ const releaseRead = pool.acquireFile(torrent, fileIndex);
219
+
220
+ const rangeStart = start ?? 0;
221
+ const rangeEnd = end ?? file.length - 1;
222
+
223
+ let failed = false;
224
+ try {
225
+ // Positions in shared memory, not bytes: the main thread maps the same pool
226
+ // and reads each fragment in place, so nothing is copied and nothing is
227
+ // transferred. See `piece-reader.js`.
228
+ for await (const fragment of readFragments({
229
+ torrent,
230
+ fileIndex,
231
+ start: rangeStart,
232
+ end: rangeEnd,
233
+ cancellation: sender,
234
+ windowBytes
235
+ })) {
236
+ if (sender.isCancelled()) {
237
+ fragment.release();
238
+ break;
239
+ }
240
+ // One fragment in flight at a time. Each one holds a piece pinned, and
241
+ // the store guarantees only two resident pieces at its smallest budget —
242
+ // holding two pins while asking for a third would deadlock it against
243
+ // itself. The round trip costs ~100 µs against a piece worth megabytes,
244
+ // so there is nothing to win by overlapping them.
245
+ await sendFragment(id, fragment);
246
+ }
247
+ } catch (error) {
248
+ // The end-of-read marker means "the body is complete". Sending it after a
249
+ // failure told the reader the file simply ended — a truncated segment that
250
+ // ffmpeg reported as `Stream ends prematurely`, with the real cause thrown
251
+ // away. Let the error propagate instead; the command handler reports it and
252
+ // the main thread fails the stream.
253
+ failed = true;
254
+ throw error;
255
+ } finally {
256
+ readsById.delete(id);
257
+ // Any fragment still awaiting confirmation will never get one now; settling
258
+ // it here releases its pin rather than leaking a held slot.
259
+ settleFragment(id);
260
+ releaseRead();
261
+ if (!failed) {
262
+ sender.end();
263
+ }
264
+ // Nothing else to tear down: the reader owns no stream of its own, and a
265
+ // cancelled read stops at its next fragment boundary because it polls the
266
+ // same `sender` for cancellation.
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Run one command and return its result.
272
+ *
273
+ * @param {string} command
274
+ * @param {object} params
275
+ * @param {number} id
276
+ * @returns {Promise<unknown>}
277
+ */
278
+ async function runCommand(command, params, id) {
279
+ switch (command) {
280
+ case Command.ADD_SOURCE: {
281
+ // Registered before it resolves, so anything naming this source while it
282
+ // is being added waits for it instead of being told it does not exist.
283
+ // Reusing the same promise for a repeated add also collapses two callers
284
+ // racing to open the same torrent into one.
285
+ sourceRecipes.set(params.sourceKey, {
286
+ sourceType: params.sourceType,
287
+ source: params.source
288
+ });
289
+ let pending = torrentsByKey.get(params.sourceKey);
290
+ if (!pending) {
291
+ pending = pool.getTorrent(params.sourceType, params.source);
292
+ torrentsByKey.set(params.sourceKey, pending);
293
+ // A failed add must not be remembered, or every later attempt at this
294
+ // source replays the same failure. The handler also marks the rejection
295
+ // as observed, so it cannot surface as an unhandled one.
296
+ pending.catch(() => {
297
+ if (torrentsByKey.get(params.sourceKey) === pending) {
298
+ torrentsByKey.delete(params.sourceKey);
299
+ }
300
+ });
301
+ }
302
+ const torrent = await pending;
303
+ return {
304
+ infoHash: torrent.infoHash,
305
+ name: torrent.name,
306
+ // The piece pool itself. A `SharedArrayBuffer` crosses as a reference to
307
+ // the same memory rather than a copy, which is what lets the main thread
308
+ // read a piece where it already lies instead of being sent its bytes.
309
+ sharedBuffer: findSharedStore(torrent)?.sharedBuffer ?? null,
310
+ // Files cross as plain data; the objects stay here.
311
+ files: (torrent.files ?? []).map((file, index) => ({
312
+ index,
313
+ name: file.name,
314
+ path: file.path,
315
+ length: file.length
316
+ }))
317
+ };
318
+ }
319
+
320
+ case Command.LIST_FILES: {
321
+ const torrent = await requireTorrent(params.sourceKey);
322
+ return (torrent.files ?? []).map((file, index) => ({
323
+ index,
324
+ name: file.name,
325
+ path: file.path,
326
+ length: file.length
327
+ }));
328
+ }
329
+
330
+ case Command.ACQUIRE_FILE: {
331
+ const torrent = await requireTorrent(params.sourceKey);
332
+ // Every acquire is its own claim. Sharing one per file meant the first
333
+ // reader to finish released the hold while others were still reading.
334
+ return fileClaims.open(
335
+ params.sourceKey,
336
+ params.fileIndex,
337
+ pool.acquireFile(torrent, params.fileIndex)
338
+ );
339
+ }
340
+
341
+ case Command.RELEASE_FILE: {
342
+ const released = fileClaims.close(params.claimId);
343
+ if (!released) {
344
+ // Not fatal — but it means a release arrived twice or after teardown,
345
+ // and silence here is what let the previous scheme look healthy.
346
+ log(`release for unknown file claim ${params.claimId}`);
347
+ }
348
+ return released;
349
+ }
350
+
351
+ case Command.TORRENT_TOTALS: {
352
+ // Downloaded and uploaded are counted apart: hashing every downloaded
353
+ // byte is work of a different order from sending one back to the swarm,
354
+ // and adding them would price both at whatever the mixture happened to
355
+ // be.
356
+ let downloaded = 0;
357
+ let uploaded = 0;
358
+ for (const torrent of pool.client?.torrents ?? []) {
359
+ const gotBytes = Number(torrent?.downloaded);
360
+ const sentBytes = Number(torrent?.uploaded);
361
+ downloaded += Number.isFinite(gotBytes) ? gotBytes : 0;
362
+ uploaded += Number.isFinite(sentBytes) ? sentBytes : 0;
363
+ }
364
+ return { downloaded, uploaded };
365
+ }
366
+
367
+ case Command.SUBTITLE_TRACKS: {
368
+ const torrent = await requireTorrent(params.sourceKey);
369
+ return {
370
+ tracks: await subtitleTracksOf(torrent, params.fileIndex, params.sourceKey),
371
+ declared: await declaredSubtitleTracksOf(torrent, params.fileIndex, params.sourceKey)
372
+ };
373
+ }
374
+
375
+ case Command.SUBTITLE_CUES: {
376
+ const torrent = await requireTorrent(params.sourceKey);
377
+ const held = await cuesHeldFor(torrent, params.fileIndex, params.sourceKey, params.trackNumber);
378
+ return {
379
+ cues: held.cues,
380
+ coveredClusters: held.coveredClusters,
381
+ indexedClusters: held.indexedClusters,
382
+ codecId: held.track?.codecId ?? "",
383
+ codecPrivate: held.track?.codecPrivate ?? "",
384
+ language: held.track?.language ?? ""
385
+ };
386
+ }
387
+
388
+ case Command.FILE_STATS: {
389
+ const torrent = await requireTorrent(params.sourceKey);
390
+ const stats = pool.getFileStats(torrent, params.fileIndex, {
391
+ resumeAnchorByteStart: params.resumeAnchorByteStart ?? null
392
+ });
393
+ // What this file's own interruptions demand, measured by the reader in
394
+ // this thread. It travels with the stats because the caller asking for
395
+ // them is the one that has to decide with them — the browser's smallest
396
+ // safe buffer, and the speed a quality step must sustain. Null until a
397
+ // second interruption has been seen: one wait shows no interval, and an
398
+ // interval invented from one point is exactly what this work removes.
399
+ const file = Array.isArray(torrent?.files) ? torrent.files[params.fileIndex] : null;
400
+ return {
401
+ ...stats,
402
+ supply: supplyFiguresFor(torrent?.infoHash, file?.name, params.segmentSeconds ?? 4)
403
+ };
404
+ }
405
+
406
+ case Command.PRIORITIZE: {
407
+ const torrent = await requireTorrent(params.sourceKey);
408
+ pool.prioritizeByteRange(torrent, params.fileIndex, params.byteStart, params.windowBytes, {
409
+ wholeFileRead: params.wholeFileRead === true
410
+ });
411
+ return true;
412
+ }
413
+
414
+ case Command.PREFETCH_EDGES: {
415
+ const torrent = await requireTorrent(params.sourceKey);
416
+ return pool.prefetchFileEdges(torrent, params.fileIndex, params.options ?? {});
417
+ }
418
+
419
+ case Command.READ_RANGE: {
420
+ // Streams its own reply; the caller's promise resolves once the body has
421
+ // been fully sent, which is what lets the client await completion.
422
+ await streamRange({
423
+ id,
424
+ sourceKey: params.sourceKey,
425
+ fileIndex: params.fileIndex,
426
+ start: params.start ?? null,
427
+ end: params.end ?? null,
428
+ windowBytes: params.windowBytes
429
+ });
430
+ return true;
431
+ }
432
+
433
+ case Command.CANCEL_READ: {
434
+ readsById.get(params.readId)?.cancel();
435
+ // A cancelled read will never have its outstanding fragment confirmed, so
436
+ // wake it here — otherwise it waits forever with a piece pinned.
437
+ settleFragment(params.readId);
438
+ return true;
439
+ }
440
+
441
+ case Command.DESTROY_ALL: {
442
+ fileClaims.closeAll();
443
+ torrentsByKey.clear();
444
+ sourceRecipes.clear();
445
+ await pool.destroyAll();
446
+ return true;
447
+ }
448
+
449
+ default:
450
+ throw new Error(`Unknown torrent-worker command: ${command}`);
451
+ }
452
+ }
453
+
454
+ parentPort.on("message", async (message) => {
455
+ // Chunk acknowledgements are not commands — they release backpressure on an
456
+ // in-flight read.
457
+ if (message?.type === Event.CHUNK_ACK) {
458
+ readsById.get(message.id)?.ack();
459
+ return;
460
+ }
461
+
462
+ // The main thread has finished reading a fragment out of shared memory, so
463
+ // its piece may be unpinned and the read may continue.
464
+ if (message?.type === Event.FRAGMENT_DONE) {
465
+ settleFragment(message.id);
466
+ return;
467
+ }
468
+
469
+ const { command, id, params } = message ?? {};
470
+ try {
471
+ const result = await runCommand(command, params ?? {}, id);
472
+ parentPort.postMessage({ type: Event.RESULT, id, result });
473
+ } catch (error) {
474
+ parentPort.postMessage({ type: Event.ERROR, id, error: error?.message ?? String(error) });
475
+ }
476
+ });
477
+
478
+ /**
479
+ * How often the piece store reports what it has been doing.
480
+ *
481
+ * The store decides whether a read costs nothing or costs a disk trip, and
482
+ * until 2.9.75 nothing about it reached the log — a field oddity would have had
483
+ * no evidence to work from. Reported only when something changed, so an idle
484
+ * proxy stays quiet.
485
+ */
486
+ const STORE_REPORT_INTERVAL_MS = 60_000;
487
+
488
+ /** Last reported figures per store, so unchanged ones stay silent. */
489
+ const lastReported = new Map();
490
+
491
+ setInterval(() => {
492
+ for (const stats of collectStoreStats()) {
493
+ const signature = `${stats.fromMemory}/${stats.fromDisk}/${stats.spills}/${stats.revivals}/${stats.blockedByPins}`;
494
+ if (lastReported.get(stats.name) === signature) {
495
+ continue;
496
+ }
497
+ lastReported.set(stats.name, signature);
498
+
499
+ const reads = stats.fromMemory + stats.fromDisk;
500
+ const fromMemoryShare = reads > 0 ? ((stats.fromMemory / reads) * 100).toFixed(1) : "—";
501
+ log(
502
+ `piece-store "${stats.name.slice(0, 40)}": resident=${stats.resident}/${stats.capacity} ` +
503
+ `pinned=${stats.pinned} spilled=${stats.spilled} reads=${reads} (${fromMemoryShare}% from memory) ` +
504
+ `spills=${stats.spills} revivals=${stats.revivals}` +
505
+ (stats.blockedByPins > 0 ? ` blocked-by-pins=${stats.blockedByPins}` : "")
506
+ );
507
+ }
508
+ }, STORE_REPORT_INTERVAL_MS).unref();
509
+
510
+ /**
511
+ * Walk subtitle cues for every actively-read file of one torrent, and PUSH
512
+ * whatever came out new to the main thread — which is what makes a browser's
513
+ * copy current without it having asked.
514
+ *
515
+ * @param {string} sourceKey
516
+ * @param {object} torrent
517
+ * @returns {void}
518
+ */
519
+ function warmActiveFiles(sourceKey, torrent) {
520
+ const usage = pool.fileUsageByTorrent.get(torrent);
521
+ if (!usage) {
522
+ return;
523
+ }
524
+ for (const fileIndex of usage.keys()) {
525
+ const key = `${sourceKey}:${fileIndex}`;
526
+ // A trigger that arrives while the previous pass is still walking is
527
+ // dropped, not queued. `verified` fires per piece, so on a fast download
528
+ // these arrive many times a second; the walk is serialized per file anyway,
529
+ // and a queue of identical passes would only postpone the one that has
530
+ // something new to find.
531
+ if (warmupInFlight.has(key)) {
532
+ continue;
533
+ }
534
+ warmupInFlight.add(key);
535
+ warmSubtitleCues(torrent, fileIndex, sourceKey)
536
+ .then((fresh) => {
537
+ for (const entry of fresh) {
538
+ const span = entry.spanStartSeconds === null
539
+ ? "empty"
540
+ : `${entry.spanStartSeconds.toFixed(1)}-${entry.spanEndSeconds.toFixed(1)}s`;
541
+ log(
542
+ `subtitle push ${sourceKey.slice(0, 8)}:${fileIndex} track ${entry.trackIndex}: ` +
543
+ `${entry.cues.length} new cue(s) covering ${span}, ` +
544
+ `clusters walked ${entry.walkedClusters}/${entry.indexedClusters}, cursor ${entry.cursor}, ` +
545
+ "posting to main thread"
546
+ );
547
+ parentPort.postMessage({
548
+ type: Event.SUBTITLE_CUES_READY,
549
+ sourceKey,
550
+ fileIndex,
551
+ trackIndex: entry.trackIndex,
552
+ cues: entry.cues,
553
+ language: entry.language,
554
+ cursor: entry.cursor
555
+ });
556
+ }
557
+ })
558
+ .catch((error) => {
559
+ log(`subtitle warmup ${sourceKey}:${fileIndex} failed: ${error instanceof Error ? error.message : error}`);
560
+ })
561
+ .finally(() => {
562
+ warmupInFlight.delete(key);
563
+ });
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Files whose warmup pass has not finished yet, by `sourceKey:fileIndex`.
569
+ *
570
+ * @type {Set<string>}
571
+ */
572
+ const warmupInFlight = new Set();
573
+
574
+ /**
575
+ * Torrents already wired to warm their subtitle cues the moment a piece
576
+ * verifies, so the same torrent is not listened to twice.
577
+ *
578
+ * @type {WeakSet<object>}
579
+ */
580
+ const subtitleWarmupWired = new WeakSet();
581
+
582
+ /**
583
+ * A piece becoming readable is the actual event a cue can be pulled from —
584
+ * "downloaded", not "about to be encoded or copied": what a viewer reaches is
585
+ * decided by the read window ahead of the playhead, not by which of the two
586
+ * paths a segment takes, and the piece exists (and is worth reading for
587
+ * subtitles) whichever one that is. `verified` is WebTorrent's own signal for
588
+ * exactly that instant, set at the same place the bitfield itself is (`
589
+ * _markVerified`), so nothing here is guessing at readiness a different way.
590
+ *
591
+ * @param {string} sourceKey
592
+ * @param {object} torrent
593
+ * @returns {void}
594
+ */
595
+ function ensureSubtitleWarmupWired(sourceKey, torrent) {
596
+ if (subtitleWarmupWired.has(torrent)) {
597
+ return;
598
+ }
599
+ subtitleWarmupWired.add(torrent);
600
+ torrent.on("verified", () => warmActiveFiles(sourceKey, torrent));
601
+ }
602
+
603
+ /**
604
+ * How often an actively-read file's subtitle cues are walked ahead of being
605
+ * asked for, as a fallback beside the per-piece `verified` listener above —
606
+ * catches a listener attached after pieces already verified, and anything the
607
+ * event path might otherwise miss. Cheap once caught up (`warmSubtitleCues`
608
+ * skips clusters it has already read).
609
+ */
610
+ const SUBTITLE_WARMUP_INTERVAL_MS = 3_000;
611
+
612
+ setInterval(() => {
613
+ for (const [sourceKey, torrent] of pool.torrents) {
614
+ ensureSubtitleWarmupWired(sourceKey, torrent);
615
+ warmActiveFiles(sourceKey, torrent);
616
+ }
617
+ }, SUBTITLE_WARMUP_INTERVAL_MS).unref();
618
+
619
+ /**
620
+ * Keeps this thread alive ON PURPOSE — the one interval left accounted for
621
+ * (no `.unref()`).
622
+ *
623
+ * Every other recurring handle here is unref'd, upload is disabled by
624
+ * default, and idle peer connections close about half a minute after the
625
+ * traffic stops — so once nothing is being read, every handle can be gone
626
+ * at once, the event loop drains, and this thread ends BY ITSELF. Node then
627
+ * tears the isolate down, that teardown touches memory some native module
628
+ * has already freed, and the fault (SIGSEGV inside `uv_timer_stop`, reached
629
+ * through `PerIsolatePlatformData::Shutdown`) kills the whole process at
630
+ * once — HTTP server, tunnel, data channels — before any JS handler runs.
631
+ * Field evidence: two deaths on 2026-08-22 (15:50:12 and 16:12:21 UTC),
632
+ * each ~35 s after the last byte of traffic, identical core dumps;
633
+ * same crash family as the utp-native faults of 2026-08-18..21
634
+ * (`research/worker-thread-drain-crash-2026-08-22.md`).
635
+ *
636
+ * An empty repeating interval costs nothing, keeps the loop from draining
637
+ * while the process lives, and thereby keeps that teardown path — and the
638
+ * corrupted structure inside it — unreachable, whichever module is guilty.
639
+ */
640
+ const WORKER_KEEPALIVE_INTERVAL_MS = 5_000;
641
+
642
+ setInterval(() => {
643
+ void process.uptime();
644
+ }, WORKER_KEEPALIVE_INTERVAL_MS);
645
+
646
+ /**
647
+ * Say why this thread is ending, from inside it, before anything is torn down.
648
+ *
649
+ * The crash of 2026-08-27 15:40 is `node::worker::Worker::Run()` returning and
650
+ * node faulting as it closes what was left on this loop. The parent DOES watch
651
+ * for an unexpected exit and has a line ready for it — but that line never
652
+ * printed, because the fault happens during this thread's own teardown, before
653
+ * the parent's `exit` event is delivered. So the one reading that would name
654
+ * the cause was being eaten by the failure it was meant to explain.
655
+ *
656
+ * These handlers run first, synchronously, and write through the same channel
657
+ * as every other line here. `beforeExit` means the loop drained despite the
658
+ * keepalive above; `exit` means the thread is going whatever the reason. The
659
+ * list of what was still holding the loop open is the part that says which.
660
+ */
661
+ process.on("beforeExit", (code) => {
662
+ log(
663
+ `thread is about to end because the event loop drained (code ${code}) — ` +
664
+ `still open: ${describeActiveResources()}`
665
+ );
666
+ });
667
+
668
+ process.on("exit", (code) => {
669
+ log(`thread ending with code ${code} — still open: ${describeActiveResources()}`);
670
+ });
671
+
672
+ process.on("uncaughtException", (error) => {
673
+ log(`thread hit an uncaught error: ${error?.stack ?? error}`);
674
+ });
675
+
676
+ process.on("unhandledRejection", (reason) => {
677
+ log(`thread hit an unhandled rejection: ${reason?.stack ?? reason}`);
678
+ });
679
+
680
+ /**
681
+ * What is still holding this thread's event loop open, as node names it.
682
+ *
683
+ * @returns {string} A tally per resource kind, or why it could not be read.
684
+ */
685
+ function describeActiveResources() {
686
+ try {
687
+ const names = process.getActiveResourcesInfo?.() ?? [];
688
+ if (names.length === 0) {
689
+ return "nothing";
690
+ }
691
+ const tally = new Map();
692
+ for (const name of names) {
693
+ tally.set(name, (tally.get(name) ?? 0) + 1);
694
+ }
695
+ return [...tally].map(([name, count]) => `${name}x${count}`).join(" ");
696
+ } catch (error) {
697
+ return `unreadable (${error?.message ?? error})`;
698
+ }
699
+ }
700
+
701
+ log("torrent worker started");