@torrent-tv/proxy 2.80.19 → 2.81.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +1 -1
  3. package/research/double-spawn-2026-09-10.md +171 -0
  4. package/services/disk/DiskSpace.js +150 -0
  5. package/services/disk/wire.js +60 -0
  6. package/services/encode/EncodeRun.js +25 -3
  7. package/services/encode/SegmentStore.js +137 -9
  8. package/services/hls-session-manager.js +26 -45
  9. package/services/orchestrators/EncodeOrchestrator.js +4 -1
  10. package/services/piece-store/allowance.js +107 -0
  11. package/services/piece-store/piece-disk-store.js +365 -0
  12. package/services/piece-store/shared-piece-store.js +1549 -1535
  13. package/services/torrent-worker/client.js +32 -0
  14. package/services/torrent-worker/pool-adapter.js +15 -0
  15. package/services/torrent-worker/protocol.js +9 -0
  16. package/services/torrent-worker/worker.js +8 -1
  17. package/services/viewer/positions.js +48 -0
  18. package/test/audio-inventory.test.js +176 -176
  19. package/test/auto-quality-step.test.js +514 -514
  20. package/test/concurrent-cost.test.js +138 -138
  21. package/test/coverage-follows-the-disk.test.js +191 -191
  22. package/test/coverage-map.test.js +195 -195
  23. package/test/declared-tracks.test.js +35 -35
  24. package/test/disk-space.test.js +150 -0
  25. package/test/encode-orchestrator.test.js +0 -3
  26. package/test/encode-run.test.js +5 -12
  27. package/test/held-request-width.test.js +155 -155
  28. package/test/helpers/encode-run.js +2 -2
  29. package/test/matroska-blocks.test.js +0 -0
  30. package/test/matroska-cues-track.test.js +192 -192
  31. package/test/mp4-composition-times.test.js +0 -0
  32. package/test/mp4-subtitles.test.js +173 -173
  33. package/test/one-authority.test.js +281 -220
  34. package/test/orchestrator-wired.test.js +199 -199
  35. package/test/packet-witness-ring.test.js +236 -236
  36. package/test/packet-witness.test.js +148 -148
  37. package/test/piece-disk-store.test.js +267 -0
  38. package/test/piece-reader.test.js +4 -4
  39. package/test/piece-store-eviction.test.js +17 -17
  40. package/test/piece-store-reservations.test.js +20 -1
  41. package/test/piece-store-slow-disk.test.js +16 -1
  42. package/test/read-window.test.js +6 -6
  43. package/test/run-intervals.test.js +100 -100
  44. package/test/seek-landing.test.js +109 -109
  45. package/test/segment-store-eviction.test.js +232 -0
  46. package/test/segments-are-shared.test.js +1 -1
  47. package/test/shared-piece-store.test.js +12 -12
  48. package/test/sidecar-naming.test.js +142 -142
  49. package/test/subtitle-cue-framing.test.js +200 -200
  50. package/test/subtitle-cue-walk.test.js +369 -369
  51. package/test/subtitle-defaults.test.js +97 -97
  52. package/test/subtitle-track-numbering.test.js +370 -370
  53. package/test/tail-duplication.test.js +167 -167
  54. package/test/tracks-begin-together.test.js +195 -195
  55. package/test/two-viewers-one-picture.test.js +374 -374
  56. package/test/video-facts.test.js +102 -102
  57. package/test/wedge-certainty.test.js +131 -131
  58. package/services/piece-store/disk-tier.js +0 -151
