@torrent-tv/proxy 2.9.93 → 2.9.95

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,447 +1,448 @@
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 } 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
- /**
27
- * Runs the torrent client on its own thread and exposes it to the main thread.
28
- *
29
- * Why this exists at all: profiling during a live seek found the main thread
30
- * ~85% busy with WebTorrent (buffer concatenation ~15%, wire updates ~9%,
31
- * garbage collection ~5%), while three of four cores idled. Serving a segment
32
- * queued behind that work, so reading a finished 10 MB file took 12-23 s where
33
- * handing it to the channel took 125 ms.
34
- */
35
- export class TorrentWorkerClient {
36
- #worker;
37
- #caller;
38
- /** Receive-side handles for in-flight reads, keyed by request id. */
39
- #reads = new Map();
40
- /** Each torrent's piece pool, so a fragment can be read where it lies. */
41
- #poolBySource = new Map();
42
- /** Which pool an in-flight read belongs to, keyed by request id. */
43
- #poolByRead = new Map();
44
- /** Reads consuming fragments in place, keyed by request id. */
45
- #fragmentReaders = new Map();
46
-
47
- /**
48
- * @param {{ maxDiskBytes?: number, memoryBytes?: number }} [options]
49
- */
50
- constructor({ maxDiskBytes, memoryBytes } = {}) {
51
- this.#worker = new Worker(fileURLToPath(WORKER_URL), {
52
- workerData: { maxDiskBytes, memoryBytes }
53
- });
54
- this.#caller = createCaller(this.#worker);
55
-
56
- this.#worker.on("message", (message) => {
57
- // A failed read must fail its stream. This is checked BEFORE the caller
58
- // sees the message: until 2.9.76 nothing here handled a read error at
59
- // all, so the worker's report was dropped as unknown, and because the
60
- // worker sent the end-of-read marker from its `finally` even when the
61
- // read had thrown, the reader saw a clean end of file instead. A read
62
- // that failed before it produced anything simply hung forever.
63
- if (message?.type === Event.ERROR && this.#reads.has(message.id)) {
64
- const read = this.#reads.get(message.id);
65
- this.#reads.delete(message.id);
66
- read.fail(new Error(message.error ?? "Torrent worker read failed."));
67
- return;
68
- }
69
- if (message?.type === Event.ERROR && this.#fragmentReaders.has(message.id)) {
70
- const reader = this.#fragmentReaders.get(message.id);
71
- this.#fragmentReaders.delete(message.id);
72
- this.#poolByRead.delete(message.id);
73
- reader.fail(new Error(message.error ?? "Torrent worker read failed."));
74
- return;
75
- }
76
- if (this.#caller.handleReply(message)) {
77
- return;
78
- }
79
- switch (message?.type) {
80
- case Event.FRAGMENT: {
81
- const pool = this.#poolByRead.get(message.id);
82
- if (!pool) {
83
- // No pool means no way to read the fragment; confirm it so the
84
- // worker is not left waiting, and let the read end short.
85
- this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
86
- break;
87
- }
88
- const view = new Uint8Array(pool, message.offset, message.length);
89
-
90
- const reader = this.#fragmentReaders.get(message.id);
91
- if (reader) {
92
- // Handed on as a view into the pool — no copy anywhere. The piece
93
- // stays pinned until the consumer says it is done with these exact
94
- // bytes, which for a response body means the socket write has
95
- // completed.
96
- reader.push(view, () => {
97
- this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
98
- });
99
- break;
100
- }
101
-
102
- // Plain-stream consumers keep what they are given while the slot may
103
- // be reused, so they get a copy and the piece is released at once.
104
- this.#reads.get(message.id)?.push(Uint8Array.prototype.slice.call(view));
105
- this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
106
- break;
107
- }
108
- case Event.CHUNK: {
109
- const bytes = message.bytes;
110
- this.#reads.get(message.id)?.push(
111
- new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length)
112
- );
113
- break;
114
- }
115
- case Event.READ_END:
116
- this.#reads.get(message.id)?.close();
117
- this.#reads.delete(message.id);
118
- this.#fragmentReaders.get(message.id)?.close();
119
- this.#fragmentReaders.delete(message.id);
120
- this.#poolByRead.delete(message.id);
121
- break;
122
- case Event.LOG:
123
- logger.info(`torrent-worker: ${message.message}`);
124
- break;
125
- default:
126
- break;
127
- }
128
- });
129
-
130
- this.#worker.on("error", (error) => {
131
- logger.error(`torrent-worker crashed: ${error?.message ?? error}`);
132
- // Fail everything outstanding rather than leaving callers hanging: a dead
133
- // worker will never answer, and a stalled request is worse than an error
134
- // the loading flow can retry.
135
- const reason = new Error("Torrent worker stopped unexpectedly.");
136
- this.#caller.rejectAll(reason);
137
- for (const [, read] of this.#reads) {
138
- read.fail(reason);
139
- }
140
- this.#reads.clear();
141
- });
142
- }
143
-
144
- /**
145
- * Add (or join) a torrent and register it under `sourceKey`.
146
- *
147
- * @param {{ sourceKey: string, sourceType: "magnet" | "torrent", source: string }} params
148
- * @returns {Promise<{ infoHash: string, name: string, files: { index: number, name: string, path: string, length: number }[] }>}
149
- */
150
- async addSource({ sourceKey, sourceType, source }) {
151
- return this.#caller.call(Command.ADD_SOURCE, { sourceKey, sourceType, source });
152
- }
153
-
154
- /**
155
- * The torrent's files, as plain data.
156
- *
157
- * @param {string} sourceKey
158
- * @returns {Promise<{ index: number, name: string, path: string, length: number }[]>}
159
- */
160
- async listFiles(sourceKey) {
161
- return this.#caller.call(Command.LIST_FILES, { sourceKey });
162
- }
163
-
164
- /**
165
- * Claim a file so it is not evicted while being read.
166
- *
167
- * @param {string} sourceKey
168
- * @param {number} fileIndex
169
- * @returns {Promise<string>} The claim's identity, for {@link releaseFile}.
170
- */
171
- async acquireFile(sourceKey, fileIndex) {
172
- return this.#caller.call(Command.ACQUIRE_FILE, { sourceKey, fileIndex });
173
- }
174
-
175
- /**
176
- * Drop one claim taken with {@link acquireFile}.
177
- *
178
- * Named by claim rather than by file: several readers hold the same file at
179
- * once, and releasing "the file" released somebody else's hold.
180
- *
181
- * @param {string} claimId
182
- * @returns {Promise<void>}
183
- */
184
- async releaseFile(claimId) {
185
- await this.#caller.call(Command.RELEASE_FILE, { claimId });
186
- }
187
-
188
- /**
189
- * Live download figures for the progress display.
190
- *
191
- * @param {{ sourceKey: string, fileIndex: number, resumeAnchorByteStart?: number | null }} params
192
- * @returns {Promise<object>}
193
- */
194
- async getFileStats({ sourceKey, fileIndex, resumeAnchorByteStart = null }) {
195
- return this.#caller.call(Command.FILE_STATS, { sourceKey, fileIndex, resumeAnchorByteStart });
196
- }
197
-
198
- /**
199
- * Reorder piece selection around a read position (seek prioritisation).
200
- *
201
- * @param {{ sourceKey: string, fileIndex: number, byteStart: number, windowBytes?: number, wholeFileRead?: boolean }} params
202
- * @returns {Promise<void>}
203
- */
204
- async prioritizeByteRange({ sourceKey, fileIndex, byteStart, windowBytes, wholeFileRead }) {
205
- await this.#caller.call(Command.PRIORITIZE, {
206
- sourceKey,
207
- fileIndex,
208
- byteStart,
209
- windowBytes,
210
- wholeFileRead
211
- });
212
- }
213
-
214
- /**
215
- * Pre-fetch the head and tail the codec probe needs.
216
- *
217
- * @param {{ sourceKey: string, fileIndex: number, options?: { headBytes?: number, tailBytes?: number, timeoutMs?: number } }} params
218
- * @returns {Promise<unknown>}
219
- */
220
- async prefetchFileEdges({ sourceKey, fileIndex, options = {} }) {
221
- return this.#caller.call(Command.PREFETCH_EDGES, { sourceKey, fileIndex, options });
222
- }
223
-
224
- /**
225
- * Read a byte range as a stream.
226
- *
227
- * Returns immediately with a stream that fills as chunks arrive; cancelling it
228
- * (viewer gone, seek superseded) stops the worker reading, so pieces are not
229
- * fetched for a stream nobody will drain.
230
- *
231
- * @param {{ sourceKey: string, fileIndex: number, start?: number | null, end?: number | null }} params
232
- * @returns {ReadableStream<Uint8Array>}
233
- */
234
- createReadStream({ sourceKey, fileIndex, start = null, end = null }) {
235
- // Same id sequence as commands — see `nextId` in `channel.js`.
236
- const readId = this.#caller.nextId();
237
- const receive = createReceiveStream({
238
- port: this.#worker,
239
- requestId: readId,
240
- onCancel: () => {
241
- void this.#caller.call(Command.CANCEL_READ, { readId }).catch(() => undefined);
242
- this.#reads.delete(readId);
243
- this.#poolByRead.delete(readId);
244
- }
245
- });
246
- this.#reads.set(readId, receive);
247
- // Which pool this read's fragments will point into. Recorded before the
248
- // command is sent, because the first fragment can arrive immediately.
249
- const pool = this.#poolBySource.get(sourceKey);
250
- if (pool) {
251
- this.#poolByRead.set(readId, pool);
252
- }
253
-
254
- // The worker replies to READ_RANGE only once the body is fully sent; a
255
- // failure before that must surface on the stream, not vanish.
256
- this.#worker.postMessage({
257
- command: Command.READ_RANGE,
258
- id: readId,
259
- params: { sourceKey, fileIndex, start, end }
260
- });
261
-
262
- return receive.stream;
263
- }
264
-
265
- /**
266
- * Read a byte range as fragments of shared memory, without copying.
267
- *
268
- * Each fragment is a view straight into the torrent's piece pool, and the
269
- * piece behind it stays pinned until `release()` is called — so the consumer
270
- * must call it once it is genuinely finished with those bytes. For a response
271
- * body that means after the socket write has completed, not when it was
272
- * queued: verified that writing a shared-memory view and then overwriting the
273
- * pool from the write callback leaves the client's copy intact, and that
274
- * overwriting it earlier corrupts it silently.
275
- *
276
- * Returns `null` when this source has no shared pool, so the caller can fall
277
- * back to {@link createReadStream}.
278
- *
279
- * @param {{ sourceKey: string, fileIndex: number, start?: number | null, end?: number | null }} params
280
- * @returns {{ [Symbol.asyncIterator]: () => AsyncGenerator<{ bytes: Uint8Array, release: () => void }>, cancel: () => void } | null}
281
- */
282
- createFragmentReader({ sourceKey, fileIndex, start = null, end = null }) {
283
- const pool = this.#poolBySource.get(sourceKey);
284
- if (!pool) {
285
- return null;
286
- }
287
-
288
- const readId = this.#caller.nextId();
289
- /** @type {{ bytes: Uint8Array, release: () => void }[]} */
290
- const queue = [];
291
- let wake = null;
292
- let finished = false;
293
- let failure = null;
294
-
295
- const notify = () => {
296
- const resume = wake;
297
- wake = null;
298
- resume?.();
299
- };
300
-
301
- this.#fragmentReaders.set(readId, {
302
- push(bytes, confirm) {
303
- queue.push({ bytes, release: confirm });
304
- notify();
305
- },
306
- close() {
307
- finished = true;
308
- notify();
309
- },
310
- fail(error) {
311
- failure = error;
312
- finished = true;
313
- notify();
314
- }
315
- });
316
- this.#poolByRead.set(readId, pool);
317
-
318
- const cancel = () => {
319
- if (this.#fragmentReaders.delete(readId)) {
320
- this.#poolByRead.delete(readId);
321
- void this.#caller.call(Command.CANCEL_READ, { readId }).catch(() => undefined);
322
- }
323
- finished = true;
324
- notify();
325
- };
326
-
327
- this.#worker.postMessage({
328
- command: Command.READ_RANGE,
329
- id: readId,
330
- params: { sourceKey, fileIndex, start, end }
331
- });
332
-
333
- return {
334
- cancel,
335
- async *[Symbol.asyncIterator]() {
336
- try {
337
- for (;;) {
338
- while (queue.length > 0) {
339
- yield queue.shift();
340
- }
341
- if (failure) {
342
- throw failure;
343
- }
344
- if (finished) {
345
- return;
346
- }
347
- await new Promise((resolve) => {
348
- wake = resolve;
349
- });
350
- }
351
- } finally {
352
- // Covers the consumer breaking out early — a client that hung up, a
353
- // superseded seek — which must stop the read rather than leave it
354
- // fetching pieces nobody will take.
355
- if (!finished) {
356
- cancel();
357
- }
358
- }
359
- }
360
- };
361
- }
362
-
363
- /**
364
- * A stand-in for the WebTorrent torrent object, backed by the worker.
365
- *
366
- * Callers already hold a torrent and reach into `torrent.files[i]` — for the
367
- * length, the name, or a read stream. Handing back an object of the same
368
- * shape keeps every one of those call sites working unchanged, which matters:
369
- * they are spread across the stream route, the subtitle route, the playback
370
- * planner and the health report, and rewriting all of them to thread a
371
- * `sourceKey` through would be a large change with nothing to show for it.
372
- *
373
- * Only what is actually used is provided. Anything else would be a promise we
374
- * cannot keep — the real object lives on the other thread and its methods are
375
- * not reachable from here.
376
- *
377
- * @param {{ sourceKey: string, sourceType: "magnet" | "torrent", source: string }} params
378
- * @returns {Promise<{ infoHash: string, name: string, sourceKey: string, files: object[] }>}
379
- */
380
- async getTorrent({ sourceKey, sourceType, source }) {
381
- const info = await this.addSource({ sourceKey, sourceType, source });
382
- // The torrent's piece pool. Both threads now hold the same memory, so a
383
- // read can be answered with an offset instead of with bytes.
384
- if (info.sharedBuffer) {
385
- this.#poolBySource.set(sourceKey, info.sharedBuffer);
386
- }
387
- const client = this;
388
- return {
389
- infoHash: info.infoHash,
390
- name: info.name,
391
- // Carried so helpers that receive only the torrent can still name it to
392
- // the worker.
393
- sourceKey,
394
- files: info.files.map((file) => ({
395
- ...file,
396
- /**
397
- * @param {{ start?: number, end?: number }} [options]
398
- * @returns {ReadableStream<Uint8Array>}
399
- */
400
- createReadStream(options = {}) {
401
- // Node stream, not a web one: Fastify replies and the ffmpeg pipe
402
- // both expect that shape, and every existing call site passes the
403
- // result straight to one of them. `Readable.fromWeb` adds no copy —
404
- // it wraps the same buffers.
405
- return Readable.fromWeb(
406
- client.createReadStream({
407
- sourceKey,
408
- fileIndex: file.index,
409
- start: options.start ?? null,
410
- end: options.end ?? null
411
- })
412
- );
413
- },
414
-
415
- /**
416
- * Fragments of shared memory, for a caller that can say when it has
417
- * finished with each one. `null` when this source has no shared pool.
418
- *
419
- * @param {{ start?: number, end?: number }} [options]
420
- * @returns {ReturnType<TorrentWorkerClient["createFragmentReader"]>}
421
- */
422
- createFragmentReader(options = {}) {
423
- return client.createFragmentReader({
424
- sourceKey,
425
- fileIndex: file.index,
426
- start: options.start ?? null,
427
- end: options.end ?? null
428
- });
429
- }
430
- }))
431
- };
432
- }
433
-
434
- /**
435
- * Shut the torrent client down and stop the thread.
436
- *
437
- * @returns {Promise<void>}
438
- */
439
- async destroyAll() {
440
- try {
441
- await this.#caller.call(Command.DESTROY_ALL, {});
442
- } catch {
443
- // Already gone — termination below is what matters.
444
- }
445
- await this.#worker.terminate();
446
- }
447
- }
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 } 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
+ /**
27
+ * Runs the torrent client on its own thread and exposes it to the main thread.
28
+ *
29
+ * Why this exists at all: profiling during a live seek found the main thread
30
+ * ~85% busy with WebTorrent (buffer concatenation ~15%, wire updates ~9%,
31
+ * garbage collection ~5%), while three of four cores idled. Serving a segment
32
+ * queued behind that work, so reading a finished 10 MB file took 12-23 s where
33
+ * handing it to the channel took 125 ms.
34
+ */
35
+ export class TorrentWorkerClient {
36
+ #worker;
37
+ #caller;
38
+ /** Receive-side handles for in-flight reads, keyed by request id. */
39
+ #reads = new Map();
40
+ /** Each torrent's piece pool, so a fragment can be read where it lies. */
41
+ #poolBySource = new Map();
42
+ /** Which pool an in-flight read belongs to, keyed by request id. */
43
+ #poolByRead = new Map();
44
+ /** Reads consuming fragments in place, keyed by request id. */
45
+ #fragmentReaders = new Map();
46
+
47
+ /**
48
+ * @param {{ maxDiskBytes?: number, memoryBytes?: number }} [options]
49
+ */
50
+ constructor({ maxDiskBytes, memoryBytes } = {}) {
51
+ this.#worker = new Worker(fileURLToPath(WORKER_URL), {
52
+ workerData: { maxDiskBytes, memoryBytes }
53
+ });
54
+ this.#caller = createCaller(this.#worker);
55
+
56
+ this.#worker.on("message", (message) => {
57
+ // A failed read must fail its stream. This is checked BEFORE the caller
58
+ // sees the message: until 2.9.76 nothing here handled a read error at
59
+ // all, so the worker's report was dropped as unknown, and because the
60
+ // worker sent the end-of-read marker from its `finally` even when the
61
+ // read had thrown, the reader saw a clean end of file instead. A read
62
+ // that failed before it produced anything simply hung forever.
63
+ if (message?.type === Event.ERROR && this.#reads.has(message.id)) {
64
+ const read = this.#reads.get(message.id);
65
+ this.#reads.delete(message.id);
66
+ read.fail(new Error(message.error ?? "Torrent worker read failed."));
67
+ return;
68
+ }
69
+ if (message?.type === Event.ERROR && this.#fragmentReaders.has(message.id)) {
70
+ const reader = this.#fragmentReaders.get(message.id);
71
+ this.#fragmentReaders.delete(message.id);
72
+ this.#poolByRead.delete(message.id);
73
+ reader.fail(new Error(message.error ?? "Torrent worker read failed."));
74
+ return;
75
+ }
76
+ if (this.#caller.handleReply(message)) {
77
+ return;
78
+ }
79
+ switch (message?.type) {
80
+ case Event.FRAGMENT: {
81
+ const pool = this.#poolByRead.get(message.id);
82
+ if (!pool) {
83
+ // No pool means no way to read the fragment; confirm it so the
84
+ // worker is not left waiting, and let the read end short.
85
+ this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
86
+ break;
87
+ }
88
+ const view = new Uint8Array(pool, message.offset, message.length);
89
+
90
+ const reader = this.#fragmentReaders.get(message.id);
91
+ if (reader) {
92
+ // Handed on as a view into the pool — no copy anywhere. The piece
93
+ // stays pinned until the consumer says it is done with these exact
94
+ // bytes, which for a response body means the socket write has
95
+ // completed.
96
+ reader.push(view, () => {
97
+ this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
98
+ });
99
+ break;
100
+ }
101
+
102
+ // Plain-stream consumers keep what they are given while the slot may
103
+ // be reused, so they get a copy and the piece is released at once.
104
+ this.#reads.get(message.id)?.push(Uint8Array.prototype.slice.call(view));
105
+ this.#worker.postMessage({ type: Event.FRAGMENT_DONE, id: message.id });
106
+ break;
107
+ }
108
+ case Event.CHUNK: {
109
+ const bytes = message.bytes;
110
+ this.#reads.get(message.id)?.push(
111
+ new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length)
112
+ );
113
+ break;
114
+ }
115
+ case Event.READ_END:
116
+ this.#reads.get(message.id)?.close();
117
+ this.#reads.delete(message.id);
118
+ this.#fragmentReaders.get(message.id)?.close();
119
+ this.#fragmentReaders.delete(message.id);
120
+ this.#poolByRead.delete(message.id);
121
+ break;
122
+ case Event.LOG:
123
+ logger.info(`torrent-worker: ${message.message}`);
124
+ break;
125
+ default:
126
+ break;
127
+ }
128
+ });
129
+
130
+ this.#worker.on("error", (error) => {
131
+ logger.error(`torrent-worker crashed: ${error?.message ?? error}`);
132
+ // Fail everything outstanding rather than leaving callers hanging: a dead
133
+ // worker will never answer, and a stalled request is worse than an error
134
+ // the loading flow can retry.
135
+ const reason = new Error("Torrent worker stopped unexpectedly.");
136
+ this.#caller.rejectAll(reason);
137
+ for (const [, read] of this.#reads) {
138
+ read.fail(reason);
139
+ }
140
+ this.#reads.clear();
141
+ });
142
+ }
143
+
144
+ /**
145
+ * Add (or join) a torrent and register it under `sourceKey`.
146
+ *
147
+ * @param {{ sourceKey: string, sourceType: "magnet" | "torrent", source: string }} params
148
+ * @returns {Promise<{ infoHash: string, name: string, files: { index: number, name: string, path: string, length: number }[] }>}
149
+ */
150
+ async addSource({ sourceKey, sourceType, source }) {
151
+ return this.#caller.call(Command.ADD_SOURCE, { sourceKey, sourceType, source });
152
+ }
153
+
154
+ /**
155
+ * The torrent's files, as plain data.
156
+ *
157
+ * @param {string} sourceKey
158
+ * @returns {Promise<{ index: number, name: string, path: string, length: number }[]>}
159
+ */
160
+ async listFiles(sourceKey) {
161
+ return this.#caller.call(Command.LIST_FILES, { sourceKey });
162
+ }
163
+
164
+ /**
165
+ * Claim a file so it is not evicted while being read.
166
+ *
167
+ * @param {string} sourceKey
168
+ * @param {number} fileIndex
169
+ * @returns {Promise<string>} The claim's identity, for {@link releaseFile}.
170
+ */
171
+ async acquireFile(sourceKey, fileIndex) {
172
+ return this.#caller.call(Command.ACQUIRE_FILE, { sourceKey, fileIndex });
173
+ }
174
+
175
+ /**
176
+ * Drop one claim taken with {@link acquireFile}.
177
+ *
178
+ * Named by claim rather than by file: several readers hold the same file at
179
+ * once, and releasing "the file" released somebody else's hold.
180
+ *
181
+ * @param {string} claimId
182
+ * @returns {Promise<void>}
183
+ */
184
+ async releaseFile(claimId) {
185
+ await this.#caller.call(Command.RELEASE_FILE, { claimId });
186
+ }
187
+
188
+ /**
189
+ * Live download figures for the progress display.
190
+ *
191
+ * @param {{ sourceKey: string, fileIndex: number, resumeAnchorByteStart?: number | null }} params
192
+ * @returns {Promise<object>}
193
+ */
194
+ async getFileStats({ sourceKey, fileIndex, resumeAnchorByteStart = null }) {
195
+ return this.#caller.call(Command.FILE_STATS, { sourceKey, fileIndex, resumeAnchorByteStart });
196
+ }
197
+
198
+ /**
199
+ * Reorder piece selection around a read position (seek prioritisation).
200
+ *
201
+ * @param {{ sourceKey: string, fileIndex: number, byteStart: number, windowBytes?: number, wholeFileRead?: boolean }} params
202
+ * @returns {Promise<void>}
203
+ */
204
+ async prioritizeByteRange({ sourceKey, fileIndex, byteStart, windowBytes, wholeFileRead }) {
205
+ await this.#caller.call(Command.PRIORITIZE, {
206
+ sourceKey,
207
+ fileIndex,
208
+ byteStart,
209
+ windowBytes,
210
+ wholeFileRead
211
+ });
212
+ }
213
+
214
+ /**
215
+ * Pre-fetch the head and tail the codec probe needs.
216
+ *
217
+ * @param {{ sourceKey: string, fileIndex: number, options?: { headBytes?: number, tailBytes?: number, timeoutMs?: number } }} params
218
+ * @returns {Promise<unknown>}
219
+ */
220
+ async prefetchFileEdges({ sourceKey, fileIndex, options = {} }) {
221
+ return this.#caller.call(Command.PREFETCH_EDGES, { sourceKey, fileIndex, options });
222
+ }
223
+
224
+ /**
225
+ * Read a byte range as a stream.
226
+ *
227
+ * Returns immediately with a stream that fills as chunks arrive; cancelling it
228
+ * (viewer gone, seek superseded) stops the worker reading, so pieces are not
229
+ * fetched for a stream nobody will drain.
230
+ *
231
+ * @param {{ sourceKey: string, fileIndex: number, start?: number | null, end?: number | null, windowBytes?: number }} params
232
+ * @returns {ReadableStream<Uint8Array>}
233
+ */
234
+ createReadStream({ sourceKey, fileIndex, start = null, end = null }) {
235
+ // Same id sequence as commands — see `nextId` in `channel.js`.
236
+ const readId = this.#caller.nextId();
237
+ const receive = createReceiveStream({
238
+ port: this.#worker,
239
+ requestId: readId,
240
+ onCancel: () => {
241
+ void this.#caller.call(Command.CANCEL_READ, { readId }).catch(() => undefined);
242
+ this.#reads.delete(readId);
243
+ this.#poolByRead.delete(readId);
244
+ }
245
+ });
246
+ this.#reads.set(readId, receive);
247
+ // Which pool this read's fragments will point into. Recorded before the
248
+ // command is sent, because the first fragment can arrive immediately.
249
+ const pool = this.#poolBySource.get(sourceKey);
250
+ if (pool) {
251
+ this.#poolByRead.set(readId, pool);
252
+ }
253
+
254
+ // The worker replies to READ_RANGE only once the body is fully sent; a
255
+ // failure before that must surface on the stream, not vanish.
256
+ this.#worker.postMessage({
257
+ command: Command.READ_RANGE,
258
+ id: readId,
259
+ params: { sourceKey, fileIndex, start, end, windowBytes }
260
+ });
261
+
262
+ return receive.stream;
263
+ }
264
+
265
+ /**
266
+ * Read a byte range as fragments of shared memory, without copying.
267
+ *
268
+ * Each fragment is a view straight into the torrent's piece pool, and the
269
+ * piece behind it stays pinned until `release()` is called — so the consumer
270
+ * must call it once it is genuinely finished with those bytes. For a response
271
+ * body that means after the socket write has completed, not when it was
272
+ * queued: verified that writing a shared-memory view and then overwriting the
273
+ * pool from the write callback leaves the client's copy intact, and that
274
+ * overwriting it earlier corrupts it silently.
275
+ *
276
+ * Returns `null` when this source has no shared pool, so the caller can fall
277
+ * back to {@link createReadStream}.
278
+ *
279
+ * @param {{ sourceKey: string, fileIndex: number, start?: number | null, end?: number | null, windowBytes?: number }} params
280
+ * @returns {{ [Symbol.asyncIterator]: () => AsyncGenerator<{ bytes: Uint8Array, release: () => void }>, cancel: () => void } | null}
281
+ */
282
+ createFragmentReader({ sourceKey, fileIndex, start = null, end = null, windowBytes }) {
283
+ const pool = this.#poolBySource.get(sourceKey);
284
+ if (!pool) {
285
+ return null;
286
+ }
287
+
288
+ const readId = this.#caller.nextId();
289
+ /** @type {{ bytes: Uint8Array, release: () => void }[]} */
290
+ const queue = [];
291
+ let wake = null;
292
+ let finished = false;
293
+ let failure = null;
294
+
295
+ const notify = () => {
296
+ const resume = wake;
297
+ wake = null;
298
+ resume?.();
299
+ };
300
+
301
+ this.#fragmentReaders.set(readId, {
302
+ push(bytes, confirm) {
303
+ queue.push({ bytes, release: confirm });
304
+ notify();
305
+ },
306
+ close() {
307
+ finished = true;
308
+ notify();
309
+ },
310
+ fail(error) {
311
+ failure = error;
312
+ finished = true;
313
+ notify();
314
+ }
315
+ });
316
+ this.#poolByRead.set(readId, pool);
317
+
318
+ const cancel = () => {
319
+ if (this.#fragmentReaders.delete(readId)) {
320
+ this.#poolByRead.delete(readId);
321
+ void this.#caller.call(Command.CANCEL_READ, { readId }).catch(() => undefined);
322
+ }
323
+ finished = true;
324
+ notify();
325
+ };
326
+
327
+ this.#worker.postMessage({
328
+ command: Command.READ_RANGE,
329
+ id: readId,
330
+ params: { sourceKey, fileIndex, start, end, windowBytes }
331
+ });
332
+
333
+ return {
334
+ cancel,
335
+ async *[Symbol.asyncIterator]() {
336
+ try {
337
+ for (;;) {
338
+ while (queue.length > 0) {
339
+ yield queue.shift();
340
+ }
341
+ if (failure) {
342
+ throw failure;
343
+ }
344
+ if (finished) {
345
+ return;
346
+ }
347
+ await new Promise((resolve) => {
348
+ wake = resolve;
349
+ });
350
+ }
351
+ } finally {
352
+ // Covers the consumer breaking out early — a client that hung up, a
353
+ // superseded seek — which must stop the read rather than leave it
354
+ // fetching pieces nobody will take.
355
+ if (!finished) {
356
+ cancel();
357
+ }
358
+ }
359
+ }
360
+ };
361
+ }
362
+
363
+ /**
364
+ * A stand-in for the WebTorrent torrent object, backed by the worker.
365
+ *
366
+ * Callers already hold a torrent and reach into `torrent.files[i]` — for the
367
+ * length, the name, or a read stream. Handing back an object of the same
368
+ * shape keeps every one of those call sites working unchanged, which matters:
369
+ * they are spread across the stream route, the subtitle route, the playback
370
+ * planner and the health report, and rewriting all of them to thread a
371
+ * `sourceKey` through would be a large change with nothing to show for it.
372
+ *
373
+ * Only what is actually used is provided. Anything else would be a promise we
374
+ * cannot keep — the real object lives on the other thread and its methods are
375
+ * not reachable from here.
376
+ *
377
+ * @param {{ sourceKey: string, sourceType: "magnet" | "torrent", source: string }} params
378
+ * @returns {Promise<{ infoHash: string, name: string, sourceKey: string, files: object[] }>}
379
+ */
380
+ async getTorrent({ sourceKey, sourceType, source }) {
381
+ const info = await this.addSource({ sourceKey, sourceType, source });
382
+ // The torrent's piece pool. Both threads now hold the same memory, so a
383
+ // read can be answered with an offset instead of with bytes.
384
+ if (info.sharedBuffer) {
385
+ this.#poolBySource.set(sourceKey, info.sharedBuffer);
386
+ }
387
+ const client = this;
388
+ return {
389
+ infoHash: info.infoHash,
390
+ name: info.name,
391
+ // Carried so helpers that receive only the torrent can still name it to
392
+ // the worker.
393
+ sourceKey,
394
+ files: info.files.map((file) => ({
395
+ ...file,
396
+ /**
397
+ * @param {{ start?: number, end?: number, windowBytes?: number }} [options]
398
+ * @returns {ReadableStream<Uint8Array>}
399
+ */
400
+ createReadStream(options = {}) {
401
+ // Node stream, not a web one: Fastify replies and the ffmpeg pipe
402
+ // both expect that shape, and every existing call site passes the
403
+ // result straight to one of them. `Readable.fromWeb` adds no copy —
404
+ // it wraps the same buffers.
405
+ return Readable.fromWeb(
406
+ client.createReadStream({
407
+ sourceKey,
408
+ fileIndex: file.index,
409
+ start: options.start ?? null,
410
+ end: options.end ?? null
411
+ })
412
+ );
413
+ },
414
+
415
+ /**
416
+ * Fragments of shared memory, for a caller that can say when it has
417
+ * finished with each one. `null` when this source has no shared pool.
418
+ *
419
+ * @param {{ start?: number, end?: number, windowBytes?: number }} [options]
420
+ * @returns {ReturnType<TorrentWorkerClient["createFragmentReader"]>}
421
+ */
422
+ createFragmentReader(options = {}) {
423
+ return client.createFragmentReader({
424
+ sourceKey,
425
+ fileIndex: file.index,
426
+ start: options.start ?? null,
427
+ end: options.end ?? null,
428
+ windowBytes: options.windowBytes
429
+ });
430
+ }
431
+ }))
432
+ };
433
+ }
434
+
435
+ /**
436
+ * Shut the torrent client down and stop the thread.
437
+ *
438
+ * @returns {Promise<void>}
439
+ */
440
+ async destroyAll() {
441
+ try {
442
+ await this.#caller.call(Command.DESTROY_ALL, {});
443
+ } catch {
444
+ // Already gone — termination below is what matters.
445
+ }
446
+ await this.#worker.terminate();
447
+ }
448
+ }