@torrent-tv/proxy 2.83.3 → 2.83.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/package.json +1 -1
  3. package/research/handover-reader-claims-removal-2026-09-12.md +166 -0
  4. package/research/piece-withdrawn-but-still-claimed-2026-09-12.md +175 -0
  5. package/research/priority-map-is-the-truth-2026-09-12.md +225 -0
  6. package/routes/api/sources/files/get.js +23 -9
  7. package/routes/api/sources/warm/post.js +26 -22
  8. package/routes/api/transcode-sessions/post.js +1 -49
  9. package/routes/stream/get.js +2 -36
  10. package/services/controllers/SubtitleController.js +0 -3
  11. package/services/download/withdraw-claim.js +80 -0
  12. package/services/hls-session-manager.js +17 -110
  13. package/services/orchestrators/EncodeOrchestrator.js +133 -0
  14. package/services/piece-store/piece-disk-store.js +24 -1
  15. package/services/piece-store/shared-piece-store.js +71 -1
  16. package/services/playback-planner.js +12 -13
  17. package/services/priority/PriorityOrchestrator.js +40 -6
  18. package/services/torrent/Contents.js +324 -0
  19. package/services/torrent/files.js +8 -1
  20. package/services/torrent-pool.js +378 -102
  21. package/services/torrent-worker/client.js +0 -24
  22. package/services/torrent-worker/piece-reader.js +30 -1
  23. package/services/torrent-worker/pool-adapter.js +3 -33
  24. package/services/torrent-worker/protocol.js +0 -4
  25. package/services/torrent-worker/worker.js +60 -60
  26. package/test/file-edges.test.js +191 -0
  27. package/test/input-lost-quiets-the-plan.test.js +261 -0
  28. package/test/logger-repeats.test.js +120 -0
  29. package/test/priority-map-emptied.test.js +207 -0
  30. package/test/read-survives-withdrawal.test.js +164 -0
  31. package/test/source-files-route.test.js +103 -0
  32. package/test/stream-route.test.js +4 -8
  33. package/test/swarm-follows-readers.test.js +96 -14
  34. package/test/torrent-contents.test.js +235 -0
  35. package/test/upload-hurry.test.js +66 -28
  36. package/test/withdraw-piece-claim.test.js +212 -0
  37. package/utils/logger.js +105 -7
  38. package/services/torrent-worker/file-claims.js +0 -91
  39. package/test/file-claims.test.js +0 -64
@@ -18,6 +18,40 @@
18
18
  import test from "node:test";
19
19
  import assert from "node:assert/strict";
20
20
  import { decideUploadLimit, torrentsForUploadPolicy } from "../services/torrent-pool.js";
21
+ import { demandFor, forgetTorrent } from "../services/download/registry.js";
22
+ import { Urgency } from "../services/demand/index.js";
23
+
24
+ /**
25
+ * A torrent whose metadata has arrived and which nothing is wanted of.
26
+ *
27
+ * The files matter: a torrent with no list of files cannot be stated about at
28
+ * all, and is wanted for that reason alone — it is still being fetched.
29
+ *
30
+ * @param {string} name
31
+ * @returns {object}
32
+ */
33
+ function quiet(name) {
34
+ return { name, files: [{ offset: 0, length: 1_000, name }] };
35
+ }
36
+
37
+ /**
38
+ * The same, with something stated for it — which is what "somebody wants this"
39
+ * means now that nothing counts readers.
40
+ *
41
+ * @param {string} name
42
+ * @returns {object}
43
+ */
44
+ function wanted(name) {
45
+ const torrent = quiet(name);
46
+ demandFor(torrent).register.state({
47
+ claimant: "priority-map:0:0",
48
+ fileIndex: 0,
49
+ byteStart: 0,
50
+ byteEnd: 999,
51
+ urgency: Urgency.NEAR
52
+ });
53
+ return torrent;
54
+ }
21
55
 
22
56
  const NOW = 1_000_000;