@@ -1,148 +1,148 @@
1
- /**
2
- * @file The packet witness's gating rules and command construction.
3
- *
4
- * Roadmap item 10: a send queue wedged longer than ~30 s must start a bounded
5
- * tcpdump on its own, because the 2026-08-24 episode proved no counter above
6
- * the wire can name the cause. Everything here is the part that decides WHEN
7
- * and WITH WHAT ARGUMENTS — the spawning itself is thin glue around these.
8
- */
9
-
10
- import assert from "node:assert/strict";
11
- import test from "node:test";
12
-
13
- import {
14
- buildTcpdumpArgs,
15
- createPacketWitness,
16
- isWitnessCapture,
17
- isWitnessRingFile,
18
- normalizeRemoteAddress,
19
- shouldStartCapture,
20
- WITNESS_RING_FILE_MB,
21
- WITNESS_RING_FILES,
22
- WITNESS_RTO_CEILING_SECONDS,
23
- WITNESS_TAIL_SECONDS
24
- } from "../services/packet-witness.js";
25
-
26
- test("an IPv4 literal survives unchanged", () => {
27
- assert.equal(normalizeRemoteAddress("192.168.178.57"), "192.168.178.57");
28
- });
29
-
30
- test("an IPv6 literal survives unchanged", () => {
31
- assert.equal(
32
- normalizeRemoteAddress("2001:1c00:a603:2100:a129:a1a1:7f07:3f0b"),
33
- "2001:1c00:a603:2100:a129:a1a1:7f07:3f0b"
34
- );
35
- });
36
-
37
- test("a zone suffix is stripped", () => {
38
- assert.equal(normalizeRemoteAddress("fe80::2aca:8001:3ba6:f16f%18"), "fe80::2aca:8001:3ba6:f16f");
39
- });
40
-
41
- test("hostnames, garbage and shell text are rejected", () => {
42
- assert.equal(normalizeRemoteAddress("homeassistant.local"), null);
43
- assert.equal(normalizeRemoteAddress("8.8.8.8; rm -rf /"), null);
44
- assert.equal(normalizeRemoteAddress("999.1.1.1"), null);
45
- assert.equal(normalizeRemoteAddress(""), null);
46
- assert.equal(normalizeRemoteAddress(undefined), null);
47
- assert.equal(normalizeRemoteAddress(42), null);
48
- });
49
-
50
- test("the tcpdump command line is bounded and filtered to one peer", () => {
51
- const args = buildTcpdumpArgs({
52
- host: "2001:db8::1",
53
- port: 9090,
54
- filePrefix: "/data/packet-witness.e2b5ef39.1787600000.pcap"
55
- });
56
- assert.deepEqual(args, [
57
- "-n",
58
- "-S",
59
- "-s",
60
- "128",
61
- "-i",
62
- "any",
63
- "-w",
64
- "/data/packet-witness.e2b5ef39.1787600000.pcap",
65
- "-C",
66
- String(WITNESS_RING_FILE_MB),
67
- "-W",
68
- String(WITNESS_RING_FILES),
69
- "udp",
70
- "and",
71
- "port",
72
- "9090",
73
- "and",
74
- "host",
75
- "2001:db8::1"
76
- ]);
77
- });
78
-
79
- test("rotation is by size, so the ring files cannot collapse onto one name", () => {
80
- // `-G` with a name carrying no strftime field overwrote a single file, which
81
- // is why both field captures held 28 s instead of the intended 120.
82
- const args = buildTcpdumpArgs({ port: 9090, filePrefix: "/data/ring.pcap" });
83
- assert.equal(args.includes("-G"), false);
84
- assert.equal(args[args.indexOf("-C") + 1], String(WITNESS_RING_FILE_MB));
85
- });
86
-
87
- test("with no peer named the ring records every peer on the port", () => {
88
- const args = buildTcpdumpArgs({ port: 9090, filePrefix: "/data/ring.pcap" });
89
- assert.equal(args.includes("host"), false);
90
- assert.deepEqual(args.slice(-4), ["udp", "and", "port", "9090"]);
91
- });
92
-
93
- test("the tail outlasts three retransmission timeouts", () => {
94
- assert.equal(WITNESS_TAIL_SECONDS, WITNESS_RTO_CEILING_SECONDS * 3);
95
- // A zero-window probe is due once per timeout, so a window shorter than the
96
- // ceiling could not tell silence from a probe that had not come round yet.
97
- assert.ok(WITNESS_TAIL_SECONDS > WITNESS_RTO_CEILING_SECONDS);
98
- });
99
-
100
- test("ring files are told apart from the copies kept as evidence", () => {
101
- assert.equal(isWitnessRingFile("packet-witness-ring.pcap"), true);
102
- assert.equal(isWitnessRingFile("packet-witness-ring.pcap3"), true);
103
- assert.equal(isWitnessRingFile("packet-witness.e2b5ef39.1787600000.before1.pcap"), false);
104
- assert.equal(isWitnessCapture("packet-witness-ring.pcap3"), false);
105
- assert.equal(isWitnessCapture("packet-witness.e2b5ef39.1787600000.before1.pcap"), true);
106
- assert.equal(isWitnessCapture("packet-witness.e2b5ef39.1787600000.tail.pcap1"), true);
107
- });
108
-
109
- test("one capture runs at a time", () => {
110
- assert.equal(shouldStartCapture({ running: true, lastStartedAt: Date.now() }), false);
111
- });
112
-
113
- test("the first capture of a process is always allowed", () => {
114
- assert.equal(shouldStartCapture({ running: false, lastStartedAt: 0, now: 1000 }), true);
115
- });
116
-
117
- test("a capture within the cooldown is refused, one after it is allowed", () => {
118
- const state = { running: false, lastStartedAt: 10_000 };
119
- assert.equal(shouldStartCapture({ ...state, now: 10_000 + 599_999 }), false);
120
- assert.equal(shouldStartCapture({ ...state, now: 10_000 + 600_000 }), true);
121
- });
122
-
123
- test("capture files are recognised by name, rotations included", () => {
124
- assert.equal(isWitnessCapture("packet-witness.e2b5ef39.1787600000.pcap"), true);
125
- assert.equal(isWitnessCapture("packet-witness.e2b5ef39.1787600000.pcap20260825T120000"), true);
126
- assert.equal(isWitnessCapture("core.WorkerThread.81.1787600000"), false);
127
- assert.equal(isWitnessCapture("proxy.log"), false);
128
- assert.equal(isWitnessCapture("../packet-witness.x.pcap"), false);
129
- });
130
-
131
- test("a trigger without a usable remote endpoint is refused without touching anything", () => {
132
- const lines = [];
133
- const witness = createPacketWitness({
134
- log: (message) => lines.push(message),
135
- dir: "",
136
- port: 9090
137
- });
138
- const started = witness.maybeCapture({
139
- sessionId: "e2b5ef39-0000",
140
- tag: "e2b5ef39",
141
- label: "proxy",
142
- remote: null,
143
- queuedBytes: 160_000_000,
144
- stuckForMs: 31_000
145
- });
146
- assert.equal(started, false);
147
- assert.deepEqual(lines, []);
148
- });
1
+ /**
2
+ * @file The packet witness's gating rules and command construction.
3
+ *
4
+ * Roadmap item 10: a send queue wedged longer than ~30 s must start a bounded
5
+ * tcpdump on its own, because the 2026-08-24 episode proved no counter above
6
+ * the wire can name the cause. Everything here is the part that decides WHEN
7
+ * and WITH WHAT ARGUMENTS — the spawning itself is thin glue around these.
8
+ */
9
+
10
+ import assert from "node:assert/strict";
11
+ import test from "node:test";
12
+
13
+ import {
14
+ buildTcpdumpArgs,
15
+ createPacketWitness,
16
+ isWitnessCapture,
17
+ isWitnessRingFile,
18
+ normalizeRemoteAddress,
19
+ shouldStartCapture,
20
+ WITNESS_RING_FILE_MB,
21
+ WITNESS_RING_FILES,
22
+ WITNESS_RTO_CEILING_SECONDS,
23
+ WITNESS_TAIL_SECONDS
24
+ } from "../services/packet-witness.js";
25
+
26
+ test("an IPv4 literal survives unchanged", () => {
27
+ assert.equal(normalizeRemoteAddress("192.168.178.57"), "192.168.178.57");
28
+ });
29
+
30
+ test("an IPv6 literal survives unchanged", () => {
31
+ assert.equal(
32
+ normalizeRemoteAddress("2001:1c00:a603:2100:a129:a1a1:7f07:3f0b"),
33
+ "2001:1c00:a603:2100:a129:a1a1:7f07:3f0b"
34
+ );
35
+ });
36
+
37
+ test("a zone suffix is stripped", () => {
38
+ assert.equal(normalizeRemoteAddress("fe80::2aca:8001:3ba6:f16f%18"), "fe80::2aca:8001:3ba6:f16f");
39
+ });
40
+
41
+ test("hostnames, garbage and shell text are rejected", () => {
42
+ assert.equal(normalizeRemoteAddress("homeassistant.local"), null);
43
+ assert.equal(normalizeRemoteAddress("8.8.8.8; rm -rf /"), null);
44
+ assert.equal(normalizeRemoteAddress("999.1.1.1"), null);
45
+ assert.equal(normalizeRemoteAddress(""), null);
46
+ assert.equal(normalizeRemoteAddress(undefined), null);
47
+ assert.equal(normalizeRemoteAddress(42), null);
48
+ });
49
+
50
+ test("the tcpdump command line is bounded and filtered to one peer", () => {
51
+ const args = buildTcpdumpArgs({
52
+ host: "2001:db8::1",
53
+ port: 9090,
54
+ filePrefix: "/data/packet-witness.e2b5ef39.1787600000.pcap"
55
+ });
56
+ assert.deepEqual(args, [
57
+ "-n",
58
+ "-S",
59
+ "-s",
60
+ "128",
61
+ "-i",
62
+ "any",
63
+ "-w",
64
+ "/data/packet-witness.e2b5ef39.1787600000.pcap",
65
+ "-C",
66
+ String(WITNESS_RING_FILE_MB),
67
+ "-W",
68
+ String(WITNESS_RING_FILES),
69
+ "udp",
70
+ "and",
71
+ "port",
72
+ "9090",
73
+ "and",
74
+ "host",
75
+ "2001:db8::1"
76
+ ]);
77
+ });
78
+
79
+ test("rotation is by size, so the ring files cannot collapse onto one name", () => {
80
+ // `-G` with a name carrying no strftime field overwrote a single file, which
81
+ // is why both field captures held 28 s instead of the intended 120.
82
+ const args = buildTcpdumpArgs({ port: 9090, filePrefix: "/data/ring.pcap" });
83
+ assert.equal(args.includes("-G"), false);
84
+ assert.equal(args[args.indexOf("-C") + 1], String(WITNESS_RING_FILE_MB));
85
+ });
86
+
87
+ test("with no peer named the ring records every peer on the port", () => {
88
+ const args = buildTcpdumpArgs({ port: 9090, filePrefix: "/data/ring.pcap" });
89
+ assert.equal(args.includes("host"), false);
90
+ assert.deepEqual(args.slice(-4), ["udp", "and", "port", "9090"]);
91
+ });
92
+
93
+ test("the tail outlasts three retransmission timeouts", () => {
94
+ assert.equal(WITNESS_TAIL_SECONDS, WITNESS_RTO_CEILING_SECONDS * 3);
95
+ // A zero-window probe is due once per timeout, so a window shorter than the
96
+ // ceiling could not tell silence from a probe that had not come round yet.
97
+ assert.ok(WITNESS_TAIL_SECONDS > WITNESS_RTO_CEILING_SECONDS);
98
+ });
99
+
100
+ test("ring files are told apart from the copies kept as evidence", () => {
101
+ assert.equal(isWitnessRingFile("packet-witness-ring.pcap"), true);
102
+ assert.equal(isWitnessRingFile("packet-witness-ring.pcap3"), true);
103
+ assert.equal(isWitnessRingFile("packet-witness.e2b5ef39.1787600000.before1.pcap"), false);
104
+ assert.equal(isWitnessCapture("packet-witness-ring.pcap3"), false);
105
+ assert.equal(isWitnessCapture("packet-witness.e2b5ef39.1787600000.before1.pcap"), true);
106
+ assert.equal(isWitnessCapture("packet-witness.e2b5ef39.1787600000.tail.pcap1"), true);
107
+ });
108
+
109
+ test("one capture runs at a time", () => {
110
+ assert.equal(shouldStartCapture({ running: true, lastStartedAt: Date.now() }), false);
111
+ });
112
+
113
+ test("the first capture of a process is always allowed", () => {
114
+ assert.equal(shouldStartCapture({ running: false, lastStartedAt: 0, now: 1000 }), true);
115
+ });
116
+
117
+ test("a capture within the cooldown is refused, one after it is allowed", () => {
118
+ const state = { running: false, lastStartedAt: 10_000 };
119
+ assert.equal(shouldStartCapture({ ...state, now: 10_000 + 599_999 }), false);
120
+ assert.equal(shouldStartCapture({ ...state, now: 10_000 + 600_000 }), true);
121
+ });
122
+
123
+ test("capture files are recognised by name, rotations included", () => {
124
+ assert.equal(isWitnessCapture("packet-witness.e2b5ef39.1787600000.pcap"), true);
125
+ assert.equal(isWitnessCapture("packet-witness.e2b5ef39.1787600000.pcap20260825T120000"), true);
126
+ assert.equal(isWitnessCapture("core.WorkerThread.81.1787600000"), false);
127
+ assert.equal(isWitnessCapture("proxy.log"), false);
128
+ assert.equal(isWitnessCapture("../packet-witness.x.pcap"), false);
129
+ });
130
+
131
+ test("a trigger without a usable remote endpoint is refused without touching anything", () => {
132
+ const lines = [];
133
+ const witness = createPacketWitness({
134
+ log: (message) => lines.push(message),
135
+ dir: "",
136
+ port: 9090
137
+ });
138
+ const started = witness.maybeCapture({
139
+ sessionId: "e2b5ef39-0000",
140
+ tag: "e2b5ef39",
141
+ label: "proxy",
142
+ remote: null,
143
+ queuedBytes: 160_000_000,
144
+ stuckForMs: 31_000
145
+ });
146
+ assert.equal(started, false);
147
+ assert.deepEqual(lines, []);
148
+ });
@@ -0,0 +1,267 @@
1
+ /**
2
+ * @file The spilled pieces are bounded, and the bound returns disk.
3
+ *
4
+ * What these pin is the difference between this store and the tier it replaced.
5
+ * That one wrote into one sparse file and answered `forget` by dropping a
6
+ * number: nothing it did returned a block, and a store holding 400 MB had
7
+ * written 14.4 GB to the disk in fifty minutes (field 2026-08-31). So the
8
+ * assertions here are about the DISK, read back from the file system, not about
9
+ * the store's own bookkeeping — the bookkeeping was never what was wrong.
10
+ */
11
+
12
+ import test from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import fs from "node:fs/promises";
15
+ import os from "node:os";
16
+ import path from "node:path";
17
+ import { PieceDiskStore } from "../services/piece-store/piece-disk-store.js";
18
+
19
+ const PIECE = 4096;
20
+
21
+ /**
22
+ * @param {number | null} allowanceBytes
23
+ * @returns {Promise<{ store: PieceDiskStore, directory: string, clock: { at: number } }>}
24
+ */
25
+ async function makeStore(allowanceBytes) {
26
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "piece-disk-test-"));
27
+ const clock = { at: 1000 };
28
+ const store = new PieceDiskStore({
29
+ directory,
30
+ name: "pieces",
31
+ chunkLength: PIECE,
32
+ allowanceBytes,
33
+ now: () => clock.at
34
+ });
35
+ return { store, directory, clock };
36
+ }
37
+
38
+ /**
39
+ * What the store's directory actually holds, in bytes and in files.
40
+ *
41
+ * @param {PieceDiskStore} store
42
+ * @returns {Promise<{ files: number, bytes: number }>}
43
+ */
44
+ async function onDisk(store) {
45
+ let names = [];
46
+ try {
47
+ names = await fs.readdir(store.path);
48
+ } catch {
49
+ return { files: 0, bytes: 0 };
50
+ }
51
+ let bytes = 0;
52
+ for (const name of names) {
53
+ const stat = await fs.stat(path.join(store.path, name));
54
+ bytes += stat.size;
55
+ }
56
+ return { files: names.length, bytes };
57
+ }
58
+
59
+ const pieceOf = (index) => Buffer.alloc(PIECE, index % 251);
60
+
61
+ test("told nothing, it holds everything — which is what it did before it could count", async () => {
62
+ const { store, directory } = await makeStore(null);
63
+ try {
64
+ for (let index = 0; index < 8; index += 1) {
65
+ await store.write(index, pieceOf(index));
66
+ }
67
+ assert.equal(store.size, 8, "a store with no allowance threw something away");
68
+ assert.equal(store.bytes, 8 * PIECE);
69
+ assert.deepEqual(await onDisk(store), { files: 8, bytes: 8 * PIECE });
70
+ } finally {
71
+ await store.destroy();
72
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
73
+ }
74
+ });
75
+
76
+ test("over its allowance it throws the least recently used away, and the disk shrinks with it", async () => {
77
+ const { store, directory, clock } = await makeStore(3 * PIECE);
78
+ try {
79
+ for (const index of [0, 1, 2]) {
80
+ clock.at += 100;
81
+ await store.write(index, pieceOf(index));
82
+ }
83
+ assert.deepEqual(await onDisk(store), { files: 3, bytes: 3 * PIECE }, "the store did not fill");
84
+
85
+ // Piece 0 is the oldest and nobody has read it since.
86
+ clock.at += 100;
87
+ await store.write(3, pieceOf(3));
88
+ await store.settled();
89
+
90
+ assert.equal(store.has(0), false, "the oldest piece was kept");
91
+ assert.equal(store.has(3), true, "the arriving piece was not stored");
92
+ assert.equal(store.bytes, 3 * PIECE, "the store counts more than its allowance");
93
+ // THE POINT: not the count in memory, the blocks on the disk.
94
+ assert.deepEqual(
95
+ await onDisk(store),
96
+ { files: 3, bytes: 3 * PIECE },
97
+ "the disk kept the bytes of the piece that was thrown away"
98
+ );
99
+ assert.equal(store.stats().evictions, 1);
100
+ } finally {
101
+ await store.destroy();
102
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
103
+ }
104
+ });
105
+
106
+ test("reading a piece keeps it: the oldest is not the least wanted", async () => {
107
+ const { store, directory, clock } = await makeStore(3 * PIECE);
108
+ try {
109
+ for (const index of [0, 1, 2]) {
110
+ clock.at += 100;
111
+ await store.write(index, pieceOf(index));
112
+ }
113
+ // Piece 0 is read, which makes piece 1 the oldest.
114
+ clock.at += 100;
115
+ await store.read(0, Buffer.alloc(PIECE));
116
+
117
+ clock.at += 100;
118
+ await store.write(3, pieceOf(3));
119
+ await store.settled();
120
+
121
+ assert.equal(store.has(0), true, "a piece that was just read was thrown away");
122
+ assert.equal(store.has(1), false, "the piece nobody had touched was kept");
123
+ } finally {
124
+ await store.destroy();
125
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
126
+ }
127
+ });
128
+
129
+ test("a piece being read is never the victim, however old it is", async () => {
130
+ const { store, directory, clock } = await makeStore(3 * PIECE);
131
+ try {
132
+ for (const index of [0, 1, 2]) {
133
+ clock.at += 100;
134
+ await store.write(index, pieceOf(index));
135
+ }
136
+ // Piece 0 is the oldest AND is being read. The read is not awaited, so the
137
+ // write below decides while it is still outstanding.
138
+ const reading = store.read(0, Buffer.alloc(PIECE));
139
+ clock.at += 100;
140
+ await store.write(3, pieceOf(3));
141
+ const bytes = await reading;
142
+ await store.settled();
143
+
144
+ assert.equal(bytes, PIECE, "the read did not complete");
145
+ assert.equal(store.has(0), true, "a piece being read was thrown away under the reader");
146
+ assert.equal(store.has(1), false, "the next oldest should have gone instead");
147
+ } finally {
148
+ await store.destroy();
149
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
150
+ }
151
+ });
152
+
153
+ test("a piece thrown away is answered as absent, so the swarm is asked for it again", async () => {
154
+ const { store, directory, clock } = await makeStore(PIECE);
155
+ try {
156
+ await store.write(0, pieceOf(0));
157
+ clock.at += 100;
158
+ await store.write(1, pieceOf(1));
159
+ await store.settled();
160
+
161
+ assert.equal(store.has(0), false, "the store still claims a piece it threw away");
162
+ await assert.rejects(
163
+ () => store.read(0, Buffer.alloc(PIECE)),
164
+ /Piece 0 is not on disk/,
165
+ "reading a thrown-away piece must say so rather than answer bytes"
166
+ );
167
+ } finally {
168
+ await store.destroy();
169
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
170
+ }
171
+ });
172
+
173
+ test("a piece wanted again after being thrown away is written, not refused", async () => {
174
+ const { store, directory, clock } = await makeStore(PIECE);
175
+ try {
176
+ await store.write(0, pieceOf(0));
177
+ clock.at += 100;
178
+ await store.write(1, pieceOf(1));
179
+ clock.at += 100;
180
+ // Piece 0 again, while its own removal may still be in flight.
181
+ await store.write(0, pieceOf(0));
182
+ await store.settled();
183
+
184
+ assert.equal(store.has(0), true, "the piece did not come back");
185
+ const target = Buffer.alloc(PIECE);
186
+ await store.read(0, target);
187
+ assert.ok(target.equals(pieceOf(0)), "the piece came back wrong");
188
+ assert.equal(store.bytes, PIECE, "the store is over its allowance");
189
+ } finally {
190
+ await store.destroy();
191
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
192
+ }
193
+ });
194
+
195
+ test("lowering the allowance frees nothing by itself, and binds the next write", async () => {
196
+ const { store, directory, clock } = await makeStore(null);
197
+ try {
198
+ for (const index of [0, 1, 2]) {
199
+ clock.at += 100;
200
+ await store.write(index, pieceOf(index));
201
+ }
202
+ store.reviseAllowance(PIECE);
203
+ assert.equal(store.size, 3, "lowering the allowance threw pieces away on its own");
204
+
205
+ clock.at += 100;
206
+ await store.write(3, pieceOf(3));
207
+ await store.settled();
208
+ assert.equal(store.size, 1, "the next write did not bring it within the allowance");
209
+ assert.deepEqual(await onDisk(store), { files: 1, bytes: PIECE });
210
+ } finally {
211
+ await store.destroy();
212
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
213
+ }
214
+ });
215
+
216
+ test("an allowance smaller than one piece keeps the arriving piece rather than losing it", async () => {
217
+ // A piece the swarm has already paid for is not thrown away because the
218
+ // arithmetic says there is no room for anything: the alternative is fetching
219
+ // it again, which costs ~1430 ms against a write measured in milliseconds.
220
+ const { store, directory } = await makeStore(1);
221
+ try {
222
+ await store.write(0, pieceOf(0));
223
+ await store.settled();
224
+ assert.equal(store.has(0), true, "the arriving piece was refused");
225
+ assert.equal(store.size, 1);
226
+ } finally {
227
+ await store.destroy();
228
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
229
+ }
230
+ });
231
+
232
+ test("destroying it takes the directory with it", async () => {
233
+ const { store, directory } = await makeStore(null);
234
+ await store.write(0, pieceOf(0));
235
+ const where = store.path;
236
+ await store.destroy();
237
+ await assert.rejects(() => fs.stat(where), /ENOENT/, "the store left its directory behind");
238
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
239
+ });
240
+
241
+ test("the spill ceiling is what the disk's owner said, divided between the stores", async () => {
242
+ const { reviseSpillBudgets, SharedPieceStore } = await import("../services/piece-store/shared-piece-store.js");
243
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "spill-share-"));
244
+ const stores = [
245
+ new SharedPieceStore(PIECE, { length: PIECE * 8, memoryBytes: PIECE, path: directory, name: "one" }),
246
+ new SharedPieceStore(PIECE, { length: PIECE * 8, memoryBytes: PIECE, path: directory, name: "two" })
247
+ ];
248
+ try {
249
+ const revised = reviseSpillBudgets(100 * PIECE, stores);
250
+ assert.deepEqual(
251
+ revised.map((store) => store.allowanceBytes),
252
+ [50 * PIECE, 50 * PIECE],
253
+ "one thread's share is divided equally between its stores"
254
+ );
255
+
256
+ // Nobody has said yet: nothing is thrown away, which is what it always did.
257
+ assert.deepEqual(
258
+ reviseSpillBudgets(null, stores).map((store) => store.allowanceBytes),
259
+ [null, null]
260
+ );
261
+ } finally {
262
+ for (const store of stores) {
263
+ await new Promise((resolve) => store.destroy(resolve));
264
+ }
265
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
266
+ }
267
+ });
@@ -99,7 +99,7 @@ test("a range inside one piece is read from that piece only", async () => {
99
99
  assert.deepEqual(bytes, expectedBytes(100, 100));
100
100
  } finally {
101
101
  store.destroy(() => undefined);
102
- await fs.rm(directory, { recursive: true, force: true });
102
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
103
103
  }
104
104
  });
105
105
 
@@ -117,7 +117,7 @@ test("a range spanning pieces reassembles in order", async () => {
117
117
  assert.deepEqual(bytes, expectedBytes(start, end - start + 1));
118
118
  } finally {
119
119
  store.destroy(() => undefined);
120
- await fs.rm(directory, { recursive: true, force: true });
120
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
121
121
  }
122
122
  });
123
123
 
@@ -136,7 +136,7 @@ test("a file that does not start at a piece boundary is still read correctly", a
136
136
  assert.deepEqual(bytes, expectedBytes(fileOffset, 1500));
137
137
  } finally {
138
138
  store.destroy(() => undefined);
139
- await fs.rm(directory, { recursive: true, force: true });
139
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
140
140
  }
141
141
  });
142
142
 
@@ -157,6 +157,6 @@ test("every fragment releases its pin, so nothing stays held", async () => {
157
157
  assert.equal(store.stats().blockedByPins, before, "a pin was left behind");
158
158
  } finally {
159
159
  store.destroy(() => undefined);
160
- await fs.rm(directory, { recursive: true, force: true });
160
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
161
161
  }
162
162
  });