@torrent-tv/proxy 2.80.18 → 2.81.0

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 (67) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/docs/encode-architecture.md +51 -2
  3. package/package.json +1 -1
  4. package/research/double-spawn-2026-09-10.md +171 -0
  5. package/services/disk/DiskSpace.js +146 -0
  6. package/services/disk/wire.js +60 -0
  7. package/services/encode/EncodeRun.js +37 -9
  8. package/services/encode/SegmentStore.js +284 -232
  9. package/services/encode/run-command.js +16 -1
  10. package/services/hls-session-manager.js +31 -128
  11. package/services/orchestrators/EncodeOrchestrator.js +52 -38
  12. package/services/piece-store/allowance.js +107 -0
  13. package/services/piece-store/piece-disk-store.js +365 -0
  14. package/services/piece-store/shared-piece-store.js +1549 -1535
  15. package/services/segment-formats/fmp4.js +54 -0
  16. package/services/segment-formats/mpegts.js +54 -0
  17. package/services/torrent-worker/client.js +32 -0
  18. package/services/torrent-worker/pool-adapter.js +15 -0
  19. package/services/torrent-worker/protocol.js +9 -0
  20. package/services/torrent-worker/worker.js +8 -1
  21. package/services/viewer/positions.js +48 -0
  22. package/test/audio-inventory.test.js +176 -176
  23. package/test/auto-quality-step.test.js +514 -514
  24. package/test/concurrent-cost.test.js +138 -138
  25. package/test/coverage-follows-the-disk.test.js +191 -187
  26. package/test/coverage-map.test.js +195 -195
  27. package/test/declared-tracks.test.js +35 -35
  28. package/test/disk-space.test.js +138 -0
  29. package/test/encode-orchestrator.test.js +0 -3
  30. package/test/encode-run.test.js +5 -12
  31. package/test/held-request-width.test.js +155 -155
  32. package/test/helpers/encode-run.js +2 -2
  33. package/test/matroska-blocks.test.js +0 -0
  34. package/test/matroska-cues-track.test.js +192 -192
  35. package/test/mp4-composition-times.test.js +0 -0
  36. package/test/mp4-subtitles.test.js +173 -173
  37. package/test/one-authority.test.js +281 -220
  38. package/test/orchestrator-wired.test.js +199 -195
  39. package/test/packet-witness-ring.test.js +236 -236
  40. package/test/packet-witness.test.js +148 -148
  41. package/test/piece-disk-store.test.js +267 -0
  42. package/test/piece-reader.test.js +4 -4
  43. package/test/piece-store-eviction.test.js +17 -17
  44. package/test/piece-store-reservations.test.js +20 -1
  45. package/test/piece-store-slow-disk.test.js +16 -1
  46. package/test/produced-copy-choice.test.js +258 -358
  47. package/test/read-window.test.js +6 -6
  48. package/test/run-intervals.test.js +100 -100
  49. package/test/seek-landing.test.js +109 -109
  50. package/test/segment-serve-wiring.test.js +8 -9
  51. package/test/segment-store-eviction.test.js +232 -0
  52. package/test/segment-store.test.js +238 -216
  53. package/test/segments-are-shared.test.js +1 -1
  54. package/test/shared-piece-store.test.js +12 -12
  55. package/test/sidecar-naming.test.js +142 -142
  56. package/test/subtitle-cue-framing.test.js +200 -200
  57. package/test/subtitle-cue-walk.test.js +369 -369
  58. package/test/subtitle-defaults.test.js +97 -97
  59. package/test/subtitle-track-numbering.test.js +370 -370
  60. package/test/tail-duplication.test.js +167 -167
  61. package/test/tracks-begin-together.test.js +195 -195
  62. package/test/two-viewers-one-picture.test.js +374 -374
  63. package/test/video-facts.test.js +102 -102
  64. package/test/wedge-certainty.test.js +131 -131
  65. package/services/encode/open-piece.js +0 -135
  66. package/services/piece-store/disk-tier.js +0 -151
  67. package/test/open-piece.test.js +0 -152
