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