23
57
  const healthy = (extra = {}) => ({
@@ -65,34 +99,38 @@ test("the reciprocity boost still works when no hurry is on", () => {
65
99
  assert.match(decision.reason, /earn unchoke/);
66
100
  });
67
101
 
68
- test("a torrent with no reader still reaches the policy while it is in a hurry", () => {
102
+ test("a torrent nothing is wanted of still reaches the policy while it is in a hurry", () => {
69
103
  // The moment that matters: a torrent has just been added and its head and
70
- // tail are being fetched for the codec probe. That read goes straight to
71
- // `createReadStream`, so no reader is registeredand the selection only
72
- // ever kept torrents that had one, which is where the gap was.
73
- const hurrying = { name: "film.mkv", hurryUntil: NOW + 20_000 };
74
- const idle = { name: "other.mkv" };
75
- const usage = new Map();
76
-
77
- assert.deepEqual(
78
- torrentsForUploadPolicy([hurrying, idle], usage, NOW),
79
- [hurrying],
80
- "a torrent with no reader yet was ignored"
81
- );
104
+ // tail are being fetched for the codec probe. Nothing is stated for it yet,
105
+ // and the selection only ever kept torrents something was which is where
106
+ // the gap was.
107
+ const hurrying = quiet("film.mkv");
108
+ hurrying.hurryUntil = NOW + 20_000;
109
+ const idle = quiet("other.mkv");
110
+ const watched = wanted("watched.mkv");
111
+ try {
112
+ assert.deepEqual(
113
+ torrentsForUploadPolicy([hurrying, idle], NOW),
114
+ [hurrying],
115
+ "a torrent nothing is stated for yet was ignored"
116
+ );
82
117
 
83
- assert.deepEqual(
84
- torrentsForUploadPolicy([{ ...hurrying, hurryUntil: NOW - 1 }, idle], usage, NOW),
85
- [],
86
- "and stops counting once the rush is over"
87
- );
118
+ assert.deepEqual(
119
+ torrentsForUploadPolicy([{ ...hurrying, hurryUntil: NOW - 1 }, idle], NOW),
120
+ [],
121
+ "and stops counting once the rush is over"
122
+ );
88
123
 
89
- const read = { name: "watched.mkv" };
90
- usage.set(read, new Set([0]));
91
- assert.deepEqual(
92
- torrentsForUploadPolicy([read], usage, NOW),
93
- [read],
94
- "a torrent being read still counts, hurry or not"
95
- );
124
+ assert.deepEqual(
125
+ torrentsForUploadPolicy([watched], NOW),
126
+ [watched],
127
+ "a torrent somebody wants something of still counts, hurry or not"
128
+ );
129
+ } finally {
130
+ forgetTorrent(hurrying);
131
+ forgetTorrent(idle);
132
+ forgetTorrent(watched);
133
+ }
96
134
  });
97
135
 
98
136
  test("a torrent nobody is reading is not treated as starving", () => {
@@ -102,7 +140,7 @@ test("a torrent nobody is reading is not treated as starving", () => {
102
140
  // minutes, every one of them reported as `earn unchoke ... down=0KB/s`.
103
141
  const idleButChoked = {
104
142
  name: "film.mkv",
105
- hasActiveReader: false,
143
+ isWanted: false,
106
144
  wires: [
107
145
  { amInterested: true, peerChoking: true },
108
146
  { amInterested: true, peerChoking: true }
@@ -112,7 +150,7 @@ test("a torrent nobody is reading is not treated as starving", () => {
112
150
  };
113
151
  assert.equal(decideUploadLimit([idleButChoked], { now: NOW }).bytesPerSec, 50 * 1024);
114
152
 
115
- const waiting = { ...idleButChoked, hasActiveReader: true };
153
+ const waiting = { ...idleButChoked, isWanted: true };
116
154
  assert.equal(
117
155
  decideUploadLimit([waiting], { now: NOW }).bytesPerSec,
118
156
  512 * 1024,
@@ -128,7 +166,7 @@ test("a torrent short of nothing is not worth uploading for", () => {
128
166
  // buying while somebody is still short of bytes.
129
167
  const complete = {
130
168
  name: "watched to the end",
131
- hasActiveReader: true,
169
+ isWanted: true,
132
170
  hasUnmetDemand: false,
133
171
  done: false,
134
172
  downloadSpeed: 0,
@@ -0,0 +1,212 @@
1
+ /**
2
+ * @file One owner of the fact "this proxy has piece N".
3
+ *
4
+ * The store holds the bytes, so it owns the fact. The library keeps a second
5
+ * copy of it in its completion bitfield, and until 2026-09-12 nothing
6
+ * reconciled them: the disk tier dropped a piece once every reader was past it
7
+ * — correctly, that is what bounds the spill — and the bitfield went on saying
8
+ * the piece was verified. A read then concluded the piece was had, asked for it,
9
+ * was told it was absent, and failed; nothing fetched it again either, because
10
+ * the library does not download what it believes it owns. Field: a film played
11
+ * 80 seconds and then answered `Piece 0 is verified but absent from the store`
12
+ * for 92 minutes.
13
+ *
14
+ * Pinned here: the announcement and its one rule — said when the piece has gone
15
+ * from EVERYWHERE, never when one tier alone lost it — and the withdrawal.
16
+ */
17
+
18
+ import test from "node:test";
19
+ import assert from "node:assert/strict";
20
+ import os from "node:os";
21
+ import path from "node:path";
22
+ import fs from "node:fs/promises";
23
+ import { SharedPieceStore } from "../services/piece-store/shared-piece-store.js";
24
+ import { withdrawClaim } from "../services/download/withdraw-claim.js";
25
+
26
+ const PIECE = 1024;
27
+
28
+ /**
29
+ * A store of four pieces with room for one, so every admission spills the last,
30
+ * plus the announcements it made.
31
+ */
32
+ async function storeWithGone(extras = {}) {
33
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "withdraw-test-"));
34
+ /** @type {number[]} */
35
+ const gone = [];
36
+ const store = new SharedPieceStore(PIECE, {
37
+ length: 4 * PIECE,
38
+ memoryBytes: PIECE,
39
+ path: directory,
40
+ name: "test",
41
+ files: [{ offset: 0, length: 4 * PIECE, name: "file.bin" }],
42
+ onPieceGone: ({ index }) => gone.push(index),
43
+ ...extras
44
+ });
45
+ const put = (index) => new Promise((resolve, reject) => {
46
+ store.put(index, Buffer.alloc(PIECE, index + 1), (error) => (error ? reject(error) : resolve()));
47
+ });
48
+ const clean = async () => {
49
+ store.destroy(() => undefined);
50
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
51
+ };
52
+ return { store, gone, put, clean };
53
+ }
54
+
55
+ /**
56
+ * Wait for the CONDITION, with a deadline only as a backstop. A fixed pause
57
+ * here would measure the machine rather than the store.
58
+ *
59
+ * @param {() => boolean} ready
60
+ * @param {string} what
61
+ */
62
+ async function until(ready, what) {
63
+ const deadline = Date.now() + 5_000;
64
+ while (!ready()) {
65
+ if (Date.now() > deadline) {
66
+ throw new Error(`timed out waiting for ${what}`);
67
+ }
68
+ await new Promise((resolve) => setImmediate(resolve));
69
+ }
70
+ }
71
+
72
+ test("a piece left behind every reader is dropped AND the claim withdrawn", async () => {
73
+ const { store, gone, put, clean } = await storeWithGone();
74
+ try {
75
+ await put(0);
76
+ await put(1);
77
+ await put(2);
78
+ // WHERE THE READERS STAND, which is the whole trigger: the encoder ran
79
+ // ahead, so pieces 0-1 are behind every one of them. This is the production
80
+ // path — `reviseSpillCeiling` asks `forgetBehind(readHeads)` — and it is
81
+ // what dropped 565 pieces in the field.
82
+ store.protectRange("reader", 2, 3, 0);
83
+ const revision = store.reviseSpillCeiling(null);
84
+
85
+ assert.ok(revision.behind >= 1, `something should have been dropped, got ${revision.behind}`);
86
+ assert.ok(gone.includes(0), `piece 0 has gone and should say so, got ${JSON.stringify(gone)}`);
87
+ assert.ok(
88
+ gone.every((index) => index < 2),
89
+ `nothing a reader still wants may be announced, got ${JSON.stringify(gone)}`
90
+ );
91
+ } finally {
92
+ await clean();
93
+ }
94
+ });
95
+
96
+ test("a piece dropped as a duplicate of a file held whole is NOT announced", async () => {
97
+ const { store, gone, put, clean } = await storeWithGone({
98
+ // Every piece can be had from the assembled file, which is exactly why the
99
+ // spilled copy is being dropped. Nothing has been lost, so nothing is said.
100
+ isPieceElsewhere: () => true
101
+ });
102
+ try {
103
+ await put(0);
104
+ await put(1);
105
+ await put(2);
106
+ // The spill is what puts a piece on disk, and it finishes on its own time;
107
+ // dropping duplicates deliberately leaves a piece whose spill is still in
108
+ // flight alone, so the precondition is waited for rather than assumed.
109
+ await until(() => store.stats().spilled >= 1, "a piece to reach the disk");
110
+ const dropped = store.dropDuplicatesHeldElsewhere();
111
+ assert.ok(dropped >= 1, "the spilled duplicate should have been dropped");
112
+ assert.deepEqual(gone, [], "a piece still readable from a whole file has not gone");
113
+ } finally {
114
+ await clean();
115
+ }
116
+ });
117
+
118
+ test("a closing store announces nothing, because its torrent is going too", async () => {
119
+ const { store, gone, put, clean } = await storeWithGone();
120
+ try {
121
+ await put(0);
122
+ await put(1);
123
+ store.protectRange("reader", 2, 3, 0);
124
+ store.close(() => undefined);
125
+ store.reviseSpillCeiling(null);
126
+ assert.deepEqual(gone, [], "a claim withdrawn against a dying torrent reaches nothing useful");
127
+ } finally {
128
+ await clean();
129
+ }
130
+ });
131
+
132
+ test("the withdrawal is counted in the store's own figures", async () => {
133
+ const { store, put, clean } = await storeWithGone();
134
+ try {
135
+ await put(0);
136
+ await put(1);
137
+ await put(2);
138
+ store.protectRange("reader", 2, 3, 0);
139
+ store.reviseSpillCeiling(null);
140
+ assert.ok(
141
+ store.stats().withdrawn >= 1,
142
+ "the figure that makes the eviction's bargain checkable must move"
143
+ );
144
+ } finally {
145
+ await clean();
146
+ }
147
+ });
148
+
149
+ test("a piece the library thinks it has is withdrawn", () => {
150
+ const asked = [];
151
+ const torrent = {
152
+ name: "film.mkv",
153
+ destroyed: false,
154
+ bitfield: { get: () => true },
155
+ _markUnverified: (index) => asked.push(index)
156
+ };
157
+ assert.equal(withdrawClaim({ index: 3, files: [{ _torrent: torrent }] }), "withdrawn");
158
+ assert.deepEqual(asked, [3]);
159
+ });
160
+
161
+ test("a piece the library already knows is missing is left alone", () => {
162
+ let touched = 0;
163
+ const torrent = {
164
+ destroyed: false,
165
+ bitfield: { get: () => false },
166
+ _markUnverified: () => { touched += 1; }
167
+ };
168
+ assert.equal(
169
+ withdrawClaim({ index: 7, torrent }),
170
+ "nothing-to-withdraw",
171
+ "re-creating a piece the library is already fetching would discard its blocks in flight"
172
+ );
173
+ assert.equal(touched, 0);
174
+ });
175
+
176
+ test("a destroyed torrent is left alone", () => {
177
+ let touched = 0;
178
+ const torrent = {
179
+ destroyed: true,
180
+ bitfield: { get: () => true },
181
+ _markUnverified: () => { touched += 1; }
182
+ };
183
+ assert.equal(withdrawClaim({ index: 1, torrent }), "no-torrent");
184
+ assert.equal(touched, 0);
185
+ });
186
+
187
+ test("a library that refuses says so instead of failing the eviction", () => {
188
+ const said = [];
189
+ const torrent = {
190
+ name: "film.mkv",
191
+ destroyed: false,
192
+ bitfield: { get: () => true },
193
+ _markUnverified: () => { throw new Error("no such method any more"); }
194
+ };
195
+ assert.equal(withdrawClaim({ index: 2, torrent, warn: (line) => said.push(line) }), "refused");
196
+ assert.equal(said.length, 1);
197
+ assert.match(said[0], /piece 2 of film\.mkv/);
198
+ });
199
+
200
+ test("a store with nobody listening evicts exactly as it did before", async () => {
201
+ const { store, put, clean } = await storeWithGone({ onPieceGone: undefined });
202
+ try {
203
+ await put(0);
204
+ await put(1);
205
+ await put(2);
206
+ store.protectRange("reader", 2, 3, 0);
207
+ const revision = store.reviseSpillCeiling(null);
208
+ assert.ok(revision.behind >= 1, "the eviction does not depend on anybody listening");
209
+ } finally {
210
+ await clean();
211
+ }
212
+ });
package/utils/logger.js CHANGED
@@ -27,11 +27,18 @@ const PREFIX = "[proxy-client]";
27
27
  /**
28
28
  * When the file is rotated, and how many turns are kept.
29
29
  *
30
- * One turn holds a few hours of a busy session at the current rate; two turns
31
- * therefore cover a night's worth of restarts, which is the span a morning
32
- * report asks about. Bounded because the addon's `/data` is the owner's disk.
30
+ * **Why it is this large.** It was 32 MiB, and that erased the beginning of
31
+ * the very failure it was needed for. Field 2026-09-12: a session froze at
32
+ * 17:20 and printed one established fact about 55 times a second, so the file
33
+ * turned over twice before the session ended — 159 000 lines covering
34
+ * 17:51-18:29, then 76 385 covering 18:29-18:52. Sixty-one minutes was all
35
+ * that survived of ninety-two, and the second rotation overwrote the turn that
36
+ * held the onset. The disk it is bounded for had 91.4 GB free at the time.
37
+ *
38
+ * The repetition is a separate fault and is being fixed separately; a log that
39
+ * cannot hold a session either way is the one that has to go first.
33
40
  */
34
- const MAX_FILE_BYTES = 32 * 1024 * 1024;
41
+ const MAX_FILE_BYTES = 1024 * 1024 * 1024;
35
42
 
36
43
  /** @type {import("node:fs").WriteStream | null} */
37
44
  let fileStream = null;
@@ -159,6 +166,92 @@ export const logger = {
159
166
  error: (message) => write("error", message, chalk.red, console.error)
160
167
  };
161
168
 
169
+ /**
170
+ * An established fact is said once, then with decreasing frequency.
171
+ *
172
+ * **Why.** A failure that establishes itself and does not change is printed by
173
+ * whatever loop meets it, at that loop's own rate. Field 2026-09-12: one
174
+ * absent piece produced 235 000 lines in 92 minutes — `Error opening input
175
+ * file …` 8514 times, `Error opening input files: End of file` 5712, the same
176
+ * `run-state` transition 2892, the same read failure 2884 — about 55 lines a
177
+ * second, and it turned the log over twice so the beginning of the failure was
178
+ * gone before anyone read it. A log is not vitiated by its size alone; it is
179
+ * vitiated by uniformity, and a bigger file does not fix that.
180
+ *
181
+ * **Matched VERBATIM — the whole line, no normalisation of numbers.** Measured
182
+ * on that log: exact repeats are 52 567 of 76 385 lines, 68.8 %, which is
183
+ * nearly all of the flood and carries no risk at all of merging two different
184
+ * statements. Normalising digits would catch a little more and would also merge
185
+ * the memory series — `rss=327MB`, `rss=726MB` — which exists precisely to
186
+ * catch a runaway, and suppressing it would be worse than the flood.
187
+ */
188
+ const REPEAT_FIRST_MS = 1_000;
189
+ const REPEAT_MAX_MS = 60_000;
190
+ /**
191
+ * How many distinct lines are tracked. Bounded because it is keyed by the full
192
+ * text: a process that logs unique lines for ever must not grow a map of them.
193
+ */
194
+ const REPEAT_KEYS = 512;
195
+ /** @type {Map<string, { suppressed: number, printedAt: number, interval: number }>} */
196
+ const recent = new Map();
197
+
198
+ /**
199
+ * Whether this line is a repeat to hold back, and what to say if it is not.
200
+ *
201
+ * @param {string} message
202
+ * @returns {{ hold: true } | { hold: false, suffix: string }}
203
+ */
204
+ function repeatCheck(message) {
205
+ const now = Date.now();
206
+ const seen = recent.get(message);
207
+ // Unseen, or not seen for longer than the longest interval — which makes it
208
+ // news again rather than a continuing fact.
209
+ if (!seen || now - seen.printedAt > REPEAT_MAX_MS) {
210
+ // WHAT WAS HELD BACK IS STILL SAID. A stale entry can carry repeats that
211
+ // were never reported — a line said just under its interval and then not
212
+ // again for a while — and dropping the count here would be the quiet lie
213
+ // this whole rule exists to avoid.
214
+ const heldBack = seen?.suppressed ?? 0;
215
+ const overMs = seen ? now - seen.printedAt : 0;
216
+ recent.delete(message);
217
+ if (recent.size >= REPEAT_KEYS) {
218
+ // The least recently printed goes: `Map` keeps insertion order and every
219
+ // print re-inserts, so the first key is the oldest.
220
+ const oldest = recent.keys().next();
221
+ if (!oldest.done) {
222
+ recent.delete(oldest.value);
223
+ }
224
+ }
225
+ recent.set(message, { suppressed: 0, printedAt: now, interval: REPEAT_FIRST_MS });
226
+ return {
227
+ hold: false,
228
+ suffix: heldBack > 0
229
+ ? ` [said ${heldBack} more time(s) in the last ${(overMs / 1000).toFixed(1)}s]`
230
+ : ""
231
+ };
232
+ }
233
+ if (now - seen.printedAt < seen.interval) {
234
+ seen.suppressed += 1;
235
+ return { hold: true };
236
+ }
237
+ const heldBack = seen.suppressed;
238
+ const overMs = now - seen.printedAt;
239
+ recent.delete(message);
240
+ recent.set(message, {
241
+ suppressed: 0,
242
+ printedAt: now,
243
+ interval: Math.min(REPEAT_MAX_MS, seen.interval * 2)
244
+ });
245
+ return {
246
+ hold: false,
247
+ // SAID, not merely hidden: the rate is the fact here, and a log that quietly
248
+ // drops repeats reports a healthy proxy where a loop was spinning.
249
+ suffix: heldBack > 0
250
+ ? ` [said ${heldBack} more time(s) in the last ${(overMs / 1000).toFixed(1)}s]`
251
+ : ""
252
+ };
253
+ }
254
+
162
255
  /**
163
256
  * One path for every level, so a line cannot reach the console and miss the
164
257
  * file depending on which method was called or which thread called it.
@@ -170,15 +263,20 @@ export const logger = {
170
263
  * @returns {void}
171
264
  */
172
265
  function write(level, message, colour, toConsole) {
173
- toConsole(colour(`${PREFIX} [${ts()}] ${message}`));
266
+ const repeat = repeatCheck(message);
267
+ if (repeat.hold) {
268
+ return;
269
+ }
270
+ const line = `${message}${repeat.suffix}`;
271
+ toConsole(colour(`${PREFIX} [${ts()}] ${line}`));
174
272
  if (forward) {
175
273
  try {
176
- forward(level, message);
274
+ forward(level, line);
177
275
  } catch {
178
276
  // silent-ok: a thread whose channel has closed is shutting down, and a
179
277
  // failed log line must not be what ends it.
180
278
  }
181
279
  return;
182
280
  }
183
- toFile(`${PREFIX} [${ts()}] ${message}`);
281
+ toFile(`${PREFIX} [${ts()}] ${line}`);
184
282
  }
@@ -1,91 +0,0 @@
1
- /**
2
- * @file Who is holding which file open.
3
- *
4
- * A claim keeps a file's data from being removed while something is reading it.
5
- * Until 2.9.77 claims were keyed by `sourceKey:fileIndex`, which quietly made
6
- * them **shared**: a second reader of the same file found the key taken and
7
- * added nothing, so the first reader to finish released the claim out from
8
- * under the second. The proxy reads one file from several places at once —
9
- * ffmpeg's input, the keyframe index, the codec probe, a second viewer — so
10
- * this was the normal case, not an edge one.
11
- *
12
- * The fix is not a counter. A counter restores the arithmetic but keeps the
13
- * ambiguity: a release names a file, not a claim, so a duplicate or late
14
- * release still decrements someone else's hold and nothing can detect it. Here
15
- * every claim gets its own identity and a release names exactly that claim —
16
- * so a stray release matches nothing, is reported, and harms no one.
17
- */
18
-
19
- /**
20
- * @typedef {object} FileClaims
21
- * @property {(sourceKey: string, fileIndex: number, release: () => void) => string} open
22
- * @property {(claimId: string) => boolean} close
23
- * @property {() => void} closeAll
24
- * @property {number} size
25
- */
26
-
27
- /**
28
- * Track file claims by identity.
29
- *
30
- * @returns {FileClaims}
31
- */
32
- export function createFileClaims() {
33
- /** Claim id → the function that releases that one claim. */
34
- const claims = new Map();
35
- let counter = 0;
36
-
37
- return {
38
- /**
39
- * Record a new claim and return its identity.
40
- *
41
- * Each call is a distinct claim even for the same file — that is the whole
42
- * point.
43
- *
44
- * @param {string} sourceKey
45
- * @param {number} fileIndex
46
- * @param {() => void} release
47
- * @returns {string}
48
- */
49
- open(sourceKey, fileIndex, release) {
50
- counter += 1;
51
- // The file is in the id purely so a log line reads usefully; matching is
52
- // on the whole string.
53
- const claimId = `${sourceKey}:${fileIndex}:${counter}`;
54
- claims.set(claimId, release);
55
- return claimId;
56
- },
57
-
58
- /**
59
- * Release one claim. Returns false when there was no such claim, which is
60
- * worth logging: it means a release arrived twice, or after teardown.
61
- *
62
- * @param {string} claimId
63
- * @returns {boolean}
64
- */
65
- close(claimId) {
66
- const release = claims.get(claimId);
67
- if (!release) {
68
- return false;
69
- }
70
- claims.delete(claimId);
71
- release();
72
- return true;
73
- },
74
-
75
- /**
76
- * Release everything — the worker is shutting down.
77
- *
78
- * @returns {void}
79
- */
80
- closeAll() {
81
- for (const [, release] of claims) {
82
- release();
83
- }
84
- claims.clear();
85
- },
86
-
87
- get size() {
88
- return claims.size;
89
- }
90
- };
91
- }
@@ -1,64 +0,0 @@
1
- /**
2
- * @file File claims must be held per reader, not per file.
3
- *
4
- * The proxy reads one file from several places at once — ffmpeg's input, the
5
- * keyframe index, the codec probe, a second viewer. Keying claims by file made
6
- * them shared, so the first reader to finish released the hold while the others
7
- * were still reading, and the file's data could then be removed under them.
8
- */
9
-
10
- import test from "node:test";
11
- import assert from "node:assert/strict";
12
- import { createFileClaims } from "../services/torrent-worker/file-claims.js";
13
-
14
- test("two readers of one file hold two claims", () => {
15
- const claims = createFileClaims();
16
- let released = 0;
17
-
18
- const first = claims.open("source", 0, () => (released += 1));
19
- const second = claims.open("source", 0, () => (released += 1));
20
-
21
- assert.notEqual(first, second, "the second reader reused the first one's claim");
22
- assert.equal(claims.size, 2);
23
-
24
- claims.close(first);
25
- assert.equal(released, 1, "closing one claim released more than one hold");
26
- assert.equal(claims.size, 1, "the second reader's claim went with the first");
27
-
28
- claims.close(second);
29
- assert.equal(released, 2);
30
- assert.equal(claims.size, 0);
31
- });
32
-
33
- test("a repeated release affects nothing and reports itself", () => {
34
- const claims = createFileClaims();
35
- let released = 0;
36
- const claimId = claims.open("source", 3, () => (released += 1));
37
-
38
- assert.equal(claims.close(claimId), true);
39
- assert.equal(claims.close(claimId), false, "a second release was accepted as valid");
40
- assert.equal(released, 1, "the hold was released twice");
41
- });
42
-
43
- test("a release naming nothing is rejected rather than guessed at", () => {
44
- const claims = createFileClaims();
45
- let released = 0;
46
- claims.open("source", 0, () => (released += 1));
47
-
48
- assert.equal(claims.close("source:0:999"), false);
49
- assert.equal(released, 0, "an unknown claim released a real hold");
50
- assert.equal(claims.size, 1);
51
- });
52
-
53
- test("teardown releases every outstanding claim", () => {
54
- const claims = createFileClaims();
55
- let released = 0;
56
- claims.open("a", 0, () => (released += 1));
57
- claims.open("a", 1, () => (released += 1));
58
- claims.open("b", 0, () => (released += 1));
59
-
60
- claims.closeAll();
61
-
62
- assert.equal(released, 3);
63
- assert.equal(claims.size, 0);
64
- });