@@ -0,0 +1,365 @@
1
+ /**
2
+ * @file Where downloaded pieces live once memory cannot hold them.
3
+ *
4
+ * The second tier of the piece store, and — unlike what it replaces — an owner
5
+ * of what it takes: it knows how many bytes it holds, it is told how many it
6
+ * may hold, and when it is over that it gives disk back.
7
+ *
8
+ * WHAT IT REPLACED, because the difference is the whole of the design. `DiskTier`
9
+ * wrote every piece into ONE sparse file at `index * chunkLength` and answered
10
+ * `forget(index)` by dropping the number from a set. The bytes stayed: a sparse
11
+ * file's blocks are returned only by hole punching, which Node exposes no
12
+ * binding for, so nothing this process could do returned a single block before
13
+ * the whole file was removed. Measured 2026-08-31: a store holding 312-424 MB
14
+ * of pieces had written **14 400 MB** to that file in fifty minutes, and free
15
+ * space on the host fell by every megabyte of it until the session ended. On a
16
+ * Home Assistant install with a 32 GB card that is the card.
17
+ *
18
+ * A PIECE IS A FILE, and that is what makes the ceiling real. Removing a file
19
+ * returns exactly its blocks, needs no binding this runtime lacks, and makes
20
+ * the unit of eviction the same as the unit of storage — so the order pieces
21
+ * leave in is the order we choose rather than the order they happen to lie in.
22
+ * The read that the single file was chosen for is unaffected: it is still one
23
+ * `read` into a buffer the caller already owns, which is what the 22.08 ms →
24
+ * 7.63 ms measurement on the field host was about. What it adds is an `open`
25
+ * per read, tens of microseconds against those milliseconds.
26
+ *
27
+ * Nothing here decides what the allowance should be. It is told, because the
28
+ * disk is one and this store is not its only user — the segments an encoder
29
+ * produces are on it too — and a ceiling that one of two users sets for itself
30
+ * is not a ceiling.
31
+ */
32
+
33
+ import fs from "node:fs/promises";
34
+ import path from "node:path";
35
+
36
+ /**
37
+ * How a removal is asked for.
38
+ *
39
+ * Windows keeps a deleted file's name reserved until the last handle on it is
40
+ * closed, and answers `rm` of the name — or `rmdir` of the directory holding it
41
+ * — with EPERM until then. These are Node's own documented options for exactly
42
+ * that, not a wait invented here; on POSIX they never come into play.
43
+ */
44
+ const REMOVAL = { force: true, maxRetries: 10, retryDelay: 20 };
45
+
46
+ /**
47
+ * One torrent's pieces on disk.
48
+ *
49
+ * Pieces are numbered by the torrent, so a file is named by its number. The
50
+ * directory is the store: nothing else writes into it, and destroying the store
51
+ * removes it whole.
52
+ */
53
+ export class PieceDiskStore {
54
+ #directory;
55
+
56
+ #chunkLength;
57
+
58
+ /** Piece index → its length on disk. @type {Map<number, number>} */
59
+ #stored = new Map();
60
+
61
+ /** Piece index → when it was last written or read. @type {Map<number, number>} */
62
+ #touched = new Map();
63
+
64
+ /** Pieces being read right now, which eviction leaves alone. @type {Map<number, number>} */
65
+ #reading = new Map();
66
+
67
+ /** Removals still in flight, by piece. @type {Map<number, Promise<unknown>>} */
68
+ #removing = new Map();
69
+
70
+ /** What this store may hold, or null while nobody has said. @type {number | null} */
71
+ #allowanceBytes = null;
72
+
73
+ #evictions = 0;
74
+
75
+ #bytes = 0;
76
+
77
+ #now;
78
+
79
+ /**
80
+ * @param {object} params
81
+ * @param {string} params.directory - Where this torrent's pieces live.
82
+ * @param {string} params.name - A name unique to the torrent; it becomes the
83
+ * directory inside `directory`.
84
+ * @param {number} params.chunkLength - The torrent's piece length. Kept for
85
+ * the caller's arithmetic; a piece's own length is recorded as it is written,
86
+ * because the last piece of a torrent is shorter.
87
+ * @param {number | null} [params.allowanceBytes] - What it may hold. Null
88
+ * means nobody has said yet, and nothing is evicted until somebody does.
89
+ * @param {() => number} [params.now]
90
+ */
91
+ constructor({ directory, name, chunkLength, allowanceBytes = null, now = Date.now }) {
92
+ this.#directory = path.join(directory, name);
93
+ this.#chunkLength = chunkLength;
94
+ this.#allowanceBytes = Number.isFinite(allowanceBytes) && allowanceBytes >= 0 ? allowanceBytes : null;
95
+ this.#now = now;
96
+ }
97
+
98
+ /** Where this store's pieces live, for logging and cleanup. */
99
+ get path() {
100
+ return this.#directory;
101
+ }
102
+
103
+ /** How many pieces are on disk. */
104
+ get size() {
105
+ return this.#stored.size;
106
+ }
107
+
108
+ /** What those pieces weigh. */
109
+ get bytes() {
110
+ return this.#bytes;
111
+ }
112
+
113
+ /** What it may hold, or null while nobody has said. */
114
+ get allowanceBytes() {
115
+ return this.#allowanceBytes;
116
+ }
117
+
118
+ /**
119
+ * Say what it may hold from now on.
120
+ *
121
+ * Lowering it does not free anything by itself: what is already written stays
122
+ * until the next write needs room. A store that is over its allowance and
123
+ * never written to again is holding disk nobody has asked for, which is the
124
+ * same bargain memory makes.
125
+ *
126
+ * @param {number | null} bytes
127
+ * @returns {number | null} What it may hold now.
128
+ */
129
+ reviseAllowance(bytes) {
130
+ this.#allowanceBytes = Number.isFinite(bytes) && bytes >= 0 ? bytes : null;
131
+ return this.#allowanceBytes;
132
+ }
133
+
134
+ /**
135
+ * @param {number} index
136
+ * @returns {boolean}
137
+ */
138
+ has(index) {
139
+ return this.#stored.has(index);
140
+ }
141
+
142
+ /**
143
+ * Write a piece out, making room for it first.
144
+ *
145
+ * @param {number} index
146
+ * @param {Uint8Array} bytes
147
+ * @returns {Promise<void>}
148
+ */
149
+ async write(index, bytes) {
150
+ // A piece thrown away and wanted again before its file has gone. Windows
151
+ // holds a deleted-but-still-open file in a pending state and answers the
152
+ // next `open` of that name with EPERM, so writing it again has to wait for
153
+ // the removal to finish. On POSIX the wait costs a resolved promise.
154
+ await this.#removing.get(index);
155
+ await this.#ensureDirectory();
156
+ await this.#makeRoomFor(bytes.length, index);
157
+ await fs.writeFile(this.#pathOf(index), bytes);
158
+ if (!this.#stored.has(index)) {
159
+ this.#bytes += bytes.length;
160
+ } else {
161
+ this.#bytes += bytes.length - (this.#stored.get(index) ?? 0);
162
+ }
163
+ this.#stored.set(index, bytes.length);
164
+ this.#touched.set(index, this.#now());
165
+ }
166
+
167
+ /**
168
+ * Read a piece back into a buffer the caller already owns.
169
+ *
170
+ * @param {number} index
171
+ * @param {Uint8Array} target - Destination; its length is what gets read.
172
+ * @returns {Promise<number>} Bytes read.
173
+ */
174
+ async read(index, target) {
175
+ if (!this.#stored.has(index)) {
176
+ throw new Error(`Piece ${index} is not on disk.`);
177
+ }
178
+ // While this runs, eviction leaves the piece alone. Removing a file that is
179
+ // open is safe on POSIX and the read would finish — but the open itself
180
+ // happens below, and between the check above and that open a file removed
181
+ // is a read that fails for a piece the caller was told is there.
182
+ this.#reading.set(index, (this.#reading.get(index) ?? 0) + 1);
183
+ let handle = null;
184
+ try {
185
+ handle = await fs.open(this.#pathOf(index), "r");
186
+ const { bytesRead } = await handle.read(target, 0, target.length, 0);
187
+ this.#touched.set(index, this.#now());
188
+ return bytesRead;
189
+ } finally {
190
+ await handle?.close().catch(() => undefined);
191
+ const outstanding = (this.#reading.get(index) ?? 1) - 1;
192
+ if (outstanding > 0) {
193
+ this.#reading.set(index, outstanding);
194
+ } else {
195
+ this.#reading.delete(index);
196
+ }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Forget a piece and give its disk back.
202
+ *
203
+ * The removal itself is left to run: the caller's contract is synchronous —
204
+ * after this returns, the store no longer has the piece — and the blocks come
205
+ * back a moment later. A failure to remove leaves a file nobody will read;
206
+ * the directory goes whole when the store is destroyed.
207
+ *
208
+ * @param {number} index
209
+ * @returns {void}
210
+ */
211
+ forget(index) {
212
+ const length = this.#stored.get(index);
213
+ if (length === undefined) {
214
+ return;
215
+ }
216
+ this.#stored.delete(index);
217
+ this.#touched.delete(index);
218
+ this.#bytes -= length;
219
+ // Kept track of, because a removal still in flight holds the directory: on
220
+ // Windows `rmdir` refuses while any handle inside is open, so `destroy`
221
+ // waits for these before removing the directory. On Linux it would succeed
222
+ // and the removals would then fail silently against a directory that is
223
+ // gone — tidy either way, and correct on both.
224
+ const removal = fs.rm(this.#pathOf(index), REMOVAL)
225
+ .catch(() => undefined)
226
+ .finally(() => {
227
+ if (this.#removing.get(index) === removal) {
228
+ this.#removing.delete(index);
229
+ }
230
+ });
231
+ this.#removing.set(index, removal);
232
+ }
233
+
234
+ /**
235
+ * What it holds, what it may hold, and what it has had to throw away.
236
+ *
237
+ * @returns {{ pieces: number, bytes: number, allowanceBytes: number | null, evictions: number }}
238
+ */
239
+ stats() {
240
+ return {
241
+ pieces: this.#stored.size,
242
+ bytes: this.#bytes,
243
+ allowanceBytes: this.#allowanceBytes,
244
+ evictions: this.#evictions
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Close it, leaving its contents in place.
250
+ *
251
+ * There is no handle to close — a read opens and closes its own — so this
252
+ * exists for the caller's lifecycle and does nothing else.
253
+ *
254
+ * @returns {Promise<void>}
255
+ */
256
+ async close() {
257
+ // Nothing to release: a read opens and closes its own handle.
258
+ }
259
+
260
+ /**
261
+ * Close and remove everything.
262
+ *
263
+ * @returns {Promise<void>}
264
+ */
265
+ async destroy() {
266
+ await this.close();
267
+ await this.settled();
268
+ this.#stored.clear();
269
+ this.#touched.clear();
270
+ this.#bytes = 0;
271
+ await fs.rm(this.#directory, { ...REMOVAL, recursive: true });
272
+ }
273
+
274
+ /**
275
+ * Wait for every removal this store has started.
276
+ *
277
+ * Removing a piece answers at once and frees the disk a moment later; this is
278
+ * how a caller that needs the disk back NOW — a test, or `destroy` — waits for
279
+ * it without making `forget` asynchronous for everybody else.
280
+ *
281
+ * @returns {Promise<void>}
282
+ */
283
+ async settled() {
284
+ while (this.#removing.size > 0) {
285
+ await Promise.all([...this.#removing.values()]);
286
+ }
287
+ }
288
+
289
+ /**
290
+ * @param {number} index
291
+ * @returns {string}
292
+ */
293
+ #pathOf(index) {
294
+ return path.join(this.#directory, `${index}.piece`);
295
+ }
296
+
297
+ /**
298
+ * Make sure the directory is there, before every write.
299
+ *
300
+ * Deliberately not remembered. A remembered "it exists" is a statement about
301
+ * the past: this store's own `destroy` removes the directory, a startup sweep
302
+ * removes what a killed process left, and an operator clearing a full disk
303
+ * removes anything. Each of those turns the memory into a lie and every write
304
+ * after it into `ENOENT`. Creating a directory that already exists costs tens
305
+ * of microseconds against a write measured in milliseconds.
306
+ *
307
+ * @returns {Promise<void>}
308
+ */
309
+ async #ensureDirectory() {
310
+ await fs.mkdir(this.#directory, { recursive: true });
311
+ }
312
+
313
+ /**
314
+ * Throw away the least recently used pieces until one more will fit.
315
+ *
316
+ * Least recently used first, and for the reason the memory tier uses the same
317
+ * order: what nobody has read for the longest is what a viewer is least
318
+ * likely to want next. A piece being read now is never a victim, and neither
319
+ * is the piece about to be written.
320
+ *
321
+ * A piece thrown away is not lost, only un-had: the store answers `has` with
322
+ * false, the read that wanted it gets nothing, and the torrent fetches it
323
+ * again. That is the same bargain the memory tier makes when it spills.
324
+ *
325
+ * @param {number} incomingBytes
326
+ * @param {number} incomingIndex
327
+ * @returns {Promise<void>}
328
+ */
329
+ async #makeRoomFor(incomingBytes, incomingIndex) {
330
+ if (this.#allowanceBytes === null) {
331
+ return;
332
+ }
333
+ const already = this.#stored.get(incomingIndex) ?? 0;
334
+ while (this.#bytes - already + incomingBytes > this.#allowanceBytes) {
335
+ const victim = this.#leastRecentlyUsed(incomingIndex);
336
+ if (victim === null) {
337
+ // Everything left is either being read or is the piece coming in. The
338
+ // write goes ahead: refusing it would lose a piece the swarm has
339
+ // already paid for, and the next write finds the readers gone.
340
+ return;
341
+ }
342
+ this.forget(victim);
343
+ this.#evictions += 1;
344
+ }
345
+ }
346
+
347
+ /**
348
+ * @param {number} except
349
+ * @returns {number | null}
350
+ */
351
+ #leastRecentlyUsed(except) {
352
+ let victim = null;
353
+ let oldest = Number.POSITIVE_INFINITY;
354
+ for (const [index, at] of this.#touched) {
355
+ if (index === except || this.#reading.has(index)) {
356
+ continue;
357
+ }
358
+ if (at < oldest) {
359
+ oldest = at;
360
+ victim = index;
361
+ }
362
+ }
363
+ return victim;
364
+ }
365
+ }