@torrent-tv/proxy 2.80.19 → 2.81.1

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +1 -1
  3. package/research/double-spawn-2026-09-10.md +171 -0
  4. package/services/disk/DiskSpace.js +150 -0
  5. package/services/disk/wire.js +60 -0
  6. package/services/encode/EncodeRun.js +25 -3
  7. package/services/encode/SegmentStore.js +137 -9
  8. package/services/hls-session-manager.js +26 -45
  9. package/services/orchestrators/EncodeOrchestrator.js +4 -1
  10. package/services/piece-store/allowance.js +107 -0
  11. package/services/piece-store/piece-disk-store.js +365 -0
  12. package/services/piece-store/shared-piece-store.js +1549 -1535
  13. package/services/torrent-worker/client.js +32 -0
  14. package/services/torrent-worker/pool-adapter.js +15 -0
  15. package/services/torrent-worker/protocol.js +9 -0
  16. package/services/torrent-worker/worker.js +8 -1
  17. package/services/viewer/positions.js +48 -0
  18. package/test/audio-inventory.test.js +176 -176
  19. package/test/auto-quality-step.test.js +514 -514
  20. package/test/concurrent-cost.test.js +138 -138
  21. package/test/coverage-follows-the-disk.test.js +191 -191
  22. package/test/coverage-map.test.js +195 -195
  23. package/test/declared-tracks.test.js +35 -35
  24. package/test/disk-space.test.js +150 -0
  25. package/test/encode-orchestrator.test.js +0 -3
  26. package/test/encode-run.test.js +5 -12
  27. package/test/held-request-width.test.js +155 -155
  28. package/test/helpers/encode-run.js +2 -2
  29. package/test/matroska-blocks.test.js +0 -0
  30. package/test/matroska-cues-track.test.js +192 -192
  31. package/test/mp4-composition-times.test.js +0 -0
  32. package/test/mp4-subtitles.test.js +173 -173
  33. package/test/one-authority.test.js +281 -220
  34. package/test/orchestrator-wired.test.js +199 -199
  35. package/test/packet-witness-ring.test.js +236 -236
  36. package/test/packet-witness.test.js +148 -148
  37. package/test/piece-disk-store.test.js +267 -0
  38. package/test/piece-reader.test.js +4 -4
  39. package/test/piece-store-eviction.test.js +17 -17
  40. package/test/piece-store-reservations.test.js +20 -1
  41. package/test/piece-store-slow-disk.test.js +16 -1
  42. package/test/read-window.test.js +6 -6
  43. package/test/run-intervals.test.js +100 -100
  44. package/test/seek-landing.test.js +109 -109
  45. package/test/segment-store-eviction.test.js +232 -0
  46. package/test/segments-are-shared.test.js +1 -1
  47. package/test/shared-piece-store.test.js +12 -12
  48. package/test/sidecar-naming.test.js +142 -142
  49. package/test/subtitle-cue-framing.test.js +200 -200
  50. package/test/subtitle-cue-walk.test.js +369 -369
  51. package/test/subtitle-defaults.test.js +97 -97
  52. package/test/subtitle-track-numbering.test.js +370 -370
  53. package/test/tail-duplication.test.js +167 -167
  54. package/test/tracks-begin-together.test.js +195 -195
  55. package/test/two-viewers-one-picture.test.js +374 -374
  56. package/test/video-facts.test.js +102 -102
  57. package/test/wedge-certainty.test.js +131 -131
  58. package/services/piece-store/disk-tier.js +0 -151
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import { createReadStream, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
11
- import { access, readdir, readFile, rm, stat, unlink } from "node:fs/promises";
11
+ import { access, readFile, rm, stat, unlink } from "node:fs/promises";
12
12
  import { Readable } from "node:stream";
13
13
  import os from "node:os";
14
14
  import path from "node:path";
@@ -88,11 +88,13 @@ import {
88
88
  // — did not move when the code did.
89
89
  export { ffmpegSeconds, onKeyframeGridFor, seekLandingOffsetFor, segmentCutTimesFrom };
90
90
  import { viewersOf } from "./viewer/Viewer.js";
91
+ import { viewerSegmentsOn } from "./viewer/positions.js";
91
92
  import { Viewers } from "./viewer/Viewers.js";
92
93
  import { LiveOutputs } from "./output/LiveOutputs.js";
93
94
  import { variantHeightsFor } from "./output/ladder.js";
94
95
  import { EncodeOrchestrator } from "./orchestrators/EncodeOrchestrator.js";
95
96
  import { readDiskFree } from "./memory-report.js";
97
+ import { wireDiskSpace } from "./disk/wire.js";
96
98
 
97
99
  /**
98
100
  * Whether an encoder run died because its INPUT went away, rather than because
@@ -473,18 +475,6 @@ const DEFAULT_SESSION_TTL_MS = 30 * 60 * 1000;
473
475
  * there for the life of the process.
474
476
  */
475
477
  const SEGMENT_STORE_IDLE_MS = 6 * 60 * 60 * 1000;
476
- /**
477
- * The share of FREE disk the produced segments may take.
478
- *
479
- * A share of what is free NOW, re-read on every sweep, for the same reason the
480
- * piece store re-derives its memory allowance every minute: a machine that
481
- * fills up after this proxy started would otherwise go on spending an allowance
482
- * taken when it was empty. A Home Assistant install often runs from a 32 GB
483
- * card carrying everything else in the house.
484
- */
485
- const SEGMENT_STORE_FREE_SHARE = 0.25;
486
- /** What the store may hold where the free space cannot be read at all. */
487
- const SEGMENT_STORE_FALLBACK_BYTES = 2 * 1024 * 1024 * 1024;
488
478
  const DEFAULT_STARTUP_WAIT_MS = 5_000;
489
479
  // Realtime budget — runtime downswitch (software encoder only). Periodically
490
480
  // check each active software-transcode session's ffmpeg `speed`; when it stays
@@ -1604,6 +1594,13 @@ export class HlsSessionManager {
1604
1594
  void this.cleanupExpired();
1605
1595
  }, CLEANUP_INTERVAL_MS);
1606
1596
  this.cleanupTimer.unref();
1597
+ // One owner of the disk, and the list of what takes it lives with the owner.
1598
+ this.diskSpace = wireDiskSpace({
1599
+ segmentStore: this.segmentStore,
1600
+ torrentPool: this.torrentPool,
1601
+ readFree: readDiskFree,
1602
+ logger
1603
+ });
1607
1604
  // Realtime-budget monitor: only meaningful for the software encoder with a
1608
1605
  // benchmark (the only path that can pick/step resolution). Cheap no-op scan
1609
1606
  // otherwise.
@@ -5530,6 +5527,9 @@ export class HlsSessionManager {
5530
5527
  inputUnavailable: (message) => isInputUnavailable(message),
5531
5528
  onProgress: (report) => this.#noteRunProgress(session, run, report),
5532
5529
  indexOfName: (name) => session.segmentFormat.segmentIndexFromName(name),
5530
+ // Why this encoder exists, recorded with its argument list. It used to be
5531
+ // handed to a separate `start` call; there is no separate call now.
5532
+ because,
5533
5533
  onClosed: (name) => this.segmentStore.publish(session.outputKey ?? "", name, session.segmentFormat),
5534
5534
  onEnded: (ended) => this.noteRunEnded(session, run, ended)
5535
5535
  });
