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