@torrent-tv/proxy 2.80.0 → 2.80.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.
@@ -1,1512 +1,1531 @@
1
- /**
2
- * @file Torrent pieces in shared memory, with disk as the second tier.
3
- *
4
- * Replaces the chunk store WebTorrent would otherwise build for itself. Two
5
- * reasons, one forced and one chosen.
6
- *
7
- * **Forced.** WebTorrent's own piece cache hands out the buffer it keeps using
8
- * and slices again on the next read. The torrent client now runs on its own
9
- * thread, and moving a piece to the main thread by transferring ownership
10
- * detached the cache's memory: proxy 2.9.71-2.9.73 answered every read with an
11
- * empty body (`Stream ends prematurely at 0`) and the failure was invisible,
12
- * because the error never reached the reader. Owning the memory ourselves
13
- * removes the question of whose it was.
14
- *
15
- * **Chosen.** Memory this side of the thread boundary can be *shared* memory,
16
- * which the main thread reads without receiving bytes as a copy — see
17
- * {@link SharedPieceStore#locate}. Measured on the field host: a piece copy
18
- * costs 3.64 ms, a read from the page cache into a buffer we own 7.63 ms, and
19
- * re-downloading a piece from the swarm ~1430 ms. So memory first, disk under
20
- * it, and never the swarm twice.
21
- *
22
- * Per piece allocation: each resident piece owns its own `SharedArrayBuffer`.
23
- * Evicting a piece deletes its entry and the memory is reclaimable by GC.
24
- * `committed` therefore equals `resident`, not a high-water mark.
25
- *
26
- * **Room for a piece is an owned reservation, not a shared number.**
27
- * `#claimSlot` hands back a release the caller runs in a `finally`; nothing
28
- * else touches `#outstandingPieces`. It was a counter incremented in one
29
- * function and decremented in another, and every consequence of that was a
30
- * defect: a failure between the two lost a slot for the life of the process,
31
- * `put`'s error path guessed at the correction and could take back a
32
- * reservation belonging to a different claim, and one lost reservation made
33
- * the five-second "everything is pinned" error permanently unreachable, so a
34
- * read retried every 50 ms for ever without completing or failing. Read out of
35
- * the field failure of 2026-08-31 (`research/worker-heap-oom-2026-08-31.md`).
36
- *
37
- * What this deliberately does NOT do is manage the disk as a cache of its own.
38
- * Pieces evicted from memory are written once and read back on demand; the file
39
- * is discarded whole when the torrent goes away. libtorrent 2.0 and webtor's
40
- * seeder both concluded that a hand-rolled disk cache earns less than it costs,
41
- * and nothing here disagrees.
42
- */
43
-
44
- import os from "node:os";
45
- import { readFileSync } from "node:fs";
46
- import { PieceLru } from "./piece-lru.js";
47
- import { DiskTier } from "./disk-tier.js";
48
-
49
- /**
50
- * Live stores, so the worker can report on them.
51
- *
52
- * @type {Set<SharedPieceStore>}
53
- */
54
- const liveStores = new Set();
55
-
56
- export function collectStoreStats() {
57
- return [...liveStores].map((store) => store.stats());
58
- }
59
-
60
- export function findSharedStore(torrent) {
61
- let candidate = torrent?.store;
62
- for (let depth = 0; candidate && depth < 8; depth += 1) {
63
- if (candidate instanceof SharedPieceStore) {
64
- return candidate;
65
- }
66
- candidate = candidate.store;
67
- }
68
- return null;
69
- }
70
-
71
- /**
72
- * The largest fall in the machine's available memory that this process has
73
- * seen and did not cause itself.
74
- *
75
- * What has to be left for everything else on the machine. It cannot be a share
76
- * of what is free — a share is a number chosen out of nothing, which is what
77
- * `AVAILABLE_MEMORY_SHARE = 0.25`, `MIN_BUDGET_BYTES` and
78
- * `MEMORY_BUDGET_CEILING_BYTES` were until 2026-09-02, all three traceable to
79
- * one observation of one host on 2026-08-03. It is measured instead: between
80
- * two readings, how much available memory went away beyond what the stores
81
- * themselves took. On the field host that quantity is large — while the proxy
82
- * held 76-133 MB overnight the machine's available memory fell from 2378 MB to
83
- * 306 MB and came back — and on a quiet host it stays near zero, which is the
84
- * right answer there.
85
- *
86
- * Starts at zero: nothing is reserved until somebody else has been seen to
87
- * need it.
88
- */
89
- const otherDemand = { falls: [], lastAvailableBytes: 0, lastStoreBytes: 0 };
90
-
91
- /**
92
- * How many observations of other processes' demand are kept.
93
- *
94
- * A window rather than a high-water, and for the reason the block re-use gap is
95
- * one too: a single spike would otherwise stand for the life of the process and
96
- * squeeze the stores against something that happened once, hours ago.
97
- */
98
- const OTHER_DEMAND_SAMPLES = 60;
99
-
100
- /**
101
- * Note what the machine had, and how much of the change was not ours.
102
- *
103
- * @param {number} availableBytes
104
- * @param {number} storeBytes - What the live stores hold right now.
105
- * @returns {number} The reserve, in bytes.
106
- */
107
- export function noteMachineMemory(availableBytes, storeBytes) {
108
- if (otherDemand.lastAvailableBytes > 0) {
109
- const fell = otherDemand.lastAvailableBytes - availableBytes;
110
- const ours = storeBytes - otherDemand.lastStoreBytes;
111
- otherDemand.falls.push(Math.max(0, fell - ours));
112
- if (otherDemand.falls.length > OTHER_DEMAND_SAMPLES) {
113
- otherDemand.falls.shift();
114
- }
115
- }
116
- otherDemand.lastAvailableBytes = availableBytes;
117
- otherDemand.lastStoreBytes = storeBytes;
118
- return machineReserveBytes();
119
- }
120
-
121
- /** What has recently been observed to be needed by everything that is not us. */
122
- export function machineReserveBytes() {
123
- return otherDemand.falls.length === 0 ? 0 : Math.max(...otherDemand.falls);
124
- }
125
-
126
- /** Forget what other processes have needed. For tests, which share a module. */
127
- export function forgetMachineMemory() {
128
- otherDemand.falls = [];
129
- otherDemand.lastAvailableBytes = 0;
130
- otherDemand.lastStoreBytes = 0;
131
- }
132
-
133
- /**
134
- * How much memory the stores may hold between them.
135
- *
136
- * `MemAvailable` is what could be allocated on top of what is already held, so
137
- * the stores' own bytes are added back: the pair is the ceiling the stores
138
- * could reach. The reserve is what has been seen to be needed elsewhere.
139
- *
140
- * @param {number} availableBytes
141
- * @param {number} storeBytes
142
- * @param {number} reserveBytes
143
- * @returns {number}
144
- */
145
- export function machineAllowanceBytes(availableBytes, storeBytes, reserveBytes) {
146
- return Math.max(0, Math.max(availableBytes, 0) + Math.max(storeBytes, 0) - Math.max(reserveBytes, 0));
147
- }
148
-
149
- /**
150
- * Divide what the machine allows between the stores, by what each is asking
151
- * for.
152
- *
153
- * A store asks for the pieces its readers have declared. When everyone's ask
154
- * fits, everyone gets it and the machine's limit never binds — which is the
155
- * usual case, since two readers of one film declare 32-192 MB against gigabytes
156
- * of free memory. When the asks do not fit, each store is cut in proportion to
157
- * what it asked, so a store wanting little is not cut to make room for one
158
- * wanting much.
159
- *
160
- * @param {number[]} wantedBytes - What each store is asking for, in order.
161
- * @param {number} allowanceBytes
162
- * @returns {number[]} What each store may hold, in the same order.
163
- */
164
- export function divideAllowance(wantedBytes, allowanceBytes) {
165
- const total = wantedBytes.reduce((sum, want) => sum + Math.max(0, want), 0);
166
- if (total <= allowanceBytes || total === 0) {
167
- return wantedBytes.map((want) => Math.max(0, want));
168
- }
169
- return wantedBytes.map((want) => Math.floor(allowanceBytes * (Math.max(0, want) / total)));
170
- }
171
-
172
- export function reviseStoreBudgets() {
173
- const stores = [...liveStores];
174
- const held = stores.reduce((sum, store) => sum + store.residentBytes, 0);
175
- const available = availableMemorySync();
176
- const reserve = noteMachineMemory(available, held);
177
- const allowance = machineAllowanceBytes(available, held, reserve);
178
- const shares = divideAllowance(stores.map((store) => store.wantedBytes), allowance);
179
- const revised = [];
180
- for (const [position, store] of stores.entries()) {
181
- revised.push(store.reviseGrowthCeiling(shares[position]));
182
- }
183
- return revised;
184
- }
185
-
186
- function defaultMemoryBytes() {
187
- const stores = [...liveStores];
188
- const held = stores.reduce((sum, store) => sum + store.residentBytes, 0);
189
- const available = availableMemorySync();
190
- const allowance = machineAllowanceBytes(available, held, machineReserveBytes());
191
- // A store being created has no readers, so it has no demand to state and no
192
- // basis for asking for more or less than the others. It opens on an equal
193
- // share and the first revision — within a minute, and within seconds of a
194
- // read starting — replaces that with what its readers actually declare.
195
- // Deliberately not the whole allowance: on a machine with gigabytes free that
196
- // would let a torrent nobody is reading yet fill memory before the first
197
- // revision arrives.
198
- return Math.floor(allowance / (stores.length + 1));
199
- }
200
-
201
- function availableMemorySync() {
202
- try {
203
- const text = readFileSync("/proc/meminfo", "utf8");
204
- const match = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(text);
205
- if (match) {
206
- return Number(match[1]) * 1024;
207
- }
208
- } catch {
209
- }
210
- return os.freemem();
211
- }
212
-
213
- /**
214
- * How many blocks of piece memory this thread has let go of, and how many the
215
- * collector has actually taken back.
216
- *
217
- * Since the store keeps a pool, one block serves many pieces, so this counts
218
- * blocks and not pieces — and a healthy store allocates only as many as its
219
- * allowance permits, so both numbers are now small and nearly equal.
220
- *
221
- * The one reading that separates the two explanations of the 700 MB nobody can
222
- * account for (roadmap item 2, field 2026-08-31): if the two numbers track each
223
- * other, this code is holding nothing and whatever grows is below us, in the
224
- * allocator — on musl there is no `malloc_trim` and no way to ask. If the gap
225
- * widens, a reference of ours outlives the piece, and then a heap snapshot can
226
- * name the holder.
227
- *
228
- * What it does NOT prove: a `SharedArrayBuffer`'s memory is shared between the
229
- * isolates, so this thread's handle going means only that THIS thread let go.
230
- * The main thread counts its own (`torrent-worker/client.js`), and the pair is
231
- * what answers the question.
232
- */
233
- const released = { count: 0, collected: 0 };
234
- const collector = typeof FinalizationRegistry === "function"
235
- ? new FinalizationRegistry(() => {
236
- released.collected += 1;
237
- })
238
- : null;
239
-
240
- /**
241
- * What the collector has taken back against what was let go.
242
- *
243
- * @returns {{ released: number, collected: number }}
244
- */
245
- export function pieceBufferCollection() {
246
- return { released: released.count, collected: released.collected };
247
- }
248
-
249
- const MIN_RESIDENT_PIECES = 2;
250
- /**
251
- * How long a claim may go without ANYTHING moving before it gives up.
252
- *
253
- * Measured against progress, not against activity. The earlier rule skipped
254
- * this timer entirely while a spill was in flight or a reservation was held —
255
- * so one reservation that was never returned made the timer unreachable and a
256
- * read retried every 50 ms for the life of the process, never completing and
257
- * never failing (field 2026-08-31).
258
- */
259
- const PINNED_WAIT_MS = 5_000;
260
-
261
- /**
262
- * How many revival ages are kept for the median. A window, not a history: two
263
- * hundred covers several minutes of the busiest session measured (7575
264
- * revivals in 44 minutes) and costs two hundred numbers.
265
- */
266
- const REVIVAL_AGE_SAMPLES = 200;
267
-
268
- /**
269
- * How many block re-use gaps are kept. The same window as the revival ages, and
270
- * for the same reason: what is wanted is the rhythm of recent work, not a
271
- * history of it.
272
- */
273
- const REUSE_GAP_SAMPLES = 200;
274
-
275
- /** How many write durations are kept for the median. */
276
- const WRITE_DURATION_SAMPLES = 50;
277
- /** How many admission times are kept, and how far back they are counted. */
278
- const ARRIVAL_SAMPLES = 100;
279
- const ARRIVAL_WINDOW_MS = 10_000;
280
-
281
- /**
282
- * The middle value of a sample, or null when there is nothing to take a middle
283
- * of. Null rather than zero: no revivals and instant revivals are different
284
- * facts and must not print the same.
285
- *
286
- * @param {number[]} values
287
- * @returns {number | null}
288
- */
289
- function median(values) {
290
- if (values.length === 0) {
291
- return null;
292
- }
293
- const sorted = [...values].sort((left, right) => left - right);
294
- const middle = Math.floor(sorted.length / 2);
295
- return sorted.length % 2 === 0
296
- ? Math.round((sorted[middle - 1] + sorted[middle]) / 2)
297
- : sorted[middle];
298
- }
299
- const CLAIM_RETRY_MS = 50;
300
-
301
- export class SharedPieceStore {
302
- #chunkLength;
303
- #lastChunkLength;
304
- #lastChunkIndex;
305
- #growthCeiling;
306
- /** Piece index → SharedArrayBuffer of that piece */
307
- #buffers = new Map();
308
- /** @type {Map<number, Promise<void>>} */
309
- #evicting = new Map();
310
- /**
311
- * Slots claimed but not yet filled.
312
- *
313
- * Handed out by {@link SharedPieceStore##claimSlot} as a release function the
314
- * caller must call in a `finally`, never as a number one function increments
315
- * and another decrements. The counter used to be paired across
316
- * `#claimSlot`/`#registerPiece`, so any failure between the two lost a slot
317
- * for the life of the process, and `put`'s error path tried to correct that
318
- * by guessing — which could take back a reservation belonging to a different
319
- * claim and let the store admit past its allowance.
320
- */
321
- #outstandingPieces = 0;
322
- /** When something last actually moved: a piece admitted, spilled or unpinned. */
323
- #lastProgressAt = 0;
324
- #waiters = [];
325
- #lru;
326
- #disk;
327
- #closed = false;
328
- #name;
329
- #counters = {
330
- fromMemory: 0,
331
- fromDisk: 0,
332
- spills: 0,
333
- revivals: 0,
334
- blockedByPins: 0,
335
- waitedForPins: 0,
336
- evictedOnRevise: 0,
337
- spillFailures: 0,
338
- // Whether the store is doing its job or being asked to hold more than it
339
- // has room for. An eviction that had to take a piece a reader declared it
340
- // wants is the second, and it comes back from disk moments later
341
- // (roadmap item 9).
342
- evictedProtected: 0,
343
- evictedDistanceSum: 0,
344
- evictedWithDistance: 0,
345
- // Where an arriving piece went. A piece nobody has declared is being
346
- // downloaded ahead of every reader; putting it in memory pushes out one
347
- // that IS declared, which is then read back from disk moments later
348
- // (roadmap item 9).
349
- admittedInsideWindow: 0,
350
- admittedOutsideWindow: 0,
351
- admittedToDisk: 0,
352
- /** Blocks given back to the operating system. */
353
- blocksReleased: 0,
354
- /**
355
- * A block put back for re-use while a reader still held the piece. Zero by
356
- * construction — a pinned piece is never evicted, and a re-put of a pinned
357
- * one drops its block instead of recycling it. Counted because if it ever
358
- * stops being zero, a consumer is reading another piece's bytes, and that
359
- * is invisible from anywhere else.
360
- */
361
- returnedWhilePinned: 0,
362
- /** Spills that found the disk already holding identical bytes. */
363
- spillsSkipped: 0,
364
- /**
365
- * Blocks a second registration of the same piece displaced. Expected to be
366
- * small and non-zero: two callers racing for one piece is ordinary. What is
367
- * NOT ordinary is the block going missing when it happens, which is what
368
- * killed the process on 2026-09-02.
369
- */
370
- blocksDisplaced: 0,
371
- /** Admissions that waited for the disk instead of evicting another piece. */
372
- waitedForDisk: 0,
373
- /**
374
- * Admissions that grew memory because the disk had stopped answering.
375
- * Non-zero means the store exceeded its allowance on purpose, and by how
376
- * many pieces.
377
- */
378
- grewWaitingForDisk: 0,
379
- /**
380
- * Times a block was wanted, none was free, and the pool was already at its
381
- * ceiling. Zero by construction — a block is only taken after a slot has
382
- * been claimed, and slots are what the ceiling counts — so a number here
383
- * means the two have come apart and the pool is growing past its allowance.
384
- */
385
- blocksBeyondCeiling: 0
386
- };
387
- /**
388
- * Blocks that hold no piece, most recently freed last.
389
- *
390
- * A block is one piece's worth of memory. Allocating a new one for every
391
- * piece meant 7575 allocations of 4 MiB in 44 minutes on 2026-09-02, each
392
- * released only when the collector got to it — which is why the process held
393
- * 1.86 GB while its own accounting said 352 MB. Blocks are taken from here
394
- * and put back here instead (roadmap item 2).
395
- *
396
- * @type {{ buffer: SharedArrayBuffer, freedAt: number }[]}
397
- */
398
- #freeBlocks = [];
399
- /** Blocks that exist at all: free plus holding a piece. */
400
- #blocksAllocated = 0;
401
- /** Whether a reader has ever declared a window here. See `wantedBytes`. */
402
- #everHadReader = false;
403
- /** Whether the last revision had to exceed the machine's share. */
404
- #beyondTheMachine = false;
405
- /**
406
- * How long a block sat free before it was taken again, in milliseconds.
407
- * Bounded, because what is wanted is the longest gap of RECENT work: an
408
- * all-time maximum would be raised by one long pause and then never let a
409
- * block go again.
410
- *
411
- * @type {number[]}
412
- */
413
- #reuseGaps = [];
414
- /**
415
- * How long recent writes to disk took, in milliseconds, and when pieces were
416
- * admitted. Together they say how much room the store needs beyond what the
417
- * readers ask for: while one write is finishing, more pieces arrive, and each
418
- * needs somewhere to go. Without that room every arrival evicts something,
419
- * which is what produced 233 evictions against 119 completed writes in a
420
- * minute on 2026-09-02.
421
- *
422
- * @type {number[]}
423
- */
424
- #writeDurations = [];
425
- /** When the last few pieces were admitted, for the arrival rate. */
426
- #admittedAt = [];
427
- /** Piece index → when it was written out, for the age it comes back at. */
428
- #spilledAt = new Map();
429
- /**
430
- * Ages, in milliseconds, of the last revivals — bounded, because the figure
431
- * wanted is a median and not a history. A piece that comes back seconds
432
- * after it left should not have left.
433
- *
434
- * @type {number[]}
435
- */
436
- #revivalAges = [];
437
-
438
- constructor(chunkLength, options = {}) {
439
- if (!Number.isInteger(chunkLength) || chunkLength < 1) {
440
- throw new Error(`Chunk length must be a positive integer, got ${chunkLength}.`);
441
- }
442
- this.#chunkLength = chunkLength;
443
-
444
- const totalLength = Number.isFinite(options.length) ? options.length : 0;
445
- this.#lastChunkIndex = totalLength > 0 ? Math.ceil(totalLength / chunkLength) - 1 : -1;
446
- const remainder = totalLength % chunkLength;
447
- this.#lastChunkLength = remainder === 0 ? chunkLength : remainder;
448
-
449
- const memoryBytes = Number.isFinite(options.memoryBytes) && options.memoryBytes > 0
450
- ? options.memoryBytes
451
- : defaultMemoryBytes();
452
- // Only where this store STARTS. It is not kept, so it cannot come back as a
453
- // cap on the revision the way `#capacity` did.
454
- const openingCeiling = Math.max(MIN_RESIDENT_PIECES, Math.floor(memoryBytes / chunkLength));
455
- this.#growthCeiling = openingCeiling;
456
- this.#lru = new PieceLru(openingCeiling);
457
- this.#name = options.name ?? "pieces";
458
- // `options.disk` exists so a test can hold a write open or make one fail on
459
- // purpose. Four of the defects fixed here live in what happens when the
460
- // disk tier does not answer immediately or at all, and none of them is
461
- // reachable from outside without saying so.
462
- this.#disk = options.disk ?? new DiskTier({
463
- directory: options.path ?? ".",
464
- name: `${this.#name}.pieces`,
465
- chunkLength
466
- });
467
- liveStores.add(this);
468
- }
469
-
470
- stats() {
471
- const resident = this.#buffers.size;
472
- const residentBytes = resident * this.#chunkLength;
473
- // Last piece may be short but stats historically use chunkLength.
474
- return {
475
- name: this.#name,
476
- resident,
477
- capacity: this.#growthCeiling,
478
- residentBytes,
479
- allocatedSlots: this.#blocksAllocated,
480
- // What the process HOLDS, which with a pool is the blocks that exist —
481
- // not the pieces in them. Holding and using are different quantities and
482
- // the difference is the point of the reading.
483
- committedBytes: this.#blocksAllocated * this.#chunkLength,
484
- budgetBytes: this.#growthCeiling * this.#chunkLength,
485
- pinned: this.#lru.pinnedCount,
486
- // Slots claimed and not yet filled. Reported because a reservation that
487
- // is never returned is invisible until the store cannot admit anything,
488
- // and by then the reason is long gone. At rest this is zero.
489
- outstanding: this.#outstandingPieces,
490
- spilled: this.#disk.size,
491
- spilledBytes: this.#disk.size * this.#chunkLength,
492
- // What the readers between them are asking this store to keep, against
493
- // what it may hold. A union wider than the capacity cannot be held
494
- // however the eviction is ordered, and that is the difference between a
495
- // policy to fix and arithmetic to accept (roadmap item 9).
496
- demand: this.#lru.demand(),
497
- // What the process actually holds for this store, which is not the same
498
- // as what it is using: blocks are kept for re-use. The difference is the
499
- // spare, and it is the whole of the question whether consumption only
500
- // grows (roadmap item 2).
501
- blocksAllocated: this.#blocksAllocated,
502
- blocksFree: this.#freeBlocks.length,
503
- blocksDisplaced: this.#counters.blocksDisplaced,
504
- blocksInUse: this.#blocksInUse(),
505
- blocksInFlight: this.#blocksInFlight(),
506
- blocksBeyondCeiling: this.#counters.blocksBeyondCeiling,
507
- blockBytes: this.#blocksAllocated * this.#chunkLength,
508
- reuseGapMs: this.#reuseGapCeilingMs(),
509
- revivalAgeMedianMs: median(this.#revivalAges),
510
- revivalAgeSamples: this.#revivalAges.length,
511
- revivedWithinFiveSeconds: this.#revivalAges.filter((age) => age <= 5_000).length,
512
- ...this.#counters
513
- };
514
- }
515
-
516
- /**
517
- * Whether the machine's share of memory is smaller than one reader's window.
518
- *
519
- * The store holds the window anyway — refusing would leave the read it is
520
- * serving unable to finish, which is worse — but it is the honest measure of
521
- * "this machine cannot take any more", and it is measured rather than
522
- * guessed: it is the last revision's own comparison of what the machine
523
- * allowed against what the widest reader declared.
524
- */
525
- get isBeyondTheMachine() {
526
- return this.#beyondTheMachine;
527
- }
528
-
529
- /** What this store holds right now, in bytes. */
530
- get residentBytes() {
531
- return this.#buffers.size * this.#chunkLength;
532
- }
533
-
534
- /**
535
- * What this store is asking to be allowed to hold, in bytes.
536
- *
537
- * The union of its readers' declared windows — what they have said they will
538
- * need — never below the widest single window, because a store that cannot
539
- * hold one reader's window cannot complete that reader's read at all: every
540
- * resident piece ends up pinned, the read returns zero bytes and ffmpeg takes
541
- * that for the end of the file (field 2026-08-15, roadmap item 9).
542
- *
543
- * With no reader declaring anything there is no demand to speak of, so the
544
- * store asks for what the machine allows and the first revision after a read
545
- * begins brings it down to what that read needs.
546
- */
547
- get wantedBytes() {
548
- const demand = this.#lru.demand();
549
- if (demand.readers > 0) {
550
- this.#everHadReader = true;
551
- const pieces = Math.max(MIN_RESIDENT_PIECES, demand.unionPieces, demand.widestPieces);
552
- // Plus room to absorb what arrives while a write is finishing. Asking for
553
- // exactly what the readers want leaves no free place ever, so every
554
- // arrival evicts one of them — measured 2026-09-02: `6 reader(s) want 23
555
- // piece(s) of 23 the store may hold`, and 233 evictions in the minute
556
- // that followed.
557
- return (pieces + this.slackPieces()) * this.#chunkLength;
558
- }
559
- // Readers that have GONE are not the same as readers that have not arrived.
560
- // A store whose readers ended has nothing to hold pieces for — its torrent
561
- // sits until the pool's idle timer removes it, which needs a refcount of
562
- // zero and can be a quarter of an hour away — so it asks for nothing and
563
- // its memory goes back to the machine now. A store that has never had a
564
- // reader is being filled for one that is on its way, and asks for what it
565
- // was opened with until the first read says what it needs.
566
- return this.#everHadReader
567
- ? (MIN_RESIDENT_PIECES + this.slackPieces()) * this.#chunkLength
568
- : this.#growthCeiling * this.#chunkLength;
569
- }
570
-
571
- reviseGrowthCeiling(allowedBytes) {
572
- // No cap at what the machine could spare when this store was CREATED.
573
- // `#capacity` was computed once in the constructor and used as an upper
574
- // bound here, so the allowance could only ever fall: a torrent opened while
575
- // the machine was full kept a small allowance for its whole life, however
576
- // much memory was freed afterwards (roadmap item 2, 2026-09-02).
577
- const wanted = Math.floor(Number(allowedBytes) / this.#chunkLength);
578
- // Never below one reader's whole window while a reader exists, even when
579
- // the machine's share says less. A store that cannot hold the window of the
580
- // read it is serving cannot complete that read at all: every resident piece
581
- // ends up pinned, the read returns zero bytes and ffmpeg takes that for the
582
- // end of the file, which killed every encoder on that file in the field on
583
- // 2026-08-15. Exceeding the share is the lesser failure, and the line below
584
- // says when it happens.
585
- const demand = this.#lru.demand();
586
- this.#growthCeiling = Math.max(
587
- MIN_RESIDENT_PIECES,
588
- demand.readers > 0 ? demand.widestPieces : MIN_RESIDENT_PIECES,
589
- Number.isFinite(wanted) ? wanted : MIN_RESIDENT_PIECES
590
- );
591
- const belowAWindow = demand.readers > 0
592
- && Number.isFinite(wanted)
593
- && wanted < demand.widestPieces;
594
- this.#beyondTheMachine = belowAWindow;
595
- // The LRU is told too. It was constructed with the store's original
596
- // capacity and never revised, so `isFull()` answered against a number that
597
- // had not been the limit for some time — dormant only because nothing calls
598
- // it, which is a trap for whoever calls it next.
599
- this.#lru.setCapacity(this.#growthCeiling);
600
- // With per-piece buffers memory CAN be given back immediately, unlike the
601
- // old growable pool. Eagerly evict excess to honour the new ceiling.
602
- let evicted = 0;
603
- while (this.#buffers.size > this.#growthCeiling) {
604
- const { index: victim, protectionYielded, distance } = this.#lru.evictionChoice();
605
- if (victim === null) {
606
- break;
607
- }
608
- const victimBuffer = this.#buffers.get(victim);
609
- if (victimBuffer === undefined) {
610
- this.#lru.remove(victim);
611
- continue;
612
- }
613
- this.#buffers.delete(victim);
614
- this.#lru.remove(victim);
615
- evicted += 1;
616
- this.#counters.evictedOnRevise += 1;
617
- this.#noteEviction(protectionYielded, distance);
618
- // Nobody awaits this spill, so its failure has to end here. Rethrowing
619
- // made it an unhandled rejection, and an unhandled rejection in the
620
- // torrent worker ends the thread — a second way to lose the torrent
621
- // client, on top of the one that already loses it.
622
- void this.#spill(victim, victimBuffer).catch(() => {
623
- this.#counters.spillFailures += 1;
624
- });
625
- }
626
- // Blocks the store is no longer using and has waited long enough to give
627
- // up. The allowance falling is the moment to ask, because that is when the
628
- // machine has been shown to need the memory.
629
- const releasedBlocks = this.sweepFreeBlocks();
630
- return {
631
- name: this.#name,
632
- ceilingBytes: this.#growthCeiling * this.#chunkLength,
633
- committedBytes: this.#blocksAllocated * this.#chunkLength,
634
- evicted,
635
- releasedBlocks,
636
- belowAWindow
637
- };
638
- }
639
-
640
- get chunkLength() {
641
- return this.#chunkLength;
642
- }
643
-
644
- get capacity() {
645
- return this.#growthCeiling;
646
- }
647
-
648
- get residentCount() {
649
- return this.#buffers.size;
650
- }
651
-
652
- get spilledCount() {
653
- return this.#disk.size;
654
- }
655
-
656
- #lengthOf(index) {
657
- return index === this.#lastChunkIndex ? this.#lastChunkLength : this.#chunkLength;
658
- }
659
-
660
- /**
661
- * Where a resident piece sits, or `null` if not resident.
662
- * Returns the piece's own SharedArrayBuffer and the intra-piece range.
663
- * @param {number} index
664
- * @returns {{ buffer: SharedArrayBuffer, offset: number, length: number } | null}
665
- */
666
- locate(index) {
667
- const buffer = this.#buffers.get(index);
668
- if (buffer === undefined) {
669
- return null;
670
- }
671
- return { buffer, offset: 0, length: this.#lengthOf(index) };
672
- }
673
-
674
- /**
675
- * Direct access to a piece's buffer for zero-copy consumers.
676
- * @param {number} index
677
- * @returns {SharedArrayBuffer | undefined}
678
- */
679
- getPieceBuffer(index) {
680
- return this.#buffers.get(index);
681
- }
682
-
683
- pin(index) {
684
- this.#lru.pin(index);
685
- }
686
-
687
- unpin(index) {
688
- this.#lru.unpin(index);
689
- this.#noteProgress();
690
- }
691
-
692
- /**
693
- * Reserve room for one piece.
694
- *
695
- * @returns {Promise<() => void>} The release, which the caller MUST call in a
696
- * `finally`. Calling it twice is harmless.
697
- */
698
- async #claimSlot() {
699
- // How long THIS claim has been trying, kept here and not on the store.
700
- // It was a field, `#pinnedWaitStartedAt`, shared by the two waits inside
701
- // `#claimSlotOnce` — the one for the disk and the one for a piece that may
702
- // be evicted — and each of them zeroed it on giving up, which restarted the
703
- // other's clock. Measured 2026-09-03: the claim cycled for ever, five
704
- // seconds per side, `grewWaitingForDisk` and `waitedForPins` both climbing
705
- // once every five seconds while `blockedByPins` stayed at 0 — the refusal
706
- // was unreachable. A claim's patience belongs to the claim; with several
707
- // claimants a shared field is wrong anyway, since one caller giving up
708
- // would reset the wait of every other.
709
- const waitingSince = Date.now();
710
- for (;;) {
711
- if (this.#closed) {
712
- throw new Error("Piece store is closed.");
713
- }
714
- const ok = await this.#claimSlotOnce(waitingSince);
715
- if (ok) {
716
- let released = false;
717
- return () => {
718
- if (released) {
719
- return;
720
- }
721
- released = true;
722
- this.#outstandingPieces -= 1;
723
- this.#noteProgress();
724
- };
725
- }
726
- await this.#waitForSlot();
727
- }
728
- }
729
-
730
- /**
731
- * Sleep until something moves, or until the retry interval, whichever first.
732
- *
733
- * One handler, idempotent, and its timer is cleared when it is woken. The
734
- * earlier version attached a fresh pair of handlers to EVERY pending spill on
735
- * every attempt and left a timer running each time, so a claim that could not
736
- * be satisfied allocated in proportion to attempts times pending spills. A
737
- * settling spill now wakes the store itself, which is where that belongs.
738
- *
739
- * @returns {Promise<void>}
740
- */
741
- #waitForSlot() {
742
- return new Promise((resolve) => {
743
- let settled = false;
744
- /** @type {ReturnType<typeof setTimeout> | null} */
745
- let retry = null;
746
- const finish = () => {
747
- if (settled) {
748
- return;
749
- }
750
- settled = true;
751
- if (retry !== null) {
752
- clearTimeout(retry);
753
- }
754
- resolve();
755
- };
756
- this.#waiters.push(finish);
757
- retry = setTimeout(finish, CLAIM_RETRY_MS);
758
- retry.unref?.();
759
- });
760
- }
761
-
762
- #registerPiece(index, buffer) {
763
- // A piece may already be here. Both paths that register one look first and
764
- // then await — `put` waits for a slot, `#revive` waits for the disk — and
765
- // in that gap another caller can register the same index. Overwriting the
766
- // entry used to drop the previous block on the floor: its memory was not
767
- // returned to the pool and the pool's own count was never decremented, so
768
- // the count climbed past the ceiling for ever and the pool degenerated into
769
- // allocating a fresh block per piece. Field 2026-09-02: a store holding
770
- // THREE pieces reported 812 MB committed against 68 MB allowed, 739 blocks
771
- // allocated and 676 still alive, and the process was killed at 4.37 GB.
772
- const displaced = this.#buffers.get(index);
773
- this.#buffers.set(index, buffer);
774
- if (displaced !== undefined && displaced !== buffer) {
775
- this.#counters.blocksDisplaced += 1;
776
- this.#returnBlock(displaced);
777
- }
778
- this.#lru.touch(index);
779
- this.#noteProgress();
780
- }
781
-
782
- /**
783
- * Write a piece out and account for it, from the one place that does it.
784
- *
785
- * @param {number} index
786
- * @param {SharedArrayBuffer} buffer
787
- * @returns {Promise<void>}
788
- */
789
- #spill(index, buffer) {
790
- // The disk may already hold these very bytes. `#revive` reads a piece back
791
- // into memory and leaves the copy on disk, and only `put` removes it — so a
792
- // piece that was revived and not re-put is identical to what is already
793
- // written, and writing it again is work for nothing. There were 7575
794
- // revivals in one session on 2026-09-02, and every later eviction of one of
795
- // them wrote a second time (roadmap item 66: 14.4 GB written in a single
796
- // viewing).
797
- if (this.#disk.has(index)) {
798
- this.#counters.spills += 1;
799
- this.#counters.spillsSkipped += 1;
800
- this.#spilledAt.set(index, Date.now());
801
- this.#returnBlock(buffer);
802
- this.#noteProgress();
803
- return Promise.resolve();
804
- }
805
-
806
- const bytes = Buffer.from(buffer, 0, this.#lengthOf(index));
807
- const startedAt = Date.now();
808
- const spill = this.#disk.write(index, bytes).then(
809
- () => {
810
- this.#noteWriteDuration(Date.now() - startedAt);
811
- this.#counters.spills += 1;
812
- this.#spilledAt.set(index, Date.now());
813
- this.#evicting.delete(index);
814
- // Only now. The write reads out of this block, so a block handed to
815
- // another piece before the write finished would put that piece's bytes
816
- // into this piece's place in the file.
817
- this.#returnBlock(buffer);
818
- this.#noteProgress();
819
- },
820
- (error) => {
821
- this.#evicting.delete(index);
822
- // The block is no longer holding anything either way; keeping it out of
823
- // the pool because the write failed would lose it for good.
824
- this.#returnBlock(buffer);
825
- this.#noteProgress();
826
- throw error;
827
- }
828
- );
829
- this.#evicting.set(index, spill);
830
- return spill;
831
- }
832
-
833
- /** Something actually moved: wake whoever is waiting and restart the clock. */
834
- #noteProgress() {
835
- this.#lastProgressAt = Date.now();
836
- this.#wake();
837
- }
838
-
839
- /**
840
- * Record how long one write to disk took.
841
- *
842
- * @param {number} durationMs
843
- * @returns {void}
844
- */
845
- #noteWriteDuration(durationMs) {
846
- this.#writeDurations.push(Math.max(0, durationMs));
847
- if (this.#writeDurations.length > WRITE_DURATION_SAMPLES) {
848
- this.#writeDurations.shift();
849
- }
850
- }
851
-
852
- /** Record that a piece arrived, for the arrival rate. */
853
- #noteArrival() {
854
- const now = Date.now();
855
- this.#admittedAt.push(now);
856
- while (this.#admittedAt.length > ARRIVAL_SAMPLES
857
- || (this.#admittedAt.length > 0 && now - this.#admittedAt[0] > ARRIVAL_WINDOW_MS)) {
858
- this.#admittedAt.shift();
859
- }
860
- }
861
-
862
- /**
863
- * How many pieces the store needs room for beyond what the readers ask for.
864
- *
865
- * Measured, not chosen: the pieces that arrive while one write to disk is
866
- * finishing. Without this room every arrival must evict something, and each
867
- * eviction holds its block until its write completes — so a disk slower than
868
- * the swarm turns every admission into one more block held. On 2026-09-02
869
- * that was 233 evictions against 119 completed writes in a minute, and 203
870
- * blocks held with three pieces resident.
871
- *
872
- * Zero until both quantities have been seen, because a slack invented before
873
- * anything is measured is a chosen number, and this store has been bitten by
874
- * those.
875
- *
876
- * @returns {number} Pieces.
877
- */
878
- slackPieces() {
879
- if (this.#writeDurations.length === 0 || this.#admittedAt.length < 2) {
880
- return 0;
881
- }
882
- const sorted = [...this.#writeDurations].sort((left, right) => left - right);
883
- const writeMs = sorted[Math.floor(sorted.length / 2)];
884
- const spanMs = this.#admittedAt[this.#admittedAt.length - 1] - this.#admittedAt[0];
885
- if (!(spanMs > 0)) {
886
- return 0;
887
- }
888
- const perMs = (this.#admittedAt.length - 1) / spanMs;
889
- return Math.ceil(perMs * writeMs);
890
- }
891
-
892
- /**
893
- * Blocks that are not free: resident pieces, blocks being written out, and
894
- * blocks taken but not yet registered.
895
- *
896
- * This is what the ceiling has to bound, and until 2026-09-02 it bounded
897
- * resident pieces instead. The difference is exactly the memory that goes
898
- * missing from the count: a piece being spilled leaves `#buffers` the moment
899
- * the eviction begins, while its block stays held until the write it feeds
900
- * has finished.
901
- *
902
- * @returns {number}
903
- */
904
- #blocksInUse() {
905
- return this.#blocksAllocated - this.#freeBlocks.length;
906
- }
907
-
908
- /**
909
- * Blocks held by writes that have not finished.
910
- *
911
- * @returns {number}
912
- */
913
- #blocksInFlight() {
914
- return Math.max(0, this.#blocksInUse() - this.#buffers.size);
915
- }
916
-
917
- /**
918
- * Whether admitting one more piece would need something evicted first.
919
- *
920
- * Reservations count: a slot claimed and not yet filled is as taken as a
921
- * resident piece.
922
- *
923
- * @returns {boolean}
924
- */
925
- #isFullNow() {
926
- return this.#blocksInUse() + this.#outstandingPieces >= this.#growthCeiling;
927
- }
928
-
929
- /**
930
- * Write an arriving piece straight to disk, without it ever occupying memory.
931
- *
932
- * Registered in `#evicting` like a spill, so a `get` for this index waits for
933
- * the write instead of finding the piece on neither tier. Deliberately NOT
934
- * recorded in `#spilledAt`: that clock measures how long an EVICTED piece
935
- * stayed away, and a piece that was never resident has no such age.
936
- *
937
- * @param {number} index
938
- * @param {Uint8Array} bytes
939
- * @returns {Promise<void>}
940
- */
941
- #writeThrough(index, bytes) {
942
- // Copied, not viewed. `DiskTier.write` opens the file before it reads the
943
- // bytes, so a view onto the caller's buffer could be written to in between
944
- // and the file would get the wrong data. The spill path may pass a view
945
- // because that memory is ours; this buffer belongs to the torrent client.
946
- // It costs nothing extra: the piece was being copied into a shared buffer
947
- // on this path before, and now it is copied here instead.
948
- const copy = Buffer.from(bytes.subarray(0, Math.min(bytes.length, this.#lengthOf(index))));
949
- const write = this.#disk.write(index, copy).then(
950
- () => {
951
- this.#evicting.delete(index);
952
- this.#noteProgress();
953
- },
954
- (error) => {
955
- this.#evicting.delete(index);
956
- this.#noteProgress();
957
- throw error;
958
- }
959
- );
960
- this.#evicting.set(index, write);
961
- return write;
962
- }
963
-
964
- /**
965
- * Record how long a piece stayed on disk before it was wanted again.
966
- *
967
- * A piece that comes back seconds after it left was evicted from a working
968
- * set that does not fit, and the write and the read were both waste. Kept as
969
- * a bounded window of ages because the figure wanted is a median, not a
970
- * history.
971
- *
972
- * @param {number} index
973
- * @returns {void}
974
- */
975
- #noteRevival(index) {
976
- const spilledAt = this.#spilledAt.get(index);
977
- if (spilledAt === undefined) {
978
- return;
979
- }
980
- this.#spilledAt.delete(index);
981
- this.#revivalAges.push(Date.now() - spilledAt);
982
- if (this.#revivalAges.length > REVIVAL_AGE_SAMPLES) {
983
- this.#revivalAges.shift();
984
- }
985
- }
986
-
987
- /**
988
- * Record what an eviction had to take.
989
- *
990
- * @param {boolean} protectionYielded - The victim was inside a window a
991
- * reader had declared, and was taken anyway because nothing else was free.
992
- * @param {number} distance - Pieces from the nearest declared window, -1 when
993
- * no reader declared one.
994
- * @returns {void}
995
- */
996
- #noteEviction(protectionYielded, distance) {
997
- if (protectionYielded) {
998
- this.#counters.evictedProtected += 1;
999
- }
1000
- if (distance >= 0) {
1001
- this.#counters.evictedDistanceSum += distance;
1002
- this.#counters.evictedWithDistance += 1;
1003
- }
1004
- }
1005
-
1006
- #wake() {
1007
- const waiting = this.#waiters;
1008
- this.#waiters = [];
1009
- for (const resolve of waiting) {
1010
- resolve();
1011
- }
1012
- }
1013
-
1014
- /**
1015
- * One attempt at a reservation.
1016
- *
1017
- * @param {number} waitingSince - When the claim this attempt belongs to began
1018
- * trying. Both waits below are measured from the later of it and the last
1019
- * time the store moved, so neither can restart the other's clock — see
1020
- * `#claimSlot`.
1021
- * @returns {Promise<boolean>} Whether a slot was reserved.
1022
- */
1023
- async #claimSlotOnce(waitingSince) {
1024
- // Reserve before suspension so concurrent callers see the reservation.
1025
- if (this.#blocksInUse() + this.#outstandingPieces < this.#growthCeiling) {
1026
- this.#outstandingPieces += 1;
1027
- return true;
1028
- }
1029
- const stillFor = () => Date.now() - Math.max(waitingSince, this.#lastProgressAt);
1030
-
1031
- // Full, and evicting would make it worse rather than better. A piece being
1032
- // written out has already left `#buffers` while its block is still held —
1033
- // the write reads from that block — so evicting another one converts a
1034
- // resident block into an in-flight block and takes a fresh block for the
1035
- // arrival: the memory in use goes UP by one per admission for as long as
1036
- // the disk is behind. Field 2026-09-02: 233 evictions against 119 completed
1037
- // writes in a minute, 203 blocks held with three pieces resident, and the
1038
- // process killed at 4.37 GB.
1039
- //
1040
- // So when the disk is what the store is waiting for, it waits. A completing
1041
- // write calls `#noteProgress`, which wakes whoever is here.
1042
- if (this.#blocksInFlight() > 0 && this.#blocksInUse() >= this.#growthCeiling) {
1043
- if (stillFor() < PINNED_WAIT_MS) {
1044
- this.#counters.waitedForDisk += 1;
1045
- return false;
1046
- }
1047
- // The disk has stopped answering. Falling through to eviction is the
1048
- // lesser failure: it grows memory, and the line above says by how much,
1049
- // where refusing would fail the read outright. The clock is NOT restarted
1050
- // here: the wait that follows asks the same question of the same claim,
1051
- // and zeroing it was half of the loop described in `#claimSlot`.
1052
- this.#counters.grewWaitingForDisk += 1;
1053
- }
1054
-
1055
- const { index: victim, protectionYielded, distance } = this.#lru.evictionChoice();
1056
- if (victim === null) {
1057
- // Nothing may leave. Wait while the store is still MOVING — a spill
1058
- // completing, a piece admitted, a pin released — and give up when it has
1059
- // not moved for PINNED_WAIT_MS, whatever is nominally in flight. The old
1060
- // rule asked whether anything was in flight rather than whether anything
1061
- // had happened, which is why one lost reservation could hold a read here
1062
- // for ever.
1063
- if (stillFor() < PINNED_WAIT_MS) {
1064
- this.#counters.waitedForPins += 1;
1065
- return false;
1066
- }
1067
- this.#counters.blockedByPins += 1;
1068
- throw new Error(
1069
- `Every resident piece is pinned and nothing moved for ${PINNED_WAIT_MS}ms; no slot can be freed.`
1070
- );
1071
- }
1072
-
1073
- const victimBuffer = this.#buffers.get(victim);
1074
- if (victimBuffer === undefined) {
1075
- // Should not happen: LRU says resident but buffer missing.
1076
- this.#lru.remove(victim);
1077
- return false;
1078
- }
1079
-
1080
- // Claim atomically before await.
1081
- this.#buffers.delete(victim);
1082
- this.#lru.remove(victim);
1083
- this.#outstandingPieces += 1;
1084
- this.#noteEviction(protectionYielded, distance);
1085
-
1086
- try {
1087
- await this.#spill(victim, victimBuffer);
1088
- } catch (error) {
1089
- // The caller never received a release for this reservation, so it is
1090
- // given back here rather than left outstanding for ever.
1091
- this.#outstandingPieces -= 1;
1092
- this.#noteProgress();
1093
- throw error;
1094
- }
1095
- // Outstanding stays +1 for the caller; the slot for the new piece is now free.
1096
- return true;
1097
- }
1098
-
1099
- /**
1100
- * Bring a spilled piece back into memory, once, however many callers ask.
1101
- *
1102
- * @param {number} index
1103
- * @returns {Promise<SharedArrayBuffer | null>} `null` when the piece is on
1104
- * neither tier.
1105
- */
1106
- async #revive(index) {
1107
- const spill = this.#evicting.get(index);
1108
- if (spill) {
1109
- await spill.catch(() => undefined);
1110
- }
1111
-
1112
- if (!this.#disk.has(index)) {
1113
- return null;
1114
- }
1115
-
1116
- const release = await this.#claimSlot();
1117
- try {
1118
- // Another caller may have brought it back while this one waited for a
1119
- // slot. Registering a second buffer for the same piece would leave
1120
- // whoever holds the first reading memory nothing evicts.
1121
- const already = this.#buffers.get(index);
1122
- if (already !== undefined) {
1123
- this.#lru.touch(index);
1124
- this.#counters.fromMemory += 1;
1125
- return already;
1126
- }
1127
- const target = this.#takeBlock();
1128
- try {
1129
- // Only this piece's own length: the block is a full piece long and the
1130
- // last piece of a file is shorter, so reading the whole block would ask
1131
- // the file for bytes past its end.
1132
- await this.#disk.read(index, Buffer.from(target, 0, this.#lengthOf(index)));
1133
- } catch (error) {
1134
- this.#returnBlock(target);
1135
- throw error;
1136
- }
1137
- this.#registerPiece(index, target);
1138
- this.#counters.fromDisk += 1;
1139
- this.#counters.revivals += 1;
1140
- this.#noteRevival(index);
1141
- return target;
1142
- } finally {
1143
- release();
1144
- }
1145
- }
1146
-
1147
- /**
1148
- * A block to hold one piece: the most recently freed one, or a new one.
1149
- *
1150
- * Every block is a full piece long, whatever piece will live in it. The last
1151
- * piece of a file is shorter, and it occupies a full block with only its own
1152
- * bytes meaningful — `#lengthOf` is what decides how much is ever read out.
1153
- * Uniform blocks are what makes them interchangeable at all.
1154
- *
1155
- * Most recently freed first, deliberately: a few blocks then carry the whole
1156
- * of a busy store's traffic and the rest age out of use, which is what makes
1157
- * {@link SharedPieceStore#sweepFreeBlocks} able to tell a spare block from a
1158
- * working one.
1159
- *
1160
- * @returns {SharedArrayBuffer}
1161
- */
1162
- #takeBlock() {
1163
- const spare = this.#freeBlocks.pop();
1164
- if (spare !== undefined) {
1165
- this.#noteReuseGap(Date.now() - spare.freedAt);
1166
- return spare.buffer;
1167
- }
1168
- // Nothing spare and the pool is already as large as it is allowed to be.
1169
- // This cannot happen while the accounting is sound: a block is taken only
1170
- // after a slot has been claimed, and slots are exactly what the ceiling
1171
- // counts. It is recorded rather than hidden because when it does happen the
1172
- // pool grows without bound, and every block it then allocates is used once
1173
- // and thrown to a collector that has no reason to run — the heap stays at
1174
- // 50 MB of 2240 while the process reaches four gigabytes.
1175
- // Strictly greater: reaching the ceiling exactly is what a full store looks
1176
- // like, and a slot has just been claimed for this block. Being ALREADY past
1177
- // it and allocating anyway is the state that runs away.
1178
- if (this.#blocksAllocated > this.#growthCeiling) {
1179
- this.#counters.blocksBeyondCeiling += 1;
1180
- }
1181
- this.#blocksAllocated += 1;
1182
- return this.#watchForCollection(new SharedArrayBuffer(this.#chunkLength));
1183
- }
1184
-
1185
- /**
1186
- * Put a block back for re-use, or give it up.
1187
- *
1188
- * Given up when the allowance has fallen below the number of blocks that
1189
- * exist: keeping it would hold memory the machine has just been shown to
1190
- * need. Otherwise it waits in the free list for the next piece.
1191
- *
1192
- * @param {SharedArrayBuffer | undefined} buffer
1193
- * @returns {void}
1194
- */
1195
- #returnBlock(buffer) {
1196
- if (buffer === undefined) {
1197
- return;
1198
- }
1199
- if (this.#closed || this.#blocksAllocated > this.#growthCeiling) {
1200
- // Never below zero: `close` gives up every block at once, and a spill
1201
- // that was already in flight resolves afterwards and arrives here.
1202
- if (this.#blocksAllocated > 0) {
1203
- this.#blocksAllocated -= 1;
1204
- this.#counters.blocksReleased += 1;
1205
- }
1206
- return;
1207
- }
1208
- this.#freeBlocks.push({ buffer, freedAt: Date.now() });
1209
- }
1210
-
1211
- /**
1212
- * Record how long a block waited to be used again.
1213
- *
1214
- * @param {number} gapMs
1215
- * @returns {void}
1216
- */
1217
- #noteReuseGap(gapMs) {
1218
- this.#reuseGaps.push(Math.max(0, gapMs));
1219
- if (this.#reuseGaps.length > REUSE_GAP_SAMPLES) {
1220
- this.#reuseGaps.shift();
1221
- }
1222
- }
1223
-
1224
- /**
1225
- * The longest a block has recently waited before being wanted again, or null
1226
- * when no block has yet been re-used.
1227
- *
1228
- * This is the store's own working rhythm, measured rather than chosen: while
1229
- * a film is being watched a block is taken again within milliseconds, because
1230
- * one is taken for every piece that arrives. A block that has been sitting
1231
- * longer than the longest of those waits is not part of the work.
1232
- *
1233
- * @returns {number | null}
1234
- */
1235
- #reuseGapCeilingMs() {
1236
- if (this.#reuseGaps.length === 0) {
1237
- return null;
1238
- }
1239
- return Math.max(...this.#reuseGaps);
1240
- }
1241
-
1242
- /**
1243
- * Give up blocks that have sat unused longer than this store's own working
1244
- * rhythm.
1245
- *
1246
- * The case it is for: a torrent whose peers have gone. Its readers are still
1247
- * attached, so nothing removes the torrent — the pool's idle timer needs a
1248
- * refcount of zero and never starts. Its allowance falls to what those
1249
- * readers declared, the pieces beyond it are written out, and their blocks
1250
- * would otherwise wait in the free list for peers that may not return.
1251
- *
1252
- * @param {number} [now]
1253
- * @returns {number} Blocks given up.
1254
- */
1255
- sweepFreeBlocks(now = Date.now()) {
1256
- const ceiling = this.#reuseGapCeilingMs();
1257
- if (ceiling === null) {
1258
- return 0;
1259
- }
1260
- const keeping = [];
1261
- let released = 0;
1262
- for (const spare of this.#freeBlocks) {
1263
- if (now - spare.freedAt <= ceiling) {
1264
- keeping.push(spare);
1265
- continue;
1266
- }
1267
- this.#blocksAllocated -= 1;
1268
- this.#counters.blocksReleased += 1;
1269
- released += 1;
1270
- }
1271
- this.#freeBlocks = keeping;
1272
- return released;
1273
- }
1274
-
1275
- /**
1276
- * Count this buffer as one this thread will have to let go of, and notice
1277
- * when the collector takes it. See {@link pieceBufferCollection}.
1278
- *
1279
- * @param {SharedArrayBuffer} buffer
1280
- * @returns {SharedArrayBuffer} The same buffer.
1281
- */
1282
- #watchForCollection(buffer) {
1283
- released.count += 1;
1284
- collector?.register(buffer, null);
1285
- return buffer;
1286
- }
1287
-
1288
- /**
1289
- * A fresh buffer holding this piece's bytes.
1290
- *
1291
- * @param {number} index
1292
- * @param {Uint8Array} bytes
1293
- * @returns {SharedArrayBuffer}
1294
- */
1295
- #copyIntoNewBuffer(index, bytes) {
1296
- const length = this.#lengthOf(index);
1297
- const block = this.#takeBlock();
1298
- const view = Buffer.from(block, 0, length);
1299
- if (bytes.copy) {
1300
- bytes.copy(view, 0, 0, length);
1301
- } else {
1302
- view.set(bytes.subarray(0, length), 0);
1303
- }
1304
- return block;
1305
- }
1306
-
1307
- /**
1308
- * Drop the disk copy of a piece that memory now holds — after any spill of
1309
- * that same piece has finished.
1310
- *
1311
- * `DiskTier.write` records the index when it COMPLETES, so forgetting while a
1312
- * spill of that index is still running let the completing write put it back,
1313
- * and a later read then returned the stale bytes.
1314
- *
1315
- * @param {number} index
1316
- * @returns {Promise<void>}
1317
- */
1318
- async #forgetOnDisk(index) {
1319
- const spill = this.#evicting.get(index);
1320
- if (spill) {
1321
- await spill.catch(() => undefined);
1322
- }
1323
- this.#disk.forget(index);
1324
- this.#spilledAt.delete(index);
1325
- }
1326
-
1327
- put(index, bytes, callback = () => undefined) {
1328
- if (this.#closed) {
1329
- queueMicrotask(() => callback(new Error("Piece store is closed.")));
1330
- return;
1331
- }
1332
-
1333
- const write = async () => {
1334
- // Already resident: the buffer is replaced, not added, so no slot is
1335
- // needed and none is claimed. A fresh buffer rather than a write into the
1336
- // old one, so a reader holding the old reference cannot see a torn write.
1337
- if (this.#buffers.has(index)) {
1338
- const previous = this.#buffers.get(index);
1339
- // A fresh block rather than a write into the old one, so a reader
1340
- // holding the old reference cannot see a torn write.
1341
- this.#buffers.set(index, this.#copyIntoNewBuffer(index, bytes));
1342
- this.#lru.touch(index);
1343
- // And the old block goes back for re-use only if nobody is reading it.
1344
- // A pinned piece has a view onto its memory somewhere; that block is
1345
- // given up instead, and the pool allocates another when it needs one.
1346
- if (this.#lru.isPinned(index)) {
1347
- if (this.#blocksAllocated > 0) {
1348
- this.#blocksAllocated -= 1;
1349
- this.#counters.blocksReleased += 1;
1350
- }
1351
- } else {
1352
- this.#returnBlock(previous);
1353
- }
1354
- await this.#forgetOnDisk(index);
1355
- this.#noteProgress();
1356
- return;
1357
- }
1358
-
1359
- this.#noteArrival();
1360
- const declared = this.#lru.wants(index);
1361
- if (declared) {
1362
- this.#counters.admittedInsideWindow += 1;
1363
- } else {
1364
- this.#counters.admittedOutsideWindow += 1;
1365
- }
1366
-
1367
- // A piece that will be wanted LATER than the one it would displace goes
1368
- // straight to disk instead of being admitted.
1369
- //
1370
- // Two cases, and the second was missing until 2026-09-02. The first: the
1371
- // arrival is in nobody's window at all. The second: it IS in somebody's
1372
- // window, but further from every read head than the piece the store would
1373
- // have to evict to make room for it so admitting it would write out the
1374
- // nearer piece and read it back sooner. The field session had six readers
1375
- // whose windows covered the whole file, so the first case never applied
1376
- // and `0 of those went straight to disk` while the store spilled 233
1377
- // pieces in a minute.
1378
- //
1379
- // Only when SOMETHING is declared: before the first read there is no
1380
- // basis for calling one piece more wanted than another.
1381
- const worseThanTheVictim = () => {
1382
- const arriving = this.#lru.waitFor(index);
1383
- if (arriving < 0) {
1384
- return false;
1385
- }
1386
- const victim = this.#lru.nextVictim();
1387
- return victim.index !== null && victim.wait >= 0 && arriving > victim.wait;
1388
- };
1389
- if (this.#lru.protectedCount > 0 && this.#isFullNow()
1390
- && (!declared || worseThanTheVictim())) {
1391
- this.#counters.admittedToDisk += 1;
1392
- await this.#writeThrough(index, bytes);
1393
- this.#noteProgress();
1394
- return;
1395
- }
1396
-
1397
- const release = await this.#claimSlot();
1398
- try {
1399
- this.#registerPiece(index, this.#copyIntoNewBuffer(index, bytes));
1400
- await this.#forgetOnDisk(index);
1401
- } finally {
1402
- release();
1403
- }
1404
- };
1405
-
1406
- write().then(() => callback(null), (error) => callback(error));
1407
- }
1408
-
1409
- get(index, options, callback) {
1410
- if (typeof options === "function") {
1411
- return this.get(index, undefined, options);
1412
- }
1413
- const done = callback ?? (() => undefined);
1414
- if (this.#closed) {
1415
- queueMicrotask(() => done(new Error("Piece store is closed.")));
1416
- return;
1417
- }
1418
-
1419
- const pieceLength = this.#lengthOf(index);
1420
- const offset = options?.offset ?? 0;
1421
- const length = options?.length ?? pieceLength - offset;
1422
-
1423
- const fetch = async () => {
1424
- const buffer = this.#buffers.get(index);
1425
- if (buffer !== undefined) {
1426
- this.#lru.touch(index);
1427
- this.#counters.fromMemory += 1;
1428
- return Buffer.from(Buffer.from(buffer, offset, length));
1429
- }
1430
-
1431
- const revived = await this.#revive(index);
1432
- if (revived === null) {
1433
- throw new Error(`Piece ${index} is not in the store.`);
1434
- }
1435
- return Buffer.from(Buffer.from(revived, offset, length));
1436
- };
1437
-
1438
- fetch().then((bytes) => done(null, bytes), (error) => done(error));
1439
- }
1440
-
1441
- protectRange(readerId, from, to) {
1442
- this.#lru.protect(readerId, from, to);
1443
- }
1444
-
1445
- protectedRanges() {
1446
- return this.#lru.protectedRanges();
1447
- }
1448
-
1449
- releaseProtection(readerId) {
1450
- this.#lru.unprotect(readerId);
1451
- }
1452
-
1453
- warmRange(from, to, limit = Math.max(1, Math.floor(this.#growthCeiling / 4))) {
1454
- if (this.#closed || !Number.isInteger(from) || !Number.isInteger(to)) {
1455
- return 0;
1456
- }
1457
- let started = 0;
1458
- for (let index = from; index <= to && started < limit; index += 1) {
1459
- if (this.#buffers.has(index) || !this.#disk.has(index)) {
1460
- continue;
1461
- }
1462
- started += 1;
1463
- void this.reside(index).catch(() => undefined);
1464
- }
1465
- return started;
1466
- }
1467
-
1468
- async reside(index) {
1469
- if (this.#closed) {
1470
- throw new Error("Piece store is closed.");
1471
- }
1472
-
1473
- const buffer = this.#buffers.get(index);
1474
- if (buffer !== undefined) {
1475
- this.#lru.touch(index);
1476
- this.#counters.fromMemory += 1;
1477
- return this.locate(index);
1478
- }
1479
-
1480
- const revived = await this.#revive(index);
1481
- if (revived === null) {
1482
- return null;
1483
- }
1484
- return { buffer: revived, offset: 0, length: this.#lengthOf(index) };
1485
- }
1486
-
1487
- close(callback = () => undefined) {
1488
- this.#closed = true;
1489
- liveStores.delete(this);
1490
- this.#buffers.clear();
1491
- this.#spilledAt.clear();
1492
- this.#counters.blocksReleased += this.#blocksAllocated;
1493
- this.#blocksAllocated = 0;
1494
- this.#freeBlocks = [];
1495
- // Whoever is waiting for a slot is woken and finds the store closed, which
1496
- // is an error they can report. Left asleep they simply never returned.
1497
- this.#wake();
1498
- this.#disk.close().then(() => callback(null), (error) => callback(error));
1499
- }
1500
-
1501
- destroy(callback = () => undefined) {
1502
- this.#closed = true;
1503
- liveStores.delete(this);
1504
- this.#buffers.clear();
1505
- this.#spilledAt.clear();
1506
- this.#counters.blocksReleased += this.#blocksAllocated;
1507
- this.#blocksAllocated = 0;
1508
- this.#freeBlocks = [];
1509
- this.#wake();
1510
- this.#disk.destroy().then(() => callback(null), (error) => callback(error));
1511
- }
1512
- }
1
+ /**
2
+ * @file Torrent pieces in shared memory, with disk as the second tier.
3
+ *
4
+ * Replaces the chunk store WebTorrent would otherwise build for itself. Two
5
+ * reasons, one forced and one chosen.
6
+ *
7
+ * **Forced.** WebTorrent's own piece cache hands out the buffer it keeps using
8
+ * and slices again on the next read. The torrent client now runs on its own
9
+ * thread, and moving a piece to the main thread by transferring ownership
10
+ * detached the cache's memory: proxy 2.9.71-2.9.73 answered every read with an
11
+ * empty body (`Stream ends prematurely at 0`) and the failure was invisible,
12
+ * because the error never reached the reader. Owning the memory ourselves
13
+ * removes the question of whose it was.
14
+ *
15
+ * **Chosen.** Memory this side of the thread boundary can be *shared* memory,
16
+ * which the main thread reads without receiving bytes as a copy — see
17
+ * {@link SharedPieceStore#locate}. Measured on the field host: a piece copy
18
+ * costs 3.64 ms, a read from the page cache into a buffer we own 7.63 ms, and
19
+ * re-downloading a piece from the swarm ~1430 ms. So memory first, disk under
20
+ * it, and never the swarm twice.
21
+ *
22
+ * Per piece allocation: each resident piece owns its own `SharedArrayBuffer`.
23
+ * Evicting a piece deletes its entry and the memory is reclaimable by GC.
24
+ * `committed` therefore equals `resident`, not a high-water mark.
25
+ *
26
+ * **Room for a piece is an owned reservation, not a shared number.**
27
+ * `#claimSlot` hands back a release the caller runs in a `finally`; nothing
28
+ * else touches `#outstandingPieces`. It was a counter incremented in one
29
+ * function and decremented in another, and every consequence of that was a
30
+ * defect: a failure between the two lost a slot for the life of the process,
31
+ * `put`'s error path guessed at the correction and could take back a
32
+ * reservation belonging to a different claim, and one lost reservation made
33
+ * the five-second "everything is pinned" error permanently unreachable, so a
34
+ * read retried every 50 ms for ever without completing or failing. Read out of
35
+ * the field failure of 2026-08-31 (`research/worker-heap-oom-2026-08-31.md`).
36
+ *
37
+ * What this deliberately does NOT do is manage the disk as a cache of its own.
38
+ * Pieces evicted from memory are written once and read back on demand; the file
39
+ * is discarded whole when the torrent goes away. libtorrent 2.0 and webtor's
40
+ * seeder both concluded that a hand-rolled disk cache earns less than it costs,
41
+ * and nothing here disagrees.
42
+ */
43
+
44
+ import os from "node:os";
45
+ import { readFileSync } from "node:fs";
46
+ import { PieceLru } from "./piece-lru.js";
47
+ import { DiskTier } from "./disk-tier.js";
48
+
49
+ /**
50
+ * Live stores, so the worker can report on them.
51
+ *
52
+ * @type {Set<SharedPieceStore>}
53
+ */
54
+ const liveStores = new Set();
55
+
56
+ export function collectStoreStats() {
57
+ return [...liveStores].map((store) => store.stats());
58
+ }
59
+
60
+ export function findSharedStore(torrent) {
61
+ let candidate = torrent?.store;
62
+ for (let depth = 0; candidate && depth < 8; depth += 1) {
63
+ if (candidate instanceof SharedPieceStore) {
64
+ return candidate;
65
+ }
66
+ candidate = candidate.store;
67
+ }
68
+ return null;
69
+ }
70
+
71
+ /**
72
+ * The largest fall in the machine's available memory that this process has
73
+ * seen and did not cause itself.
74
+ *
75
+ * What has to be left for everything else on the machine. It cannot be a share
76
+ * of what is free — a share is a number chosen out of nothing, which is what
77
+ * `AVAILABLE_MEMORY_SHARE = 0.25`, `MIN_BUDGET_BYTES` and
78
+ * `MEMORY_BUDGET_CEILING_BYTES` were until 2026-09-02, all three traceable to
79
+ * one observation of one host on 2026-08-03. It is measured instead: between
80
+ * two readings, how much available memory went away beyond what the stores
81
+ * themselves took. On the field host that quantity is large — while the proxy
82
+ * held 76-133 MB overnight the machine's available memory fell from 2378 MB to
83
+ * 306 MB and came back — and on a quiet host it stays near zero, which is the
84
+ * right answer there.
85
+ *
86
+ * Starts at zero: nothing is reserved until somebody else has been seen to
87
+ * need it.
88
+ */
89
+ const otherDemand = { falls: [], lastAvailableBytes: 0, lastStoreBytes: 0 };
90
+
91
+ /**
92
+ * How many observations of other processes' demand are kept.
93
+ *
94
+ * A window rather than a high-water, and for the reason the block re-use gap is
95
+ * one too: a single spike would otherwise stand for the life of the process and
96
+ * squeeze the stores against something that happened once, hours ago.
97
+ */
98
+ const OTHER_DEMAND_SAMPLES = 60;
99
+
100
+ /**
101
+ * Note what the machine had, and how much of the change was not ours.
102
+ *
103
+ * @param {number} availableBytes
104
+ * @param {number} storeBytes - What the live stores hold right now.
105
+ * @returns {number} The reserve, in bytes.
106
+ */
107
+ export function noteMachineMemory(availableBytes, storeBytes) {
108
+ if (otherDemand.lastAvailableBytes > 0) {
109
+ const fell = otherDemand.lastAvailableBytes - availableBytes;
110
+ const ours = storeBytes - otherDemand.lastStoreBytes;
111
+ otherDemand.falls.push(Math.max(0, fell - ours));
112
+ if (otherDemand.falls.length > OTHER_DEMAND_SAMPLES) {
113
+ otherDemand.falls.shift();
114
+ }
115
+ }
116
+ otherDemand.lastAvailableBytes = availableBytes;
117
+ otherDemand.lastStoreBytes = storeBytes;
118
+ return machineReserveBytes();
119
+ }
120
+
121
+ /** What has recently been observed to be needed by everything that is not us. */
122
+ export function machineReserveBytes() {
123
+ return otherDemand.falls.length === 0 ? 0 : Math.max(...otherDemand.falls);
124
+ }
125
+
126
+ /** Forget what other processes have needed. For tests, which share a module. */
127
+ export function forgetMachineMemory() {
128
+ otherDemand.falls = [];
129
+ otherDemand.lastAvailableBytes = 0;
130
+ otherDemand.lastStoreBytes = 0;
131
+ }
132
+
133
+ /**
134
+ * How much memory the stores may hold between them.
135
+ *
136
+ * `MemAvailable` is what could be allocated on top of what is already held, so
137
+ * the stores' own bytes are added back: the pair is the ceiling the stores
138
+ * could reach. The reserve is what has been seen to be needed elsewhere.
139
+ *
140
+ * @param {number} availableBytes
141
+ * @param {number} storeBytes
142
+ * @param {number} reserveBytes
143
+ * @returns {number}
144
+ */
145
+ export function machineAllowanceBytes(availableBytes, storeBytes, reserveBytes) {
146
+ return Math.max(0, Math.max(availableBytes, 0) + Math.max(storeBytes, 0) - Math.max(reserveBytes, 0));
147
+ }
148
+
149
+ /**
150
+ * Divide what the machine allows between the stores, by what each is asking
151
+ * for.
152
+ *
153
+ * A store asks for the pieces its readers have declared. When everyone's ask
154
+ * fits, everyone gets it and the machine's limit never binds — which is the
155
+ * usual case, since two readers of one film declare 32-192 MB against gigabytes
156
+ * of free memory. When the asks do not fit, each store is cut in proportion to
157
+ * what it asked, so a store wanting little is not cut to make room for one
158
+ * wanting much.
159
+ *
160
+ * @param {number[]} wantedBytes - What each store is asking for, in order.
161
+ * @param {number} allowanceBytes
162
+ * @returns {number[]} What each store may hold, in the same order.
163
+ */
164
+ export function divideAllowance(wantedBytes, allowanceBytes) {
165
+ const total = wantedBytes.reduce((sum, want) => sum + Math.max(0, want), 0);
166
+ if (total <= allowanceBytes || total === 0) {
167
+ return wantedBytes.map((want) => Math.max(0, want));
168
+ }
169
+ return wantedBytes.map((want) => Math.floor(allowanceBytes * (Math.max(0, want) / total)));
170
+ }
171
+
172
+ export function reviseStoreBudgets() {
173
+ const stores = [...liveStores];
174
+ const held = stores.reduce((sum, store) => sum + store.residentBytes, 0);
175
+ const available = availableMemorySync();
176
+ const reserve = noteMachineMemory(available, held);
177
+ const allowance = machineAllowanceBytes(available, held, reserve);
178
+ const shares = divideAllowance(stores.map((store) => store.wantedBytes), allowance);
179
+ const revised = [];
180
+ for (const [position, store] of stores.entries()) {
181
+ revised.push(store.reviseGrowthCeiling(shares[position]));
182
+ }
183
+ return revised;
184
+ }
185
+
186
+ function defaultMemoryBytes() {
187
+ const stores = [...liveStores];
188
+ const held = stores.reduce((sum, store) => sum + store.residentBytes, 0);
189
+ const available = availableMemorySync();
190
+ const allowance = machineAllowanceBytes(available, held, machineReserveBytes());
191
+ // A store being created has no readers, so it has no demand to state and no
192
+ // basis for asking for more or less than the others. It opens on an equal
193
+ // share and the first revision — within a minute, and within seconds of a
194
+ // read starting — replaces that with what its readers actually declare.
195
+ // Deliberately not the whole allowance: on a machine with gigabytes free that
196
+ // would let a torrent nobody is reading yet fill memory before the first
197
+ // revision arrives.
198
+ return Math.floor(allowance / (stores.length + 1));
199
+ }
200
+
201
+ function availableMemorySync() {
202
+ try {
203
+ const text = readFileSync("/proc/meminfo", "utf8");
204
+ const match = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(text);
205
+ if (match) {
206
+ return Number(match[1]) * 1024;
207
+ }
208
+ } catch {
209
+ }
210
+ return os.freemem();
211
+ }
212
+
213
+ /**
214
+ * How many blocks of piece memory this thread has let go of, and how many the
215
+ * collector has actually taken back.
216
+ *
217
+ * Since the store keeps a pool, one block serves many pieces, so this counts
218
+ * blocks and not pieces — and a healthy store allocates only as many as its
219
+ * allowance permits, so both numbers are now small and nearly equal.
220
+ *
221
+ * The one reading that separates the two explanations of the 700 MB nobody can
222
+ * account for (roadmap item 2, field 2026-08-31): if the two numbers track each
223
+ * other, this code is holding nothing and whatever grows is below us, in the
224
+ * allocator — on musl there is no `malloc_trim` and no way to ask. If the gap
225
+ * widens, a reference of ours outlives the piece, and then a heap snapshot can
226
+ * name the holder.
227
+ *
228
+ * What it does NOT prove: a `SharedArrayBuffer`'s memory is shared between the
229
+ * isolates, so this thread's handle going means only that THIS thread let go.
230
+ * The main thread counts its own (`torrent-worker/client.js`), and the pair is
231
+ * what answers the question.
232
+ */
233
+ const released = { count: 0, collected: 0 };
234
+ const collector = typeof FinalizationRegistry === "function"
235
+ ? new FinalizationRegistry(() => {
236
+ released.collected += 1;
237
+ })
238
+ : null;
239
+
240
+ /**
241
+ * What the collector has taken back against what was let go.
242
+ *
243
+ * @returns {{ released: number, collected: number }}
244
+ */
245
+ export function pieceBufferCollection() {
246
+ return { released: released.count, collected: released.collected };
247
+ }
248
+
249
+ const MIN_RESIDENT_PIECES = 2;
250
+ /**
251
+ * How long a claim may go without ANYTHING moving before it gives up.
252
+ *
253
+ * Measured against progress, not against activity. The earlier rule skipped
254
+ * this timer entirely while a spill was in flight or a reservation was held —
255
+ * so one reservation that was never returned made the timer unreachable and a
256
+ * read retried every 50 ms for the life of the process, never completing and
257
+ * never failing (field 2026-08-31).
258
+ */
259
+ const PINNED_WAIT_MS = 5_000;
260
+
261
+ /**
262
+ * How many revival ages are kept for the median. A window, not a history: two
263
+ * hundred covers several minutes of the busiest session measured (7575
264
+ * revivals in 44 minutes) and costs two hundred numbers.
265
+ */
266
+ const REVIVAL_AGE_SAMPLES = 200;
267
+
268
+ /**
269
+ * How many block re-use gaps are kept. The same window as the revival ages, and
270
+ * for the same reason: what is wanted is the rhythm of recent work, not a
271
+ * history of it.
272
+ */
273
+ const REUSE_GAP_SAMPLES = 200;
274
+
275
+ /** How many write durations are kept for the median. */
276
+ const WRITE_DURATION_SAMPLES = 50;
277
+ /** How many admission times are kept, and how far back they are counted. */
278
+ const ARRIVAL_SAMPLES = 100;
279
+ const ARRIVAL_WINDOW_MS = 10_000;
280
+
281
+ /**
282
+ * The middle value of a sample, or null when there is nothing to take a middle
283
+ * of. Null rather than zero: no revivals and instant revivals are different
284
+ * facts and must not print the same.
285
+ *
286
+ * @param {number[]} values
287
+ * @returns {number | null}
288
+ */
289
+ function median(values) {
290
+ if (values.length === 0) {
291
+ return null;
292
+ }
293
+ const sorted = [...values].sort((left, right) => left - right);
294
+ const middle = Math.floor(sorted.length / 2);
295
+ return sorted.length % 2 === 0
296
+ ? Math.round((sorted[middle - 1] + sorted[middle]) / 2)
297
+ : sorted[middle];
298
+ }
299
+ const CLAIM_RETRY_MS = 50;
300
+
301
+ export class SharedPieceStore {
302
+ #chunkLength;
303
+ #lastChunkLength;
304
+ #lastChunkIndex;
305
+ #growthCeiling;
306
+ /** Piece index → SharedArrayBuffer of that piece */
307
+ #buffers = new Map();
308
+ /** @type {Map<number, Promise<void>>} */
309
+ #evicting = new Map();
310
+ /**
311
+ * Slots claimed but not yet filled.
312
+ *
313
+ * Handed out by {@link SharedPieceStore##claimSlot} as a release function the
314
+ * caller must call in a `finally`, never as a number one function increments
315
+ * and another decrements. The counter used to be paired across
316
+ * `#claimSlot`/`#registerPiece`, so any failure between the two lost a slot
317
+ * for the life of the process, and `put`'s error path tried to correct that
318
+ * by guessing — which could take back a reservation belonging to a different
319
+ * claim and let the store admit past its allowance.
320
+ */
321
+ #outstandingPieces = 0;
322
+ /** When something last actually moved: a piece admitted, spilled or unpinned. */
323
+ #lastProgressAt = 0;
324
+ #waiters = [];
325
+ #lru;
326
+ #disk;
327
+ #closed = false;
328
+ #name;
329
+ #counters = {
330
+ fromMemory: 0,
331
+ fromDisk: 0,
332
+ spills: 0,
333
+ revivals: 0,
334
+ blockedByPins: 0,
335
+ waitedForPins: 0,
336
+ evictedOnRevise: 0,
337
+ spillFailures: 0,
338
+ // Whether the store is doing its job or being asked to hold more than it
339
+ // has room for. An eviction that had to take a piece a reader declared it
340
+ // wants is the second, and it comes back from disk moments later
341
+ // (roadmap item 9).
342
+ evictedProtected: 0,
343
+ evictedDistanceSum: 0,
344
+ evictedWithDistance: 0,
345
+ // Where an arriving piece went. A piece nobody has declared is being
346
+ // downloaded ahead of every reader; putting it in memory pushes out one
347
+ // that IS declared, which is then read back from disk moments later
348
+ // (roadmap item 9).
349
+ admittedInsideWindow: 0,
350
+ admittedOutsideWindow: 0,
351
+ admittedToDisk: 0,
352
+ /** Blocks given back to the operating system. */
353
+ blocksReleased: 0,
354
+ /**
355
+ * A block put back for re-use while a reader still held the piece. Zero by
356
+ * construction — a pinned piece is never evicted, and a re-put of a pinned
357
+ * one drops its block instead of recycling it. Counted because if it ever
358
+ * stops being zero, a consumer is reading another piece's bytes, and that
359
+ * is invisible from anywhere else.
360
+ */
361
+ returnedWhilePinned: 0,
362
+ /** Spills that found the disk already holding identical bytes. */
363
+ spillsSkipped: 0,
364
+ /**
365
+ * Blocks a second registration of the same piece displaced. Expected to be
366
+ * small and non-zero: two callers racing for one piece is ordinary. What is
367
+ * NOT ordinary is the block going missing when it happens, which is what
368
+ * killed the process on 2026-09-02.
369
+ */
370
+ blocksDisplaced: 0,
371
+ /** Admissions that waited for the disk instead of evicting another piece. */
372
+ waitedForDisk: 0,
373
+ /**
374
+ * Admissions that grew memory because the disk had stopped answering.
375
+ * Non-zero means the store exceeded its allowance on purpose, and by how
376
+ * many pieces.
377
+ */
378
+ grewWaitingForDisk: 0,
379
+ /**
380
+ * Times a block was wanted, none was free, and the pool was already at its
381
+ * ceiling. Zero by construction — a block is only taken after a slot has
382
+ * been claimed, and slots are what the ceiling counts — so a number here
383
+ * means the two have come apart and the pool is growing past its allowance.
384
+ */
385
+ blocksBeyondCeiling: 0
386
+ };
387
+ /**
388
+ * Blocks that hold no piece, most recently freed last.
389
+ *
390
+ * A block is one piece's worth of memory. Allocating a new one for every
391
+ * piece meant 7575 allocations of 4 MiB in 44 minutes on 2026-09-02, each
392
+ * released only when the collector got to it — which is why the process held
393
+ * 1.86 GB while its own accounting said 352 MB. Blocks are taken from here
394
+ * and put back here instead (roadmap item 2).
395
+ *
396
+ * @type {{ buffer: SharedArrayBuffer, freedAt: number }[]}
397
+ */
398
+ #freeBlocks = [];
399
+ /** Blocks that exist at all: free plus holding a piece. */
400
+ #blocksAllocated = 0;
401
+ /** Whether a reader has ever declared a window here. See `wantedBytes`. */
402
+ #everHadReader = false;
403
+ /** Whether the last revision had to exceed the machine's share. */
404
+ #beyondTheMachine = false;
405
+ /**
406
+ * How long a block sat free before it was taken again, in milliseconds.
407
+ * Bounded, because what is wanted is the longest gap of RECENT work: an
408
+ * all-time maximum would be raised by one long pause and then never let a
409
+ * block go again.
410
+ *
411
+ * @type {number[]}
412
+ */
413
+ #reuseGaps = [];
414
+ /**
415
+ * How long recent writes to disk took, in milliseconds, and when pieces were
416
+ * admitted. Together they say how much room the store needs beyond what the
417
+ * readers ask for: while one write is finishing, more pieces arrive, and each
418
+ * needs somewhere to go. Without that room every arrival evicts something,
419
+ * which is what produced 233 evictions against 119 completed writes in a
420
+ * minute on 2026-09-02.
421
+ *
422
+ * @type {number[]}
423
+ */
424
+ #writeDurations = [];
425
+ /** When the last few pieces were admitted, for the arrival rate. */
426
+ #admittedAt = [];
427
+ /** Piece index → when it was written out, for the age it comes back at. */
428
+ #spilledAt = new Map();
429
+ /**
430
+ * Ages, in milliseconds, of the last revivals — bounded, because the figure
431
+ * wanted is a median and not a history. A piece that comes back seconds
432
+ * after it left should not have left.
433
+ *
434
+ * @type {number[]}
435
+ */
436
+ #revivalAges = [];
437
+
438
+ constructor(chunkLength, options = {}) {
439
+ if (!Number.isInteger(chunkLength) || chunkLength < 1) {
440
+ throw new Error(`Chunk length must be a positive integer, got ${chunkLength}.`);
441
+ }
442
+ this.#chunkLength = chunkLength;
443
+
444
+ const totalLength = Number.isFinite(options.length) ? options.length : 0;
445
+ this.#lastChunkIndex = totalLength > 0 ? Math.ceil(totalLength / chunkLength) - 1 : -1;
446
+ const remainder = totalLength % chunkLength;
447
+ this.#lastChunkLength = remainder === 0 ? chunkLength : remainder;
448
+
449
+ const memoryBytes = Number.isFinite(options.memoryBytes) && options.memoryBytes > 0
450
+ ? options.memoryBytes
451
+ : defaultMemoryBytes();
452
+ // Only where this store STARTS. It is not kept, so it cannot come back as a
453
+ // cap on the revision the way `#capacity` did.
454
+ const openingCeiling = Math.max(MIN_RESIDENT_PIECES, Math.floor(memoryBytes / chunkLength));
455
+ this.#growthCeiling = openingCeiling;
456
+ this.#lru = new PieceLru(openingCeiling);
457
+ this.#name = options.name ?? "pieces";
458
+ // `options.disk` exists so a test can hold a write open or make one fail on
459
+ // purpose. Four of the defects fixed here live in what happens when the
460
+ // disk tier does not answer immediately or at all, and none of them is
461
+ // reachable from outside without saying so.
462
+ this.#disk = options.disk ?? new DiskTier({
463
+ directory: options.path ?? ".",
464
+ name: `${this.#name}.pieces`,
465
+ chunkLength
466
+ });
467
+ liveStores.add(this);
468
+ }
469
+
470
+ stats() {
471
+ const resident = this.#buffers.size;
472
+ const residentBytes = resident * this.#chunkLength;
473
+ // Last piece may be short but stats historically use chunkLength.
474
+ return {
475
+ name: this.#name,
476
+ resident,
477
+ capacity: this.#growthCeiling,
478
+ residentBytes,
479
+ allocatedSlots: this.#blocksAllocated,
480
+ // What the process HOLDS, which with a pool is the blocks that exist —
481
+ // not the pieces in them. Holding and using are different quantities and
482
+ // the difference is the point of the reading.
483
+ committedBytes: this.#blocksAllocated * this.#chunkLength,
484
+ budgetBytes: this.#growthCeiling * this.#chunkLength,
485
+ pinned: this.#lru.pinnedCount,
486
+ // Slots claimed and not yet filled. Reported because a reservation that
487
+ // is never returned is invisible until the store cannot admit anything,
488
+ // and by then the reason is long gone. At rest this is zero.
489
+ outstanding: this.#outstandingPieces,
490
+ spilled: this.#disk.size,
491
+ spilledBytes: this.#disk.size * this.#chunkLength,
492
+ // What the readers between them are asking this store to keep, against
493
+ // what it may hold. A union wider than the capacity cannot be held
494
+ // however the eviction is ordered, and that is the difference between a
495
+ // policy to fix and arithmetic to accept (roadmap item 9).
496
+ demand: this.#lru.demand(),
497
+ // What the process actually holds for this store, which is not the same
498
+ // as what it is using: blocks are kept for re-use. The difference is the
499
+ // spare, and it is the whole of the question whether consumption only
500
+ // grows (roadmap item 2).
501
+ blocksAllocated: this.#blocksAllocated,
502
+ blocksFree: this.#freeBlocks.length,
503
+ blocksDisplaced: this.#counters.blocksDisplaced,
504
+ blocksInUse: this.#blocksInUse(),
505
+ blocksInFlight: this.#blocksInFlight(),
506
+ blocksBeyondCeiling: this.#counters.blocksBeyondCeiling,
507
+ blockBytes: this.#blocksAllocated * this.#chunkLength,
508
+ reuseGapMs: this.#reuseGapCeilingMs(),
509
+ revivalAgeMedianMs: median(this.#revivalAges),
510
+ revivalAgeSamples: this.#revivalAges.length,
511
+ revivedWithinFiveSeconds: this.#revivalAges.filter((age) => age <= 5_000).length,
512
+ ...this.#counters
513
+ };
514
+ }
515
+
516
+ /**
517
+ * Whether the machine's share of memory is smaller than one reader's window.
518
+ *
519
+ * The store holds the window anyway — refusing would leave the read it is
520
+ * serving unable to finish, which is worse — but it is the honest measure of
521
+ * "this machine cannot take any more", and it is measured rather than
522
+ * guessed: it is the last revision's own comparison of what the machine
523
+ * allowed against what the widest reader declared.
524
+ */
525
+ get isBeyondTheMachine() {
526
+ return this.#beyondTheMachine;
527
+ }
528
+
529
+ /** What this store holds right now, in bytes. */
530
+ get residentBytes() {
531
+ return this.#buffers.size * this.#chunkLength;
532
+ }
533
+
534
+ /**
535
+ * What this store is asking to be allowed to hold, in bytes.
536
+ *
537
+ * The union of its readers' declared windows — what they have said they will
538
+ * need — never below the widest single window, because a store that cannot
539
+ * hold one reader's window cannot complete that reader's read at all: every
540
+ * resident piece ends up pinned, the read returns zero bytes and ffmpeg takes
541
+ * that for the end of the file (field 2026-08-15, roadmap item 9).
542
+ *
543
+ * With no reader declaring anything there is no demand to speak of, so the
544
+ * store asks for what the machine allows and the first revision after a read
545
+ * begins brings it down to what that read needs.
546
+ */
547
+ get wantedBytes() {
548
+ const demand = this.#lru.demand();
549
+ if (demand.readers > 0) {
550
+ this.#everHadReader = true;
551
+ const pieces = Math.max(MIN_RESIDENT_PIECES, demand.unionPieces, demand.widestPieces);
552
+ // Plus room to absorb what arrives while a write is finishing. Asking for
553
+ // exactly what the readers want leaves no free place ever, so every
554
+ // arrival evicts one of them — measured 2026-09-02: `6 reader(s) want 23
555
+ // piece(s) of 23 the store may hold`, and 233 evictions in the minute
556
+ // that followed.
557
+ return (pieces + this.slackPieces()) * this.#chunkLength;
558
+ }
559
+ // Readers that have GONE are not the same as readers that have not arrived.
560
+ // A store whose readers ended has nothing to hold pieces for — its torrent
561
+ // sits until the pool's idle timer removes it, which needs a refcount of
562
+ // zero and can be a quarter of an hour away — so it asks for nothing and
563
+ // its memory goes back to the machine now. A store that has never had a
564
+ // reader is being filled for one that is on its way, and asks for what it
565
+ // was opened with until the first read says what it needs.
566
+ return this.#everHadReader
567
+ ? (MIN_RESIDENT_PIECES + this.slackPieces()) * this.#chunkLength
568
+ : this.#growthCeiling * this.#chunkLength;
569
+ }
570
+
571
+ reviseGrowthCeiling(allowedBytes) {
572
+ // No cap at what the machine could spare when this store was CREATED.
573
+ // `#capacity` was computed once in the constructor and used as an upper
574
+ // bound here, so the allowance could only ever fall: a torrent opened while
575
+ // the machine was full kept a small allowance for its whole life, however
576
+ // much memory was freed afterwards (roadmap item 2, 2026-09-02).
577
+ const wanted = Math.floor(Number(allowedBytes) / this.#chunkLength);
578
+ // Never below one reader's whole window while a reader exists, even when
579
+ // the machine's share says less. A store that cannot hold the window of the
580
+ // read it is serving cannot complete that read at all: every resident piece
581
+ // ends up pinned, the read returns zero bytes and ffmpeg takes that for the
582
+ // end of the file, which killed every encoder on that file in the field on
583
+ // 2026-08-15. Exceeding the share is the lesser failure, and the line below
584
+ // says when it happens.
585
+ const demand = this.#lru.demand();
586
+ this.#growthCeiling = Math.max(
587
+ MIN_RESIDENT_PIECES,
588
+ demand.readers > 0 ? demand.widestPieces : MIN_RESIDENT_PIECES,
589
+ Number.isFinite(wanted) ? wanted : MIN_RESIDENT_PIECES
590
+ );
591
+ const belowAWindow = demand.readers > 0
592
+ && Number.isFinite(wanted)
593
+ && wanted < demand.widestPieces;
594
+ this.#beyondTheMachine = belowAWindow;
595
+ // The LRU is told too. It was constructed with the store's original
596
+ // capacity and never revised, so `isFull()` answered against a number that
597
+ // had not been the limit for some time — dormant only because nothing calls
598
+ // it, which is a trap for whoever calls it next.
599
+ this.#lru.setCapacity(this.#growthCeiling);
600
+ // With per-piece buffers memory CAN be given back immediately, unlike the
601
+ // old growable pool. Eagerly evict excess to honour the new ceiling.
602
+ let evicted = 0;
603
+ while (this.#buffers.size > this.#growthCeiling) {
604
+ const { index: victim, protectionYielded, distance } = this.#lru.evictionChoice();
605
+ if (victim === null) {
606
+ break;
607
+ }
608
+ const victimBuffer = this.#buffers.get(victim);
609
+ if (victimBuffer === undefined) {
610
+ this.#lru.remove(victim);
611
+ continue;
612
+ }
613
+ this.#buffers.delete(victim);
614
+ this.#lru.remove(victim);
615
+ evicted += 1;
616
+ this.#counters.evictedOnRevise += 1;
617
+ this.#noteEviction(protectionYielded, distance);
618
+ // Nobody awaits this spill, so its failure has to end here. Rethrowing
619
+ // made it an unhandled rejection, and an unhandled rejection in the
620
+ // torrent worker ends the thread — a second way to lose the torrent
621
+ // client, on top of the one that already loses it.
622
+ void this.#spill(victim, victimBuffer).catch(() => {
623
+ this.#counters.spillFailures += 1;
624
+ });
625
+ }
626
+ // Blocks the store is no longer using and has waited long enough to give
627
+ // up. The allowance falling is the moment to ask, because that is when the
628
+ // machine has been shown to need the memory.
629
+ const releasedBlocks = this.sweepFreeBlocks();
630
+ return {
631
+ name: this.#name,
632
+ ceilingBytes: this.#growthCeiling * this.#chunkLength,
633
+ committedBytes: this.#blocksAllocated * this.#chunkLength,
634
+ evicted,
635
+ releasedBlocks,
636
+ belowAWindow
637
+ };
638
+ }
639
+
640
+ get chunkLength() {
641
+ return this.#chunkLength;
642
+ }
643
+
644
+ get capacity() {
645
+ return this.#growthCeiling;
646
+ }
647
+
648
+ get residentCount() {
649
+ return this.#buffers.size;
650
+ }
651
+
652
+ get spilledCount() {
653
+ return this.#disk.size;
654
+ }
655
+
656
+ #lengthOf(index) {
657
+ return index === this.#lastChunkIndex ? this.#lastChunkLength : this.#chunkLength;
658
+ }
659
+
660
+ /**
661
+ * Where a resident piece sits, or `null` if not resident.
662
+ * Returns the piece's own SharedArrayBuffer and the intra-piece range.
663
+ * @param {number} index
664
+ * @returns {{ buffer: SharedArrayBuffer, offset: number, length: number } | null}
665
+ */
666
+ locate(index) {
667
+ const buffer = this.#buffers.get(index);
668
+ if (buffer === undefined) {
669
+ return null;
670
+ }
671
+ return { buffer, offset: 0, length: this.#lengthOf(index) };
672
+ }
673
+
674
+ /**
675
+ * Direct access to a piece's buffer for zero-copy consumers.
676
+ * @param {number} index
677
+ * @returns {SharedArrayBuffer | undefined}
678
+ */
679
+ getPieceBuffer(index) {
680
+ return this.#buffers.get(index);
681
+ }
682
+
683
+ pin(index) {
684
+ this.#lru.pin(index);
685
+ }
686
+
687
+ unpin(index) {
688
+ this.#lru.unpin(index);
689
+ this.#noteProgress();
690
+ }
691
+
692
+ /**
693
+ * Reserve room for one piece.
694
+ *
695
+ * @returns {Promise<() => void>} The release, which the caller MUST call in a
696
+ * `finally`. Calling it twice is harmless.
697
+ */
698
+ async #claimSlot() {
699
+ // How long THIS claim has been trying, kept here and not on the store.
700
+ // It was a field, `#pinnedWaitStartedAt`, shared by the two waits inside
701
+ // `#claimSlotOnce` — the one for the disk and the one for a piece that may
702
+ // be evicted — and each of them zeroed it on giving up, which restarted the
703
+ // other's clock. Measured 2026-09-03: the claim cycled for ever, five
704
+ // seconds per side, `grewWaitingForDisk` and `waitedForPins` both climbing
705
+ // once every five seconds while `blockedByPins` stayed at 0 — the refusal
706
+ // was unreachable. A claim's patience belongs to the claim; with several
707
+ // claimants a shared field is wrong anyway, since one caller giving up
708
+ // would reset the wait of every other.
709
+ const waitingSince = Date.now();
710
+ for (;;) {
711
+ if (this.#closed) {
712
+ throw new Error("Piece store is closed.");
713
+ }
714
+ const ok = await this.#claimSlotOnce(waitingSince);
715
+ if (ok) {
716
+ let released = false;
717
+ return () => {
718
+ if (released) {
719
+ return;
720
+ }
721
+ released = true;
722
+ this.#outstandingPieces -= 1;
723
+ this.#noteProgress();
724
+ };
725
+ }
726
+ await this.#waitForSlot();
727
+ }
728
+ }
729
+
730
+ /**
731
+ * Sleep until something moves, or until the retry interval, whichever first.
732
+ *
733
+ * One handler, idempotent, and its timer is cleared when it is woken. The
734
+ * earlier version attached a fresh pair of handlers to EVERY pending spill on
735
+ * every attempt and left a timer running each time, so a claim that could not
736
+ * be satisfied allocated in proportion to attempts times pending spills. A
737
+ * settling spill now wakes the store itself, which is where that belongs.
738
+ *
739
+ * @returns {Promise<void>}
740
+ */
741
+ #waitForSlot() {
742
+ return new Promise((resolve) => {
743
+ let settled = false;
744
+ /** @type {ReturnType<typeof setTimeout> | null} */
745
+ let retry = null;
746
+ const finish = () => {
747
+ if (settled) {
748
+ return;
749
+ }
750
+ settled = true;
751
+ if (retry !== null) {
752
+ clearTimeout(retry);
753
+ }
754
+ resolve();
755
+ };
756
+ this.#waiters.push(finish);
757
+ retry = setTimeout(finish, CLAIM_RETRY_MS);
758
+ retry.unref?.();
759
+ });
760
+ }
761
+
762
+ #registerPiece(index, buffer) {
763
+ // A piece may already be here. Both paths that register one look first and
764
+ // then await — `put` waits for a slot, `#revive` waits for the disk — and
765
+ // in that gap another caller can register the same index. Overwriting the
766
+ // entry used to drop the previous block on the floor: its memory was not
767
+ // returned to the pool and the pool's own count was never decremented, so
768
+ // the count climbed past the ceiling for ever and the pool degenerated into
769
+ // allocating a fresh block per piece. Field 2026-09-02: a store holding
770
+ // THREE pieces reported 812 MB committed against 68 MB allowed, 739 blocks
771
+ // allocated and 676 still alive, and the process was killed at 4.37 GB.
772
+ const displaced = this.#buffers.get(index);
773
+ this.#buffers.set(index, buffer);
774
+ if (displaced !== undefined && displaced !== buffer) {
775
+ this.#counters.blocksDisplaced += 1;
776
+ this.#returnBlock(displaced);
777
+ }
778
+ this.#lru.touch(index);
779
+ this.#noteProgress();
780
+ }
781
+
782
+ /**
783
+ * Write a piece out and account for it, from the one place that does it.
784
+ *
785
+ * @param {number} index
786
+ * @param {SharedArrayBuffer} buffer
787
+ * @returns {Promise<void>}
788
+ */
789
+ #spill(index, buffer) {
790
+ // The disk may already hold these very bytes. `#revive` reads a piece back
791
+ // into memory and leaves the copy on disk, and only `put` removes it — so a
792
+ // piece that was revived and not re-put is identical to what is already
793
+ // written, and writing it again is work for nothing. There were 7575
794
+ // revivals in one session on 2026-09-02, and every later eviction of one of
795
+ // them wrote a second time (roadmap item 66: 14.4 GB written in a single
796
+ // viewing).
797
+ if (this.#disk.has(index)) {
798
+ this.#counters.spills += 1;
799
+ this.#counters.spillsSkipped += 1;
800
+ this.#spilledAt.set(index, Date.now());
801
+ this.#returnBlock(buffer);
802
+ this.#noteProgress();
803
+ return Promise.resolve();
804
+ }
805
+
806
+ const bytes = Buffer.from(buffer, 0, this.#lengthOf(index));
807
+ const startedAt = Date.now();
808
+ const spill = this.#disk.write(index, bytes).then(
809
+ () => {
810
+ this.#noteWriteDuration(Date.now() - startedAt);
811
+ this.#counters.spills += 1;
812
+ this.#spilledAt.set(index, Date.now());
813
+ this.#evicting.delete(index);
814
+ // Only now. The write reads out of this block, so a block handed to
815
+ // another piece before the write finished would put that piece's bytes
816
+ // into this piece's place in the file.
817
+ this.#returnBlock(buffer);
818
+ this.#noteProgress();
819
+ },
820
+ (error) => {
821
+ this.#evicting.delete(index);
822
+ // The block is no longer holding anything either way; keeping it out of
823
+ // the pool because the write failed would lose it for good.
824
+ this.#returnBlock(buffer);
825
+ this.#noteProgress();
826
+ throw error;
827
+ }
828
+ );
829
+ this.#evicting.set(index, spill);
830
+ return spill;
831
+ }
832
+
833
+ /** Something actually moved: wake whoever is waiting and restart the clock. */
834
+ #noteProgress() {
835
+ this.#lastProgressAt = Date.now();
836
+ this.#wake();
837
+ }
838
+
839
+ /**
840
+ * Record how long one write to disk took.
841
+ *
842
+ * @param {number} durationMs
843
+ * @returns {void}
844
+ */
845
+ #noteWriteDuration(durationMs) {
846
+ this.#writeDurations.push(Math.max(0, durationMs));
847
+ if (this.#writeDurations.length > WRITE_DURATION_SAMPLES) {
848
+ this.#writeDurations.shift();
849
+ }
850
+ }
851
+
852
+ /** Record that a piece arrived, for the arrival rate. */
853
+ #noteArrival() {
854
+ const now = Date.now();
855
+ this.#admittedAt.push(now);
856
+ while (this.#admittedAt.length > ARRIVAL_SAMPLES
857
+ || (this.#admittedAt.length > 0 && now - this.#admittedAt[0] > ARRIVAL_WINDOW_MS)) {
858
+ this.#admittedAt.shift();
859
+ }
860
+ }
861
+
862
+ /**
863
+ * How many pieces the store needs room for beyond what the readers ask for.
864
+ *
865
+ * Measured, not chosen: the pieces that arrive while one write to disk is
866
+ * finishing. Without this room every arrival must evict something, and each
867
+ * eviction holds its block until its write completes — so a disk slower than
868
+ * the swarm turns every admission into one more block held. On 2026-09-02
869
+ * that was 233 evictions against 119 completed writes in a minute, and 203
870
+ * blocks held with three pieces resident.
871
+ *
872
+ * Zero until both quantities have been seen, because a slack invented before
873
+ * anything is measured is a chosen number, and this store has been bitten by
874
+ * those.
875
+ *
876
+ * @returns {number} Pieces.
877
+ */
878
+ slackPieces() {
879
+ if (this.#writeDurations.length === 0 || this.#admittedAt.length < 2) {
880
+ return 0;
881
+ }
882
+ const sorted = [...this.#writeDurations].sort((left, right) => left - right);
883
+ const writeMs = sorted[Math.floor(sorted.length / 2)];
884
+ const spanMs = this.#admittedAt[this.#admittedAt.length - 1] - this.#admittedAt[0];
885
+ if (!(spanMs > 0)) {
886
+ return 0;
887
+ }
888
+ const perMs = (this.#admittedAt.length - 1) / spanMs;
889
+ return Math.ceil(perMs * writeMs);
890
+ }
891
+
892
+ /**
893
+ * Blocks that are not free: resident pieces, blocks being written out, and
894
+ * blocks taken but not yet registered.
895
+ *
896
+ * This is what the ceiling has to bound, and until 2026-09-02 it bounded
897
+ * resident pieces instead. The difference is exactly the memory that goes
898
+ * missing from the count: a piece being spilled leaves `#buffers` the moment
899
+ * the eviction begins, while its block stays held until the write it feeds
900
+ * has finished.
901
+ *
902
+ * @returns {number}
903
+ */
904
+ #blocksInUse() {
905
+ return this.#blocksAllocated - this.#freeBlocks.length;
906
+ }
907
+
908
+ /**
909
+ * Blocks held by writes that have not finished.
910
+ *
911
+ * @returns {number}
912
+ */
913
+ #blocksInFlight() {
914
+ return Math.max(0, this.#blocksInUse() - this.#buffers.size);
915
+ }
916
+
917
+ /**
918
+ * Whether admitting one more piece would need something evicted first.
919
+ *
920
+ * Reservations count: a slot claimed and not yet filled is as taken as a
921
+ * resident piece.
922
+ *
923
+ * @returns {boolean}
924
+ */
925
+ #isFullNow() {
926
+ return this.#blocksInUse() + this.#outstandingPieces >= this.#growthCeiling;
927
+ }
928
+
929
+ /**
930
+ * Write an arriving piece straight to disk, without it ever occupying memory.
931
+ *
932
+ * Registered in `#evicting` like a spill, so a `get` for this index waits for
933
+ * the write instead of finding the piece on neither tier. Deliberately NOT
934
+ * recorded in `#spilledAt`: that clock measures how long an EVICTED piece
935
+ * stayed away, and a piece that was never resident has no such age.
936
+ *
937
+ * @param {number} index
938
+ * @param {Uint8Array} bytes
939
+ * @returns {Promise<void>}
940
+ */
941
+ #writeThrough(index, bytes) {
942
+ // Copied, not viewed. `DiskTier.write` opens the file before it reads the
943
+ // bytes, so a view onto the caller's buffer could be written to in between
944
+ // and the file would get the wrong data. The spill path may pass a view
945
+ // because that memory is ours; this buffer belongs to the torrent client.
946
+ // It costs nothing extra: the piece was being copied into a shared buffer
947
+ // on this path before, and now it is copied here instead.
948
+ const copy = Buffer.from(bytes.subarray(0, Math.min(bytes.length, this.#lengthOf(index))));
949
+ const write = this.#disk.write(index, copy).then(
950
+ () => {
951
+ this.#evicting.delete(index);
952
+ this.#noteProgress();
953
+ },
954
+ (error) => {
955
+ this.#evicting.delete(index);
956
+ this.#noteProgress();
957
+ throw error;
958
+ }
959
+ );
960
+ this.#evicting.set(index, write);
961
+ return write;
962
+ }
963
+
964
+ /**
965
+ * Record how long a piece stayed on disk before it was wanted again.
966
+ *
967
+ * A piece that comes back seconds after it left was evicted from a working
968
+ * set that does not fit, and the write and the read were both waste. Kept as
969
+ * a bounded window of ages because the figure wanted is a median, not a
970
+ * history.
971
+ *
972
+ * @param {number} index
973
+ * @returns {void}
974
+ */
975
+ #noteRevival(index) {
976
+ const spilledAt = this.#spilledAt.get(index);
977
+ if (spilledAt === undefined) {
978
+ return;
979
+ }
980
+ this.#spilledAt.delete(index);
981
+ this.#revivalAges.push(Date.now() - spilledAt);
982
+ if (this.#revivalAges.length > REVIVAL_AGE_SAMPLES) {
983
+ this.#revivalAges.shift();
984
+ }
985
+ }
986
+
987
+ /**
988
+ * Record what an eviction had to take.
989
+ *
990
+ * @param {boolean} protectionYielded - The victim was inside a window a
991
+ * reader had declared, and was taken anyway because nothing else was free.
992
+ * @param {number} distance - Pieces from the nearest declared window, -1 when
993
+ * no reader declared one.
994
+ * @returns {void}
995
+ */
996
+ #noteEviction(protectionYielded, distance) {
997
+ if (protectionYielded) {
998
+ this.#counters.evictedProtected += 1;
999
+ }
1000
+ if (distance >= 0) {
1001
+ this.#counters.evictedDistanceSum += distance;
1002
+ this.#counters.evictedWithDistance += 1;
1003
+ }
1004
+ }
1005
+
1006
+ #wake() {
1007
+ const waiting = this.#waiters;
1008
+ this.#waiters = [];
1009
+ for (const resolve of waiting) {
1010
+ resolve();
1011
+ }
1012
+ }
1013
+
1014
+ /**
1015
+ * One attempt at a reservation.
1016
+ *
1017
+ * @param {number} waitingSince - When the claim this attempt belongs to began
1018
+ * trying. Both waits below are measured from the later of it and the last
1019
+ * time the store moved, so neither can restart the other's clock — see
1020
+ * `#claimSlot`.
1021
+ * @returns {Promise<boolean>} Whether a slot was reserved.
1022
+ */
1023
+ async #claimSlotOnce(waitingSince) {
1024
+ // Reserve before suspension so concurrent callers see the reservation.
1025
+ if (this.#blocksInUse() + this.#outstandingPieces < this.#growthCeiling) {
1026
+ this.#outstandingPieces += 1;
1027
+ return true;
1028
+ }
1029
+ const stillFor = () => Date.now() - Math.max(waitingSince, this.#lastProgressAt);
1030
+
1031
+ // Full, and evicting would make it worse rather than better. A piece being
1032
+ // written out has already left `#buffers` while its block is still held —
1033
+ // the write reads from that block — so evicting another one converts a
1034
+ // resident block into an in-flight block and takes a fresh block for the
1035
+ // arrival: the memory in use goes UP by one per admission for as long as
1036
+ // the disk is behind. Field 2026-09-02: 233 evictions against 119 completed
1037
+ // writes in a minute, 203 blocks held with three pieces resident, and the
1038
+ // process killed at 4.37 GB.
1039
+ //
1040
+ // So when the disk is what the store is waiting for, it waits. A completing
1041
+ // write calls `#noteProgress`, which wakes whoever is here.
1042
+ if (this.#blocksInFlight() > 0 && this.#blocksInUse() >= this.#growthCeiling) {
1043
+ if (stillFor() < PINNED_WAIT_MS) {
1044
+ this.#counters.waitedForDisk += 1;
1045
+ return false;
1046
+ }
1047
+ // The disk has stopped answering. Falling through to eviction is the
1048
+ // lesser failure: it grows memory, and the line above says by how much,
1049
+ // where refusing would fail the read outright. The clock is NOT restarted
1050
+ // here: the wait that follows asks the same question of the same claim,
1051
+ // and zeroing it was half of the loop described in `#claimSlot`.
1052
+ this.#counters.grewWaitingForDisk += 1;
1053
+ }
1054
+
1055
+ const { index: victim, protectionYielded, distance } = this.#lru.evictionChoice();
1056
+ if (victim === null) {
1057
+ // Nothing may leave. Wait while the store is still MOVING — a spill
1058
+ // completing, a piece admitted, a pin released — and give up when it has
1059
+ // not moved for PINNED_WAIT_MS, whatever is nominally in flight. The old
1060
+ // rule asked whether anything was in flight rather than whether anything
1061
+ // had happened, which is why one lost reservation could hold a read here
1062
+ // for ever.
1063
+ if (stillFor() < PINNED_WAIT_MS) {
1064
+ this.#counters.waitedForPins += 1;
1065
+ return false;
1066
+ }
1067
+ this.#counters.blockedByPins += 1;
1068
+ throw new Error(
1069
+ `Every resident piece is pinned and nothing moved for ${PINNED_WAIT_MS}ms; no slot can be freed.`
1070
+ );
1071
+ }
1072
+
1073
+ const victimBuffer = this.#buffers.get(victim);
1074
+ if (victimBuffer === undefined) {
1075
+ // Should not happen: LRU says resident but buffer missing.
1076
+ this.#lru.remove(victim);
1077
+ return false;
1078
+ }
1079
+
1080
+ // Claim atomically before await.
1081
+ this.#buffers.delete(victim);
1082
+ this.#lru.remove(victim);
1083
+ this.#outstandingPieces += 1;
1084
+ this.#noteEviction(protectionYielded, distance);
1085
+
1086
+ try {
1087
+ await this.#spill(victim, victimBuffer);
1088
+ } catch (error) {
1089
+ // The caller never received a release for this reservation, so it is
1090
+ // given back here rather than left outstanding for ever.
1091
+ this.#outstandingPieces -= 1;
1092
+ this.#noteProgress();
1093
+ throw error;
1094
+ }
1095
+ // Outstanding stays +1 for the caller; the slot for the new piece is now free.
1096
+ return true;
1097
+ }
1098
+
1099
+ /**
1100
+ * Bring a spilled piece back into memory, once, however many callers ask.
1101
+ *
1102
+ * @param {number} index
1103
+ * @returns {Promise<SharedArrayBuffer | null>} `null` when the piece is on
1104
+ * neither tier.
1105
+ */
1106
+ async #revive(index) {
1107
+ const spill = this.#evicting.get(index);
1108
+ if (spill) {
1109
+ await spill.catch(() => undefined);
1110
+ }
1111
+
1112
+ if (!this.#disk.has(index)) {
1113
+ return null;
1114
+ }
1115
+
1116
+ const release = await this.#claimSlot();
1117
+ try {
1118
+ // Another caller may have brought it back while this one waited for a
1119
+ // slot. Registering a second buffer for the same piece would leave
1120
+ // whoever holds the first reading memory nothing evicts.
1121
+ const already = this.#buffers.get(index);
1122
+ if (already !== undefined) {
1123
+ this.#lru.touch(index);
1124
+ this.#counters.fromMemory += 1;
1125
+ return already;
1126
+ }
1127
+ const target = this.#takeBlock();
1128
+ try {
1129
+ // Only this piece's own length: the block is a full piece long and the
1130
+ // last piece of a file is shorter, so reading the whole block would ask
1131
+ // the file for bytes past its end.
1132
+ await this.#disk.read(index, Buffer.from(target, 0, this.#lengthOf(index)));
1133
+ } catch (error) {
1134
+ this.#returnBlock(target);
1135
+ throw error;
1136
+ }
1137
+ this.#registerPiece(index, target);
1138
+ this.#counters.fromDisk += 1;
1139
+ this.#counters.revivals += 1;
1140
+ this.#noteRevival(index);
1141
+ return target;
1142
+ } finally {
1143
+ release();
1144
+ }
1145
+ }
1146
+
1147
+ /**
1148
+ * A block to hold one piece: the most recently freed one, or a new one.
1149
+ *
1150
+ * Every block is a full piece long, whatever piece will live in it. The last
1151
+ * piece of a file is shorter, and it occupies a full block with only its own
1152
+ * bytes meaningful — `#lengthOf` is what decides how much is ever read out.
1153
+ * Uniform blocks are what makes them interchangeable at all.
1154
+ *
1155
+ * Most recently freed first, deliberately: a few blocks then carry the whole
1156
+ * of a busy store's traffic and the rest age out of use, which is what makes
1157
+ * {@link SharedPieceStore#sweepFreeBlocks} able to tell a spare block from a
1158
+ * working one.
1159
+ *
1160
+ * @returns {SharedArrayBuffer}
1161
+ */
1162
+ #takeBlock() {
1163
+ const spare = this.#freeBlocks.pop();
1164
+ if (spare !== undefined) {
1165
+ this.#noteReuseGap(Date.now() - spare.freedAt);
1166
+ return spare.buffer;
1167
+ }
1168
+ // Nothing spare and the pool is already as large as it is allowed to be.
1169
+ // This cannot happen while the accounting is sound: a block is taken only
1170
+ // after a slot has been claimed, and slots are exactly what the ceiling
1171
+ // counts. It is recorded rather than hidden because when it does happen the
1172
+ // pool grows without bound, and every block it then allocates is used once
1173
+ // and thrown to a collector that has no reason to run — the heap stays at
1174
+ // 50 MB of 2240 while the process reaches four gigabytes.
1175
+ // Strictly greater: reaching the ceiling exactly is what a full store looks
1176
+ // like, and a slot has just been claimed for this block. Being ALREADY past
1177
+ // it and allocating anyway is the state that runs away.
1178
+ if (this.#blocksAllocated > this.#growthCeiling) {
1179
+ this.#counters.blocksBeyondCeiling += 1;
1180
+ }
1181
+ this.#blocksAllocated += 1;
1182
+ return this.#watchForCollection(new SharedArrayBuffer(this.#chunkLength));
1183
+ }
1184
+
1185
+ /**
1186
+ * Put a block back for re-use, or give it up.
1187
+ *
1188
+ * Given up when the allowance has fallen below the number of blocks that
1189
+ * exist: keeping it would hold memory the machine has just been shown to
1190
+ * need. Otherwise it waits in the free list for the next piece.
1191
+ *
1192
+ * @param {SharedArrayBuffer | undefined} buffer
1193
+ * @returns {void}
1194
+ */
1195
+ #returnBlock(buffer) {
1196
+ if (buffer === undefined) {
1197
+ return;
1198
+ }
1199
+ if (this.#closed || this.#blocksAllocated > this.#growthCeiling) {
1200
+ // Never below zero: `close` gives up every block at once, and a spill
1201
+ // that was already in flight resolves afterwards and arrives here.
1202
+ if (this.#blocksAllocated > 0) {
1203
+ this.#blocksAllocated -= 1;
1204
+ this.#counters.blocksReleased += 1;
1205
+ }
1206
+ return;
1207
+ }
1208
+ this.#freeBlocks.push({ buffer, freedAt: Date.now() });
1209
+ }
1210
+
1211
+ /**
1212
+ * Record how long a block waited to be used again.
1213
+ *
1214
+ * @param {number} gapMs
1215
+ * @returns {void}
1216
+ */
1217
+ #noteReuseGap(gapMs) {
1218
+ this.#reuseGaps.push(Math.max(0, gapMs));
1219
+ if (this.#reuseGaps.length > REUSE_GAP_SAMPLES) {
1220
+ this.#reuseGaps.shift();
1221
+ }
1222
+ }
1223
+
1224
+ /**
1225
+ * The longest a block has recently waited before being wanted again, or null
1226
+ * when no block has yet been re-used.
1227
+ *
1228
+ * This is the store's own working rhythm, measured rather than chosen: while
1229
+ * a film is being watched a block is taken again within milliseconds, because
1230
+ * one is taken for every piece that arrives. A block that has been sitting
1231
+ * longer than the longest of those waits is not part of the work.
1232
+ *
1233
+ * @returns {number | null}
1234
+ */
1235
+ #reuseGapCeilingMs() {
1236
+ if (this.#reuseGaps.length === 0) {
1237
+ return null;
1238
+ }
1239
+ return Math.max(...this.#reuseGaps);
1240
+ }
1241
+
1242
+ /**
1243
+ * Give up blocks that have sat unused longer than this store's own working
1244
+ * rhythm.
1245
+ *
1246
+ * The case it is for: a torrent whose peers have gone. Its readers are still
1247
+ * attached, so nothing removes the torrent — the pool's idle timer needs a
1248
+ * refcount of zero and never starts. Its allowance falls to what those
1249
+ * readers declared, the pieces beyond it are written out, and their blocks
1250
+ * would otherwise wait in the free list for peers that may not return.
1251
+ *
1252
+ * @param {number} [now]
1253
+ * @returns {number} Blocks given up.
1254
+ */
1255
+ sweepFreeBlocks(now = Date.now()) {
1256
+ const ceiling = this.#reuseGapCeilingMs();
1257
+ if (ceiling === null) {
1258
+ return 0;
1259
+ }
1260
+ const keeping = [];
1261
+ let released = 0;
1262
+ for (const spare of this.#freeBlocks) {
1263
+ if (now - spare.freedAt <= ceiling) {
1264
+ keeping.push(spare);
1265
+ continue;
1266
+ }
1267
+ this.#blocksAllocated -= 1;
1268
+ this.#counters.blocksReleased += 1;
1269
+ released += 1;
1270
+ }
1271
+ this.#freeBlocks = keeping;
1272
+ return released;
1273
+ }
1274
+
1275
+ /**
1276
+ * Count this buffer as one this thread will have to let go of, and notice
1277
+ * when the collector takes it. See {@link pieceBufferCollection}.
1278
+ *
1279
+ * @param {SharedArrayBuffer} buffer
1280
+ * @returns {SharedArrayBuffer} The same buffer.
1281
+ */
1282
+ #watchForCollection(buffer) {
1283
+ released.count += 1;
1284
+ collector?.register(buffer, null);
1285
+ return buffer;
1286
+ }
1287
+
1288
+ /**
1289
+ * A fresh buffer holding this piece's bytes.
1290
+ *
1291
+ * @param {number} index
1292
+ * @param {Uint8Array} bytes
1293
+ * @returns {SharedArrayBuffer}
1294
+ */
1295
+ #copyIntoNewBuffer(index, bytes) {
1296
+ const length = this.#lengthOf(index);
1297
+ const block = this.#takeBlock();
1298
+ const view = Buffer.from(block, 0, length);
1299
+ if (bytes.copy) {
1300
+ bytes.copy(view, 0, 0, length);
1301
+ } else {
1302
+ view.set(bytes.subarray(0, length), 0);
1303
+ }
1304
+ return block;
1305
+ }
1306
+
1307
+ /**
1308
+ * Drop the disk copy of a piece that memory now holds — after any spill of
1309
+ * that same piece has finished.
1310
+ *
1311
+ * `DiskTier.write` records the index when it COMPLETES, so forgetting while a
1312
+ * spill of that index is still running let the completing write put it back,
1313
+ * and a later read then returned the stale bytes.
1314
+ *
1315
+ * @param {number} index
1316
+ * @returns {Promise<void>}
1317
+ */
1318
+ async #forgetOnDisk(index) {
1319
+ const spill = this.#evicting.get(index);
1320
+ if (spill) {
1321
+ await spill.catch(() => undefined);
1322
+ }
1323
+ this.#disk.forget(index);
1324
+ this.#spilledAt.delete(index);
1325
+ }
1326
+
1327
+ put(index, bytes, callback = () => undefined) {
1328
+ if (this.#closed) {
1329
+ queueMicrotask(() => callback(new Error("Piece store is closed.")));
1330
+ return;
1331
+ }
1332
+
1333
+ const write = async () => {
1334
+ // Already resident: the buffer is replaced, not added, so no slot is
1335
+ // needed and none is claimed. A fresh buffer rather than a write into the
1336
+ // old one, so a reader holding the old reference cannot see a torn write.
1337
+ if (this.#buffers.has(index)) {
1338
+ const previous = this.#buffers.get(index);
1339
+ // A fresh block rather than a write into the old one, so a reader
1340
+ // holding the old reference cannot see a torn write.
1341
+ this.#buffers.set(index, this.#copyIntoNewBuffer(index, bytes));
1342
+ this.#lru.touch(index);
1343
+ // And the old block goes back for re-use only if nobody is reading it.
1344
+ // A pinned piece has a view onto its memory somewhere; that block is
1345
+ // given up instead, and the pool allocates another when it needs one.
1346
+ if (this.#lru.isPinned(index)) {
1347
+ if (this.#blocksAllocated > 0) {
1348
+ this.#blocksAllocated -= 1;
1349
+ this.#counters.blocksReleased += 1;
1350
+ }
1351
+ } else {
1352
+ this.#returnBlock(previous);
1353
+ }
1354
+ await this.#forgetOnDisk(index);
1355
+ this.#noteProgress();
1356
+ return;
1357
+ }
1358
+
1359
+ this.#noteArrival();
1360
+ const declared = this.#lru.wants(index);
1361
+ if (declared) {
1362
+ this.#counters.admittedInsideWindow += 1;
1363
+ } else {
1364
+ this.#counters.admittedOutsideWindow += 1;
1365
+ }
1366
+
1367
+ // A piece wanted LESS than the one it would displace goes straight to
1368
+ // disk instead of being admitted.
1369
+ //
1370
+ // The same comparison eviction makes, in the same order, from the other
1371
+ // end: the priority map's level first, and the distance to a read head
1372
+ // only between pieces the map wants equally. Answering the two from
1373
+ // different quantities would let the store admit a piece by one rule and
1374
+ // evict it again by the other in the same second.
1375
+ //
1376
+ // Two cases, and the second was missing until 2026-09-02. The first: the
1377
+ // arrival is in nobody's zone at all. The second: it IS in a zone, but
1378
+ // one the map wants less than the zone holding the piece the store would
1379
+ // have to evict for it. The field session had six readers whose windows
1380
+ // covered the whole file, so the first case never applied and `0 of those
1381
+ // went straight to disk` while the store spilled 233 pieces in a minute.
1382
+ //
1383
+ // Only when SOMETHING is stated: before that there is no basis for
1384
+ // calling one piece more wanted than another.
1385
+ const worseThanTheVictim = () => {
1386
+ const victim = this.#lru.nextVictim();
1387
+ if (victim.index === null) {
1388
+ return false;
1389
+ }
1390
+ const arrivingWant = this.#lru.wantAt(index);
1391
+ if (arrivingWant !== victim.want) {
1392
+ return arrivingWant > victim.want;
1393
+ }
1394
+ const arriving = this.#lru.waitFor(index);
1395
+ return arriving >= 0 && victim.wait >= 0 && arriving > victim.wait;
1396
+ };
1397
+ if (this.#lru.protectedCount > 0 && this.#isFullNow()
1398
+ && (!declared || worseThanTheVictim())) {
1399
+ this.#counters.admittedToDisk += 1;
1400
+ await this.#writeThrough(index, bytes);
1401
+ this.#noteProgress();
1402
+ return;
1403
+ }
1404
+
1405
+ const release = await this.#claimSlot();
1406
+ try {
1407
+ this.#registerPiece(index, this.#copyIntoNewBuffer(index, bytes));
1408
+ await this.#forgetOnDisk(index);
1409
+ } finally {
1410
+ release();
1411
+ }
1412
+ };
1413
+
1414
+ write().then(() => callback(null), (error) => callback(error));
1415
+ }
1416
+
1417
+ get(index, options, callback) {
1418
+ if (typeof options === "function") {
1419
+ return this.get(index, undefined, options);
1420
+ }
1421
+ const done = callback ?? (() => undefined);
1422
+ if (this.#closed) {
1423
+ queueMicrotask(() => done(new Error("Piece store is closed.")));
1424
+ return;
1425
+ }
1426
+
1427
+ const pieceLength = this.#lengthOf(index);
1428
+ const offset = options?.offset ?? 0;
1429
+ const length = options?.length ?? pieceLength - offset;
1430
+
1431
+ const fetch = async () => {
1432
+ const buffer = this.#buffers.get(index);
1433
+ if (buffer !== undefined) {
1434
+ this.#lru.touch(index);
1435
+ this.#counters.fromMemory += 1;
1436
+ return Buffer.from(Buffer.from(buffer, offset, length));
1437
+ }
1438
+
1439
+ const revived = await this.#revive(index);
1440
+ if (revived === null) {
1441
+ throw new Error(`Piece ${index} is not in the store.`);
1442
+ }
1443
+ return Buffer.from(Buffer.from(revived, offset, length));
1444
+ };
1445
+
1446
+ fetch().then((bytes) => done(null, bytes), (error) => done(error));
1447
+ }
1448
+
1449
+ /**
1450
+ * State a range of pieces and how much they are wanted. The number is the
1451
+ * priority map's own, and it is what eviction compares — see
1452
+ * {@link PieceLru#protect}.
1453
+ *
1454
+ * @param {string|number} readerId
1455
+ * @param {number} from
1456
+ * @param {number} to
1457
+ * @param {number} [urgency]
1458
+ * @returns {void}
1459
+ */
1460
+ protectRange(readerId, from, to, urgency) {
1461
+ this.#lru.protect(readerId, from, to, urgency);
1462
+ }
1463
+
1464
+ protectedRanges() {
1465
+ return this.#lru.protectedRanges();
1466
+ }
1467
+
1468
+ releaseProtection(readerId) {
1469
+ this.#lru.unprotect(readerId);
1470
+ }
1471
+
1472
+ warmRange(from, to, limit = Math.max(1, Math.floor(this.#growthCeiling / 4))) {
1473
+ if (this.#closed || !Number.isInteger(from) || !Number.isInteger(to)) {
1474
+ return 0;
1475
+ }
1476
+ let started = 0;
1477
+ for (let index = from; index <= to && started < limit; index += 1) {
1478
+ if (this.#buffers.has(index) || !this.#disk.has(index)) {
1479
+ continue;
1480
+ }
1481
+ started += 1;
1482
+ void this.reside(index).catch(() => undefined);
1483
+ }
1484
+ return started;
1485
+ }
1486
+
1487
+ async reside(index) {
1488
+ if (this.#closed) {
1489
+ throw new Error("Piece store is closed.");
1490
+ }
1491
+
1492
+ const buffer = this.#buffers.get(index);
1493
+ if (buffer !== undefined) {
1494
+ this.#lru.touch(index);
1495
+ this.#counters.fromMemory += 1;
1496
+ return this.locate(index);
1497
+ }
1498
+
1499
+ const revived = await this.#revive(index);
1500
+ if (revived === null) {
1501
+ return null;
1502
+ }
1503
+ return { buffer: revived, offset: 0, length: this.#lengthOf(index) };
1504
+ }
1505
+
1506
+ close(callback = () => undefined) {
1507
+ this.#closed = true;
1508
+ liveStores.delete(this);
1509
+ this.#buffers.clear();
1510
+ this.#spilledAt.clear();
1511
+ this.#counters.blocksReleased += this.#blocksAllocated;
1512
+ this.#blocksAllocated = 0;
1513
+ this.#freeBlocks = [];
1514
+ // Whoever is waiting for a slot is woken and finds the store closed, which
1515
+ // is an error they can report. Left asleep they simply never returned.
1516
+ this.#wake();
1517
+ this.#disk.close().then(() => callback(null), (error) => callback(error));
1518
+ }
1519
+
1520
+ destroy(callback = () => undefined) {
1521
+ this.#closed = true;
1522
+ liveStores.delete(this);
1523
+ this.#buffers.clear();
1524
+ this.#spilledAt.clear();
1525
+ this.#counters.blocksReleased += this.#blocksAllocated;
1526
+ this.#blocksAllocated = 0;
1527
+ this.#freeBlocks = [];
1528
+ this.#wake();
1529
+ this.#disk.destroy().then(() => callback(null), (error) => callback(error));
1530
+ }
1531
+ }