@torrent-tv/proxy 2.64.7 → 2.64.9

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,750 +1,765 @@
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, WORKER_MEMORY_SAMPLE_MS } 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, 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
- buffer: fragment.buffer,
180
- offset: fragment.offset,
181
- length: fragment.length
182
- });
183
- });
184
- }
185
-
186
- /**
187
- * Stream a byte range back as CHUNK messages.
188
- *
189
- * Reads through WebTorrent's own read stream — which serves already-downloaded
190
- * pieces from disk and waits for the rest — and forwards it in
191
- * {@link STREAM_CHUNK_BYTES} pieces, transferring ownership of each so nothing
192
- * is copied across the boundary. `createSendStream` applies the backpressure,
193
- * so a fast disk cannot outrun the main thread and rebuild the queue in memory.
194
- *
195
- * @param {object} params
196
- * @param {number} params.id - Request id; CHUNK/READ_END carry it.
197
- * @param {string} params.sourceKey
198
- * @param {number} params.fileIndex
199
- * @param {number | null} params.start - Inclusive, or null for the whole file.
200
- * @param {number | null} params.end - Inclusive.
201
- * @returns {Promise<void>}
202
- */
203
- async function streamRange({ id, sourceKey, fileIndex, start, end, windowBytes }) {
204
- const torrent = await requireTorrent(sourceKey);
205
- const file = torrent.files?.[fileIndex];
206
- if (!file) {
207
- throw new Error(`File ${fileIndex} not found in ${sourceKey}.`);
208
- }
209
-
210
- const sender = createSendStream({ port: parentPort, requestId: id });
211
- readsById.set(id, sender);
212
-
213
- // Hold the file for as long as this read runs. The caller also acquires it,
214
- // but that acquire and its release are separate messages from another thread
215
- // and can be reordered; this one cannot, because it lives entirely inside the
216
- // read. Without it the idle sweep saw a zero reader count and removed the
217
- // torrent AND its store mid-read — field 2026-08-02: "removed idle torrent
218
- // ... and its store", after which every subsequent read hung and ffmpeg got
219
- // an empty input.
220
- const releaseRead = pool.acquireFile(torrent, fileIndex);
221
-
222
- const rangeStart = start ?? 0;
223
- const rangeEnd = end ?? file.length - 1;
224
-
225
- let failed = false;
226
- try {
227
- // Positions in shared memory, not bytes: the main thread maps the same pool
228
- // and reads each fragment in place, so nothing is copied and nothing is
229
- // transferred. See `piece-reader.js`.
230
- for await (const fragment of readFragments({
231
- torrent,
232
- fileIndex,
233
- start: rangeStart,
234
- end: rangeEnd,
235
- cancellation: sender,
236
- windowBytes
237
- })) {
238
- if (sender.isCancelled()) {
239
- fragment.release();
240
- break;
241
- }
242
- // One fragment in flight at a time. Each one holds a piece pinned, and
243
- // the store guarantees only two resident pieces at its smallest budget —
244
- // holding two pins while asking for a third would deadlock it against
245
- // itself. The round trip costs ~100 µs against a piece worth megabytes,
246
- // so there is nothing to win by overlapping them.
247
- await sendFragment(id, fragment);
248
- }
249
- } catch (error) {
250
- // The end-of-read marker means "the body is complete". Sending it after a
251
- // failure told the reader the file simply ended — a truncated segment that
252
- // ffmpeg reported as `Stream ends prematurely`, with the real cause thrown
253
- // away. Let the error propagate instead; the command handler reports it and
254
- // the main thread fails the stream.
255
- failed = true;
256
- throw error;
257
- } finally {
258
- readsById.delete(id);
259
- // Any fragment still awaiting confirmation will never get one now; settling
260
- // it here releases its pin rather than leaking a held slot.
261
- settleFragment(id);
262
- releaseRead();
263
- if (!failed) {
264
- sender.end();
265
- }
266
- // Nothing else to tear down: the reader owns no stream of its own, and a
267
- // cancelled read stops at its next fragment boundary because it polls the
268
- // same `sender` for cancellation.
269
- }
270
- }
271
-
272
- /**
273
- * Run one command and return its result.
274
- *
275
- * @param {string} command
276
- * @param {object} params
277
- * @param {number} id
278
- * @returns {Promise<unknown>}
279
- */
280
- async function runCommand(command, params, id) {
281
- switch (command) {
282
- case Command.ADD_SOURCE: {
283
- // Registered before it resolves, so anything naming this source while it
284
- // is being added waits for it instead of being told it does not exist.
285
- // Reusing the same promise for a repeated add also collapses two callers
286
- // racing to open the same torrent into one.
287
- sourceRecipes.set(params.sourceKey, {
288
- sourceType: params.sourceType,
289
- source: params.source
290
- });
291
- let pending = torrentsByKey.get(params.sourceKey);
292
- if (!pending) {
293
- pending = pool.getTorrent(params.sourceType, params.source);
294
- torrentsByKey.set(params.sourceKey, pending);
295
- // A failed add must not be remembered, or every later attempt at this
296
- // source replays the same failure. The handler also marks the rejection
297
- // as observed, so it cannot surface as an unhandled one.
298
- pending.catch(() => {
299
- if (torrentsByKey.get(params.sourceKey) === pending) {
300
- torrentsByKey.delete(params.sourceKey);
301
- }
302
- });
303
- }
304
- const torrent = await pending;
305
- return {
306
- infoHash: torrent.infoHash,
307
- name: torrent.name,
308
- // Files cross as plain data; the objects stay here.
309
- files: (torrent.files ?? []).map((file, index) => ({
310
- index,
311
- name: file.name,
312
- path: file.path,
313
- length: file.length
314
- }))
315
- };
316
- }
317
-
318
- case Command.LIST_FILES: {
319
- const torrent = await requireTorrent(params.sourceKey);
320
- return (torrent.files ?? []).map((file, index) => ({
321
- index,
322
- name: file.name,
323
- path: file.path,
324
- length: file.length
325
- }));
326
- }
327
-
328
- case Command.ACQUIRE_FILE: {
329
- const torrent = await requireTorrent(params.sourceKey);
330
- // Every acquire is its own claim. Sharing one per file meant the first
331
- // reader to finish released the hold while others were still reading.
332
- return fileClaims.open(
333
- params.sourceKey,
334
- params.fileIndex,
335
- pool.acquireFile(torrent, params.fileIndex)
336
- );
337
- }
338
-
339
- case Command.RELEASE_FILE: {
340
- const released = fileClaims.close(params.claimId);
341
- if (!released) {
342
- // Not fatal — but it means a release arrived twice or after teardown,
343
- // and silence here is what let the previous scheme look healthy.
344
- log(`release for unknown file claim ${params.claimId}`);
345
- }
346
- return released;
347
- }
348
-
349
- case Command.TORRENT_TOTALS: {
350
- // Downloaded and uploaded are counted apart: hashing every downloaded
351
- // byte is work of a different order from sending one back to the swarm,
352
- // and adding them would price both at whatever the mixture happened to
353
- // be.
354
- let downloaded = 0;
355
- let uploaded = 0;
356
- for (const torrent of pool.client?.torrents ?? []) {
357
- const gotBytes = Number(torrent?.downloaded);
358
- const sentBytes = Number(torrent?.uploaded);
359
- downloaded += Number.isFinite(gotBytes) ? gotBytes : 0;
360
- uploaded += Number.isFinite(sentBytes) ? sentBytes : 0;
361
- }
362
- return { downloaded, uploaded };
363
- }
364
-
365
- case Command.SUBTITLE_TRACKS: {
366
- const torrent = await requireTorrent(params.sourceKey);
367
- return {
368
- tracks: await subtitleTracksOf(torrent, params.fileIndex, params.sourceKey),
369
- declared: await declaredSubtitleTracksOf(torrent, params.fileIndex, params.sourceKey)
370
- };
371
- }
372
-
373
- case Command.SUBTITLE_CUES: {
374
- const torrent = await requireTorrent(params.sourceKey);
375
- const held = await cuesHeldFor(torrent, params.fileIndex, params.sourceKey, params.trackNumber);
376
- return {
377
- cues: held.cues,
378
- coveredClusters: held.coveredClusters,
379
- indexedClusters: held.indexedClusters,
380
- codecId: held.track?.codecId ?? "",
381
- codecPrivate: held.track?.codecPrivate ?? "",
382
- language: held.track?.language ?? ""
383
- };
384
- }
385
-
386
- case Command.FILE_STATS: {
387
- const torrent = await requireTorrent(params.sourceKey);
388
- const stats = pool.getFileStats(torrent, params.fileIndex, {
389
- resumeAnchorByteStart: params.resumeAnchorByteStart ?? null
390
- });
391
- // What this file's own interruptions demand, measured by the reader in
392
- // this thread. It travels with the stats because the caller asking for
393
- // them is the one that has to decide with them — the browser's smallest
394
- // safe buffer, and the speed a quality step must sustain. Null until a
395
- // second interruption has been seen: one wait shows no interval, and an
396
- // interval invented from one point is exactly what this work removes.
397
- const file = Array.isArray(torrent?.files) ? torrent.files[params.fileIndex] : null;
398
- return {
399
- ...stats,
400
- supply: supplyFiguresFor(torrent?.infoHash, file?.name, params.segmentSeconds ?? 4)
401
- };
402
- }
403
-
404
- case Command.PRIORITIZE: {
405
- const torrent = await requireTorrent(params.sourceKey);
406
- pool.prioritizeByteRange(torrent, params.fileIndex, params.byteStart, params.windowBytes, {
407
- wholeFileRead: params.wholeFileRead === true
408
- });
409
- return true;
410
- }
411
-
412
- case Command.PREFETCH_EDGES: {
413
- const torrent = await requireTorrent(params.sourceKey);
414
- return pool.prefetchFileEdges(torrent, params.fileIndex, params.options ?? {});
415
- }
416
-
417
- case Command.READ_RANGE: {
418
- // Streams its own reply; the caller's promise resolves once the body has
419
- // been fully sent, which is what lets the client await completion.
420
- await streamRange({
421
- id,
422
- sourceKey: params.sourceKey,
423
- fileIndex: params.fileIndex,
424
- start: params.start ?? null,
425
- end: params.end ?? null,
426
- windowBytes: params.windowBytes
427
- });
428
- return true;
429
- }
430
-
431
- case Command.CANCEL_READ: {
432
- readsById.get(params.readId)?.cancel();
433
- // A cancelled read will never have its outstanding fragment confirmed, so
434
- // wake it here — otherwise it waits forever with a piece pinned.
435
- settleFragment(params.readId);
436
- return true;
437
- }
438
-
439
- case Command.DESTROY_ALL: {
440
- fileClaims.closeAll();
441
- torrentsByKey.clear();
442
- sourceRecipes.clear();
443
- await pool.destroyAll();
444
- return true;
445
- }
446
-
447
- default:
448
- throw new Error(`Unknown torrent-worker command: ${command}`);
449
- }
450
- }
451
-
452
- parentPort.on("message", async (message) => {
453
- // Chunk acknowledgements are not commands — they release backpressure on an
454
- // in-flight read.
455
- if (message?.type === Event.CHUNK_ACK) {
456
- readsById.get(message.id)?.ack();
457
- return;
458
- }
459
-
460
- // The main thread has finished reading a fragment out of shared memory, so
461
- // its piece may be unpinned and the read may continue.
462
- if (message?.type === Event.FRAGMENT_DONE) {
463
- settleFragment(message.id);
464
- return;
465
- }
466
-
467
- const { command, id, params } = message ?? {};
468
- try {
469
- const result = await runCommand(command, params ?? {}, id);
470
- parentPort.postMessage({ type: Event.RESULT, id, result });
471
- } catch (error) {
472
- parentPort.postMessage({ type: Event.ERROR, id, error: error?.message ?? String(error) });
473
- }
474
- });
475
-
476
- /**
477
- * How often the piece store reports what it has been doing.
478
- *
479
- * The store decides whether a read costs nothing or costs a disk trip, and
480
- * until 2.9.75 nothing about it reached the log — a field oddity would have had
481
- * no evidence to work from. Reported only when something changed, so an idle
482
- * proxy stays quiet.
483
- */
484
- // The torrent worker's OWN isolate, reported from inside it. The piece pool is
485
- // a `SharedArrayBuffer` allocated here, so the main thread's counters cannot
486
- // see it however carefully they are read — which is half the reason 650 MB of a
487
- // 893 MB process had no explanation on 2026-08-28 (roadmap item 2).
488
- // A second between readings, a minute between lines unless the heap moved by
489
- // 25 MB, and a heap snapshot of THIS isolate on every new high-water above
490
- // 400 MB. Three deaths — 2026-08-30 14:00 and 23:19, and
491
- // 2026-08-31 13:27 — went from a 30 MB heap to the 2240 MB ceiling inside one
492
- // sixty-second gap, and the only snapshots ever written were of the main
493
- // isolate, whose heap is 26 MB. So the isolate that dies has never once been
494
- // looked at (roadmap item 2, `research/worker-heap-oom-2026-08-31.md`).
495
- startMemoryReport({
496
- log,
497
- readStores: collectStoreStats,
498
- scope: "thread",
499
- label: "torrent worker",
500
- intervalMs: WORKER_MEMORY_SAMPLE_MS,
501
- quietMs: 60_000,
502
- changeBytes: 25 * 1024 * 1024,
503
- snapshotDir: workerData?.stateDir || undefined,
504
- snapshotFloorBytes: 400 * 1024 * 1024,
505
- snapshotGrowthBytes: 400 * 1024 * 1024,
506
- keepSnapshots: 3
507
- });
508
-
509
- const STORE_REPORT_INTERVAL_MS = 60_000;
510
-
511
- /** Last reported figures per store, so unchanged ones stay silent. */
512
- const lastReported = new Map();
513
-
514
- setInterval(() => {
515
- // What the machine can spare NOW, not what it could spare when each store was
516
- // created. With per-piece buffers a lowered ceiling is honoured immediately:
517
- // excess pieces are evicted to disk and their memory is reclaimable.
518
- for (const revised of reviseStoreBudgets()) {
519
- if (revised.evicted > 0) {
520
- log(
521
- `piece-store "${revised.name.slice(0, 40)}": allowance is now ` +
522
- `${Math.round(revised.ceilingBytes / 1048576)}MB, evicted ${revised.evicted} piece(s) to meet it — ` +
523
- `now ${Math.round(revised.committedBytes / 1048576)}MB committed`
524
- );
525
- } else if (revised.committedBytes > revised.ceilingBytes) {
526
- log(
527
- `piece-store "${revised.name.slice(0, 40)}": allowance is now ` +
528
- `${Math.round(revised.ceilingBytes / 1048576)}MB and ` +
529
- `${Math.round(revised.committedBytes / 1048576)}MB is committed — ` +
530
- `all resident pieces are pinned, cannot shrink yet`
531
- );
532
- }
533
- }
534
- for (const stats of collectStoreStats()) {
535
- const signature = `${stats.fromMemory}/${stats.fromDisk}/${stats.spills}/${stats.revivals}/${stats.blockedByPins}/${stats.evictedOnRevise}/${stats.spillFailures}`;
536
- if (lastReported.get(stats.name) === signature) {
537
- continue;
538
- }
539
- lastReported.set(stats.name, signature);
540
-
541
- const reads = stats.fromMemory + stats.fromDisk;
542
- const fromMemoryShare = reads > 0 ? ((stats.fromMemory / reads) * 100).toFixed(1) : "—";
543
- log(
544
- `piece-store "${stats.name.slice(0, 40)}": resident=${stats.resident}/${stats.capacity} ` +
545
- `(${Math.round((stats.residentBytes || 0) / 1048576)}MB of ` +
546
- `${Math.round((stats.budgetBytes || 0) / 1048576)}MB allowed) ` +
547
- `committed=${Math.round((stats.committedBytes || 0) / 1048576)}MB ` +
548
- `on-disk=${Math.round((stats.spilledBytes || 0) / 1048576)}MB ` +
549
- `pinned=${stats.pinned} spilled=${stats.spilled} reads=${reads} (${fromMemoryShare}% from memory) ` +
550
- `spills=${stats.spills} revivals=${stats.revivals}` +
551
- (stats.blockedByPins > 0 ? ` blocked-by-pins=${stats.blockedByPins}` : "") +
552
- (stats.evictedOnRevise > 0 ? ` evictedOnRevise=${stats.evictedOnRevise}` : "") +
553
- (stats.spillFailures > 0 ? ` spill-failures=${stats.spillFailures}` : "") +
554
- (stats.outstanding > 0 ? ` outstanding=${stats.outstanding}` : "")
555
- );
556
- }
557
- }, STORE_REPORT_INTERVAL_MS).unref();
558
-
559
- /**
560
- * Walk subtitle cues for every actively-read file of one torrent, and PUSH
561
- * whatever came out new to the main thread — which is what makes a browser's
562
- * copy current without it having asked.
563
- *
564
- * @param {string} sourceKey
565
- * @param {object} torrent
566
- * @returns {void}
567
- */
568
- function warmActiveFiles(sourceKey, torrent) {
569
- const usage = pool.fileUsageByTorrent.get(torrent);
570
- if (!usage) {
571
- return;
572
- }
573
- for (const fileIndex of usage.keys()) {
574
- const key = `${sourceKey}:${fileIndex}`;
575
- // A trigger that arrives while the previous pass is still walking is
576
- // dropped, not queued. `verified` fires per piece, so on a fast download
577
- // these arrive many times a second; the walk is serialized per file anyway,
578
- // and a queue of identical passes would only postpone the one that has
579
- // something new to find.
580
- if (warmupInFlight.has(key)) {
581
- continue;
582
- }
583
- warmupInFlight.add(key);
584
- warmSubtitleCues(torrent, fileIndex, sourceKey)
585
- .then((fresh) => {
586
- for (const entry of fresh) {
587
- const span = entry.spanStartSeconds === null
588
- ? "empty"
589
- : `${entry.spanStartSeconds.toFixed(1)}-${entry.spanEndSeconds.toFixed(1)}s`;
590
- log(
591
- `subtitle push ${sourceKey.slice(0, 8)}:${fileIndex} track ${entry.trackIndex}: ` +
592
- `${entry.cues.length} new cue(s) covering ${span}, ` +
593
- `clusters walked ${entry.walkedClusters}/${entry.indexedClusters}, cursor ${entry.cursor}, ` +
594
- "posting to main thread"
595
- );
596
- parentPort.postMessage({
597
- type: Event.SUBTITLE_CUES_READY,
598
- sourceKey,
599
- fileIndex,
600
- trackIndex: entry.trackIndex,
601
- cues: entry.cues,
602
- language: entry.language,
603
- cursor: entry.cursor
604
- });
605
- }
606
- })
607
- .catch((error) => {
608
- log(`subtitle warmup ${sourceKey}:${fileIndex} failed: ${error instanceof Error ? error.message : error}`);
609
- })
610
- .finally(() => {
611
- warmupInFlight.delete(key);
612
- });
613
- }
614
- }
615
-
616
- /**
617
- * Files whose warmup pass has not finished yet, by `sourceKey:fileIndex`.
618
- *
619
- * @type {Set<string>}
620
- */
621
- const warmupInFlight = new Set();
622
-
623
- /**
624
- * Torrents already wired to warm their subtitle cues the moment a piece
625
- * verifies, so the same torrent is not listened to twice.
626
- *
627
- * @type {WeakSet<object>}
628
- */
629
- const subtitleWarmupWired = new WeakSet();
630
-
631
- /**
632
- * A piece becoming readable is the actual event a cue can be pulled from —
633
- * "downloaded", not "about to be encoded or copied": what a viewer reaches is
634
- * decided by the read window ahead of the playhead, not by which of the two
635
- * paths a segment takes, and the piece exists (and is worth reading for
636
- * subtitles) whichever one that is. `verified` is WebTorrent's own signal for
637
- * exactly that instant, set at the same place the bitfield itself is (`
638
- * _markVerified`), so nothing here is guessing at readiness a different way.
639
- *
640
- * @param {string} sourceKey
641
- * @param {object} torrent
642
- * @returns {void}
643
- */
644
- function ensureSubtitleWarmupWired(sourceKey, torrent) {
645
- if (subtitleWarmupWired.has(torrent)) {
646
- return;
647
- }
648
- subtitleWarmupWired.add(torrent);
649
- torrent.on("verified", () => warmActiveFiles(sourceKey, torrent));
650
- }
651
-
652
- /**
653
- * How often an actively-read file's subtitle cues are walked ahead of being
654
- * asked for, as a fallback beside the per-piece `verified` listener above —
655
- * catches a listener attached after pieces already verified, and anything the
656
- * event path might otherwise miss. Cheap once caught up (`warmSubtitleCues`
657
- * skips clusters it has already read).
658
- */
659
- const SUBTITLE_WARMUP_INTERVAL_MS = 3_000;
660
-
661
- setInterval(() => {
662
- for (const [sourceKey, torrent] of pool.torrents) {
663
- ensureSubtitleWarmupWired(sourceKey, torrent);
664
- warmActiveFiles(sourceKey, torrent);
665
- }
666
- }, SUBTITLE_WARMUP_INTERVAL_MS).unref();
667
-
668
- /**
669
- * Keeps this thread alive ON PURPOSE the one interval left accounted for
670
- * (no `.unref()`).
671
- *
672
- * Every other recurring handle here is unref'd, upload is disabled by
673
- * default, and idle peer connections close about half a minute after the
674
- * traffic stops — so once nothing is being read, every handle can be gone
675
- * at once, the event loop drains, and this thread ends BY ITSELF. Node then
676
- * tears the isolate down, that teardown touches memory some native module
677
- * has already freed, and the fault (SIGSEGV inside `uv_timer_stop`, reached
678
- * through `PerIsolatePlatformData::Shutdown`) kills the whole process at
679
- * once — HTTP server, tunnel, data channels — before any JS handler runs.
680
- * Field evidence: two deaths on 2026-08-22 (15:50:12 and 16:12:21 UTC),
681
- * each ~35 s after the last byte of traffic, identical core dumps;
682
- * same crash family as the utp-native faults of 2026-08-18..21
683
- * (`research/worker-thread-drain-crash-2026-08-22.md`).
684
- *
685
- * An empty repeating interval costs nothing, keeps the loop from draining
686
- * while the process lives, and thereby keeps that teardown path — and the
687
- * corrupted structure inside it unreachable, whichever module is guilty.
688
- */
689
- const WORKER_KEEPALIVE_INTERVAL_MS = 5_000;
690
-
691
- setInterval(() => {
692
- void process.uptime();
693
- }, WORKER_KEEPALIVE_INTERVAL_MS);
694
-
695
- /**
696
- * Say why this thread is ending, from inside it, before anything is torn down.
697
- *
698
- * The crash of 2026-08-27 15:40 is `node::worker::Worker::Run()` returning and
699
- * node faulting as it closes what was left on this loop. The parent DOES watch
700
- * for an unexpected exit and has a line ready for it — but that line never
701
- * printed, because the fault happens during this thread's own teardown, before
702
- * the parent's `exit` event is delivered. So the one reading that would name
703
- * the cause was being eaten by the failure it was meant to explain.
704
- *
705
- * These handlers run first, synchronously, and write through the same channel
706
- * as every other line here. `beforeExit` means the loop drained despite the
707
- * keepalive above; `exit` means the thread is going whatever the reason. The
708
- * list of what was still holding the loop open is the part that says which.
709
- */
710
- process.on("beforeExit", (code) => {
711
- log(
712
- `thread is about to end because the event loop drained (code ${code}) — ` +
713
- `still open: ${describeActiveResources()}`
714
- );
715
- });
716
-
717
- process.on("exit", (code) => {
718
- log(`thread ending with code ${code} still open: ${describeActiveResources()}`);
719
- });
720
-
721
- process.on("uncaughtException", (error) => {
722
- log(`thread hit an uncaught error: ${error?.stack ?? error}`);
723
- });
724
-
725
- process.on("unhandledRejection", (reason) => {
726
- log(`thread hit an unhandled rejection: ${reason?.stack ?? reason}`);
727
- });
728
-
729
- /**
730
- * What is still holding this thread's event loop open, as node names it.
731
- *
732
- * @returns {string} A tally per resource kind, or why it could not be read.
733
- */
734
- function describeActiveResources() {
735
- try {
736
- const names = process.getActiveResourcesInfo?.() ?? [];
737
- if (names.length === 0) {
738
- return "nothing";
739
- }
740
- const tally = new Map();
741
- for (const name of names) {
742
- tally.set(name, (tally.get(name) ?? 0) + 1);
743
- }
744
- return [...tally].map(([name, count]) => `${name}x${count}`).join(" ");
745
- } catch (error) {
746
- return `unreadable (${error?.message ?? error})`;
747
- }
748
- }
749
-
750
- 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, WORKER_MEMORY_SAMPLE_MS } 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, pieceBufferCollection, 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
+ buffer: fragment.buffer,
180
+ offset: fragment.offset,
181
+ length: fragment.length
182
+ });
183
+ });
184
+ }
185
+
186
+ /**
187
+ * Stream a byte range back as CHUNK messages.
188
+ *
189
+ * Reads through WebTorrent's own read stream — which serves already-downloaded
190
+ * pieces from disk and waits for the rest — and forwards it in
191
+ * {@link STREAM_CHUNK_BYTES} pieces, transferring ownership of each so nothing
192
+ * is copied across the boundary. `createSendStream` applies the backpressure,
193
+ * so a fast disk cannot outrun the main thread and rebuild the queue in memory.
194
+ *
195
+ * @param {object} params
196
+ * @param {number} params.id - Request id; CHUNK/READ_END carry it.
197
+ * @param {string} params.sourceKey
198
+ * @param {number} params.fileIndex
199
+ * @param {number | null} params.start - Inclusive, or null for the whole file.
200
+ * @param {number | null} params.end - Inclusive.
201
+ * @returns {Promise<void>}
202
+ */
203
+ async function streamRange({ id, sourceKey, fileIndex, start, end, windowBytes }) {
204
+ const torrent = await requireTorrent(sourceKey);
205
+ const file = torrent.files?.[fileIndex];
206
+ if (!file) {
207
+ throw new Error(`File ${fileIndex} not found in ${sourceKey}.`);
208
+ }
209
+
210
+ const sender = createSendStream({ port: parentPort, requestId: id });
211
+ readsById.set(id, sender);
212
+
213
+ // Hold the file for as long as this read runs. The caller also acquires it,
214
+ // but that acquire and its release are separate messages from another thread
215
+ // and can be reordered; this one cannot, because it lives entirely inside the
216
+ // read. Without it the idle sweep saw a zero reader count and removed the
217
+ // torrent AND its store mid-read — field 2026-08-02: "removed idle torrent
218
+ // ... and its store", after which every subsequent read hung and ffmpeg got
219
+ // an empty input.
220
+ const releaseRead = pool.acquireFile(torrent, fileIndex);
221
+
222
+ const rangeStart = start ?? 0;
223
+ const rangeEnd = end ?? file.length - 1;
224
+
225
+ let failed = false;
226
+ try {
227
+ // Positions in shared memory, not bytes: the main thread maps the same pool
228
+ // and reads each fragment in place, so nothing is copied and nothing is
229
+ // transferred. See `piece-reader.js`.
230
+ for await (const fragment of readFragments({
231
+ torrent,
232
+ fileIndex,
233
+ start: rangeStart,
234
+ end: rangeEnd,
235
+ cancellation: sender,
236
+ windowBytes
237
+ })) {
238
+ if (sender.isCancelled()) {
239
+ fragment.release();
240
+ break;
241
+ }
242
+ // One fragment in flight at a time. Each one holds a piece pinned, and
243
+ // the store guarantees only two resident pieces at its smallest budget —
244
+ // holding two pins while asking for a third would deadlock it against
245
+ // itself. The round trip costs ~100 µs against a piece worth megabytes,
246
+ // so there is nothing to win by overlapping them.
247
+ await sendFragment(id, fragment);
248
+ }
249
+ } catch (error) {
250
+ // The end-of-read marker means "the body is complete". Sending it after a
251
+ // failure told the reader the file simply ended — a truncated segment that
252
+ // ffmpeg reported as `Stream ends prematurely`, with the real cause thrown
253
+ // away. Let the error propagate instead; the command handler reports it and
254
+ // the main thread fails the stream.
255
+ failed = true;
256
+ throw error;
257
+ } finally {
258
+ readsById.delete(id);
259
+ // Any fragment still awaiting confirmation will never get one now; settling
260
+ // it here releases its pin rather than leaking a held slot.
261
+ settleFragment(id);
262
+ releaseRead();
263
+ if (!failed) {
264
+ sender.end();
265
+ }
266
+ // Nothing else to tear down: the reader owns no stream of its own, and a
267
+ // cancelled read stops at its next fragment boundary because it polls the
268
+ // same `sender` for cancellation.
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Run one command and return its result.
274
+ *
275
+ * @param {string} command
276
+ * @param {object} params
277
+ * @param {number} id
278
+ * @returns {Promise<unknown>}
279
+ */
280
+ async function runCommand(command, params, id) {
281
+ switch (command) {
282
+ case Command.ADD_SOURCE: {
283
+ // Registered before it resolves, so anything naming this source while it
284
+ // is being added waits for it instead of being told it does not exist.
285
+ // Reusing the same promise for a repeated add also collapses two callers
286
+ // racing to open the same torrent into one.
287
+ sourceRecipes.set(params.sourceKey, {
288
+ sourceType: params.sourceType,
289
+ source: params.source
290
+ });
291
+ let pending = torrentsByKey.get(params.sourceKey);
292
+ if (!pending) {
293
+ pending = pool.getTorrent(params.sourceType, params.source);
294
+ torrentsByKey.set(params.sourceKey, pending);
295
+ // A failed add must not be remembered, or every later attempt at this
296
+ // source replays the same failure. The handler also marks the rejection
297
+ // as observed, so it cannot surface as an unhandled one.
298
+ pending.catch(() => {
299
+ if (torrentsByKey.get(params.sourceKey) === pending) {
300
+ torrentsByKey.delete(params.sourceKey);
301
+ }
302
+ });
303
+ }
304
+ const torrent = await pending;
305
+ return {
306
+ infoHash: torrent.infoHash,
307
+ name: torrent.name,
308
+ // Files cross as plain data; the objects stay here.
309
+ files: (torrent.files ?? []).map((file, index) => ({
310
+ index,
311
+ name: file.name,
312
+ path: file.path,
313
+ length: file.length
314
+ }))
315
+ };
316
+ }
317
+
318
+ case Command.LIST_FILES: {
319
+ const torrent = await requireTorrent(params.sourceKey);
320
+ return (torrent.files ?? []).map((file, index) => ({
321
+ index,
322
+ name: file.name,
323
+ path: file.path,
324
+ length: file.length
325
+ }));
326
+ }
327
+
328
+ case Command.ACQUIRE_FILE: {
329
+ const torrent = await requireTorrent(params.sourceKey);
330
+ // Every acquire is its own claim. Sharing one per file meant the first
331
+ // reader to finish released the hold while others were still reading.
332
+ return fileClaims.open(
333
+ params.sourceKey,
334
+ params.fileIndex,
335
+ pool.acquireFile(torrent, params.fileIndex)
336
+ );
337
+ }
338
+
339
+ case Command.RELEASE_FILE: {
340
+ const released = fileClaims.close(params.claimId);
341
+ if (!released) {
342
+ // Not fatal — but it means a release arrived twice or after teardown,
343
+ // and silence here is what let the previous scheme look healthy.
344
+ log(`release for unknown file claim ${params.claimId}`);
345
+ }
346
+ return released;
347
+ }
348
+
349
+ case Command.TORRENT_TOTALS: {
350
+ // Downloaded and uploaded are counted apart: hashing every downloaded
351
+ // byte is work of a different order from sending one back to the swarm,
352
+ // and adding them would price both at whatever the mixture happened to
353
+ // be.
354
+ let downloaded = 0;
355
+ let uploaded = 0;
356
+ for (const torrent of pool.client?.torrents ?? []) {
357
+ const gotBytes = Number(torrent?.downloaded);
358
+ const sentBytes = Number(torrent?.uploaded);
359
+ downloaded += Number.isFinite(gotBytes) ? gotBytes : 0;
360
+ uploaded += Number.isFinite(sentBytes) ? sentBytes : 0;
361
+ }
362
+ return { downloaded, uploaded };
363
+ }
364
+
365
+ case Command.SUBTITLE_TRACKS: {
366
+ const torrent = await requireTorrent(params.sourceKey);
367
+ return {
368
+ tracks: await subtitleTracksOf(torrent, params.fileIndex, params.sourceKey),
369
+ declared: await declaredSubtitleTracksOf(torrent, params.fileIndex, params.sourceKey)
370
+ };
371
+ }
372
+
373
+ case Command.SUBTITLE_CUES: {
374
+ const torrent = await requireTorrent(params.sourceKey);
375
+ const held = await cuesHeldFor(torrent, params.fileIndex, params.sourceKey, params.trackNumber);
376
+ return {
377
+ cues: held.cues,
378
+ coveredClusters: held.coveredClusters,
379
+ indexedClusters: held.indexedClusters,
380
+ codecId: held.track?.codecId ?? "",
381
+ codecPrivate: held.track?.codecPrivate ?? "",
382
+ language: held.track?.language ?? ""
383
+ };
384
+ }
385
+
386
+ case Command.FILE_STATS: {
387
+ const torrent = await requireTorrent(params.sourceKey);
388
+ const stats = pool.getFileStats(torrent, params.fileIndex, {
389
+ resumeAnchorByteStart: params.resumeAnchorByteStart ?? null
390
+ });
391
+ // What this file's own interruptions demand, measured by the reader in
392
+ // this thread. It travels with the stats because the caller asking for
393
+ // them is the one that has to decide with them — the browser's smallest
394
+ // safe buffer, and the speed a quality step must sustain. Null until a
395
+ // second interruption has been seen: one wait shows no interval, and an
396
+ // interval invented from one point is exactly what this work removes.
397
+ const file = Array.isArray(torrent?.files) ? torrent.files[params.fileIndex] : null;
398
+ return {
399
+ ...stats,
400
+ supply: supplyFiguresFor(torrent?.infoHash, file?.name, params.segmentSeconds ?? 4)
401
+ };
402
+ }
403
+
404
+ case Command.PRIORITIZE: {
405
+ const torrent = await requireTorrent(params.sourceKey);
406
+ pool.prioritizeByteRange(torrent, params.fileIndex, params.byteStart, params.windowBytes, {
407
+ wholeFileRead: params.wholeFileRead === true
408
+ });
409
+ return true;
410
+ }
411
+
412
+ case Command.PREFETCH_EDGES: {
413
+ const torrent = await requireTorrent(params.sourceKey);
414
+ return pool.prefetchFileEdges(torrent, params.fileIndex, params.options ?? {});
415
+ }
416
+
417
+ case Command.READ_RANGE: {
418
+ // Streams its own reply; the caller's promise resolves once the body has
419
+ // been fully sent, which is what lets the client await completion.
420
+ await streamRange({
421
+ id,
422
+ sourceKey: params.sourceKey,
423
+ fileIndex: params.fileIndex,
424
+ start: params.start ?? null,
425
+ end: params.end ?? null,
426
+ windowBytes: params.windowBytes
427
+ });
428
+ return true;
429
+ }
430
+
431
+ case Command.CANCEL_READ: {
432
+ readsById.get(params.readId)?.cancel();
433
+ // A cancelled read will never have its outstanding fragment confirmed, so
434
+ // wake it here — otherwise it waits forever with a piece pinned.
435
+ settleFragment(params.readId);
436
+ return true;
437
+ }
438
+
439
+ case Command.DESTROY_ALL: {
440
+ fileClaims.closeAll();
441
+ torrentsByKey.clear();
442
+ sourceRecipes.clear();
443
+ await pool.destroyAll();
444
+ return true;
445
+ }
446
+
447
+ default:
448
+ throw new Error(`Unknown torrent-worker command: ${command}`);
449
+ }
450
+ }
451
+
452
+ parentPort.on("message", async (message) => {
453
+ // Chunk acknowledgements are not commands — they release backpressure on an
454
+ // in-flight read.
455
+ if (message?.type === Event.CHUNK_ACK) {
456
+ readsById.get(message.id)?.ack();
457
+ return;
458
+ }
459
+
460
+ // The main thread has finished reading a fragment out of shared memory, so
461
+ // its piece may be unpinned and the read may continue.
462
+ if (message?.type === Event.FRAGMENT_DONE) {
463
+ settleFragment(message.id);
464
+ return;
465
+ }
466
+
467
+ const { command, id, params } = message ?? {};
468
+ try {
469
+ const result = await runCommand(command, params ?? {}, id);
470
+ parentPort.postMessage({ type: Event.RESULT, id, result });
471
+ } catch (error) {
472
+ parentPort.postMessage({ type: Event.ERROR, id, error: error?.message ?? String(error) });
473
+ }
474
+ });
475
+
476
+ /**
477
+ * How often the piece store reports what it has been doing.
478
+ *
479
+ * The store decides whether a read costs nothing or costs a disk trip, and
480
+ * until 2.9.75 nothing about it reached the log — a field oddity would have had
481
+ * no evidence to work from. Reported only when something changed, so an idle
482
+ * proxy stays quiet.
483
+ */
484
+ // The torrent worker's OWN isolate, reported from inside it. The piece pool is
485
+ // a `SharedArrayBuffer` allocated here, so the main thread's counters cannot
486
+ // see it however carefully they are read — which is half the reason 650 MB of a
487
+ // 893 MB process had no explanation on 2026-08-28 (roadmap item 2).
488
+ // A second between readings, a minute between lines unless the heap moved by
489
+ // 25 MB, and a heap snapshot of THIS isolate on every new high-water above
490
+ // 400 MB. Three deaths — 2026-08-30 14:00 and 23:19, and
491
+ // 2026-08-31 13:27 — went from a 30 MB heap to the 2240 MB ceiling inside one
492
+ // sixty-second gap, and the only snapshots ever written were of the main
493
+ // isolate, whose heap is 26 MB. So the isolate that dies has never once been
494
+ // looked at (roadmap item 2, `research/worker-heap-oom-2026-08-31.md`).
495
+ startMemoryReport({
496
+ log,
497
+ readStores: collectStoreStats,
498
+ scope: "thread",
499
+ label: "torrent worker",
500
+ intervalMs: WORKER_MEMORY_SAMPLE_MS,
501
+ quietMs: 60_000,
502
+ changeBytes: 25 * 1024 * 1024,
503
+ snapshotDir: workerData?.stateDir || undefined,
504
+ snapshotFloorBytes: 400 * 1024 * 1024,
505
+ snapshotGrowthBytes: 400 * 1024 * 1024,
506
+ keepSnapshots: 3
507
+ });
508
+
509
+ const STORE_REPORT_INTERVAL_MS = 60_000;
510
+
511
+ /** Last reported figures per store, so unchanged ones stay silent. */
512
+ const lastReported = new Map();
513
+
514
+ setInterval(() => {
515
+ // What the machine can spare NOW, not what it could spare when each store was
516
+ // created. With per-piece buffers a lowered ceiling is honoured immediately:
517
+ // excess pieces are evicted to disk and their memory is reclaimable.
518
+ for (const revised of reviseStoreBudgets()) {
519
+ if (revised.evicted > 0) {
520
+ log(
521
+ `piece-store "${revised.name.slice(0, 40)}": allowance is now ` +
522
+ `${Math.round(revised.ceilingBytes / 1048576)}MB, evicted ${revised.evicted} piece(s) to meet it — ` +
523
+ `now ${Math.round(revised.committedBytes / 1048576)}MB committed`
524
+ );
525
+ } else if (revised.committedBytes > revised.ceilingBytes) {
526
+ log(
527
+ `piece-store "${revised.name.slice(0, 40)}": allowance is now ` +
528
+ `${Math.round(revised.ceilingBytes / 1048576)}MB and ` +
529
+ `${Math.round(revised.committedBytes / 1048576)}MB is committed — ` +
530
+ `all resident pieces are pinned, cannot shrink yet`
531
+ );
532
+ }
533
+ }
534
+ for (const stats of collectStoreStats()) {
535
+ const signature = `${stats.fromMemory}/${stats.fromDisk}/${stats.spills}/${stats.revivals}/${stats.blockedByPins}/${stats.evictedOnRevise}/${stats.spillFailures}`;
536
+ if (lastReported.get(stats.name) === signature) {
537
+ continue;
538
+ }
539
+ lastReported.set(stats.name, signature);
540
+
541
+ const reads = stats.fromMemory + stats.fromDisk;
542
+ const fromMemoryShare = reads > 0 ? ((stats.fromMemory / reads) * 100).toFixed(1) : "—";
543
+ log(
544
+ `piece-store "${stats.name.slice(0, 40)}": resident=${stats.resident}/${stats.capacity} ` +
545
+ `(${Math.round((stats.residentBytes || 0) / 1048576)}MB of ` +
546
+ `${Math.round((stats.budgetBytes || 0) / 1048576)}MB allowed) ` +
547
+ `committed=${Math.round((stats.committedBytes || 0) / 1048576)}MB ` +
548
+ `on-disk=${Math.round((stats.spilledBytes || 0) / 1048576)}MB ` +
549
+ `pinned=${stats.pinned} spilled=${stats.spilled} reads=${reads} (${fromMemoryShare}% from memory) ` +
550
+ `spills=${stats.spills} revivals=${stats.revivals}` +
551
+ (stats.blockedByPins > 0 ? ` blocked-by-pins=${stats.blockedByPins}` : "") +
552
+ (stats.evictedOnRevise > 0 ? ` evictedOnRevise=${stats.evictedOnRevise}` : "") +
553
+ (stats.spillFailures > 0 ? ` spill-failures=${stats.spillFailures}` : "") +
554
+ (stats.outstanding > 0 ? ` outstanding=${stats.outstanding}` : "")
555
+ );
556
+ }
557
+ // Not per store: the collector is per thread, and the question it answers —
558
+ // is anything of ours outliving a piece — is about the thread. Printed
559
+ // whenever the two disagree by more than the pieces actually held, which is
560
+ // the only shape worth looking at (roadmap item 2).
561
+ const collection = pieceBufferCollection();
562
+ const outstandingBuffers = collection.released - collection.collected;
563
+ const heldNow = collectStoreStats().reduce((sum, stats) => sum + (stats.resident || 0), 0);
564
+ if (outstandingBuffers > heldNow) {
565
+ log(
566
+ `piece buffers: ${collection.released} let go, ${collection.collected} collected — ` +
567
+ `${outstandingBuffers} still alive against ${heldNow} the store holds. ` +
568
+ "A gap that keeps widening means a reference of ours outlives the piece; " +
569
+ "a gap that does not means whatever grows is below us, in the allocator"
570
+ );
571
+ }
572
+ }, STORE_REPORT_INTERVAL_MS).unref();
573
+
574
+ /**
575
+ * Walk subtitle cues for every actively-read file of one torrent, and PUSH
576
+ * whatever came out new to the main thread — which is what makes a browser's
577
+ * copy current without it having asked.
578
+ *
579
+ * @param {string} sourceKey
580
+ * @param {object} torrent
581
+ * @returns {void}
582
+ */
583
+ function warmActiveFiles(sourceKey, torrent) {
584
+ const usage = pool.fileUsageByTorrent.get(torrent);
585
+ if (!usage) {
586
+ return;
587
+ }
588
+ for (const fileIndex of usage.keys()) {
589
+ const key = `${sourceKey}:${fileIndex}`;
590
+ // A trigger that arrives while the previous pass is still walking is
591
+ // dropped, not queued. `verified` fires per piece, so on a fast download
592
+ // these arrive many times a second; the walk is serialized per file anyway,
593
+ // and a queue of identical passes would only postpone the one that has
594
+ // something new to find.
595
+ if (warmupInFlight.has(key)) {
596
+ continue;
597
+ }
598
+ warmupInFlight.add(key);
599
+ warmSubtitleCues(torrent, fileIndex, sourceKey)
600
+ .then((fresh) => {
601
+ for (const entry of fresh) {
602
+ const span = entry.spanStartSeconds === null
603
+ ? "empty"
604
+ : `${entry.spanStartSeconds.toFixed(1)}-${entry.spanEndSeconds.toFixed(1)}s`;
605
+ log(
606
+ `subtitle push ${sourceKey.slice(0, 8)}:${fileIndex} track ${entry.trackIndex}: ` +
607
+ `${entry.cues.length} new cue(s) covering ${span}, ` +
608
+ `clusters walked ${entry.walkedClusters}/${entry.indexedClusters}, cursor ${entry.cursor}, ` +
609
+ "posting to main thread"
610
+ );
611
+ parentPort.postMessage({
612
+ type: Event.SUBTITLE_CUES_READY,
613
+ sourceKey,
614
+ fileIndex,
615
+ trackIndex: entry.trackIndex,
616
+ cues: entry.cues,
617
+ language: entry.language,
618
+ cursor: entry.cursor
619
+ });
620
+ }
621
+ })
622
+ .catch((error) => {
623
+ log(`subtitle warmup ${sourceKey}:${fileIndex} failed: ${error instanceof Error ? error.message : error}`);
624
+ })
625
+ .finally(() => {
626
+ warmupInFlight.delete(key);
627
+ });
628
+ }
629
+ }
630
+
631
+ /**
632
+ * Files whose warmup pass has not finished yet, by `sourceKey:fileIndex`.
633
+ *
634
+ * @type {Set<string>}
635
+ */
636
+ const warmupInFlight = new Set();
637
+
638
+ /**
639
+ * Torrents already wired to warm their subtitle cues the moment a piece
640
+ * verifies, so the same torrent is not listened to twice.
641
+ *
642
+ * @type {WeakSet<object>}
643
+ */
644
+ const subtitleWarmupWired = new WeakSet();
645
+
646
+ /**
647
+ * A piece becoming readable is the actual event a cue can be pulled from —
648
+ * "downloaded", not "about to be encoded or copied": what a viewer reaches is
649
+ * decided by the read window ahead of the playhead, not by which of the two
650
+ * paths a segment takes, and the piece exists (and is worth reading for
651
+ * subtitles) whichever one that is. `verified` is WebTorrent's own signal for
652
+ * exactly that instant, set at the same place the bitfield itself is (`
653
+ * _markVerified`), so nothing here is guessing at readiness a different way.
654
+ *
655
+ * @param {string} sourceKey
656
+ * @param {object} torrent
657
+ * @returns {void}
658
+ */
659
+ function ensureSubtitleWarmupWired(sourceKey, torrent) {
660
+ if (subtitleWarmupWired.has(torrent)) {
661
+ return;
662
+ }
663
+ subtitleWarmupWired.add(torrent);
664
+ torrent.on("verified", () => warmActiveFiles(sourceKey, torrent));
665
+ }
666
+
667
+ /**
668
+ * How often an actively-read file's subtitle cues are walked ahead of being
669
+ * asked for, as a fallback beside the per-piece `verified` listener above
670
+ * catches a listener attached after pieces already verified, and anything the
671
+ * event path might otherwise miss. Cheap once caught up (`warmSubtitleCues`
672
+ * skips clusters it has already read).
673
+ */
674
+ const SUBTITLE_WARMUP_INTERVAL_MS = 3_000;
675
+
676
+ setInterval(() => {
677
+ for (const [sourceKey, torrent] of pool.torrents) {
678
+ ensureSubtitleWarmupWired(sourceKey, torrent);
679
+ warmActiveFiles(sourceKey, torrent);
680
+ }
681
+ }, SUBTITLE_WARMUP_INTERVAL_MS).unref();
682
+
683
+ /**
684
+ * Keeps this thread alive ON PURPOSE — the one interval left accounted for
685
+ * (no `.unref()`).
686
+ *
687
+ * Every other recurring handle here is unref'd, upload is disabled by
688
+ * default, and idle peer connections close about half a minute after the
689
+ * traffic stops — so once nothing is being read, every handle can be gone
690
+ * at once, the event loop drains, and this thread ends BY ITSELF. Node then
691
+ * tears the isolate down, that teardown touches memory some native module
692
+ * has already freed, and the fault (SIGSEGV inside `uv_timer_stop`, reached
693
+ * through `PerIsolatePlatformData::Shutdown`) kills the whole process at
694
+ * once — HTTP server, tunnel, data channels — before any JS handler runs.
695
+ * Field evidence: two deaths on 2026-08-22 (15:50:12 and 16:12:21 UTC),
696
+ * each ~35 s after the last byte of traffic, identical core dumps;
697
+ * same crash family as the utp-native faults of 2026-08-18..21
698
+ * (`research/worker-thread-drain-crash-2026-08-22.md`).
699
+ *
700
+ * An empty repeating interval costs nothing, keeps the loop from draining
701
+ * while the process lives, and thereby keeps that teardown path — and the
702
+ * corrupted structure inside it unreachable, whichever module is guilty.
703
+ */
704
+ const WORKER_KEEPALIVE_INTERVAL_MS = 5_000;
705
+
706
+ setInterval(() => {
707
+ void process.uptime();
708
+ }, WORKER_KEEPALIVE_INTERVAL_MS);
709
+
710
+ /**
711
+ * Say why this thread is ending, from inside it, before anything is torn down.
712
+ *
713
+ * The crash of 2026-08-27 15:40 is `node::worker::Worker::Run()` returning and
714
+ * node faulting as it closes what was left on this loop. The parent DOES watch
715
+ * for an unexpected exit and has a line ready for it — but that line never
716
+ * printed, because the fault happens during this thread's own teardown, before
717
+ * the parent's `exit` event is delivered. So the one reading that would name
718
+ * the cause was being eaten by the failure it was meant to explain.
719
+ *
720
+ * These handlers run first, synchronously, and write through the same channel
721
+ * as every other line here. `beforeExit` means the loop drained despite the
722
+ * keepalive above; `exit` means the thread is going whatever the reason. The
723
+ * list of what was still holding the loop open is the part that says which.
724
+ */
725
+ process.on("beforeExit", (code) => {
726
+ log(
727
+ `thread is about to end because the event loop drained (code ${code}) — ` +
728
+ `still open: ${describeActiveResources()}`
729
+ );
730
+ });
731
+
732
+ process.on("exit", (code) => {
733
+ log(`thread ending with code ${code} — still open: ${describeActiveResources()}`);
734
+ });
735
+
736
+ process.on("uncaughtException", (error) => {
737
+ log(`thread hit an uncaught error: ${error?.stack ?? error}`);
738
+ });
739
+
740
+ process.on("unhandledRejection", (reason) => {
741
+ log(`thread hit an unhandled rejection: ${reason?.stack ?? reason}`);
742
+ });
743
+
744
+ /**
745
+ * What is still holding this thread's event loop open, as node names it.
746
+ *
747
+ * @returns {string} A tally per resource kind, or why it could not be read.
748
+ */
749
+ function describeActiveResources() {
750
+ try {
751
+ const names = process.getActiveResourcesInfo?.() ?? [];
752
+ if (names.length === 0) {
753
+ return "nothing";
754
+ }
755
+ const tally = new Map();
756
+ for (const name of names) {
757
+ tally.set(name, (tally.get(name) ?? 0) + 1);
758
+ }
759
+ return [...tally].map(([name, count]) => `${name}x${count}`).join(" ");
760
+ } catch (error) {
761
+ return `unreadable (${error?.message ?? error})`;
762
+ }
763
+ }
764
+
765
+ log("torrent worker started");