@torrent-tv/proxy 2.83.0 → 2.83.2
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 +41 -0
- package/package.json +1 -1
- package/routes/api/sources/stats/get.js +11 -2
- package/routes/stream/get.js +74 -3
- package/services/delivery-probe.js +248 -43
- package/services/download/SwarmSelection.js +5 -5
- package/services/download/registry.js +20 -0
- package/services/encode/EncodeRun.js +1 -0
- package/services/encode/encode-exit.js +17 -0
- package/services/files/CompletedFiles.js +276 -0
- package/services/files/piece-from-whole-file.js +118 -0
- package/services/output/cut-grid.js +13 -3
- package/services/piece-store/piece-disk-store.js +72 -2
- package/services/piece-store/shared-piece-store.js +274 -27
- package/services/torrent-pool.js +259 -19
- package/services/torrent-worker/client.js +21 -0
- package/services/torrent-worker/protocol.js +9 -1
- package/services/torrent-worker/worker.js +183 -2
- package/test/completed-files.test.js +115 -0
- package/test/cuts-follow-published-grid.test.js +35 -0
- package/test/delivery-probe.test.js +114 -1
- package/test/encode-exit.test.js +18 -0
- package/test/piece-disk-store.test.js +26 -0
- package/test/piece-from-whole-file.test.js +129 -0
- package/test/piece-store-eviction.test.js +28 -15
- package/test/piece-store-never-refuses.test.js +153 -0
- package/test/piece-store-reservations.test.js +16 -3
- package/test/probe-wedge-certainty.test.js +3 -3
- package/test/shared-piece-store.test.js +27 -13
- package/test/stream-route.test.js +41 -0
- package/test/swarm-follows-readers.test.js +168 -0
- package/test/swarm-reach.test.js +5 -0
- package/test/upload-hurry.test.js +27 -0
package/services/torrent-pool.js
CHANGED
|
@@ -17,7 +17,7 @@ import WebTorrent from "webtorrent";
|
|
|
17
17
|
import { logger } from "../utils/logger.js";
|
|
18
18
|
import { SharedPieceStore, findSharedStore } from "./piece-store/shared-piece-store.js";
|
|
19
19
|
import { Urgency, urgencyName } from "./demand/index.js";
|
|
20
|
-
import { demandFor, forgetTorrent, reconcileAll } from "./download/registry.js";
|
|
20
|
+
import { demandFor, forgetTorrent, reconcileAll, hasUnmetDemand } from "./download/registry.js";
|
|
21
21
|
import { isAtAWatchingViewer, isBehindEverybody, isNobodyComingNow } from "./priority/PriorityMap.js";
|
|
22
22
|
import { deriveSourceKey } from "./torrent-source-key.js";
|
|
23
23
|
|
|
@@ -164,10 +164,19 @@ const STALL_REPORT_INTERVAL_MS = 30_000;
|
|
|
164
164
|
* makes every two seconds.
|
|
165
165
|
*
|
|
166
166
|
* @param {import("webtorrent").Torrent} torrent
|
|
167
|
-
* @returns {{ connectedPeers: number,
|
|
167
|
+
* @returns {{ connectedPeers: number, deliveringPeers: number, knownPeers: number | null,
|
|
168
|
+
* queuedPeers: number | null }}
|
|
168
169
|
*/
|
|
169
170
|
export function describeSwarmReach(torrent) {
|
|
170
171
|
const wires = Array.isArray(torrent?.wires) ? torrent.wires.length : 0;
|
|
172
|
+
// HOW MANY OF THEM ARE DOING ANYTHING. Connections accumulated without bound
|
|
173
|
+
// in the field — 249 to 596 over one viewing, 15 862 more queued — and
|
|
174
|
+
// whether that helped or merely cost memory and requests is not answerable
|
|
175
|
+
// from a count of wires. A wire that has delivered a byte is the measured
|
|
176
|
+
// unit; the rest are held open for nothing.
|
|
177
|
+
const delivering = Array.isArray(torrent?.wires)
|
|
178
|
+
? torrent.wires.filter((wire) => Number(wire?.downloaded) > 0).length
|
|
179
|
+
: 0;
|
|
171
180
|
const read = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
|
|
172
181
|
let knownPeers = null;
|
|
173
182
|
let queuedPeers = null;
|
|
@@ -179,7 +188,7 @@ export function describeSwarmReach(torrent) {
|
|
|
179
188
|
// destroyed torrent, and the reading is a diagnostic. Nothing here is
|
|
180
189
|
// worth failing a stats poll for.
|
|
181
190
|
}
|
|
182
|
-
return { connectedPeers: wires, knownPeers, queuedPeers };
|
|
191
|
+
return { connectedPeers: wires, deliveringPeers: delivering, knownPeers, queuedPeers };
|
|
183
192
|
}
|
|
184
193
|
|
|
185
194
|
/**
|
|
@@ -345,6 +354,11 @@ export function torrentsForUploadPolicy(torrents, usageByTorrent, now) {
|
|
|
345
354
|
// Recorded so the policy can tell "nothing is arriving and somebody is
|
|
346
355
|
// waiting" from "nothing is arriving because nobody asked".
|
|
347
356
|
torrent.hasActiveReader = hasReader;
|
|
357
|
+
// Whether anybody is still short of bytes of it. Upload is bought with
|
|
358
|
+
// reciprocity and reciprocity is only worth buying while something is
|
|
359
|
+
// missing; a torrent whose declared windows are all present wants nothing
|
|
360
|
+
// from the swarm, and what it gives it gives for nobody.
|
|
361
|
+
torrent.hasUnmetDemand = hasUnmetDemand(torrent);
|
|
348
362
|
chosen.push(torrent);
|
|
349
363
|
}
|
|
350
364
|
}
|
|
@@ -390,7 +404,8 @@ export function decideUploadLimit(activeTorrents, opts = {}) {
|
|
|
390
404
|
// 2026-08-04: four cycles of 512 -> 50 KB/s in three minutes, each
|
|
391
405
|
// reported as `earn unchoke ... down=0KB/s`, all of them raising the
|
|
392
406
|
// upload at moments when no byte was wanted by anyone.
|
|
393
|
-
const starving = notDone && torrent?.hasActiveReader !== false
|
|
407
|
+
const starving = notDone && torrent?.hasActiveReader !== false
|
|
408
|
+
&& torrent?.hasUnmetDemand !== false && downloadSpeed < starvingSpeed;
|
|
394
409
|
if (starving && chokedInterested >= chokedThreshold) {
|
|
395
410
|
const name = typeof torrent?.name === "string" ? torrent.name : "?";
|
|
396
411
|
return {
|
|
@@ -402,6 +417,14 @@ export function decideUploadLimit(activeTorrents, opts = {}) {
|
|
|
402
417
|
}
|
|
403
418
|
}
|
|
404
419
|
|
|
420
|
+
// NOTHING TO BUY. Every torrent here has a reader, and not one of them is
|
|
421
|
+
// short of a byte anybody asked for: the upload would be given for nobody.
|
|
422
|
+
// Field 2026-09-11 — 512 KB/s held for forty-eight minutes on a file that was
|
|
423
|
+
// complete, 596 peers connected and climbing, and every 16 KB served read a
|
|
424
|
+
// 4 MB piece back off the disk.
|
|
425
|
+
if (activeTorrents.every((torrent) => torrent?.hasUnmetDemand === false)) {
|
|
426
|
+
return { bytesPerSec: idleFloor, reason: "nothing anybody asked for is missing — upload buys nothing" };
|
|
427
|
+
}
|
|
405
428
|
return { bytesPerSec: floor, reason: "active readers, not choke-starved" };
|
|
406
429
|
}
|
|
407
430
|
|
|
@@ -783,6 +806,52 @@ export class TorrentPool {
|
|
|
783
806
|
* default is computed from free disk (min(10 GB, half free)). Pass 0 to
|
|
784
807
|
* disable the cap.
|
|
785
808
|
*/
|
|
809
|
+
/**
|
|
810
|
+
* Sources every file of which this proxy holds whole.
|
|
811
|
+
*
|
|
812
|
+
* A torrent added again for one of these has nothing to fetch and nothing to
|
|
813
|
+
* check: what it would verify was written out of pieces this client had
|
|
814
|
+
* already hashed, and the file's size was checked against what the torrent
|
|
815
|
+
* says. So it is added with verification skipped — otherwise a viewer
|
|
816
|
+
* returning to a film waits for a gigabyte and a half to be hashed to learn
|
|
817
|
+
* what we wrote down.
|
|
818
|
+
*
|
|
819
|
+
* @type {Set<string>}
|
|
820
|
+
*/
|
|
821
|
+
#wholeSources = new Set();
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Say that every file of a source is held whole.
|
|
825
|
+
*
|
|
826
|
+
* @param {string} sourceKey
|
|
827
|
+
* @returns {void}
|
|
828
|
+
*/
|
|
829
|
+
addWholeSource(sourceKey) {
|
|
830
|
+
this.#wholeSources.add(String(sourceKey));
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* Anything else every store of this pool is built with.
|
|
835
|
+
*
|
|
836
|
+
* Today: where a piece can be had when neither of the store's own tiers has
|
|
837
|
+
* it — the files this proxy has assembled. Given to the pool rather than
|
|
838
|
+
* discovered by the store, which knows nothing about files.
|
|
839
|
+
*
|
|
840
|
+
* @type {object}
|
|
841
|
+
*/
|
|
842
|
+
#storeExtras = {};
|
|
843
|
+
|
|
844
|
+
/**
|
|
845
|
+
* Say where a piece can be had when the store has neither a resident nor a
|
|
846
|
+
* spilled copy.
|
|
847
|
+
*
|
|
848
|
+
* @param {object} extras
|
|
849
|
+
* @returns {void}
|
|
850
|
+
*/
|
|
851
|
+
buildStoresWith(extras) {
|
|
852
|
+
this.#storeExtras = extras && typeof extras === "object" ? extras : {};
|
|
853
|
+
}
|
|
854
|
+
|
|
786
855
|
constructor({ maxDiskBytes, memoryBytes, dhtBootstrap } = {}) {
|
|
787
856
|
this.#memoryBytes = Number.isFinite(memoryBytes) && memoryBytes > 0 ? memoryBytes : undefined;
|
|
788
857
|
|
|
@@ -851,8 +920,8 @@ export class TorrentPool {
|
|
|
851
920
|
? maxDiskBytes
|
|
852
921
|
: computeDefaultDiskCap(os.tmpdir());
|
|
853
922
|
if (this.#maxDiskBytes > 0) {
|
|
854
|
-
const
|
|
855
|
-
logger.info(`torrent-pool: disk cap ${
|
|
923
|
+
const gigabytes = (this.#maxDiskBytes / (1024 * 1024 * 1024)).toFixed(1);
|
|
924
|
+
logger.info(`torrent-pool: disk cap ${gigabytes} GB (LRU eviction of idle torrents above it)`);
|
|
856
925
|
this.#diskSweepTimer = setInterval(() => this.#enforceDiskCap(), DISK_CAP_SWEEP_INTERVAL_MS);
|
|
857
926
|
this.#diskSweepTimer.unref?.();
|
|
858
927
|
}
|
|
@@ -869,6 +938,88 @@ export class TorrentPool {
|
|
|
869
938
|
this.#uploadAdjustTimer.unref?.();
|
|
870
939
|
}
|
|
871
940
|
|
|
941
|
+
/**
|
|
942
|
+
* Leave the swarm of a torrent nobody is reading, and rejoin it when
|
|
943
|
+
* somebody is.
|
|
944
|
+
*
|
|
945
|
+
* A PROXY THAT NEEDS NOTHING FROM A SWARM SHOULD NOT BE IN THAT SWARM. While
|
|
946
|
+
* a file is being watched every connection is worth keeping — the one that
|
|
947
|
+
* has delivered nothing yet may deliver next — so this is not a limit on
|
|
948
|
+
* connections and never fires during playback. It fires when NOTHING is
|
|
949
|
+
* stated about this torrent at all: no window from any reader, no file held.
|
|
950
|
+
*
|
|
951
|
+
* What that state cost until now: WebTorrent enforces `maxConns` only on
|
|
952
|
+
* peers it dials (`_drain`), while `_addIncomingPeer` checks that the torrent
|
|
953
|
+
* is neither destroyed nor paused and registers the peer. A proxy with its
|
|
954
|
+
* port mapped is reachable, so connections arrive and are never turned away —
|
|
955
|
+
* field 2026-09-11, 249 connected at the start of one viewing and 596 at the
|
|
956
|
+
* end, 15 862 more queued, on a file complete for three quarters of an hour,
|
|
957
|
+
* each of them served by reading a 4 MB piece off the disk for every 16 KB
|
|
958
|
+
* sent.
|
|
959
|
+
*
|
|
960
|
+
* `paused` is the library's own word for this and the path it already checks,
|
|
961
|
+
* so nothing here fights it. The pause alone does not close what is already
|
|
962
|
+
* open, so the peers are let go by hand; the data stays exactly where it is,
|
|
963
|
+
* and the next reader resumes the torrent rather than fetching it again.
|
|
964
|
+
*
|
|
965
|
+
* @param {import("webtorrent").Torrent} torrent
|
|
966
|
+
* @returns {void}
|
|
967
|
+
*/
|
|
968
|
+
followTheReaders(torrent) {
|
|
969
|
+
if (!torrent || torrent.destroyed) {
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
const usage = this.fileUsageByTorrent.get(torrent);
|
|
973
|
+
const isRead = Boolean(usage && usage.size > 0);
|
|
974
|
+
if (isRead) {
|
|
975
|
+
// Recorded on the torrent, as `hasActiveReader` and `hasUnmetDemand`
|
|
976
|
+
// beside it are: it is a fact about this torrent and it lives as long as
|
|
977
|
+
// the torrent does.
|
|
978
|
+
torrent.hasBeenRead = true;
|
|
979
|
+
}
|
|
980
|
+
const isWanted = isRead || demandFor(torrent).register.windows().length > 0;
|
|
981
|
+
// A TORRENT NOBODY HAS READ YET IS BEING SET UP, NOT ABANDONED. Field
|
|
982
|
+
// 2026-09-11, and it broke playback outright: a torrent was added at
|
|
983
|
+
// 20:57:17, its first peer connected at 20:57:18, and this pass took it out
|
|
984
|
+
// of the swarm at 20:57:21 — while the read of the file's edges was still
|
|
985
|
+
// in flight and the playback plan was being built. Nothing rejoined it,
|
|
986
|
+
// because rejoining waits for a reader and a reader cannot arrive: the
|
|
987
|
+
// header it needs is downloaded by the swarm that was just let go.
|
|
988
|
+
//
|
|
989
|
+
// The condition is a state and not a period: having been read at least once
|
|
990
|
+
// is what tells a film somebody left from a film nobody has opened yet. One
|
|
991
|
+
// that is never read at all goes by the pool's own idle removal, which is
|
|
992
|
+
// where that belongs.
|
|
993
|
+
if (!isWanted && torrent.hasBeenRead !== true) {
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
if (isWanted && torrent.paused === true) {
|
|
997
|
+
torrent.resume();
|
|
998
|
+
logger.info(
|
|
999
|
+
`torrent-pool: [${String(torrent.infoHash ?? "?").slice(0, 8)}] rejoined the swarm — somebody is reading it again`
|
|
1000
|
+
);
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
1003
|
+
if (isWanted || torrent.paused === true) {
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
torrent.pause();
|
|
1007
|
+
const open = Array.isArray(torrent.wires) ? torrent.wires.length : 0;
|
|
1008
|
+
let closed = 0;
|
|
1009
|
+
for (const peer of [...(torrent._peers?.values?.() ?? [])]) {
|
|
1010
|
+
try {
|
|
1011
|
+
peer.destroy();
|
|
1012
|
+
closed += 1;
|
|
1013
|
+
} catch {
|
|
1014
|
+
// A peer already going: nothing to do, and nothing worth failing for.
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
logger.info(
|
|
1018
|
+
`torrent-pool: [${String(torrent.infoHash ?? "?").slice(0, 8)}] left the swarm — nobody is reading it, ` +
|
|
1019
|
+
`${open} connection(s) open, ${closed} let go; the data stays and the next reader rejoins`
|
|
1020
|
+
);
|
|
1021
|
+
}
|
|
1022
|
+
|
|
872
1023
|
/**
|
|
873
1024
|
* Re-evaluate and apply the client-wide upload limit from current swarm state
|
|
874
1025
|
* (see {@link decideUploadLimit}). Runs on a timer; only calls into WebTorrent
|
|
@@ -1201,6 +1352,9 @@ export class TorrentPool {
|
|
|
1201
1352
|
this.#stateBackgroundFill(torrent);
|
|
1202
1353
|
}
|
|
1203
1354
|
this.#reportStalledDownloads();
|
|
1355
|
+
for (const torrent of this.torrents.values()) {
|
|
1356
|
+
this.followTheReaders(torrent);
|
|
1357
|
+
}
|
|
1204
1358
|
const { bytesPerSec, reason } = decideUploadLimit(active);
|
|
1205
1359
|
if (bytesPerSec === this.#uploadLimit) {
|
|
1206
1360
|
return;
|
|
@@ -1241,11 +1395,14 @@ export class TorrentPool {
|
|
|
1241
1395
|
}
|
|
1242
1396
|
// Candidates: pooled torrents with zero active readers, LRU first.
|
|
1243
1397
|
const candidates = [...this.torrents.values()]
|
|
1244
|
-
.filter((
|
|
1245
|
-
const usage = this.fileUsageByTorrent.get(
|
|
1398
|
+
.filter((torrent) => {
|
|
1399
|
+
const usage = this.fileUsageByTorrent.get(torrent);
|
|
1246
1400
|
return !usage || usage.size === 0;
|
|
1247
1401
|
})
|
|
1248
|
-
.sort(
|
|
1402
|
+
.sort(
|
|
1403
|
+
(earlier, later) =>
|
|
1404
|
+
(this.#lastAccess.get(earlier) ?? 0) - (this.#lastAccess.get(later) ?? 0)
|
|
1405
|
+
);
|
|
1249
1406
|
|
|
1250
1407
|
for (const torrent of candidates) {
|
|
1251
1408
|
if (used <= this.#maxDiskBytes) {
|
|
@@ -1253,9 +1410,9 @@ export class TorrentPool {
|
|
|
1253
1410
|
}
|
|
1254
1411
|
const freed = Math.max(0, torrentDownloadedBytes(torrent));
|
|
1255
1412
|
const name = typeof torrent?.name === "string" ? torrent.name : "(unknown)";
|
|
1256
|
-
const
|
|
1413
|
+
const gigabytes = (this.#maxDiskBytes / (1024 * 1024 * 1024)).toFixed(1);
|
|
1257
1414
|
logger.info(
|
|
1258
|
-
`torrent-pool: disk cap ${
|
|
1415
|
+
`torrent-pool: disk cap ${gigabytes} GB exceeded — evicting idle torrent "${name}" ` +
|
|
1259
1416
|
`(~${(freed / (1024 * 1024)).toFixed(0)} MB)`
|
|
1260
1417
|
);
|
|
1261
1418
|
this.#cancelIdleRemoval(torrent);
|
|
@@ -1330,6 +1487,21 @@ export class TorrentPool {
|
|
|
1330
1487
|
logger.warn(`torrent-pool: [${label()}] warning: ${formatWarning(warning)}`);
|
|
1331
1488
|
});
|
|
1332
1489
|
|
|
1490
|
+
// A TORRENT THAT DIED WITHOUT US ASKING LEAVES ITS RECORD BEHIND, and the
|
|
1491
|
+
// record goes on answering. Field 2026-09-11: the store refused a block,
|
|
1492
|
+
// the client destroyed the torrent, and for the rest of the process every
|
|
1493
|
+
// read answered `File 1 not found in torrent:d4022ff4…` while `/stats`
|
|
1494
|
+
// reported `peers=0 connected of 1186 known` — so the browser's own remedy,
|
|
1495
|
+
// adding the source again, returned the corpse and the viewer could not
|
|
1496
|
+
// open anything until the addon was restarted.
|
|
1497
|
+
//
|
|
1498
|
+
// Forgetting the record is the whole fix: the next request builds the
|
|
1499
|
+
// torrent again, from the same magnet, against the same data on disk.
|
|
1500
|
+
torrent.on("error", (error) => {
|
|
1501
|
+
logger.error(`torrent-pool: [${label()}] died: ${formatWarning(error)}`);
|
|
1502
|
+
this.#forgetDeadTorrent(torrent);
|
|
1503
|
+
});
|
|
1504
|
+
|
|
1333
1505
|
// Everything below needs the torrent to have been PARSED, and `add` returns
|
|
1334
1506
|
// before that: `announce`, `files` and `private` are all still empty, and
|
|
1335
1507
|
// `discovery` — which owns the tracker client — is not created until
|
|
@@ -1437,7 +1609,7 @@ export class TorrentPool {
|
|
|
1437
1609
|
const message = error instanceof Error ? error.message : String(error);
|
|
1438
1610
|
const dupMatch = /duplicate torrent ([0-9a-f]{40})/i.exec(message);
|
|
1439
1611
|
if (dupMatch) {
|
|
1440
|
-
const existing = this.client.torrents.find((
|
|
1612
|
+
const existing = this.client.torrents.find((candidate) => candidate?.infoHash === dupMatch[1]);
|
|
1441
1613
|
// A torrent already here but WITHOUT metadata is not an answer to a
|
|
1442
1614
|
// request that carries metadata. A magnet whose swarm never answered
|
|
1443
1615
|
// leaves exactly that: an entry with the right infohash, no file
|
|
@@ -1501,7 +1673,7 @@ export class TorrentPool {
|
|
|
1501
1673
|
const addedReplacement = this.client.add(torrentId, {
|
|
1502
1674
|
store: SharedPieceStore,
|
|
1503
1675
|
storeCacheSlots: 0,
|
|
1504
|
-
storeOpts: { memoryBytes: this.#memoryBytes },
|
|
1676
|
+
storeOpts: { memoryBytes: this.#memoryBytes, ...this.#storeExtras },
|
|
1505
1677
|
deselect: true
|
|
1506
1678
|
}, (replacement) => {
|
|
1507
1679
|
this.torrents.set(key, replacement);
|
|
@@ -1534,14 +1706,19 @@ export class TorrentPool {
|
|
|
1534
1706
|
const added = this.client.add(torrentId, {
|
|
1535
1707
|
store: SharedPieceStore,
|
|
1536
1708
|
storeCacheSlots: 0,
|
|
1537
|
-
storeOpts: { memoryBytes: this.#memoryBytes },
|
|
1709
|
+
storeOpts: { memoryBytes: this.#memoryBytes, ...this.#storeExtras },
|
|
1538
1710
|
// Nothing is fetched until somebody says they want it. WebTorrent's own
|
|
1539
1711
|
// default is `this.select(0, this.pieces.length - 1)` — the whole
|
|
1540
1712
|
// torrent — and this proxy used to undo that afterwards by deselecting
|
|
1541
1713
|
// the files nobody had opened. On a season pack that meant every
|
|
1542
1714
|
// episode was being fetched for as long as the viewer took to choose
|
|
1543
1715
|
// one. The download set is built up from stated needs instead.
|
|
1544
|
-
deselect: true
|
|
1716
|
+
deselect: true,
|
|
1717
|
+
// Nothing to check when every file of this source is already here
|
|
1718
|
+
// whole: what would be verified was written out of pieces this client
|
|
1719
|
+
// had hashed, and the file's size was checked against what the torrent
|
|
1720
|
+
// says. See `#wholeSources`.
|
|
1721
|
+
skipVerify: this.#wholeSources.has(key)
|
|
1545
1722
|
}, (readyTorrent) => {
|
|
1546
1723
|
this.client.off("error", onError);
|
|
1547
1724
|
this.torrents.set(key, readyTorrent);
|
|
@@ -1592,6 +1769,15 @@ export class TorrentPool {
|
|
|
1592
1769
|
// it recently accessed so LRU eviction keeps it.
|
|
1593
1770
|
this.#cancelIdleRemoval(torrent);
|
|
1594
1771
|
this.#lastAccess.set(torrent, Date.now());
|
|
1772
|
+
// And rejoin its swarm HERE rather than at the next five-second pass: a
|
|
1773
|
+
// reader that has just arrived is about to ask for bytes, and a torrent
|
|
1774
|
+
// still paused answers by fetching nothing at all.
|
|
1775
|
+
if (torrent.paused === true) {
|
|
1776
|
+
torrent.resume();
|
|
1777
|
+
logger.info(
|
|
1778
|
+
`torrent-pool: [${String(torrent.infoHash ?? "?").slice(0, 8)}] rejoined the swarm — a reader arrived`
|
|
1779
|
+
);
|
|
1780
|
+
}
|
|
1595
1781
|
usage.set(fileIndex, (usage.get(fileIndex) ?? 0) + 1);
|
|
1596
1782
|
|
|
1597
1783
|
let released = false;
|
|
@@ -1628,18 +1814,18 @@ export class TorrentPool {
|
|
|
1628
1814
|
}
|
|
1629
1815
|
this.#cancelIdleRemoval(torrent);
|
|
1630
1816
|
const name = typeof torrent.name === "string" ? torrent.name : "(unknown)";
|
|
1631
|
-
const
|
|
1632
|
-
logger.info(`torrent-pool: scheduling idle removal for "${name}" [${
|
|
1817
|
+
const infoHashShort = String(torrent.infoHash ?? "?").slice(0, 8);
|
|
1818
|
+
logger.info(`torrent-pool: scheduling idle removal for "${name}" [${infoHashShort}] in ${TORRENT_IDLE_TTL_MS / 1000}s`);
|
|
1633
1819
|
const timer = setTimeout(() => {
|
|
1634
1820
|
this.#idleTimers.delete(torrent);
|
|
1635
1821
|
// Re-check: a new acquire since scheduling would have cancelled this
|
|
1636
1822
|
// timer, but guard anyway against a race.
|
|
1637
1823
|
const usage = this.fileUsageByTorrent.get(torrent);
|
|
1638
1824
|
if (usage && usage.size > 0) {
|
|
1639
|
-
logger.info(`torrent-pool: idle timer fired for "${name}" [${
|
|
1825
|
+
logger.info(`torrent-pool: idle timer fired for "${name}" [${infoHashShort}] but refcount ${usage.size} >0 — keep`);
|
|
1640
1826
|
return;
|
|
1641
1827
|
}
|
|
1642
|
-
logger.warn(`torrent-pool: idle TTL fired for "${name}" [${
|
|
1828
|
+
logger.warn(`torrent-pool: idle TTL fired for "${name}" [${infoHashShort}] — removing torrent (reason=idle-ttl caller=scheduleIdleRemoval)`);
|
|
1643
1829
|
this.#removeTorrent(torrent, "idle-ttl");
|
|
1644
1830
|
}, TORRENT_IDLE_TTL_MS);
|
|
1645
1831
|
timer.unref?.();
|
|
@@ -1668,6 +1854,59 @@ export class TorrentPool {
|
|
|
1668
1854
|
* @param {string} [reason="unknown"] - Why removal was requested (idle-ttl, disk-cap, evict, api).
|
|
1669
1855
|
* @returns {void}
|
|
1670
1856
|
*/
|
|
1857
|
+
/**
|
|
1858
|
+
* Forget a torrent that died on its own, keeping its bytes.
|
|
1859
|
+
*
|
|
1860
|
+
* NOT `#removeTorrent`: that one destroys the store as well, and the data on
|
|
1861
|
+
* disk is the expensive thing here — re-downloading a film costs the swarm
|
|
1862
|
+
* and the viewer, while re-adding a torrent costs a tracker announce. What
|
|
1863
|
+
* has to go is only the RECORD, which otherwise answers every later request
|
|
1864
|
+
* with a corpse.
|
|
1865
|
+
*
|
|
1866
|
+
* @param {import("webtorrent").Torrent} torrent
|
|
1867
|
+
* @returns {void}
|
|
1868
|
+
*/
|
|
1869
|
+
#forgetDeadTorrent(torrent) {
|
|
1870
|
+
if (!torrent) {
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1873
|
+
let forgotten = false;
|
|
1874
|
+
for (const [key, value] of this.torrents) {
|
|
1875
|
+
if (value === torrent) {
|
|
1876
|
+
this.torrents.delete(key);
|
|
1877
|
+
forgotten = true;
|
|
1878
|
+
break;
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
if (!forgotten) {
|
|
1882
|
+
return;
|
|
1883
|
+
}
|
|
1884
|
+
forgetTorrent(torrent);
|
|
1885
|
+
this.fileUsageByTorrent.delete(torrent);
|
|
1886
|
+
this.#lastAccess.delete(torrent);
|
|
1887
|
+
this.#readPositionByTorrent.delete(torrent);
|
|
1888
|
+
const name = typeof torrent.name === "string" ? torrent.name : "(unknown)";
|
|
1889
|
+
logger.warn(
|
|
1890
|
+
`torrent-pool: forgot "${name}" [${String(torrent.infoHash ?? "?").slice(0, 8)}] — ` +
|
|
1891
|
+
"it died without being asked to; its data stays on disk and the next request adds it again"
|
|
1892
|
+
);
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
/**
|
|
1896
|
+
* Remove a torrent and its store, by name of the reason.
|
|
1897
|
+
*
|
|
1898
|
+
* The public form of what the idle timer and the disk cap already do. Taking
|
|
1899
|
+
* the store with it is the point where a torrent downloaded whole is
|
|
1900
|
+
* concerned: its pieces are a duplicate of the files kept elsewhere.
|
|
1901
|
+
*
|
|
1902
|
+
* @param {import("webtorrent").Torrent} torrent
|
|
1903
|
+
* @param {string} reason
|
|
1904
|
+
* @returns {void}
|
|
1905
|
+
*/
|
|
1906
|
+
remove(torrent, reason) {
|
|
1907
|
+
this.#removeTorrent(torrent, reason);
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1671
1910
|
#removeTorrent(torrent, reason = "unknown") {
|
|
1672
1911
|
// Everything anybody stated for this torrent goes with it.
|
|
1673
1912
|
forgetTorrent(torrent);
|
|
@@ -1755,6 +1994,7 @@ export class TorrentPool {
|
|
|
1755
1994
|
downloadSpeed,
|
|
1756
1995
|
uploadSpeed,
|
|
1757
1996
|
connectedPeers: reach.connectedPeers,
|
|
1997
|
+
deliveringPeers: reach.deliveringPeers,
|
|
1758
1998
|
knownPeers: reach.knownPeers,
|
|
1759
1999
|
queuedPeers: reach.queuedPeers,
|
|
1760
2000
|
trackerSeeders: announce.seeders,
|
|
@@ -94,6 +94,18 @@ export class TorrentWorkerClient {
|
|
|
94
94
|
/** Reads consuming fragments in place, keyed by request id. */
|
|
95
95
|
#fragmentReaders = new Map();
|
|
96
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
|
+
|
|
97
109
|
/** @type {(event: { sourceKey: string, fileIndex: number, trackIndex: number, cues: object[], language: string }) => void} */
|
|
98
110
|
#onSubtitleCues;
|
|
99
111
|
|
|
@@ -208,6 +220,15 @@ export class TorrentWorkerClient {
|
|
|
208
220
|
case Event.LOG:
|
|
209
221
|
logger.info(`torrent-worker: ${message.message}`);
|
|
210
222
|
break;
|
|
223
|
+
case Event.FILE_COMPLETE:
|
|
224
|
+
// Recorded here so the stream route can answer from the file without
|
|
225
|
+
// going near the torrent thread at all.
|
|
226
|
+
this.wholeFiles.set(`${message.infoHash}/${message.fileIndex}`, {
|
|
227
|
+
path: message.path,
|
|
228
|
+
length: message.length,
|
|
229
|
+
name: message.name
|
|
230
|
+
});
|
|
231
|
+
break;
|
|
211
232
|
case Event.SUBTITLE_CUES_READY:
|
|
212
233
|
this.#onSubtitleCues({
|
|
213
234
|
sourceKey: message.sourceKey,
|
|
@@ -164,7 +164,15 @@ export const Event = {
|
|
|
164
164
|
* {@link Command.SUBTITLE_CUES} call. Lets the main thread PUSH them to
|
|
165
165
|
* whichever browser is watching instead of waiting to be asked.
|
|
166
166
|
*/
|
|
167
|
-
SUBTITLE_CUES_READY: "subtitle-cues-ready"
|
|
167
|
+
SUBTITLE_CUES_READY: "subtitle-cues-ready",
|
|
168
|
+
/**
|
|
169
|
+
* A file has been downloaded whole and written out as a file.
|
|
170
|
+
*
|
|
171
|
+
* The main thread serves it from disk after this, without asking this thread
|
|
172
|
+
* for anything: an ordinary read of an ordinary file, with no piece store
|
|
173
|
+
* between them and nothing that can refuse it for want of memory.
|
|
174
|
+
*/
|
|
175
|
+
FILE_COMPLETE: "file-complete"
|
|
168
176
|
};
|
|
169
177
|
|
|
170
178
|
/**
|