@torrent-tv/proxy 2.9.73 → 2.9.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ ## 2.9.74
2
+
3
+ - **Fix**: Playback works again. Since 2.9.71 every read answered with headers and an empty body — ffmpeg reported `Stream ends prematurely at 0, should be <size>` and the loading screen sat on "Preparing HLS transcode" until it gave up. Root cause, reproduced locally on two different torrents once the right conditions were used (a large, **partially downloaded** file — a complete one never shows it): the worker transferred ownership of a buffer belonging to WebTorrent's piece cache, the cache's memory was detached, and from that moment every read failed with `Cannot perform %TypedArray%.prototype.slice on a detached ArrayBuffer`. Nobody saw that error, because the worker sent the end-of-read marker from its `finally` before posting the failure and the main thread had no handler for a read error at all — so a broken read was indistinguishable from an empty file. Fixed at the root by owning the memory (the new piece store) and at the boundary by having the transport copy into memory it allocated itself rather than trying to guess whether the caller's buffer was safe to take. Verified end to end on both an almost-complete and a freshly-added torrent: playback plan, byte range, transcode session, init segment and first media segment all produced.
4
+ - **New**: A piece store of our own (`services/piece-store/`): pieces live in a `SharedArrayBuffer`, spill to a single sparse file when the memory budget is full, and come back from it on demand. Owning the memory is what makes the thread split safe — WebTorrent's own cache hands out buffers it keeps using, which is why transferring one detached the cache and killed every subsequent read. Two properties are enforced rather than hoped for: a piece being read is **pinned** and cannot be evicted (with every piece pinned the store refuses to make room instead of taking memory from under a reader — the exact failure of 2.9.71), and a buffer handed to a caller is never invalidated by later writes. Sized by measurement on the field host: a piece copy costs 3.64 ms, reading one back from disk into a buffer we already own 7.63 ms, and re-downloading it from the swarm ~1430 ms — so memory first, disk under it, the swarm never twice. Found while testing: opening the spill file in append mode makes POSIX ignore the write position entirely, so pieces piled up in arrival order and reads returned whichever piece happened to sit at that offset.
5
+ - **Fix**: A torrent carrying a `wss://` tracker took the **whole proxy process** down from 2.9.71 — including the demo magnet on the site's own button. node-datachannel is native and cannot be used from two V8 isolates at once (`HandleScope: Entering the V8 API without proper locking in place`); measured identically on win32/x64 and linux/arm64, with one isolate fine either way, two fatal, and `preload()` in both no help. Before the thread split both users lived in one isolate; afterwards the browser's video channel sat on the main thread while the torrent's tracker announces created peer connections on the worker. Fixed by leaving the native stack where it carries video and giving the torrent thread a JavaScript one (`werift`) through a module-resolution hook scoped to that worker — no dependency is patched, which matters because the addon installs with `--ignore-scripts`. The shim supplies the three things werift's data channel lacks and `simple-peer` depends on: `binaryType` (without it every payload goes through a text decoder and arrives corrupted), the buffered-amount-low event (its backpressure never resumes without it), and a session description built from one object rather than two positional arguments (werift's own signature is `(sdp, type)`, so `{ type, sdp }` was rejected as `invalid sessionDescription`). Verified end to end: a magnet with **only** wss trackers now connects to browser peers and downloads the file completely.
6
+ - **Chore**: The proxy has tests, and publishing runs them. There were none before, and nothing stood between writing code and `npm publish` — which is how the 2.9.71 thread split reached the field with a defect that stopped every read. `npm test` (Node's own runner, no new dependencies) plus `prepublishOnly`, so an unproven package cannot be published. The first cases cover the transport's memory contract and are written to FAIL on the current code: sending a chunk must leave the source buffer usable by its owner, and a second read of the same piece must still return its bytes. Both fail today, which is the point — they describe the shipped defect.
7
+
1
8
  ## 2.9.73
2
9
 
3
10
  - **Fix**: File stats came back as `{}` after the torrent moved to its own thread (2.9.71), which left the loading screen with no peers, no speed and no progress. Two call sites — the stats route and the health report — invoked `getFileStats` **without awaiting**: it used to answer locally and immediately, and now crosses a thread boundary, so the reply was the pending promise itself, serialised to an empty object. Both now await it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.9.73",
3
+ "version": "2.9.74",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "publishConfig": {
@@ -15,7 +15,9 @@
15
15
  "minor": "npm whoami && npm version minor && npm publish && git push --follow-tags",
16
16
  "major": "npm whoami && npm version major && npm publish && git push --follow-tags",
17
17
  "start": "node ./bin/cli.js",
18
- "dev": "node --inspect=0 --experimental-network-inspection ./bin/cli.js"
18
+ "dev": "node --inspect=0 --experimental-network-inspection ./bin/cli.js",
19
+ "test": "node --test",
20
+ "prepublishOnly": "npm test"
19
21
  },
20
22
  "dependencies": {
21
23
  "@fastify/cors": "^11.2.0",
@@ -31,6 +33,7 @@
31
33
  "node-datachannel": "^0.32.0",
32
34
  "uint8-util": "2.2.6",
33
35
  "webtorrent": "2.8.5",
36
+ "werift": "^0.24.2",
34
37
  "ws": "^8.18.2"
35
38
  }
36
39
  }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * @file The second tier: pieces that no longer fit in memory.
3
+ *
4
+ * One sparse file per torrent, a piece at `index * chunkLength`. Not the
5
+ * torrent's real files — nobody reads those directly; playback goes through
6
+ * `/stream`, and the data is discarded when the torrent goes idle. A single
7
+ * file by piece index keeps the mapping arithmetic instead of bookkeeping, and
8
+ * sparseness means the untouched gaps cost nothing.
9
+ *
10
+ * Reads take a destination buffer rather than returning a fresh one. That is
11
+ * not a style preference — measured on the field host, an 8 MB piece costs
12
+ * 22.08 ms via `readFile`, which allocates, and **7.63 ms** read into a buffer
13
+ * we already hold. Two thirds of the apparent "disk" cost was allocation.
14
+ */
15
+
16
+ import fs from "node:fs/promises";
17
+ import { constants } from "node:fs";
18
+ import path from "node:path";
19
+
20
+ export class DiskTier {
21
+ #filePath;
22
+ #chunkLength;
23
+ /** @type {import("node:fs/promises").FileHandle | null} */
24
+ #handle = null;
25
+ /** Piece indices known to be on disk. */
26
+ #stored = new Set();
27
+ /** @type {Promise<void> | null} */
28
+ #opening = null;
29
+
30
+ /**
31
+ * @param {object} params
32
+ * @param {string} params.directory - Where the backing file lives.
33
+ * @param {string} params.name - File name, unique per torrent.
34
+ * @param {number} params.chunkLength - Piece size; fixes the stride on disk.
35
+ */
36
+ constructor({ directory, name, chunkLength }) {
37
+ this.#filePath = path.join(directory, name);
38
+ this.#chunkLength = chunkLength;
39
+ }
40
+
41
+ /** Where the backing file lives, for logging and cleanup. */
42
+ get filePath() {
43
+ return this.#filePath;
44
+ }
45
+
46
+ /** How many pieces are currently held on disk. */
47
+ get size() {
48
+ return this.#stored.size;
49
+ }
50
+
51
+ /**
52
+ * Open the backing file, creating it and its directory if needed.
53
+ *
54
+ * Concurrent callers share one open — several evictions can start at once.
55
+ *
56
+ * @returns {Promise<import("node:fs/promises").FileHandle>}
57
+ */
58
+ async #open() {
59
+ if (this.#handle) {
60
+ return this.#handle;
61
+ }
62
+ if (!this.#opening) {
63
+ this.#opening = (async () => {
64
+ await fs.mkdir(path.dirname(this.#filePath), { recursive: true });
65
+ // Read/write, created if absent — NOT append mode. Under `a+` POSIX
66
+ // ignores the position on every write and puts the bytes at the end of
67
+ // the file, so pieces would pile up in arrival order and each read
68
+ // would return whichever piece happened to land at that offset.
69
+ this.#handle = await fs.open(this.#filePath, constants.O_RDWR | constants.O_CREAT);
70
+ })();
71
+ }
72
+ await this.#opening;
73
+ if (!this.#handle) {
74
+ throw new Error(`Could not open the piece file at ${this.#filePath}.`);
75
+ }
76
+ return this.#handle;
77
+ }
78
+
79
+ /**
80
+ * @param {number} index
81
+ * @returns {boolean}
82
+ */
83
+ has(index) {
84
+ return this.#stored.has(index);
85
+ }
86
+
87
+ /**
88
+ * Write a piece out.
89
+ *
90
+ * @param {number} index
91
+ * @param {Uint8Array} bytes
92
+ * @returns {Promise<void>}
93
+ */
94
+ async write(index, bytes) {
95
+ const handle = await this.#open();
96
+ await handle.write(bytes, 0, bytes.length, index * this.#chunkLength);
97
+ this.#stored.add(index);
98
+ }
99
+
100
+ /**
101
+ * Read a piece back into a buffer the caller already owns.
102
+ *
103
+ * @param {number} index
104
+ * @param {Uint8Array} target - Destination; its length is what gets read.
105
+ * @returns {Promise<number>} Bytes read.
106
+ */
107
+ async read(index, target) {
108
+ if (!this.#stored.has(index)) {
109
+ throw new Error(`Piece ${index} is not on disk.`);
110
+ }
111
+ const handle = await this.#open();
112
+ const { bytesRead } = await handle.read(target, 0, target.length, index * this.#chunkLength);
113
+ return bytesRead;
114
+ }
115
+
116
+ /**
117
+ * Forget a piece. The bytes stay on disk until the file is removed — there is
118
+ * nothing to gain from punching them out, since the file is discarded whole.
119
+ *
120
+ * @param {number} index
121
+ * @returns {void}
122
+ */
123
+ forget(index) {
124
+ this.#stored.delete(index);
125
+ }
126
+
127
+ /**
128
+ * Close the file, leaving its contents in place.
129
+ *
130
+ * @returns {Promise<void>}
131
+ */
132
+ async close() {
133
+ const handle = this.#handle;
134
+ this.#handle = null;
135
+ this.#opening = null;
136
+ if (handle) {
137
+ await handle.close();
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Close and delete the backing file.
143
+ *
144
+ * @returns {Promise<void>}
145
+ */
146
+ async destroy() {
147
+ await this.close();
148
+ this.#stored.clear();
149
+ await fs.rm(this.#filePath, { force: true });
150
+ }
151
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * @file Which piece leaves memory next — and which one may not.
3
+ *
4
+ * Two responsibilities, deliberately kept apart from any storage:
5
+ *
6
+ * - **recency**, so the piece evicted is the one least likely to be wanted;
7
+ * - **pinning**, so a piece being read cannot be evicted at all.
8
+ *
9
+ * The second is not a refinement of the first. webtor's seeder relies on recency
10
+ * alone and guards the actual eviction with a read/write lock per piece
11
+ * (`mmap.go`, 1024 shards) — because ordering says a piece is *unlikely* to be
12
+ * in use, never that it is not. We have already paid for that difference once:
13
+ * proxy 2.9.71 removed a torrent, and its data, out from under an active reader,
14
+ * after which every read hung and ffmpeg saw an empty input. Here the guarantee
15
+ * is explicit: a pinned piece is never returned as an eviction candidate, and
16
+ * pins nest, because a piece can be read by several sessions at once.
17
+ */
18
+
19
+ /**
20
+ * Recency and pin bookkeeping for one torrent's pieces.
21
+ *
22
+ * Holds no data — it answers "what may go" and nothing else, which is what
23
+ * makes it testable without a torrent, a disk or a thread.
24
+ */
25
+ export class PieceLru {
26
+ /** Insertion-ordered: the first key is the least recently used. */
27
+ #order = new Set();
28
+ /** Piece index → number of readers currently holding it. */
29
+ #pins = new Map();
30
+ #capacity;
31
+
32
+ /**
33
+ * @param {number} capacity - How many pieces may be resident at once.
34
+ */
35
+ constructor(capacity) {
36
+ if (!Number.isInteger(capacity) || capacity < 1) {
37
+ throw new Error(`Piece capacity must be a positive integer, got ${capacity}.`);
38
+ }
39
+ this.#capacity = capacity;
40
+ }
41
+
42
+ /** How many pieces are resident. */
43
+ get size() {
44
+ return this.#order.size;
45
+ }
46
+
47
+ /** How many pieces may be resident at once. */
48
+ get capacity() {
49
+ return this.#capacity;
50
+ }
51
+
52
+ /**
53
+ * Mark a piece as resident, or as used again if it already was.
54
+ *
55
+ * A `Set` preserves insertion order, so deleting and re-adding is what moves
56
+ * a piece to the most-recent end.
57
+ *
58
+ * @param {number} index
59
+ * @returns {void}
60
+ */
61
+ touch(index) {
62
+ this.#order.delete(index);
63
+ this.#order.add(index);
64
+ }
65
+
66
+ /**
67
+ * @param {number} index
68
+ * @returns {boolean}
69
+ */
70
+ has(index) {
71
+ return this.#order.has(index);
72
+ }
73
+
74
+ /**
75
+ * Stop tracking a piece — it is no longer resident.
76
+ *
77
+ * @param {number} index
78
+ * @returns {void}
79
+ */
80
+ remove(index) {
81
+ this.#order.delete(index);
82
+ }
83
+
84
+ /**
85
+ * Hold a piece in memory for the duration of a read.
86
+ *
87
+ * Nested: two readers of the same piece take two pins, and the piece stays
88
+ * held until both let go.
89
+ *
90
+ * @param {number} index
91
+ * @returns {void}
92
+ */
93
+ pin(index) {
94
+ this.#pins.set(index, (this.#pins.get(index) ?? 0) + 1);
95
+ }
96
+
97
+ /**
98
+ * Release one pin taken with {@link pin}.
99
+ *
100
+ * @param {number} index
101
+ * @returns {void}
102
+ */
103
+ unpin(index) {
104
+ const held = this.#pins.get(index);
105
+ if (held === undefined) {
106
+ return;
107
+ }
108
+ if (held <= 1) {
109
+ this.#pins.delete(index);
110
+ return;
111
+ }
112
+ this.#pins.set(index, held - 1);
113
+ }
114
+
115
+ /**
116
+ * @param {number} index
117
+ * @returns {boolean}
118
+ */
119
+ isPinned(index) {
120
+ return this.#pins.has(index);
121
+ }
122
+
123
+ /**
124
+ * The least recently used piece that is free to go, or `null` when every
125
+ * resident piece is pinned.
126
+ *
127
+ * Returning `null` rather than evicting a pinned piece is the whole point:
128
+ * the caller must then wait or fail, never take memory out from under a
129
+ * reader.
130
+ *
131
+ * @returns {number | null}
132
+ */
133
+ evictionCandidate() {
134
+ for (const index of this.#order) {
135
+ if (!this.#pins.has(index)) {
136
+ return index;
137
+ }
138
+ }
139
+ return null;
140
+ }
141
+
142
+ /**
143
+ * Whether admitting one more piece would exceed the capacity.
144
+ *
145
+ * @returns {boolean}
146
+ */
147
+ isFull() {
148
+ return this.#order.size >= this.#capacity;
149
+ }
150
+ }
@@ -0,0 +1,315 @@
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 by offset instead of receiving as bytes — 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
+ * What this deliberately does NOT do is manage the disk as a cache of its own.
23
+ * Pieces evicted from memory are written once and read back on demand; the file
24
+ * is discarded whole when the torrent goes away. libtorrent 2.0 and webtor's
25
+ * seeder both concluded that a hand-rolled disk cache earns less than it costs,
26
+ * and nothing here disagrees.
27
+ */
28
+
29
+ import { PieceLru } from "./piece-lru.js";
30
+ import { DiskTier } from "./disk-tier.js";
31
+
32
+ /** Fallback budget when the caller names none: enough for a comfortable window. */
33
+ const DEFAULT_MEMORY_BYTES = 512 * 1024 * 1024;
34
+ /**
35
+ * Never keep fewer than this many pieces resident, whatever the budget says.
36
+ *
37
+ * Two is the smallest workable number rather than a round one: a piece being
38
+ * read holds its slot, so a second slot must exist for the next piece to land
39
+ * in. With one, a single reader would deadlock the store against itself.
40
+ */
41
+ const MIN_RESIDENT_PIECES = 2;
42
+
43
+ /**
44
+ * A chunk store holding pieces in a `SharedArrayBuffer`, spilling to disk.
45
+ *
46
+ * Implements the `abstract-chunk-store` shape WebTorrent expects — `put`,
47
+ * `get`, `close`, `destroy` — plus {@link locate}, {@link pin} and
48
+ * {@link unpin}, which is how the main thread reads a piece without it being
49
+ * copied or moved.
50
+ */
51
+ export class SharedPieceStore {
52
+ #chunkLength;
53
+ #lastChunkLength;
54
+ #lastChunkIndex;
55
+ #capacity;
56
+ /** @type {SharedArrayBuffer} */
57
+ #shared;
58
+ /** @type {Buffer} A view over the whole pool, for slot arithmetic. */
59
+ #pool;
60
+ /** Piece index → slot number. */
61
+ #slotOf = new Map();
62
+ /** Slot numbers not currently holding a piece. */
63
+ #freeSlots = [];
64
+ #lru;
65
+ #disk;
66
+ #closed = false;
67
+
68
+ /**
69
+ * @param {number} chunkLength - Piece length, and therefore the slot size.
70
+ * @param {object} [options]
71
+ * @param {number} [options.length] - Total torrent length, so the short last piece is sized correctly.
72
+ * @param {number} [options.memoryBytes] - Budget for resident pieces.
73
+ * @param {string} [options.path] - Directory for the spill file.
74
+ * @param {string} [options.name] - Spill file name; must be unique per torrent.
75
+ */
76
+ constructor(chunkLength, options = {}) {
77
+ if (!Number.isInteger(chunkLength) || chunkLength < 1) {
78
+ throw new Error(`Chunk length must be a positive integer, got ${chunkLength}.`);
79
+ }
80
+ this.#chunkLength = chunkLength;
81
+
82
+ const totalLength = Number.isFinite(options.length) ? options.length : 0;
83
+ this.#lastChunkIndex = totalLength > 0 ? Math.ceil(totalLength / chunkLength) - 1 : -1;
84
+ const remainder = totalLength % chunkLength;
85
+ this.#lastChunkLength = remainder === 0 ? chunkLength : remainder;
86
+
87
+ const memoryBytes = Number.isFinite(options.memoryBytes) && options.memoryBytes > 0
88
+ ? options.memoryBytes
89
+ : DEFAULT_MEMORY_BYTES;
90
+ this.#capacity = Math.max(MIN_RESIDENT_PIECES, Math.floor(memoryBytes / chunkLength));
91
+
92
+ this.#shared = new SharedArrayBuffer(this.#capacity * chunkLength);
93
+ this.#pool = Buffer.from(this.#shared);
94
+ for (let slot = 0; slot < this.#capacity; slot += 1) {
95
+ this.#freeSlots.push(slot);
96
+ }
97
+ this.#lru = new PieceLru(this.#capacity);
98
+ this.#disk = new DiskTier({
99
+ directory: options.path ?? ".",
100
+ name: `${options.name ?? "pieces"}.pieces`,
101
+ chunkLength
102
+ });
103
+ }
104
+
105
+ /** `abstract-chunk-store` exposes the piece size under this name. */
106
+ get chunkLength() {
107
+ return this.#chunkLength;
108
+ }
109
+
110
+ /**
111
+ * The pool itself, so another thread can map the same memory and read a piece
112
+ * by the offset {@link locate} reports.
113
+ *
114
+ * @returns {SharedArrayBuffer}
115
+ */
116
+ get sharedBuffer() {
117
+ return this.#shared;
118
+ }
119
+
120
+ /** How many pieces fit in memory at once. */
121
+ get capacity() {
122
+ return this.#capacity;
123
+ }
124
+
125
+ /** How many pieces are resident right now. */
126
+ get residentCount() {
127
+ return this.#slotOf.size;
128
+ }
129
+
130
+ /** How many pieces have been spilled to disk. */
131
+ get spilledCount() {
132
+ return this.#disk.size;
133
+ }
134
+
135
+ /**
136
+ * Length of a given piece — the last one is usually short.
137
+ *
138
+ * @param {number} index
139
+ * @returns {number}
140
+ */
141
+ #lengthOf(index) {
142
+ return index === this.#lastChunkIndex ? this.#lastChunkLength : this.#chunkLength;
143
+ }
144
+
145
+ /**
146
+ * Where a resident piece sits in the shared pool, or `null` if it is not
147
+ * resident.
148
+ *
149
+ * The main thread reads straight from those bytes, so callers MUST hold a pin
150
+ * across the read — see {@link pin}.
151
+ *
152
+ * @param {number} index
153
+ * @returns {{ offset: number, length: number } | null}
154
+ */
155
+ locate(index) {
156
+ const slot = this.#slotOf.get(index);
157
+ if (slot === undefined) {
158
+ return null;
159
+ }
160
+ return { offset: slot * this.#chunkLength, length: this.#lengthOf(index) };
161
+ }
162
+
163
+ /**
164
+ * Hold a piece in memory across a read. Nested; release with {@link unpin}.
165
+ *
166
+ * @param {number} index
167
+ * @returns {void}
168
+ */
169
+ pin(index) {
170
+ this.#lru.pin(index);
171
+ }
172
+
173
+ /**
174
+ * @param {number} index
175
+ * @returns {void}
176
+ */
177
+ unpin(index) {
178
+ this.#lru.unpin(index);
179
+ }
180
+
181
+ /**
182
+ * Make a slot available, spilling the least recently used piece if need be.
183
+ *
184
+ * @returns {Promise<number>} Slot number.
185
+ */
186
+ async #claimSlot() {
187
+ const free = this.#freeSlots.pop();
188
+ if (free !== undefined) {
189
+ return free;
190
+ }
191
+
192
+ const victim = this.#lru.evictionCandidate();
193
+ if (victim === null) {
194
+ // Every resident piece is being read. Taking one anyway is precisely the
195
+ // failure this store exists to make impossible.
196
+ throw new Error("Every resident piece is pinned; no slot can be freed.");
197
+ }
198
+
199
+ const slot = this.#slotOf.get(victim);
200
+ const bytes = this.#pool.subarray(slot * this.#chunkLength, slot * this.#chunkLength + this.#lengthOf(victim));
201
+ await this.#disk.write(victim, bytes);
202
+
203
+ this.#slotOf.delete(victim);
204
+ this.#lru.remove(victim);
205
+ return slot;
206
+ }
207
+
208
+ /**
209
+ * Store a piece.
210
+ *
211
+ * @param {number} index
212
+ * @param {Uint8Array} bytes
213
+ * @param {(error?: Error | null) => void} [callback]
214
+ * @returns {void}
215
+ */
216
+ put(index, bytes, callback = () => undefined) {
217
+ if (this.#closed) {
218
+ queueMicrotask(() => callback(new Error("Piece store is closed.")));
219
+ return;
220
+ }
221
+
222
+ const existing = this.#slotOf.get(index);
223
+ const write = async () => {
224
+ const slot = existing ?? (await this.#claimSlot());
225
+ bytes.copy
226
+ ? bytes.copy(this.#pool, slot * this.#chunkLength)
227
+ : this.#pool.set(bytes, slot * this.#chunkLength);
228
+ this.#slotOf.set(index, slot);
229
+ this.#lru.touch(index);
230
+ // A newer copy is in memory; whatever is on disk is stale.
231
+ this.#disk.forget(index);
232
+ };
233
+
234
+ write().then(() => callback(null), (error) => callback(error));
235
+ }
236
+
237
+ /**
238
+ * Fetch a piece, or a range within it.
239
+ *
240
+ * Returns a buffer of its own rather than a view into the pool: WebTorrent
241
+ * keeps what it is given — to verify a hash, to serve a peer — and the slot
242
+ * underneath may be reused meanwhile. The thread-crossing path avoids this
243
+ * copy entirely by going through {@link locate}.
244
+ *
245
+ * @param {number} index
246
+ * @param {{ offset?: number, length?: number } | ((error: Error | null, bytes?: Buffer) => void)} [options]
247
+ * @param {(error: Error | null, bytes?: Buffer) => void} [callback]
248
+ * @returns {void}
249
+ */
250
+ get(index, options, callback) {
251
+ if (typeof options === "function") {
252
+ return this.get(index, undefined, options);
253
+ }
254
+ const done = callback ?? (() => undefined);
255
+ if (this.#closed) {
256
+ queueMicrotask(() => done(new Error("Piece store is closed.")));
257
+ return;
258
+ }
259
+
260
+ const pieceLength = this.#lengthOf(index);
261
+ const offset = options?.offset ?? 0;
262
+ const length = options?.length ?? pieceLength - offset;
263
+
264
+ const fetch = async () => {
265
+ const slot = this.#slotOf.get(index);
266
+ if (slot !== undefined) {
267
+ this.#lru.touch(index);
268
+ const start = slot * this.#chunkLength + offset;
269
+ return Buffer.from(this.#pool.subarray(start, start + length));
270
+ }
271
+
272
+ if (!this.#disk.has(index)) {
273
+ throw new Error(`Piece ${index} is not in the store.`);
274
+ }
275
+
276
+ // Bring it back into memory: it was just asked for, so it is likely to be
277
+ // asked for again, and the caller may follow up with `locate`.
278
+ const revived = await this.#claimSlot();
279
+ const target = this.#pool.subarray(
280
+ revived * this.#chunkLength,
281
+ revived * this.#chunkLength + pieceLength
282
+ );
283
+ await this.#disk.read(index, target);
284
+ this.#slotOf.set(index, revived);
285
+ this.#lru.touch(index);
286
+ const start = revived * this.#chunkLength + offset;
287
+ return Buffer.from(this.#pool.subarray(start, start + length));
288
+ };
289
+
290
+ fetch().then((bytes) => done(null, bytes), (error) => done(error));
291
+ }
292
+
293
+ /**
294
+ * Close the store, keeping the spill file.
295
+ *
296
+ * @param {(error?: Error | null) => void} [callback]
297
+ * @returns {void}
298
+ */
299
+ close(callback = () => undefined) {
300
+ this.#closed = true;
301
+ this.#disk.close().then(() => callback(null), (error) => callback(error));
302
+ }
303
+
304
+ /**
305
+ * Close the store and delete everything it wrote.
306
+ *
307
+ * @param {(error?: Error | null) => void} [callback]
308
+ * @returns {void}
309
+ */
310
+ destroy(callback = () => undefined) {
311
+ this.#closed = true;
312
+ this.#slotOf.clear();
313
+ this.#disk.destroy().then(() => callback(null), (error) => callback(error));
314
+ }
315
+ }