@@ -5543,8 +5543,6 @@ export class HlsSessionManager {
5543
5543
  // premature downscale.
5544
5544
  session.budgetSlowSince = 0;
5545
5545
 
5546
- run.start(because);
5547
-
5548
5546
  logger.info(
5549
5547
  `transcode ${session.id} encode-run #${safeIndex}..#${runEnd} from segment #${safeIndex} ` +
5550
5548
  `(+${Date.now() - restartEnteredAt}ms since the restart was asked for) ` +
@@ -9667,32 +9665,22 @@ export class HlsSessionManager {
9667
9665
  // The segments outlive every session on them, so what they cost is decided
9668
9666
  // here rather than by anybody's departure: how long ago each output was
9669
9667
  // last read, and how much room the disk has for the lot.
9668
+ // The room is the disk owner's to divide; this asks what the share is now.
9669
+ await this.diskSpace.revise();
9670
9670
  this.segmentStore.enforce({
9671
9671
  idleMs: SEGMENT_STORE_IDLE_MS,
9672
- maxBytes: await this.#segmentStoreAllowance()
9672
+ maxBytes: this.diskSpace.segmentBytes(),
9673
+ viewersAt: (key) =>
9674
+ viewerSegmentsOn({
9675
+ sessions: this.sessionsById.values(),
9676
+ outputKey: key,
9677
+ segmentAt: (session, seconds) => this.#segmentIndexForTime(session, seconds),
9678
+ now: Date.now(),
9679
+ staleAfterMs: this.presenceStaleAfterMs()
9680
+ })
9673
9681
  });
9674
9682
  }
9675
9683
 
9676
- /**
9677
- * How much disk the produced segments may hold.
9678
- *
9679
- * A share of what is FREE now rather than a figure fixed at startup, for the
9680
- * same reason the piece store's memory allowance is re-derived every minute:
9681
- * a machine that fills up after this proxy started would otherwise go on
9682
- * spending an allowance taken when it was empty. On a Home Assistant install
9683
- * that disk is often a 32 GB card carrying everything else the household
9684
- * runs.
9685
- *
9686
- * @returns {Promise<number>}
9687
- */
9688
- async #segmentStoreAllowance() {
9689
- const free = await readDiskFree(this.segmentStore.root);
9690
- if (!Number.isFinite(free) || free <= 0) {
9691
- return SEGMENT_STORE_FALLBACK_BYTES;
9692
- }
9693
- return Math.max(SEGMENT_STORE_FALLBACK_BYTES, Math.floor(free * SEGMENT_STORE_FREE_SHARE));
9694
- }
9695
-
9696
9684
  /**
9697
9685
  * Return a progress snapshot for the given session, or `null` if not found.
9698
9686
  * Also refreshes `lastAccessedAt` to prevent the session from expiring.
@@ -10078,14 +10066,7 @@ export class HlsSessionManager {
10078
10066
  for (const sessionId of activeIds) {
10079
10067
  await this.disposeSession(sessionId);
10080
10068
  }
10081
- const rootDir = path.join(os.tmpdir(), "torrent-tv-hls");
10082
- try {
10083
- const dirs = await readdir(rootDir);
10084
- if (dirs.length === 0) {
10085
- await rm(rootDir, { recursive: true, force: true });
10086
- }
10087
- } catch (_error) {
10088
- // Best effort cleanup.
10089
- }
10069
+ // Everything this process owns, root included. See SegmentStore.dropAll.
10070
+ this.segmentStore.dropAll("the proxy is shutting down");
10090
10071
  }
10091
10072
  }
@@ -572,8 +572,11 @@ export class EncodeOrchestrator {
572
572
  // a run writing that number again writes under a working name until it
573
573
  // closes its own — so the file standing there is a complete piece made by
574
574
  // somebody, and serving it is right until the newer one replaces it whole.
575
+ // The claim comes after the run exists, and that is not a race: everything
576
+ // between is synchronous, and a process cannot say a word before the next
577
+ // tick. What it removes is the second act — building a run and starting it
578
+ // were two steps, and two owners each performed the second one.
575
579
  this.coverageOf(address).claim(run, from, endOfRun({ from, to }));
576
- run.start(because);
577
580
  }
578
581
 
579
582
  /**
@@ -0,0 +1,107 @@
1
+ /**
2
+ * @file How much of a machine's resource the stores may hold between them.
3
+ *
4
+ * Written once and used twice, because memory and disk are the same question
5
+ * asked of two resources: what is free now, plus what we already hold, less
6
+ * what everything that is not us has recently been seen to need.
7
+ *
8
+ * It used to exist only for memory, inside the memory store, keyed on module
9
+ * state. Disk had no such rule at all — the spill file grew until the machine
10
+ * did, 14.4 GB in a single viewing on 2026-08-31 — and copying the memory rule
11
+ * across would have made two rules to keep in step. One rule, two readings.
12
+ */
13
+
14
+ /**
15
+ * How many observations of other processes' demand are kept.
16
+ *
17
+ * A window rather than a high-water: a single spike would otherwise stand for
18
+ * the life of the process and hold the stores down long after whatever caused
19
+ * it had finished.
20
+ */
21
+ const OTHER_DEMAND_SAMPLES = 60;
22
+
23
+ /**
24
+ * What everything that is not us has recently been seen to need.
25
+ *
26
+ * One instance per resource. A fall in what is free that we did not cause is a
27
+ * measurement of somebody else's demand; a fall we did cause is our own doing
28
+ * and says nothing about the machine.
29
+ */
30
+ export class OtherDemand {
31
+ /** @type {number[]} */
32
+ #falls = [];
33
+
34
+ #lastFreeBytes = 0;
35
+
36
+ #lastHeldBytes = 0;
37
+
38
+ /**
39
+ * Take a reading, and answer what to reserve for others.
40
+ *
41
+ * @param {number} freeBytes - What the machine says is free now.
42
+ * @param {number} heldBytes - What the stores hold of this resource now.
43
+ * @returns {number} The reserve, in bytes.
44
+ */
45
+ note(freeBytes, heldBytes) {
46
+ if (this.#lastFreeBytes > 0) {
47
+ const fell = this.#lastFreeBytes - freeBytes;
48
+ const ours = heldBytes - this.#lastHeldBytes;
49
+ this.#falls.push(Math.max(0, fell - ours));
50
+ if (this.#falls.length > OTHER_DEMAND_SAMPLES) {
51
+ this.#falls.shift();
52
+ }
53
+ }
54
+ this.#lastFreeBytes = freeBytes;
55
+ this.#lastHeldBytes = heldBytes;
56
+ return this.reserve();
57
+ }
58
+
59
+ /** @returns {number} */
60
+ reserve() {
61
+ return this.#falls.length === 0 ? 0 : Math.max(...this.#falls);
62
+ }
63
+
64
+ /** Forget the readings. For tests, which share a module. */
65
+ forget() {
66
+ this.#falls = [];
67
+ this.#lastFreeBytes = 0;
68
+ this.#lastHeldBytes = 0;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * How much of the resource the stores may hold between them.
74
+ *
75
+ * What the machine reports free is what could be taken ON TOP of what is
76
+ * already held, so the stores' own bytes are added back: the pair is the
77
+ * ceiling the stores could reach.
78
+ *
79
+ * @param {number} freeBytes
80
+ * @param {number} heldBytes
81
+ * @param {number} reserveBytes
82
+ * @returns {number}
83
+ */
84
+ export function machineAllowanceBytes(freeBytes, heldBytes, reserveBytes) {
85
+ return Math.max(0, Math.max(freeBytes, 0) + Math.max(heldBytes, 0) - Math.max(reserveBytes, 0));
86
+ }
87
+
88
+ /**
89
+ * Divide what the machine allows between the stores, by what each is asking
90
+ * for.
91
+ *
92
+ * When everyone's ask fits, everyone gets it and the machine's limit never
93
+ * binds. When the asks do not fit, each store is cut in proportion to what it
94
+ * asked, so a store wanting little is not cut to make room for one wanting
95
+ * much.
96
+ *
97
+ * @param {number[]} wantedBytes - What each store is asking for, in order.
98
+ * @param {number} allowanceBytes
99
+ * @returns {number[]} What each store may hold, in the same order.
100
+ */
101
+ export function divideAllowance(wantedBytes, allowanceBytes) {
102
+ const total = wantedBytes.reduce((sum, want) => sum + Math.max(0, want), 0);
103
+ if (total <= allowanceBytes || total === 0) {
104
+ return wantedBytes.map((want) => Math.max(0, want));
105
+ }
106
+ return wantedBytes.map((want) => Math.floor(allowanceBytes * (Math.max(0, want) / total)));
107
+ }
@@ -0,0 +1,365 @@
1
+ /**
2
+ * @file Where downloaded pieces live once memory cannot hold them.
3
+ *
4
+ * The second tier of the piece store, and — unlike what it replaces — an owner
5
+ * of what it takes: it knows how many bytes it holds, it is told how many it
6
+ * may hold, and when it is over that it gives disk back.
7
+ *
8
+ * WHAT IT REPLACED, because the difference is the whole of the design. `DiskTier`
9
+ * wrote every piece into ONE sparse file at `index * chunkLength` and answered
10
+ * `forget(index)` by dropping the number from a set. The bytes stayed: a sparse
11
+ * file's blocks are returned only by hole punching, which Node exposes no
12
+ * binding for, so nothing this process could do returned a single block before
13
+ * the whole file was removed. Measured 2026-08-31: a store holding 312-424 MB
14
+ * of pieces had written **14 400 MB** to that file in fifty minutes, and free
15
+ * space on the host fell by every megabyte of it until the session ended. On a
16
+ * Home Assistant install with a 32 GB card that is the card.
17
+ *
18
+ * A PIECE IS A FILE, and that is what makes the ceiling real. Removing a file
19
+ * returns exactly its blocks, needs no binding this runtime lacks, and makes
20
+ * the unit of eviction the same as the unit of storage — so the order pieces
21
+ * leave in is the order we choose rather than the order they happen to lie in.
22
+ * The read that the single file was chosen for is unaffected: it is still one
23
+ * `read` into a buffer the caller already owns, which is what the 22.08 ms →
24
+ * 7.63 ms measurement on the field host was about. What it adds is an `open`
25
+ * per read, tens of microseconds against those milliseconds.
26
+ *
27
+ * Nothing here decides what the allowance should be. It is told, because the
28
+ * disk is one and this store is not its only user — the segments an encoder
29
+ * produces are on it too — and a ceiling that one of two users sets for itself
30
+ * is not a ceiling.
31
+ */
32
+
33
+ import fs from "node:fs/promises";
34
+ import path from "node:path";
35
+
36
+ /**
37
+ * How a removal is asked for.
38
+ *
39
+ * Windows keeps a deleted file's name reserved until the last handle on it is
40
+ * closed, and answers `rm` of the name — or `rmdir` of the directory holding it
41
+ * — with EPERM until then. These are Node's own documented options for exactly
42
+ * that, not a wait invented here; on POSIX they never come into play.
43
+ */
44
+ const REMOVAL = { force: true, maxRetries: 10, retryDelay: 20 };
45
+
46
+ /**
47
+ * One torrent's pieces on disk.
48
+ *
49
+ * Pieces are numbered by the torrent, so a file is named by its number. The
50
+ * directory is the store: nothing else writes into it, and destroying the store
51
+ * removes it whole.
52
+ */
53
+ export class PieceDiskStore {
54
+ #directory;
55
+
56
+ #chunkLength;
57
+
58
+ /** Piece index → its length on disk. @type {Map<number, number>} */
59
+ #stored = new Map();
60
+
61
+ /** Piece index → when it was last written or read. @type {Map<number, number>} */
62
+ #touched = new Map();
63
+
64
+ /** Pieces being read right now, which eviction leaves alone. @type {Map<number, number>} */
65
+ #reading = new Map();
66
+
67
+ /** Removals still in flight, by piece. @type {Map<number, Promise<unknown>>} */
68
+ #removing = new Map();
69
+
70
+ /** What this store may hold, or null while nobody has said. @type {number | null} */
71
+ #allowanceBytes = null;
72
+
73
+ #evictions = 0;
74
+
75
+ #bytes = 0;
76
+
77
+ #now;
78
+
79
+ /**
80
+ * @param {object} params
81
+ * @param {string} params.directory - Where this torrent's pieces live.
82
+ * @param {string} params.name - A name unique to the torrent; it becomes the
83
+ * directory inside `directory`.
84
+ * @param {number} params.chunkLength - The torrent's piece length. Kept for
85
+ * the caller's arithmetic; a piece's own length is recorded as it is written,
86
+ * because the last piece of a torrent is shorter.
87
+ * @param {number | null} [params.allowanceBytes] - What it may hold. Null
88
+ * means nobody has said yet, and nothing is evicted until somebody does.
89
+ * @param {() => number} [params.now]
90
+ */
91
+ constructor({ directory, name, chunkLength, allowanceBytes = null, now = Date.now }) {
92
+ this.#directory = path.join(directory, name);
93
+ this.#chunkLength = chunkLength;
94
+ this.#allowanceBytes = Number.isFinite(allowanceBytes) && allowanceBytes >= 0 ? allowanceBytes : null;
95
+ this.#now = now;
96
+ }
97
+
98
+ /** Where this store's pieces live, for logging and cleanup. */
99
+ get path() {
100
+ return this.#directory;
101
+ }
102
+
103
+ /** How many pieces are on disk. */
104
+ get size() {
105
+ return this.#stored.size;
106
+ }
107
+
108
+ /** What those pieces weigh. */
109
+ get bytes() {
110
+ return this.#bytes;
111
+ }
112
+
113
+ /** What it may hold, or null while nobody has said. */
114
+ get allowanceBytes() {
115
+ return this.#allowanceBytes;
116
+ }
117
+
118
+ /**
119
+ * Say what it may hold from now on.
120
+ *
121
+ * Lowering it does not free anything by itself: what is already written stays
122
+ * until the next write needs room. A store that is over its allowance and
123
+ * never written to again is holding disk nobody has asked for, which is the
124
+ * same bargain memory makes.
125
+ *
126
+ * @param {number | null} bytes
127
+ * @returns {number | null} What it may hold now.
128
+ */
129
+ reviseAllowance(bytes) {
130
+ this.#allowanceBytes = Number.isFinite(bytes) && bytes >= 0 ? bytes : null;
131
+ return this.#allowanceBytes;
132
+ }
133
+
134
+ /**
135
+ * @param {number} index
136
+ * @returns {boolean}
137
+ */
138
+ has(index) {
139
+ return this.#stored.has(index);
140
+ }
141
+
142
+ /**
143
+ * Write a piece out, making room for it first.
144
+ *
145
+ * @param {number} index
146
+ * @param {Uint8Array} bytes
147
+ * @returns {Promise<void>}
148
+ */
149
+ async write(index, bytes) {
150
+ // A piece thrown away and wanted again before its file has gone. Windows
151
+ // holds a deleted-but-still-open file in a pending state and answers the
152
+ // next `open` of that name with EPERM, so writing it again has to wait for
153
+ // the removal to finish. On POSIX the wait costs a resolved promise.
154
+ await this.#removing.get(index);
155
+ await this.#ensureDirectory();
156
+ await this.#makeRoomFor(bytes.length, index);
157
+ await fs.writeFile(this.#pathOf(index), bytes);
158
+ if (!this.#stored.has(index)) {
159
+ this.#bytes += bytes.length;
160
+ } else {
161
+ this.#bytes += bytes.length - (this.#stored.get(index) ?? 0);
162
+ }
163
+ this.#stored.set(index, bytes.length);
164
+ this.#touched.set(index, this.#now());
165
+ }
166
+
167
+ /**
168
+ * Read a piece back into a buffer the caller already owns.
169
+ *
170
+ * @param {number} index
171
+ * @param {Uint8Array} target - Destination; its length is what gets read.
172
+ * @returns {Promise<number>} Bytes read.
173
+ */
174
+ async read(index, target) {
175
+ if (!this.#stored.has(index)) {
176
+ throw new Error(`Piece ${index} is not on disk.`);
177
+ }
178
+ // While this runs, eviction leaves the piece alone. Removing a file that is
179
+ // open is safe on POSIX and the read would finish — but the open itself
180
+ // happens below, and between the check above and that open a file removed
181
+ // is a read that fails for a piece the caller was told is there.
182
+ this.#reading.set(index, (this.#reading.get(index) ?? 0) + 1);
183
+ let handle = null;
184
+ try {
185
+ handle = await fs.open(this.#pathOf(index), "r");
186
+ const { bytesRead } = await handle.read(target, 0, target.length, 0);
187
+ this.#touched.set(index, this.#now());
188
+ return bytesRead;
189
+ } finally {
190
+ await handle?.close().catch(() => undefined);
191
+ const outstanding = (this.#reading.get(index) ?? 1) - 1;
192
+ if (outstanding > 0) {
193
+ this.#reading.set(index, outstanding);
194
+ } else {
195
+ this.#reading.delete(index);
196
+ }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Forget a piece and give its disk back.
202
+ *
203
+ * The removal itself is left to run: the caller's contract is synchronous —
204
+ * after this returns, the store no longer has the piece — and the blocks come
205
+ * back a moment later. A failure to remove leaves a file nobody will read;
206
+ * the directory goes whole when the store is destroyed.
207
+ *
208
+ * @param {number} index
209
+ * @returns {void}
210
+ */
211
+ forget(index) {
212
+ const length = this.#stored.get(index);
213
+ if (length === undefined) {
214
+ return;
215
+ }
216
+ this.#stored.delete(index);
217
+ this.#touched.delete(index);
218
+ this.#bytes -= length;
219
+ // Kept track of, because a removal still in flight holds the directory: on
220
+ // Windows `rmdir` refuses while any handle inside is open, so `destroy`
221
+ // waits for these before removing the directory. On Linux it would succeed
222
+ // and the removals would then fail silently against a directory that is
223
+ // gone — tidy either way, and correct on both.
224
+ const removal = fs.rm(this.#pathOf(index), REMOVAL)
225
+ .catch(() => undefined)
226
+ .finally(() => {
227
+ if (this.#removing.get(index) === removal) {
228
+ this.#removing.delete(index);
229
+ }
230
+ });
231
+ this.#removing.set(index, removal);
232
+ }
233
+
234
+ /**
235
+ * What it holds, what it may hold, and what it has had to throw away.
236
+ *
237
+ * @returns {{ pieces: number, bytes: number, allowanceBytes: number | null, evictions: number }}
238
+ */
239
+ stats() {
240
+ return {
241
+ pieces: this.#stored.size,
242
+ bytes: this.#bytes,
243
+ allowanceBytes: this.#allowanceBytes,
244
+ evictions: this.#evictions
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Close it, leaving its contents in place.
250
+ *
251
+ * There is no handle to close — a read opens and closes its own — so this
252
+ * exists for the caller's lifecycle and does nothing else.
253
+ *
254
+ * @returns {Promise<void>}
255
+ */
256
+ async close() {
257
+ // Nothing to release: a read opens and closes its own handle.
258
+ }
259
+
260
+ /**
261
+ * Close and remove everything.
262
+ *
263
+ * @returns {Promise<void>}
264
+ */
265
+ async destroy() {
266
+ await this.close();
267
+ await this.settled();
268
+ this.#stored.clear();
269
+ this.#touched.clear();
270
+ this.#bytes = 0;
271
+ await fs.rm(this.#directory, { ...REMOVAL, recursive: true });
272
+ }
273
+
274
+ /**
275
+ * Wait for every removal this store has started.
276
+ *
277
+ * Removing a piece answers at once and frees the disk a moment later; this is
278
+ * how a caller that needs the disk back NOW — a test, or `destroy` — waits for
279
+ * it without making `forget` asynchronous for everybody else.
280
+ *
281
+ * @returns {Promise<void>}
282
+ */
283
+ async settled() {
284
+ while (this.#removing.size > 0) {
285
+ await Promise.all([...this.#removing.values()]);
286
+ }
287
+ }
288
+
289
+ /**
290
+ * @param {number} index
291
+ * @returns {string}
292
+ */
293
+ #pathOf(index) {
294
+ return path.join(this.#directory, `${index}.piece`);
295
+ }
296
+
297
+ /**
298
+ * Make sure the directory is there, before every write.
299
+ *
300
+ * Deliberately not remembered. A remembered "it exists" is a statement about
301
+ * the past: this store's own `destroy` removes the directory, a startup sweep
302
+ * removes what a killed process left, and an operator clearing a full disk
303
+ * removes anything. Each of those turns the memory into a lie and every write
304
+ * after it into `ENOENT`. Creating a directory that already exists costs tens
305
+ * of microseconds against a write measured in milliseconds.
306
+ *
307
+ * @returns {Promise<void>}
308
+ */
309
+ async #ensureDirectory() {
310
+ await fs.mkdir(this.#directory, { recursive: true });
311
+ }
312
+
313
+ /**
314
+ * Throw away the least recently used pieces until one more will fit.
315
+ *
316
+ * Least recently used first, and for the reason the memory tier uses the same
317
+ * order: what nobody has read for the longest is what a viewer is least
318
+ * likely to want next. A piece being read now is never a victim, and neither
319
+ * is the piece about to be written.
320
+ *
321
+ * A piece thrown away is not lost, only un-had: the store answers `has` with
322
+ * false, the read that wanted it gets nothing, and the torrent fetches it
323
+ * again. That is the same bargain the memory tier makes when it spills.
324
+ *
325
+ * @param {number} incomingBytes
326
+ * @param {number} incomingIndex
327
+ * @returns {Promise<void>}
328
+ */
329
+ async #makeRoomFor(incomingBytes, incomingIndex) {
330
+ if (this.#allowanceBytes === null) {
331
+ return;
332
+ }
333
+ const already = this.#stored.get(incomingIndex) ?? 0;
334
+ while (this.#bytes - already + incomingBytes > this.#allowanceBytes) {
335
+ const victim = this.#leastRecentlyUsed(incomingIndex);
336
+ if (victim === null) {
337
+ // Everything left is either being read or is the piece coming in. The
338
+ // write goes ahead: refusing it would lose a piece the swarm has
339
+ // already paid for, and the next write finds the readers gone.
340
+ return;
341
+ }
342
+ this.forget(victim);
343
+ this.#evictions += 1;
344
+ }
345
+ }
346
+
347
+ /**
348
+ * @param {number} except
349
+ * @returns {number | null}
350
+ */
351
+ #leastRecentlyUsed(except) {
352
+ let victim = null;
353
+ let oldest = Number.POSITIVE_INFINITY;
354
+ for (const [index, at] of this.#touched) {
355
+ if (index === except || this.#reading.has(index)) {
356
+ continue;
357
+ }
358
+ if (at < oldest) {
359
+ oldest = at;
360
+ victim = index;
361
+ }
362
+ }
363
+ return victim;
364
+ }
365
+ }