@torrent-tv/proxy 2.87.11 → 2.87.12

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,765 +1,765 @@
1
- /**
2
- * @file Main-thread face of the torrent worker.
3
- *
4
- * Presents the same operations the routes and session manager already use, so
5
- * moving the torrent to its own thread does not ripple through calling code.
6
- * The one unavoidable change is that torrents are named by `sourceKey` instead
7
- * of passed around as objects — objects cannot cross a thread boundary, and
8
- * pretending otherwise would mean copying them on every call.
9
- *
10
- * Reads come back as an ordinary `ReadableStream`, so `/stream` and the codec
11
- * probe consume them exactly as they consume WebTorrent's own streams today.
12
- * What that hides is the part that matters: chunks arrive as transferred
13
- * buffers, never copied — 5.3 ms per 10 MB against 37 ms if cloned and 104 ms
14
- * through a transferable stream (measured 2026-08-02, see `protocol.js`).
15
- */
16
-
17
- import { Worker } from "node:worker_threads";
18
- import { Readable } from "node:stream";
19
- import { fileURLToPath } from "node:url";
20
- import { logger, writeAlreadyDecided } from "../../../utils/logger.js";
21
- import { createCaller, createReceiveStream } from "./channel.js";
22
- import { Command, Event } from "./protocol.js";
23
-
24
- const WORKER_URL = new URL("./worker.js", import.meta.url);
25
- /**
26
- * How long a shutdown waits for the thread to end by itself before forcing it.
27
- *
28
- * Ending by itself is what lets libuv drain the handle callbacks it is holding;
29
- * forcing it is what ran one of those against a freed isolate. Five seconds is
30
- * long enough for a destroyed torrent client to release its sockets and short
31
- * enough that a shutdown never appears to hang.
32
- */
33
- const WORKER_EXIT_GRACE_MS = 5_000;
34
-
35
- /**
36
- * Runs the torrent client on its own thread and exposes it to the main thread.
37
- *
38
- * Why this exists at all: profiling during a live seek found the main thread
39
- * ~85% busy with WebTorrent (buffer concatenation ~15%, wire updates ~9%,
40
- * garbage collection ~5%), while three of four cores idled. Serving a segment
41
- * queued behind that work, so reading a finished 10 MB file took 12-23 s where
42
- * handing it to the channel took 125 ms.
43
- */
44
- /**
45
- * Piece buffers this thread has been handed, and how many the collector has
46
- * taken back.
47
- *
48
- * A `SharedArrayBuffer`'s memory belongs to neither isolate: it lives until
49
- * BOTH have let go. So the worker's own count answers only half the question,
50
- * and this is the other half — 700 MB grew in the field on 2026-08-31 with the
51
- * store's own memory falling, and the two candidates are "a reference of ours
52
- * outlives the piece" and "the allocator keeps what we free". These two
53
- * counters separate them (roadmap item 2).
54
- *
55
- * A fragment arrives as a fresh handle onto the same shared memory every time,
56
- * so what is counted is handles, not pieces. That is the right quantity anyway:
57
- * one handle retained keeps the whole piece alive.
58
- */
59
- const fragmentBuffers = { seen: 0, collected: 0 };
60
- const fragmentCollector = typeof FinalizationRegistry === "function"
61
- ? new FinalizationRegistry(() => {
62
- fragmentBuffers.collected += 1;
63
- })
64
- : null;
65
-
66
- /**
67
- * What the collector has taken back against what this thread was handed.
68
- *
69
- * @returns {{ seen: number, collected: number }}
70
- */
71
- export function fragmentBufferCollection() {
72
- return { seen: fragmentBuffers.seen, collected: fragmentBuffers.collected };
73
- }
74
-
75
- export class TorrentWorkerClient {
76
- #worker;
77
- /**
78
- * Whether this shutdown was asked for, so the thread ending can be told from
79
- * the thread dying. Without it both look identical from outside, which is how
80
- * five crashes produced no line in the log.
81
- */
82
- #stopping = false;
83
- #caller;
84
- /** Receive-side handles for in-flight reads, keyed by request id. */
85
- #reads = new Map();
86
-
87
- /**
88
- * The last piece served to each open read, so a fragment arriving out of
89
- * order can be named. Cleared when the read ends.
90
- *
91
- * @type {Map<number, number>}
92
- */
93
- #lastPieceByRead = new Map();
94
- /** Reads consuming fragments in place, keyed by request id. */
95
- #fragmentReaders = new Map();
96
-
97
- /**
98
- * Files downloaded whole, by `${infoHash}/${fileIndex}`.
99
- *
100
- * Held on THIS thread because it is this thread that serves them: a file that
101
- * is whole is read with an ordinary file read, and asking the torrent thread
102
- * for anything about it would put back the very hop this removes. The torrent
103
- * thread writes the files and says so; this is what it says.
104
- *
105
- * @type {Map<string, { path: string, length: number, name: string }>}
106
- */
107
- wholeFiles = new Map();
108
-
109
- /** @type {(event: { sourceKey: string, fileIndex: number, trackIndex: number, cues: object[], language: string }) => void} */
110
- /** @type {(event: { sourceKey: string, fileIndexes: number[] }) => void} */
111
- #onPiecesArrived;
112
-
113
- /**
114
- * @param {{ memoryBytes?: number, stateDir?: string, onPiecesArrived?: (event: object) => void }} [options]
115
- */
116
- constructor({ memoryBytes, stateDir, onPiecesArrived } = {}) {
117
- this.#worker = new Worker(fileURLToPath(WORKER_URL), {
118
- // `stateDir` travels because the worker writes heap snapshots of its own
119
- // isolate there. It cannot choose a directory any other way: a worker may
120
- // not change the process's working directory, and the isolate that has
121
- // died three times is the one no snapshot has ever been taken of.
122
- workerData: { memoryBytes, stateDir }
123
- });
124
- this.#caller = createCaller(this.#worker);
125
- this.#onPiecesArrived = onPiecesArrived ?? (() => undefined);
126
-
127
- this.#worker.on("message", (message) => {
128
- // A failed read must fail its stream. This is checked BEFORE the caller
129
- // sees the message: until 2.9.76 nothing here handled a read error at
130
- // all, so the worker's report was dropped as unknown, and because the
131
- // worker sent the end-of-read marker from its `finally` even when the
132
- // read had thrown, the reader saw a clean end of file instead. A read
133
- // that failed before it produced anything simply hung forever.
134
- if (message?.type === Event.ERROR && this.#reads.has(message.id)) {
135
- const read = this.#reads.get(message.id);
136
- this.#reads.delete(message.id);
137
- read.fail(new Error(message.error ?? "Torrent worker read failed."));
138
- return;
139
- }
140
- if (message?.type === Event.ERROR && this.#fragmentReaders.has(message.id)) {
141
- const reader = this.#fragmentReaders.get(message.id);
142
- this.#fragmentReaders.delete(message.id);
143
- reader.fail(new Error(message.error ?? "Torrent worker read failed."));
144
- return;
145
- }
146
- if (this.#caller.handleReply(message)) {
147
- return;
148
- }
149
- switch (message?.type) {
150
- case Event.FRAGMENT: {
151
- const buffer = message.buffer;
152
- if (!buffer) {
153
- // No buffer means no way to read the fragment; confirm it so the
154
- // worker is not left waiting, and let the read end short.
155
- this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
156
- break;
157
- }
158
- if (message.offset + message.length > buffer.byteLength) {
159
- logger.warn(
160
- `torrent-worker: fragment ${message.offset}+${message.length} lies outside ` +
161
- `its buffer of ${buffer.byteLength}B (read ${message.id}) — ending the read short`
162
- );
163
- this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
164
- break;
165
- }
166
- // A sequential read walks the file forwards, so each fragment either
167
- // continues the piece before it or moves to the very next one.
168
- // Anything else means the bytes handed to the decoder are not the
169
- // file's bytes in order — which is what a decoder complaining about
170
- // its input has twice turned out to mean (2.9.126, and the AC-3
171
- // failure of 2026-08-09: the encoder ran at 9.3x, the piece store
172
- // reported no spills and 100% of reads from memory, and the decoder
173
- // still saw "new coupling strategy must be present in block 0"). The
174
- // bounds check catches a fragment outside the pool; this catches one
175
- // inside it that belongs somewhere else.
176
- const lastPiece = this.#lastPieceByRead.get(message.id);
177
- if (lastPiece !== undefined && message.pieceIndex !== lastPiece && message.pieceIndex !== lastPiece + 1) {
178
- logger.warn(
179
- `torrent-worker: read ${message.id} jumped from piece ${lastPiece} to ` +
180
- `${message.pieceIndex} (${message.length}B at pool offset ${message.offset}) — ` +
181
- "the consumer is being handed the file out of order"
182
- );
183
- }
184
- this.#lastPieceByRead.set(message.id, message.pieceIndex);
185
- fragmentBuffers.seen += 1;
186
- fragmentCollector?.register(buffer, null);
187
- const view = new Uint8Array(buffer, message.offset, message.length);
188
-
189
- const reader = this.#fragmentReaders.get(message.id);
190
- if (reader) {
191
- // Handed on as a view into the pool — no copy anywhere. The piece
192
- // stays pinned until the consumer says it is done with these exact
193
- // bytes, which for a response body means the socket write has
194
- // completed.
195
- reader.push(view, () => {
196
- this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
197
- });
198
- break;
199
- }
200
-
201
- // Plain-stream consumers keep what they are given while the slot may
202
- // be reused, so they get a copy and the piece is released at once.
203
- this.#reads.get(message.id)?.push(Uint8Array.prototype.slice.call(view));
204
- this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
205
- break;
206
- }
207
- case Event.CHUNK: {
208
- const bytes = message.bytes;
209
- this.#reads.get(message.id)?.push(
210
- new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length)
211
- );
212
- break;
213
- }
214
- case Event.READ_END:
215
- this.#lastPieceByRead.delete(message.id);
216
- this.#reads.get(message.id)?.close();
217
- this.#reads.delete(message.id);
218
- this.#fragmentReaders.get(message.id)?.close();
219
- this.#fragmentReaders.delete(message.id);
220
- break;
221
- case Event.LOG:
222
- // Written as it is: the worker holds the same repeat rule and has
223
- // already applied it, and deciding again here would be one decision
224
- // taken twice on two different histories.
225
- writeAlreadyDecided(message.level ?? "info", `torrent-worker: ${message.message}`);
226
- break;
227
- case Event.FILE_COMPLETE:
228
- // Recorded here so the stream route can answer from the file without
229
- // going near the torrent thread at all.
230
- this.wholeFiles.set(`${message.infoHash}/${message.fileIndex}`, {
231
- path: message.path,
232
- length: message.length,
233
- name: message.name
234
- });
235
- break;
236
- case Event.PIECES_ARRIVED:
237
- // ANNOUNCED by the thread that owns the swarm, acted on here: the
238
- // subtitle walk is this thread's and needs to know a piece arrived.
239
- this.#onPiecesArrived({
240
- sourceKey: message.sourceKey,
241
- fileIndexes: Array.isArray(message.fileIndexes) ? message.fileIndexes : []
242
- });
243
- break;
244
- default:
245
- break;
246
- }
247
- });
248
-
249
- this.#worker.on("error", (error) => {
250
- logger.error(`torrent-worker crashed: ${error?.message ?? error}`);
251
- // Fail everything outstanding rather than leaving callers hanging: a dead
252
- // worker will never answer, and a stalled request is worse than an error
253
- // the loading flow can retry.
254
- this.#failEverythingOutstanding(new Error("Torrent worker stopped unexpectedly."));
255
- });
256
-
257
- // A worker that ENDS was, until now, not noticed at all: only `message` and
258
- // `error` were listened for. So when the thread went away the proxy simply
259
- // stopped, the log ended mid-sentence, and nothing said whether we had
260
- // asked for it — which is precisely the reading that was missing on
261
- // 2026-08-21, when a core dump showed the thread faulting inside
262
- // `Environment::CleanupHandles` and there was no way to tell our own
263
- // shutdown from the thread ending on its own.
264
- this.#worker.on("exit", (code) => {
265
- if (this.#stopping) {
266
- logger.info(`torrent-worker: thread ended as asked (code ${code})`);
267
- return;
268
- }
269
- logger.error(
270
- `torrent-worker: thread ended on its own with code ${code} — nobody asked it to. ` +
271
- "Everything waiting on it is failed; the proxy has no torrent client until it is rebuilt."
272
- );
273
- this.#failEverythingOutstanding(new Error("Torrent worker ended unexpectedly."));
274
- });
275
- }
276
-
277
- /**
278
- * A dead thread will never answer, so everything waiting on it is failed.
279
- *
280
- * INCLUDING THE FRAGMENT READS, which is what ffmpeg's input is. Both death
281
- * handlers walked `#reads` alone and left `#fragmentReaders` untouched, so an
282
- * encoder's input neither ended nor errored — it went quiet. Field 2026-08-31,
283
- * three times: the thread died, both ffmpeg runs stayed ALIVE and stopped
284
- * producing (167 `holding segment-00085.mp4 … encoder alive` lines), the
285
- * browser drained its cushion and then retried a segment that would never
286
- * exist, for ever, with nothing shown to the viewer.
287
- *
288
- * @param {Error} reason
289
- */
290
- #failEverythingOutstanding(reason) {
291
- this.#caller.rejectAll(reason);
292
- for (const [, read] of this.#reads) {
293
- read.fail(reason);
294
- }
295
- this.#reads.clear();
296
- for (const [, reader] of this.#fragmentReaders) {
297
- reader.fail(reason);
298
- }
299
- this.#fragmentReaders.clear();
300
- }
301
-
302
- /**
303
- * Add (or join) a torrent and register it under `sourceKey`.
304
- *
305
- * @param {{ sourceKey: string, sourceType: "magnet" | "torrent", source: string }} params
306
- * @returns {Promise<{ infoHash: string, name: string, files: { index: number, name: string, path: string, length: number }[] }>}
307
- */
308
- async addSource({ sourceKey, sourceType, source }) {
309
- return this.#caller.call(Command.ADD_SOURCE, { sourceKey, sourceType, source });
310
- }
311
-
312
- /**
313
- * The torrent's files, as plain data.
314
- *
315
- * @param {string} sourceKey
316
- * @returns {Promise<{ index: number, name: string, path: string, length: number }[]>}
317
- */
318
- async listFiles(sourceKey) {
319
- return this.#caller.call(Command.LIST_FILES, { sourceKey });
320
- }
321
-
322
- /**
323
- * Live download figures for the progress display.
324
- *
325
- * @param {{ sourceKey: string, fileIndex: number, resumeAnchorByteStart?: number | null }} params
326
- * @returns {Promise<object>}
327
- */
328
- async getFileStats({ sourceKey, fileIndex, resumeAnchorByteStart = null }) {
329
- return this.#caller.call(Command.FILE_STATS, { sourceKey, fileIndex, resumeAnchorByteStart });
330
- }
331
-
332
- /**
333
- * The text subtitle tracks a file carries.
334
- *
335
- * @param {{ sourceKey: string, fileIndex: number }} params
336
- * @returns {Promise<{ tracks: object[] }>}
337
- */
338
-
339
-
340
-
341
-
342
- /**
343
- * Start fetching the region a viewer is about to resume at.
344
- *
345
- * @param {{ sourceKey: string, fileIndex: number, positionSeconds: number }} params
346
- * @returns {Promise<{ started: boolean }>}
347
- */
348
- /**
349
- * Fetch one whole file in the room the viewer's own reading leaves.
350
- *
351
- * @param {{ sourceKey: string, fileIndex: number }} params
352
- * @returns {Promise<{ started: boolean }>}
353
- */
354
- async fillFile({ sourceKey, fileIndex }) {
355
- return this.#caller.call(Command.FILL_FILE, { sourceKey, fileIndex });
356
- }
357
-
358
- /**
359
- * The byte ranges of one file the torrent holds WHOLE.
360
- *
361
- * @param {{ sourceKey: string, fileIndex: number }} params
362
- * @returns {Promise<Array<[number, number]>>}
363
- */
364
- async heldRanges({ sourceKey, fileIndex }) {
365
- const answer = await this.#caller.call(Command.HELD_RANGES, { sourceKey, fileIndex });
366
- return Array.isArray(answer?.ranges) ? answer.ranges : [];
367
- }
368
-
369
- /**
370
- * Bytes of a range the torrent already holds. Never fetched: null where they
371
- * are not there.
372
- *
373
- * @param {{ sourceKey: string, fileIndex: number, start: number, end: number }} params
374
- * @returns {Promise<Buffer | null>}
375
- */
376
- async readHeld({ sourceKey, fileIndex, start, end }) {
377
- const answer = await this.#caller.call(Command.READ_HELD, { sourceKey, fileIndex, start, end });
378
- return answer?.bytes ? Buffer.from(answer.bytes) : null;
379
- }
380
-
381
- async warmResumePosition({ sourceKey, fileIndex, positionSeconds, durationSeconds }) {
382
- return this.#caller.call(Command.WARM_POSITION, { sourceKey, fileIndex, positionSeconds, durationSeconds });
383
- }
384
-
385
-
386
- /**
387
- * Bytes every torrent on the worker has moved, downloaded and uploaded apart.
388
- *
389
- * The client lives on the worker thread, so this cannot be read as a property
390
- * from here — which is exactly the mistake 2.19.0 shipped, leaving the figure
391
- * always zero and the whole feature inert.
392
- *
393
- * @returns {Promise<{ downloaded: number, uploaded: number }>}
394
- */
395
- async getTorrentTotals() {
396
- return this.#caller.call(Command.TORRENT_TOTALS, {});
397
- }
398
-
399
- /**
400
- * Which films this proxy holds right now, and how much of each.
401
- *
402
- * Asked of the worker rather than of the main thread's map of stand-ins: that
403
- * map is only cleared on shutdown, so it names films this proxy let go of
404
- * hours ago.
405
- *
406
- * @returns {Promise<{ held: { infoHash: string, progress: number, bytes: number }[] }>}
407
- */
408
- async heldTorrents() {
409
- return this.#caller.call(Command.HELD_TORRENTS, {});
410
- }
411
-
412
- /** State conditional demand for every file in a selected torrent. */
413
- async fillTorrent(sourceKey) {
414
- return this.#caller.call(Command.FILL_TORRENT, { sourceKey });
415
- }
416
-
417
- /**
418
- * Reorder piece selection around a read position (seek prioritisation).
419
- *
420
- * @param {{ sourceKey: string, fileIndex: number, byteStart: number, windowBytes?: number, wholeFileRead?: boolean }} params
421
- * @returns {Promise<void>}
422
- */
423
- async prioritizeByteRange({ sourceKey, fileIndex, byteStart, windowBytes, wholeFileRead }) {
424
- await this.#caller.call(Command.PRIORITIZE, {
425
- sourceKey,
426
- fileIndex,
427
- byteStart,
428
- windowBytes,
429
- wholeFileRead
430
- });
431
- }
432
-
433
- /**
434
- * Hand the download the priority map for one file.
435
- *
436
- * Seconds of film against a number, and nothing else: what is wanted and in
437
- * what order. Turning that into bytes, into pieces, and into what the swarm
438
- * is asked for is the download's own business, and so is what it keeps in
439
- * memory.
440
- *
441
- * @param {{ sourceKey: string, fileIndex: number, durationSeconds: number, zones: { from: number, to: number, priority: number }[] }} params
442
- * @returns {Promise<void>}
443
- */
444
- async setPriorityMap({ sourceKey, fileIndex, zones, durationSeconds }) {
445
- await this.#caller.call(Command.PRIORITY_MAP, {
446
- sourceKey,
447
- fileIndex,
448
- zones,
449
- durationSeconds
450
- });
451
- }
452
-
453
- /**
454
- * Pre-fetch the head and tail the codec probe needs.
455
- *
456
- * @param {{ sourceKey: string, fileIndex: number, options?: { headBytes?: number, tailBytes?: number, timeoutMs?: number, awaited?: boolean } }} params
457
- * @returns {Promise<unknown>}
458
- */
459
- async prefetchFileEdges({ sourceKey, fileIndex, options = {} }) {
460
- return this.#caller.call(Command.PREFETCH_EDGES, { sourceKey, fileIndex, options });
461
- }
462
-
463
- /**
464
- * Read a byte range as a stream.
465
- *
466
- * Returns immediately with a stream that fills as chunks arrive; cancelling it
467
- * (viewer gone, seek superseded) stops the worker reading, so pieces are not
468
- * fetched for a stream nobody will drain.
469
- *
470
- * @param {{ sourceKey: string, fileIndex: number, start?: number | null, end?: number | null, windowBytes?: number }} params
471
- * @returns {ReadableStream<Uint8Array>}
472
- */
473
- createReadStream({ sourceKey, fileIndex, start = null, end = null, windowBytes }) {
474
- // Same id sequence as commands — see `nextId` in `channel.js`.
475
- const readId = this.#caller.nextId();
476
- const receive = createReceiveStream({
477
- port: this.#worker,
478
- requestId: readId,
479
- onCancel: () => {
480
- void this.#caller.call(Command.CANCEL_READ, { readId }).catch(() => undefined);
481
- this.#reads.delete(readId);
482
- this.#lastPieceByRead.delete(readId);
483
- }
484
- });
485
- this.#reads.set(readId, receive);
486
-
487
- // The worker replies to READ_RANGE only once the body is fully sent; a
488
- // failure before that must surface on the stream, not vanish.
489
- this.#worker.postMessage({
490
- command: Command.READ_RANGE,
491
- id: readId,
492
- params: { sourceKey, fileIndex, start, end, windowBytes }
493
- });
494
-
495
- return receive.stream;
496
- }
497
-
498
- /**
499
- * Read a byte range as fragments of shared memory, without copying.
500
- *
501
- * Each fragment is a view straight into the torrent's piece pool, and the
502
- * piece behind it stays pinned until `release()` is called — so the consumer
503
- * must call it once it is genuinely finished with those bytes. For a response
504
- * body that means after the socket write has completed, not when it was
505
- * queued: verified that writing a shared-memory view and then overwriting the
506
- * pool from the write callback leaves the client's copy intact, and that
507
- * overwriting it earlier corrupts it silently.
508
- *
509
- * Returns `null` when this source has no shared pool, so the caller can fall
510
- * back to {@link createReadStream}.
511
- *
512
- * @param {{ sourceKey: string, fileIndex: number, start?: number | null, end?: number | null, windowBytes?: number }} params
513
- * @returns {{ [Symbol.asyncIterator]: () => AsyncGenerator<{ bytes: Uint8Array, release: () => void }>, cancel: () => void } | null}
514
- */
515
- createFragmentReader({ sourceKey, fileIndex, start = null, end = null, windowBytes }) {
516
- const readId = this.#caller.nextId();
517
- /** @type {{ bytes: Uint8Array, release: () => void }[]} */
518
- const queue = [];
519
- let wake = null;
520
- let finished = false;
521
- let failure = null;
522
-
523
- const notify = () => {
524
- const resume = wake;
525
- wake = null;
526
- resume?.();
527
- };
528
-
529
- this.#fragmentReaders.set(readId, {
530
- push(bytes, confirm) {
531
- queue.push({ bytes, release: confirm });
532
- notify();
533
- },
534
- close() {
535
- finished = true;
536
- notify();
537
- },
538
- fail(error) {
539
- failure = error;
540
- finished = true;
541
- notify();
542
- }
543
- });
544
-
545
- const cancel = () => {
546
- if (this.#fragmentReaders.delete(readId)) {
547
- void this.#caller.call(Command.CANCEL_READ, { readId }).catch(() => undefined);
548
- }
549
- finished = true;
550
- notify();
551
- };
552
-
553
- this.#worker.postMessage({
554
- command: Command.READ_RANGE,
555
- id: readId,
556
- params: { sourceKey, fileIndex, start, end, windowBytes }
557
- });
558
-
559
- return {
560
- cancel,
561
- async *[Symbol.asyncIterator]() {
562
- try {
563
- for (;;) {
564
- while (queue.length > 0) {
565
- yield queue.shift();
566
- }
567
- if (failure) {
568
- throw failure;
569
- }
570
- if (finished) {
571
- return;
572
- }
573
- await new Promise((resolve) => {
574
- wake = resolve;
575
- });
576
- }
577
- } finally {
578
- // Covers the consumer breaking out early — a client that hung up, a
579
- // superseded seek — which must stop the read rather than leave it
580
- // fetching pieces nobody will take.
581
- if (!finished) {
582
- cancel();
583
- }
584
- }
585
- }
586
- };
587
- }
588
-
589
- /**
590
- * A stand-in for the WebTorrent torrent object, backed by the worker.
591
- *
592
- * Callers already hold a torrent and reach into `torrent.files[i]` — for the
593
- * length, the name, or a read stream. Handing back an object of the same
594
- * shape keeps every one of those call sites working unchanged, which matters:
595
- * they are spread across the stream route, the subtitle route, the playback
596
- * planner and the health report, and rewriting all of them to thread a
597
- * `sourceKey` through would be a large change with nothing to show for it.
598
- *
599
- * Only what is actually used is provided. Anything else would be a promise we
600
- * cannot keep — the real object lives on the other thread and its methods are
601
- * not reachable from here.
602
- *
603
- * @param {{ sourceKey: string, sourceType: "magnet" | "torrent", source: string }} params
604
- * @returns {Promise<{ infoHash: string, name: string, sourceKey: string, files: object[] }>}
605
- */
606
- async getTorrent({ sourceKey, sourceType, source }) {
607
- const info = await this.addSource({ sourceKey, sourceType, source });
608
- const client = this;
609
- return {
610
- infoHash: info.infoHash,
611
- name: info.name,
612
- // Carried so helpers that receive only the torrent can still name it to
613
- // the worker.
614
- sourceKey,
615
- files: info.files.map((file) => ({
616
- ...file,
617
- /**
618
- * @param {{ start?: number, end?: number, windowBytes?: number }} [options]
619
- * @returns {ReadableStream<Uint8Array>}
620
- */
621
- createReadStream(options = {}) {
622
- // Node stream, not a web one: Fastify replies and the ffmpeg pipe
623
- // both expect that shape, and every existing call site passes the
624
- // result straight to one of them. `Readable.fromWeb` adds no copy —
625
- // it wraps the same buffers.
626
- return Readable.fromWeb(
627
- client.createReadStream({
628
- sourceKey,
629
- fileIndex: file.index,
630
- start: options.start ?? null,
631
- end: options.end ?? null,
632
- windowBytes: options.windowBytes
633
- })
634
- );
635
- },
636
-
637
- /**
638
- * Fragments of shared memory, for a caller that can say when it has
639
- * finished with each one. `null` when this source has no shared pool.
640
- *
641
- * @param {{ start?: number, end?: number, windowBytes?: number }} [options]
642
- * @returns {ReturnType<TorrentWorkerClient["createFragmentReader"]>}
643
- */
644
- createFragmentReader(options = {}) {
645
- return client.createFragmentReader({
646
- sourceKey,
647
- fileIndex: file.index,
648
- start: options.start ?? null,
649
- end: options.end ?? null,
650
- windowBytes: options.windowBytes
651
- });
652
- }
653
- }))
654
- };
655
- }
656
-
657
- /**
658
- * Shut the torrent client down and stop the thread.
659
- *
660
- * @returns {Promise<void>}
661
- */
662
- /**
663
- * What the spilled pieces weigh, as of the last revision. Zero until one has
664
- * happened, which is what "we have not asked yet" means.
665
- *
666
- * @type {number}
667
- */
668
- spilledBytes = 0;
669
-
670
- /**
671
- * Tell the piece stores on the torrent thread their share of MEMORY.
672
- *
673
- * The same owner divides memory and disk, because the two trade: pieces that
674
- * do not fit in memory are spilled to disk, so what the stores are given here
675
- * decides how much disk they need there.
676
- *
677
- * @param {number} bytes
678
- * @returns {Promise<{ held: number, wanted: number }>}
679
- */
680
- async allowMemoryBytes(bytes) {
681
- try {
682
- const claim = await this.#caller.call(Command.MEMORY_ALLOWANCE, { bytes });
683
- this.memoryClaim = {
684
- held: Number(claim?.held) || 0,
685
- wanted: Number(claim?.wanted) || 0
686
- };
687
- } catch {
688
- // The thread is gone or busy; the next revision says it again.
689
- }
690
- return this.memoryClaim ?? { held: 0, wanted: 0 };
691
- }
692
-
693
- /**
694
- * Tell the whole files on the torrent thread their share of the disk.
695
- *
696
- * Same shape as the spilled pieces, and for the same reason: they hold bytes
697
- * on this machine and the owner of the disk is on the other thread.
698
- *
699
- * @param {number} bytes
700
- * @returns {Promise<number>} What they hold after it.
701
- */
702
- async allowWholeFileBytes(bytes) {
703
- try {
704
- this.wholeFileBytes = Number(await this.#caller.call(Command.WHOLE_FILES_ALLOWANCE, { bytes })) || 0;
705
- } catch {
706
- // The thread is gone or busy; the next revision says it again.
707
- }
708
- return this.wholeFileBytes ?? 0;
709
- }
710
-
711
- /**
712
- * Say how much disk the spilled pieces on this thread may take between them.
713
- *
714
- * Best effort and never awaited by anything that matters: a share that does
715
- * not arrive leaves the ceiling where it was, and the next revision is a
716
- * minute away.
717
- *
718
- * @param {number} bytes
719
- * @returns {Promise<void>}
720
- */
721
- async allowSpillBytes(bytes) {
722
- try {
723
- const revised = await this.#caller.call(Command.SPILL_ALLOWANCE, { bytes });
724
- // The reply says what those stores actually hold, which is what the owner
725
- // of the disk needs for the next division. One exchange, both directions.
726
- this.spilledBytes = Array.isArray(revised)
727
- ? revised.reduce((sum, store) => sum + (Number(store?.bytes) || 0), 0)
728
- : this.spilledBytes;
729
- } catch {
730
- // The thread is gone or busy; the next revision says it again.
731
- }
732
- return this.spilledBytes;
733
- }
734
-
735
- async destroyAll() {
736
- this.#stopping = true;
737
- try {
738
- await this.#caller.call(Command.DESTROY_ALL, {});
739
- } catch {
740
- // Already gone — the wait below settles either way.
741
- }
742
- // Let the thread END rather than tearing it down under itself.
743
- //
744
- // `terminate()` frees the environment immediately, with the handle
745
- // callbacks libuv still holds queued. One of those is utp-native's UDP
746
- // read, and running it against a freed isolate is what the core dump of
747
- // 2026-08-21 caught: `on_utp_accept` → `napi_get_buffer_info` →
748
- // `v8::Value::IsArrayBufferView` inside `Environment::CleanupHandles`.
749
- // Once the client inside is destroyed the thread has nothing left holding
750
- // its loop open, so it exits by itself and the callbacks drain first.
751
- //
752
- // `terminate()` stays as the bounded fallback, because a shutdown that
753
- // hangs is worse than one that is forced.
754
- await new Promise((resolve) => {
755
- const timer = setTimeout(() => {
756
- logger.warn("torrent-worker: thread did not end in 5s; terminating it");
757
- void this.#worker.terminate().finally(resolve);
758
- }, WORKER_EXIT_GRACE_MS);
759
- this.#worker.once("exit", () => {
760
- clearTimeout(timer);
761
- resolve();
762
- });
763
- });
764
- }
765
- }
1
+ /**
2
+ * @file Main-thread face of the torrent worker.
3
+ *
4
+ * Presents the same operations the routes and session manager already use, so
5
+ * moving the torrent to its own thread does not ripple through calling code.
6
+ * The one unavoidable change is that torrents are named by `sourceKey` instead
7
+ * of passed around as objects — objects cannot cross a thread boundary, and
8
+ * pretending otherwise would mean copying them on every call.
9
+ *
10
+ * Reads come back as an ordinary `ReadableStream`, so `/stream` and the codec
11
+ * probe consume them exactly as they consume WebTorrent's own streams today.
12
+ * What that hides is the part that matters: chunks arrive as transferred
13
+ * buffers, never copied — 5.3 ms per 10 MB against 37 ms if cloned and 104 ms
14
+ * through a transferable stream (measured 2026-08-02, see `protocol.js`).
15
+ */
16
+
17
+ import { Worker } from "node:worker_threads";
18
+ import { Readable } from "node:stream";
19
+ import { fileURLToPath } from "node:url";
20
+ import { logger, writeAlreadyDecided } from "../../../utils/logger.js";
21
+ import { createCaller, createReceiveStream } from "./channel.js";
22
+ import { Command, Event } from "./protocol.js";
23
+
24
+ const WORKER_URL = new URL("./worker.js", import.meta.url);
25
+ /**
26
+ * How long a shutdown waits for the thread to end by itself before forcing it.
27
+ *
28
+ * Ending by itself is what lets libuv drain the handle callbacks it is holding;
29
+ * forcing it is what ran one of those against a freed isolate. Five seconds is
30
+ * long enough for a destroyed torrent client to release its sockets and short
31
+ * enough that a shutdown never appears to hang.
32
+ */
33
+ const WORKER_EXIT_GRACE_MS = 5_000;
34
+
35
+ /**
36
+ * Runs the torrent client on its own thread and exposes it to the main thread.
37
+ *
38
+ * Why this exists at all: profiling during a live seek found the main thread
39
+ * ~85% busy with WebTorrent (buffer concatenation ~15%, wire updates ~9%,
40
+ * garbage collection ~5%), while three of four cores idled. Serving a segment
41
+ * queued behind that work, so reading a finished 10 MB file took 12-23 s where
42
+ * handing it to the channel took 125 ms.
43
+ */
44
+ /**
45
+ * Piece buffers this thread has been handed, and how many the collector has
46
+ * taken back.
47
+ *
48
+ * A `SharedArrayBuffer`'s memory belongs to neither isolate: it lives until
49
+ * BOTH have let go. So the worker's own count answers only half the question,
50
+ * and this is the other half — 700 MB grew in the field on 2026-08-31 with the
51
+ * store's own memory falling, and the two candidates are "a reference of ours
52
+ * outlives the piece" and "the allocator keeps what we free". These two
53
+ * counters separate them (roadmap item 2).
54
+ *
55
+ * A fragment arrives as a fresh handle onto the same shared memory every time,
56
+ * so what is counted is handles, not pieces. That is the right quantity anyway:
57
+ * one handle retained keeps the whole piece alive.
58
+ */
59
+ const fragmentBuffers = { seen: 0, collected: 0 };
60
+ const fragmentCollector = typeof FinalizationRegistry === "function"
61
+ ? new FinalizationRegistry(() => {
62
+ fragmentBuffers.collected += 1;
63
+ })
64
+ : null;
65
+
66
+ /**
67
+ * What the collector has taken back against what this thread was handed.
68
+ *
69
+ * @returns {{ seen: number, collected: number }}
70
+ */
71
+ export function fragmentBufferCollection() {
72
+ return { seen: fragmentBuffers.seen, collected: fragmentBuffers.collected };
73
+ }
74
+
75
+ export class TorrentWorkerClient {
76
+ #worker;
77
+ /**
78
+ * Whether this shutdown was asked for, so the thread ending can be told from
79
+ * the thread dying. Without it both look identical from outside, which is how
80
+ * five crashes produced no line in the log.
81
+ */
82
+ #stopping = false;
83
+ #caller;
84
+ /** Receive-side handles for in-flight reads, keyed by request id. */
85
+ #reads = new Map();
86
+
87
+ /**
88
+ * The last piece served to each open read, so a fragment arriving out of
89
+ * order can be named. Cleared when the read ends.
90
+ *
91
+ * @type {Map<number, number>}
92
+ */
93
+ #lastPieceByRead = new Map();
94
+ /** Reads consuming fragments in place, keyed by request id. */
95
+ #fragmentReaders = new Map();
96
+
97
+ /**
98
+ * Files downloaded whole, by `${infoHash}/${fileIndex}`.
99
+ *
100
+ * Held on THIS thread because it is this thread that serves them: a file that
101
+ * is whole is read with an ordinary file read, and asking the torrent thread
102
+ * for anything about it would put back the very hop this removes. The torrent
103
+ * thread writes the files and says so; this is what it says.
104
+ *
105
+ * @type {Map<string, { path: string, length: number, name: string }>}
106
+ */
107
+ wholeFiles = new Map();
108
+
109
+ /** @type {(event: { sourceKey: string, fileIndex: number, trackIndex: number, cues: object[], language: string }) => void} */
110
+ /** @type {(event: { sourceKey: string, fileIndexes: number[] }) => void} */
111
+ #onPiecesArrived;
112
+
113
+ /**
114
+ * @param {{ memoryBytes?: number, stateDir?: string, onPiecesArrived?: (event: object) => void }} [options]
115
+ */
116
+ constructor({ memoryBytes, stateDir, onPiecesArrived } = {}) {
117
+ this.#worker = new Worker(fileURLToPath(WORKER_URL), {
118
+ // `stateDir` travels because the worker writes heap snapshots of its own
119
+ // isolate there. It cannot choose a directory any other way: a worker may
120
+ // not change the process's working directory, and the isolate that has
121
+ // died three times is the one no snapshot has ever been taken of.
122
+ workerData: { memoryBytes, stateDir }
123
+ });
124
+ this.#caller = createCaller(this.#worker);
125
+ this.#onPiecesArrived = onPiecesArrived ?? (() => undefined);
126
+
127
+ this.#worker.on("message", (message) => {
128
+ // A failed read must fail its stream. This is checked BEFORE the caller
129
+ // sees the message: until 2.9.76 nothing here handled a read error at
130
+ // all, so the worker's report was dropped as unknown, and because the
131
+ // worker sent the end-of-read marker from its `finally` even when the
132
+ // read had thrown, the reader saw a clean end of file instead. A read
133
+ // that failed before it produced anything simply hung forever.
134
+ if (message?.type === Event.ERROR && this.#reads.has(message.id)) {
135
+ const read = this.#reads.get(message.id);
136
+ this.#reads.delete(message.id);
137
+ read.fail(new Error(message.error ?? "Torrent worker read failed."));
138
+ return;
139
+ }
140
+ if (message?.type === Event.ERROR && this.#fragmentReaders.has(message.id)) {
141
+ const reader = this.#fragmentReaders.get(message.id);
142
+ this.#fragmentReaders.delete(message.id);
143
+ reader.fail(new Error(message.error ?? "Torrent worker read failed."));
144
+ return;
145
+ }
146
+ if (this.#caller.handleReply(message)) {
147
+ return;
148
+ }
149
+ switch (message?.type) {
150
+ case Event.FRAGMENT: {
151
+ const buffer = message.buffer;
152
+ if (!buffer) {
153
+ // No buffer means no way to read the fragment; confirm it so the
154
+ // worker is not left waiting, and let the read end short.
155
+ this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
156
+ break;
157
+ }
158
+ if (message.offset + message.length > buffer.byteLength) {
159
+ logger.warn(
160
+ `torrent-worker: fragment ${message.offset}+${message.length} lies outside ` +
161
+ `its buffer of ${buffer.byteLength}B (read ${message.id}) — ending the read short`
162
+ );
163
+ this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
164
+ break;
165
+ }
166
+ // A sequential read walks the file forwards, so each fragment either
167
+ // continues the piece before it or moves to the very next one.
168
+ // Anything else means the bytes handed to the decoder are not the
169
+ // file's bytes in order — which is what a decoder complaining about
170
+ // its input has twice turned out to mean (2.9.126, and the AC-3
171
+ // failure of 2026-08-09: the encoder ran at 9.3x, the piece store
172
+ // reported no spills and 100% of reads from memory, and the decoder
173
+ // still saw "new coupling strategy must be present in block 0"). The
174
+ // bounds check catches a fragment outside the pool; this catches one
175
+ // inside it that belongs somewhere else.
176
+ const lastPiece = this.#lastPieceByRead.get(message.id);
177
+ if (lastPiece !== undefined && message.pieceIndex !== lastPiece && message.pieceIndex !== lastPiece + 1) {
178
+ logger.warn(
179
+ `torrent-worker: read ${message.id} jumped from piece ${lastPiece} to ` +
180
+ `${message.pieceIndex} (${message.length}B at pool offset ${message.offset}) — ` +
181
+ "the consumer is being handed the file out of order"
182
+ );
183
+ }
184
+ this.#lastPieceByRead.set(message.id, message.pieceIndex);
185
+ fragmentBuffers.seen += 1;
186
+ fragmentCollector?.register(buffer, null);
187
+ const view = new Uint8Array(buffer, message.offset, message.length);
188
+
189
+ const reader = this.#fragmentReaders.get(message.id);
190
+ if (reader) {
191
+ // Handed on as a view into the pool — no copy anywhere. The piece
192
+ // stays pinned until the consumer says it is done with these exact
193
+ // bytes, which for a response body means the socket write has
194
+ // completed.
195
+ reader.push(view, () => {
196
+ this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
197
+ });
198
+ break;
199
+ }
200
+
201
+ // Plain-stream consumers keep what they are given while the slot may
202
+ // be reused, so they get a copy and the piece is released at once.
203
+ this.#reads.get(message.id)?.push(Uint8Array.prototype.slice.call(view));
204
+ this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
205
+ break;
206
+ }
207
+ case Event.CHUNK: {
208
+ const bytes = message.bytes;
209
+ this.#reads.get(message.id)?.push(
210
+ new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length)
211
+ );
212
+ break;
213
+ }
214
+ case Event.READ_END:
215
+ this.#lastPieceByRead.delete(message.id);
216
+ this.#reads.get(message.id)?.close();
217
+ this.#reads.delete(message.id);
218
+ this.#fragmentReaders.get(message.id)?.close();
219
+ this.#fragmentReaders.delete(message.id);
220
+ break;
221
+ case Event.LOG:
222
+ // Written as it is: the worker holds the same repeat rule and has
223
+ // already applied it, and deciding again here would be one decision
224
+ // taken twice on two different histories.
225
+ writeAlreadyDecided(message.level ?? "info", `torrent-worker: ${message.message}`);
226
+ break;
227
+ case Event.FILE_COMPLETE:
228
+ // Recorded here so the stream route can answer from the file without
229
+ // going near the torrent thread at all.
230
+ this.wholeFiles.set(`${message.infoHash}/${message.fileIndex}`, {
231
+ path: message.path,
232
+ length: message.length,
233
+ name: message.name
234
+ });
235
+ break;
236
+ case Event.PIECES_ARRIVED:
237
+ // ANNOUNCED by the thread that owns the swarm, acted on here: the
238
+ // subtitle walk is this thread's and needs to know a piece arrived.
239
+ this.#onPiecesArrived({
240
+ sourceKey: message.sourceKey,
241
+ fileIndexes: Array.isArray(message.fileIndexes) ? message.fileIndexes : []
242
+ });
243
+ break;
244
+ default:
245
+ break;
246
+ }
247
+ });
248
+
249
+ this.#worker.on("error", (error) => {
250
+ logger.error(`torrent-worker crashed: ${error?.message ?? error}`);
251
+ // Fail everything outstanding rather than leaving callers hanging: a dead
252
+ // worker will never answer, and a stalled request is worse than an error
253
+ // the loading flow can retry.
254
+ this.#failEverythingOutstanding(new Error("Torrent worker stopped unexpectedly."));
255
+ });
256
+
257
+ // A worker that ENDS was, until now, not noticed at all: only `message` and
258
+ // `error` were listened for. So when the thread went away the proxy simply
259
+ // stopped, the log ended mid-sentence, and nothing said whether we had
260
+ // asked for it — which is precisely the reading that was missing on
261
+ // 2026-08-21, when a core dump showed the thread faulting inside
262
+ // `Environment::CleanupHandles` and there was no way to tell our own
263
+ // shutdown from the thread ending on its own.
264
+ this.#worker.on("exit", (code) => {
265
+ if (this.#stopping) {
266
+ logger.info(`torrent-worker: thread ended as asked (code ${code})`);
267
+ return;
268
+ }
269
+ logger.error(
270
+ `torrent-worker: thread ended on its own with code ${code} — nobody asked it to. ` +
271
+ "Everything waiting on it is failed; the proxy has no torrent client until it is rebuilt."
272
+ );
273
+ this.#failEverythingOutstanding(new Error("Torrent worker ended unexpectedly."));
274
+ });
275
+ }
276
+
277
+ /**
278
+ * A dead thread will never answer, so everything waiting on it is failed.
279
+ *
280
+ * INCLUDING THE FRAGMENT READS, which is what ffmpeg's input is. Both death
281
+ * handlers walked `#reads` alone and left `#fragmentReaders` untouched, so an
282
+ * encoder's input neither ended nor errored — it went quiet. Field 2026-08-31,
283
+ * three times: the thread died, both ffmpeg runs stayed ALIVE and stopped
284
+ * producing (167 `holding segment-00085.mp4 … encoder alive` lines), the
285
+ * browser drained its cushion and then retried a segment that would never
286
+ * exist, for ever, with nothing shown to the viewer.
287
+ *
288
+ * @param {Error} reason
289
+ */
290
+ #failEverythingOutstanding(reason) {
291
+ this.#caller.rejectAll(reason);
292
+ for (const [, read] of this.#reads) {
293
+ read.fail(reason);
294
+ }
295
+ this.#reads.clear();
296
+ for (const [, reader] of this.#fragmentReaders) {
297
+ reader.fail(reason);
298
+ }
299
+ this.#fragmentReaders.clear();
300
+ }
301
+
302
+ /**
303
+ * Add (or join) a torrent and register it under `sourceKey`.
304
+ *
305
+ * @param {{ sourceKey: string, sourceType: "magnet" | "torrent", source: string }} params
306
+ * @returns {Promise<{ infoHash: string, name: string, files: { index: number, name: string, path: string, length: number }[] }>}
307
+ */
308
+ async addSource({ sourceKey, sourceType, source }) {
309
+ return this.#caller.call(Command.ADD_SOURCE, { sourceKey, sourceType, source });
310
+ }
311
+
312
+ /**
313
+ * The torrent's files, as plain data.
314
+ *
315
+ * @param {string} sourceKey
316
+ * @returns {Promise<{ index: number, name: string, path: string, length: number }[]>}
317
+ */
318
+ async listFiles(sourceKey) {
319
+ return this.#caller.call(Command.LIST_FILES, { sourceKey });
320
+ }
321
+
322
+ /**
323
+ * Live download figures for the progress display.
324
+ *
325
+ * @param {{ sourceKey: string, fileIndex: number, resumeAnchorByteStart?: number | null }} params
326
+ * @returns {Promise<object>}
327
+ */
328
+ async getFileStats({ sourceKey, fileIndex, resumeAnchorByteStart = null }) {
329
+ return this.#caller.call(Command.FILE_STATS, { sourceKey, fileIndex, resumeAnchorByteStart });
330
+ }
331
+
332
+ /**
333
+ * The text subtitle tracks a file carries.
334
+ *
335
+ * @param {{ sourceKey: string, fileIndex: number }} params
336
+ * @returns {Promise<{ tracks: object[] }>}
337
+ */
338
+
339
+
340
+
341
+
342
+ /**
343
+ * Start fetching the region a viewer is about to resume at.
344
+ *
345
+ * @param {{ sourceKey: string, fileIndex: number, positionSeconds: number }} params
346
+ * @returns {Promise<{ started: boolean }>}
347
+ */
348
+ /**
349
+ * Fetch one whole file in the room the viewer's own reading leaves.
350
+ *
351
+ * @param {{ sourceKey: string, fileIndex: number }} params
352
+ * @returns {Promise<{ started: boolean }>}
353
+ */
354
+ async fillFile({ sourceKey, fileIndex }) {
355
+ return this.#caller.call(Command.FILL_FILE, { sourceKey, fileIndex });
356
+ }
357
+
358
+ /**
359
+ * The byte ranges of one file the torrent holds WHOLE.
360
+ *
361
+ * @param {{ sourceKey: string, fileIndex: number }} params
362
+ * @returns {Promise<Array<[number, number]>>}
363
+ */
364
+ async heldRanges({ sourceKey, fileIndex }) {
365
+ const answer = await this.#caller.call(Command.HELD_RANGES, { sourceKey, fileIndex });
366
+ return Array.isArray(answer?.ranges) ? answer.ranges : [];
367
+ }
368
+
369
+ /**
370
+ * Bytes of a range the torrent already holds. Never fetched: null where they
371
+ * are not there.
372
+ *
373
+ * @param {{ sourceKey: string, fileIndex: number, start: number, end: number }} params
374
+ * @returns {Promise<Buffer | null>}
375
+ */
376
+ async readHeld({ sourceKey, fileIndex, start, end }) {
377
+ const answer = await this.#caller.call(Command.READ_HELD, { sourceKey, fileIndex, start, end });
378
+ return answer?.bytes ? Buffer.from(answer.bytes) : null;
379
+ }
380
+
381
+ async warmResumePosition({ sourceKey, fileIndex, positionSeconds, durationSeconds }) {
382
+ return this.#caller.call(Command.WARM_POSITION, { sourceKey, fileIndex, positionSeconds, durationSeconds });
383
+ }
384
+
385
+
386
+ /**
387
+ * Bytes every torrent on the worker has moved, downloaded and uploaded apart.
388
+ *
389
+ * The client lives on the worker thread, so this cannot be read as a property
390
+ * from here — which is exactly the mistake 2.19.0 shipped, leaving the figure
391
+ * always zero and the whole feature inert.
392
+ *
393
+ * @returns {Promise<{ downloaded: number, uploaded: number }>}
394
+ */
395
+ async getTorrentTotals() {
396
+ return this.#caller.call(Command.TORRENT_TOTALS, {});
397
+ }
398
+
399
+ /**
400
+ * Which films this proxy holds right now, and how much of each.
401
+ *
402
+ * Asked of the worker rather than of the main thread's map of stand-ins: that
403
+ * map is only cleared on shutdown, so it names films this proxy let go of
404
+ * hours ago.
405
+ *
406
+ * @returns {Promise<{ held: { infoHash: string, progress: number, bytes: number }[] }>}
407
+ */
408
+ async heldTorrents() {
409
+ return this.#caller.call(Command.HELD_TORRENTS, {});
410
+ }
411
+
412
+ /** State conditional demand for every file in a selected torrent. */
413
+ async fillTorrent(sourceKey) {
414
+ return this.#caller.call(Command.FILL_TORRENT, { sourceKey });
415
+ }
416
+
417
+ /**
418
+ * Reorder piece selection around a read position (seek prioritisation).
419
+ *
420
+ * @param {{ sourceKey: string, fileIndex: number, byteStart: number, windowBytes?: number, wholeFileRead?: boolean }} params
421
+ * @returns {Promise<void>}
422
+ */
423
+ async prioritizeByteRange({ sourceKey, fileIndex, byteStart, windowBytes, wholeFileRead }) {
424
+ await this.#caller.call(Command.PRIORITIZE, {
425
+ sourceKey,
426
+ fileIndex,
427
+ byteStart,
428
+ windowBytes,
429
+ wholeFileRead
430
+ });
431
+ }
432
+
433
+ /**
434
+ * Hand the download the priority map for one file.
435
+ *
436
+ * Seconds of film against a number, and nothing else: what is wanted and in
437
+ * what order. Turning that into bytes, into pieces, and into what the swarm
438
+ * is asked for is the download's own business, and so is what it keeps in
439
+ * memory.
440
+ *
441
+ * @param {{ sourceKey: string, fileIndex: number, durationSeconds: number, zones: { from: number, to: number, priority: number }[] }} params
442
+ * @returns {Promise<void>}
443
+ */
444
+ async setPriorityMap({ sourceKey, fileIndex, zones, durationSeconds }) {
445
+ await this.#caller.call(Command.PRIORITY_MAP, {
446
+ sourceKey,
447
+ fileIndex,
448
+ zones,
449
+ durationSeconds
450
+ });
451
+ }
452
+
453
+ /**
454
+ * Pre-fetch the head and tail the codec probe needs.
455
+ *
456
+ * @param {{ sourceKey: string, fileIndex: number, options?: { headBytes?: number, tailBytes?: number, timeoutMs?: number, awaited?: boolean } }} params
457
+ * @returns {Promise<unknown>}
458
+ */
459
+ async prefetchFileEdges({ sourceKey, fileIndex, options = {} }) {
460
+ return this.#caller.call(Command.PREFETCH_EDGES, { sourceKey, fileIndex, options });
461
+ }
462
+
463
+ /**
464
+ * Read a byte range as a stream.
465
+ *
466
+ * Returns immediately with a stream that fills as chunks arrive; cancelling it
467
+ * (viewer gone, seek superseded) stops the worker reading, so pieces are not
468
+ * fetched for a stream nobody will drain.
469
+ *
470
+ * @param {{ sourceKey: string, fileIndex: number, start?: number | null, end?: number | null, windowBytes?: number }} params
471
+ * @returns {ReadableStream<Uint8Array>}
472
+ */
473
+ createReadStream({ sourceKey, fileIndex, start = null, end = null, windowBytes }) {
474
+ // Same id sequence as commands — see `nextId` in `channel.js`.
475
+ const readId = this.#caller.nextId();
476
+ const receive = createReceiveStream({
477
+ port: this.#worker,
478
+ requestId: readId,
479
+ onCancel: () => {
480
+ void this.#caller.call(Command.CANCEL_READ, { readId }).catch(() => undefined);
481
+ this.#reads.delete(readId);
482
+ this.#lastPieceByRead.delete(readId);
483
+ }
484
+ });
485
+ this.#reads.set(readId, receive);
486
+
487
+ // The worker replies to READ_RANGE only once the body is fully sent; a
488
+ // failure before that must surface on the stream, not vanish.
489
+ this.#worker.postMessage({
490
+ command: Command.READ_RANGE,
491
+ id: readId,
492
+ params: { sourceKey, fileIndex, start, end, windowBytes }
493
+ });
494
+
495
+ return receive.stream;
496
+ }
497
+
498
+ /**
499
+ * Read a byte range as fragments of shared memory, without copying.
500
+ *
501
+ * Each fragment is a view straight into the torrent's piece pool, and the
502
+ * piece behind it stays pinned until `release()` is called — so the consumer
503
+ * must call it once it is genuinely finished with those bytes. For a response
504
+ * body that means after the socket write has completed, not when it was
505
+ * queued: verified that writing a shared-memory view and then overwriting the
506
+ * pool from the write callback leaves the client's copy intact, and that
507
+ * overwriting it earlier corrupts it silently.
508
+ *
509
+ * Returns `null` when this source has no shared pool, so the caller can fall
510
+ * back to {@link createReadStream}.
511
+ *
512
+ * @param {{ sourceKey: string, fileIndex: number, start?: number | null, end?: number | null, windowBytes?: number }} params
513
+ * @returns {{ [Symbol.asyncIterator]: () => AsyncGenerator<{ bytes: Uint8Array, release: () => void }>, cancel: () => void } | null}
514
+ */
515
+ createFragmentReader({ sourceKey, fileIndex, start = null, end = null, windowBytes }) {
516
+ const readId = this.#caller.nextId();
517
+ /** @type {{ bytes: Uint8Array, release: () => void }[]} */
518
+ const queue = [];
519
+ let wake = null;
520
+ let finished = false;
521
+ let failure = null;
522
+
523
+ const notify = () => {
524
+ const resume = wake;
525
+ wake = null;
526
+ resume?.();
527
+ };
528
+
529
+ this.#fragmentReaders.set(readId, {
530
+ push(bytes, confirm) {
531
+ queue.push({ bytes, release: confirm });
532
+ notify();
533
+ },
534
+ close() {
535
+ finished = true;
536
+ notify();
537
+ },
538
+ fail(error) {
539
+ failure = error;
540
+ finished = true;
541
+ notify();
542
+ }
543
+ });
544
+
545
+ const cancel = () => {
546
+ if (this.#fragmentReaders.delete(readId)) {
547
+ void this.#caller.call(Command.CANCEL_READ, { readId }).catch(() => undefined);
548
+ }
549
+ finished = true;
550
+ notify();
551
+ };
552
+
553
+ this.#worker.postMessage({
554
+ command: Command.READ_RANGE,
555
+ id: readId,
556
+ params: { sourceKey, fileIndex, start, end, windowBytes }
557
+ });
558
+
559
+ return {
560
+ cancel,
561
+ async *[Symbol.asyncIterator]() {
562
+ try {
563
+ for (;;) {
564
+ while (queue.length > 0) {
565
+ yield queue.shift();
566
+ }
567
+ if (failure) {
568
+ throw failure;
569
+ }
570
+ if (finished) {
571
+ return;
572
+ }
573
+ await new Promise((resolve) => {
574
+ wake = resolve;
575
+ });
576
+ }
577
+ } finally {
578
+ // Covers the consumer breaking out early — a client that hung up, a
579
+ // superseded seek — which must stop the read rather than leave it
580
+ // fetching pieces nobody will take.
581
+ if (!finished) {
582
+ cancel();
583
+ }
584
+ }
585
+ }
586
+ };
587
+ }
588
+
589
+ /**
590
+ * A stand-in for the WebTorrent torrent object, backed by the worker.
591
+ *
592
+ * Callers already hold a torrent and reach into `torrent.files[i]` — for the
593
+ * length, the name, or a read stream. Handing back an object of the same
594
+ * shape keeps every one of those call sites working unchanged, which matters:
595
+ * they are spread across the stream route, the subtitle route, the playback
596
+ * planner and the health report, and rewriting all of them to thread a
597
+ * `sourceKey` through would be a large change with nothing to show for it.
598
+ *
599
+ * Only what is actually used is provided. Anything else would be a promise we
600
+ * cannot keep — the real object lives on the other thread and its methods are
601
+ * not reachable from here.
602
+ *
603
+ * @param {{ sourceKey: string, sourceType: "magnet" | "torrent", source: string }} params
604
+ * @returns {Promise<{ infoHash: string, name: string, sourceKey: string, files: object[] }>}
605
+ */
606
+ async getTorrent({ sourceKey, sourceType, source }) {
607
+ const info = await this.addSource({ sourceKey, sourceType, source });
608
+ const client = this;
609
+ return {
610
+ infoHash: info.infoHash,
611
+ name: info.name,
612
+ // Carried so helpers that receive only the torrent can still name it to
613
+ // the worker.
614
+ sourceKey,
615
+ files: info.files.map((file) => ({
616
+ ...file,
617
+ /**
618
+ * @param {{ start?: number, end?: number, windowBytes?: number }} [options]
619
+ * @returns {ReadableStream<Uint8Array>}
620
+ */
621
+ createReadStream(options = {}) {
622
+ // Node stream, not a web one: Fastify replies and the ffmpeg pipe
623
+ // both expect that shape, and every existing call site passes the
624
+ // result straight to one of them. `Readable.fromWeb` adds no copy —
625
+ // it wraps the same buffers.
626
+ return Readable.fromWeb(
627
+ client.createReadStream({
628
+ sourceKey,
629
+ fileIndex: file.index,
630
+ start: options.start ?? null,
631
+ end: options.end ?? null,
632
+ windowBytes: options.windowBytes
633
+ })
634
+ );
635
+ },
636
+
637
+ /**
638
+ * Fragments of shared memory, for a caller that can say when it has
639
+ * finished with each one. `null` when this source has no shared pool.
640
+ *
641
+ * @param {{ start?: number, end?: number, windowBytes?: number }} [options]
642
+ * @returns {ReturnType<TorrentWorkerClient["createFragmentReader"]>}
643
+ */
644
+ createFragmentReader(options = {}) {
645
+ return client.createFragmentReader({
646
+ sourceKey,
647
+ fileIndex: file.index,
648
+ start: options.start ?? null,
649
+ end: options.end ?? null,
650
+ windowBytes: options.windowBytes
651
+ });
652
+ }
653
+ }))
654
+ };
655
+ }
656
+
657
+ /**
658
+ * Shut the torrent client down and stop the thread.
659
+ *
660
+ * @returns {Promise<void>}
661
+ */
662
+ /**
663
+ * What the spilled pieces weigh, as of the last revision. Zero until one has
664
+ * happened, which is what "we have not asked yet" means.
665
+ *
666
+ * @type {number}
667
+ */
668
+ spilledBytes = 0;
669
+
670
+ /**
671
+ * Tell the piece stores on the torrent thread their share of MEMORY.
672
+ *
673
+ * The same owner divides memory and disk, because the two trade: pieces that
674
+ * do not fit in memory are spilled to disk, so what the stores are given here
675
+ * decides how much disk they need there.
676
+ *
677
+ * @param {number} bytes
678
+ * @returns {Promise<{ held: number, wanted: number }>}
679
+ */
680
+ async allowMemoryBytes(bytes) {
681
+ try {
682
+ const claim = await this.#caller.call(Command.MEMORY_ALLOWANCE, { bytes });
683
+ this.memoryClaim = {
684
+ held: Number(claim?.held) || 0,
685
+ wanted: Number(claim?.wanted) || 0
686
+ };
687
+ } catch {
688
+ // The thread is gone or busy; the next revision says it again.
689
+ }
690
+ return this.memoryClaim ?? { held: 0, wanted: 0 };
691
+ }
692
+
693
+ /**
694
+ * Tell the whole files on the torrent thread their share of the disk.
695
+ *
696
+ * Same shape as the spilled pieces, and for the same reason: they hold bytes
697
+ * on this machine and the owner of the disk is on the other thread.
698
+ *
699
+ * @param {number} bytes
700
+ * @returns {Promise<number>} What they hold after it.
701
+ */
702
+ async allowWholeFileBytes(bytes) {
703
+ try {
704
+ this.wholeFileBytes = Number(await this.#caller.call(Command.WHOLE_FILES_ALLOWANCE, { bytes })) || 0;
705
+ } catch {
706
+ // The thread is gone or busy; the next revision says it again.
707
+ }
708
+ return this.wholeFileBytes ?? 0;
709
+ }
710
+
711
+ /**
712
+ * Say how much disk the spilled pieces on this thread may take between them.
713
+ *
714
+ * Best effort and never awaited by anything that matters: a share that does
715
+ * not arrive leaves the ceiling where it was, and the next revision is a
716
+ * minute away.
717
+ *
718
+ * @param {number} bytes
719
+ * @returns {Promise<void>}
720
+ */
721
+ async allowSpillBytes(bytes) {
722
+ try {
723
+ const revised = await this.#caller.call(Command.SPILL_ALLOWANCE, { bytes });
724
+ // The reply says what those stores actually hold, which is what the owner
725
+ // of the disk needs for the next division. One exchange, both directions.
726
+ this.spilledBytes = Array.isArray(revised)
727
+ ? revised.reduce((sum, store) => sum + (Number(store?.bytes) || 0), 0)
728
+ : this.spilledBytes;
729
+ } catch {
730
+ // The thread is gone or busy; the next revision says it again.
731
+ }
732
+ return this.spilledBytes;
733
+ }
734
+
735
+ async destroyAll() {
736
+ this.#stopping = true;
737
+ try {
738
+ await this.#caller.call(Command.DESTROY_ALL, {});
739
+ } catch {
740
+ // Already gone — the wait below settles either way.
741
+ }
742
+ // Let the thread END rather than tearing it down under itself.
743
+ //
744
+ // `terminate()` frees the environment immediately, with the handle
745
+ // callbacks libuv still holds queued. One of those is utp-native's UDP
746
+ // read, and running it against a freed isolate is what the core dump of
747
+ // 2026-08-21 caught: `on_utp_accept` → `napi_get_buffer_info` →
748
+ // `v8::Value::IsArrayBufferView` inside `Environment::CleanupHandles`.
749
+ // Once the client inside is destroyed the thread has nothing left holding
750
+ // its loop open, so it exits by itself and the callbacks drain first.
751
+ //
752
+ // `terminate()` stays as the bounded fallback, because a shutdown that
753
+ // hangs is worse than one that is forced.
754
+ await new Promise((resolve) => {
755
+ const timer = setTimeout(() => {
756
+ logger.warn("torrent-worker: thread did not end in 5s; terminating it");
757
+ void this.#worker.terminate().finally(resolve);
758
+ }, WORKER_EXIT_GRACE_MS);
759
+ this.#worker.once("exit", () => {
760
+ clearTimeout(timer);
761
+ resolve();
762
+ });
763
+ });
764
+ }
765
+ }