@torrent-tv/proxy 2.83.4 → 2.83.6

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.
@@ -0,0 +1,261 @@
1
+ /**
2
+ * @file An output whose input is away gets no encoders until it may.
3
+ *
4
+ * A run whose input has gone is not alive, so the plan reads the stretch it held
5
+ * as free and places another run there at once — which dies the same way,
6
+ * because nothing about the state has changed. A delay existed for exactly this,
7
+ * doubling from 2 s to 15 s, and it was timed against the DEAD RUN, which the
8
+ * plan never consults. Field 2026-09-12: 2432 ffmpeg starts in 23 minutes, one
9
+ * every 0.57 s, for 61 minutes, against a delay that had reached its ceiling
10
+ * long before; the flood also turned the log over twice and destroyed the
11
+ * record of how the failure began.
12
+ *
13
+ * The delay lives beside the decision it governs now, and these check that it
14
+ * binds.
15
+ */
16
+
17
+ import test from "node:test";
18
+ import assert from "node:assert/strict";
19
+ import { EventEmitter } from "node:events";
20
+ import { EncodeRun } from "../services/encode/EncodeRun.js";
21
+ import { ENCODE_EXIT } from "../services/encode/encode-exit.js";
22
+ import { SoftwareEncoder } from "../services/encode/SoftwareEncoder.js";
23
+ import { EncodeOrchestrator } from "../services/orchestrators/EncodeOrchestrator.js";
24
+
25
+ const PICTURE = "torrent:abc:fmt=fmp4:grid=kf@0:video-only:v=0/copy";
26
+
27
+ class FakeProcess extends EventEmitter {
28
+ constructor() {
29
+ super();
30
+ this.pid = 1;
31
+ }
32
+
33
+ kill(signal) {
34
+ this.emit("exit", null, signal);
35
+ }
36
+ }
37
+
38
+ /** An orchestrator whose clock the test moves, and a count of what it started. */
39
+ function orchestrator() {
40
+ const lines = [];
41
+ let clock = 1_000;
42
+ let started = 0;
43
+ let asked = 0;
44
+ /** @type {EncodeOrchestrator} */
45
+ let made;
46
+ /** @type {{ run: EncodeRun, process: FakeProcess }[]} */
47
+ const runs = [];
48
+ made = new EncodeOrchestrator({
49
+ maxRunsFor: () => 1,
50
+ segmentSeconds: 4,
51
+ startingSpeedFor: () => 2,
52
+ refetchSecPerFilmSecond: () => 0.25,
53
+ now: () => clock,
54
+ planSoon: () => { asked += 1; },
55
+ logger: { info: (line) => lines.push(line), warn: (line) => lines.push(line) },
56
+ makeRun: ({ address, from, to }) => {
57
+ started += 1;
58
+ const process_ = new FakeProcess();
59
+ const run = new EncodeRun({
60
+ address,
61
+ encoder: new SoftwareEncoder(),
62
+ from,
63
+ to,
64
+ buildArgs: () => ["-i", "in", "out"],
65
+ spawn: () => process_,
66
+ logger: { info: (line) => lines.push(line), warn: (line) => lines.push(line) },
67
+ now: () => clock,
68
+ onEnded: (ended) => made.noteEnded(ended)
69
+ });
70
+ runs.push({ run, process: process_ });
71
+ return run;
72
+ }
73
+ });
74
+ made.setSegmentCount(PICTURE, 1000);
75
+ made.noteStartupCosts({ killCostSec: 0, firstByteWaitSec: 0.12 });
76
+
77
+ const wants = () => made.notePriorityMap(PICTURE, [
78
+ { from: 0, to: 20, priority: 1, withinSeconds: 0 }
79
+ ]);
80
+
81
+ return {
82
+ made,
83
+ lines,
84
+ wants,
85
+ runs,
86
+ startedCount: () => started,
87
+ askedToPlanAgain: () => asked,
88
+ advance: (ms) => { clock += ms; },
89
+ /** End the newest run the way a torrent going away ends one. */
90
+ loseTheInput: () => {
91
+ const newest = runs[runs.length - 1];
92
+ made.noteEnded({
93
+ address: PICTURE,
94
+ run: newest.run,
95
+ from: newest.run.from,
96
+ to: newest.run.to,
97
+ ending: ENCODE_EXIT.INPUT_LOST,
98
+ because: "the torrent went away"
99
+ });
100
+ }
101
+ };
102
+ }
103
+
104
+ test("nothing is placed on an output whose input has just gone", () => {
105
+ const stand = orchestrator();
106
+ stand.wants();
107
+ stand.made.reconcile();
108
+ assert.equal(stand.startedCount(), 1, "one encoder for the one thing wanted");
109
+
110
+ stand.loseTheInput();
111
+ // The plan is asked again by every event there is — a request, a report, a
112
+ // piece — and in the field that was about twice a second.
113
+ for (let attempt = 0; attempt < 20; attempt += 1) {
114
+ stand.made.reconcile();
115
+ }
116
+ assert.equal(
117
+ stand.startedCount(),
118
+ 1,
119
+ "twenty decisions while the input is away must not be twenty processes"
120
+ );
121
+ });
122
+
123
+ test("once the wait is over the plan places again", () => {
124
+ const stand = orchestrator();
125
+ stand.wants();
126
+ stand.made.reconcile();
127
+ stand.loseTheInput();
128
+ stand.made.reconcile();
129
+ assert.equal(stand.startedCount(), 1);
130
+
131
+ // The first wait is the base delay; anything past it lets the plan act.
132
+ stand.advance(2_001);
133
+ stand.made.reconcile();
134
+ assert.equal(stand.startedCount(), 2, "the data may be back, and that is worth one attempt");
135
+ });
136
+
137
+ test("the wait doubles while the input stays away, and is capped", () => {
138
+ const stand = orchestrator();
139
+ stand.wants();
140
+ stand.made.reconcile();
141
+
142
+ const waits = [];
143
+ for (let attempt = 0; attempt < 8; attempt += 1) {
144
+ stand.loseTheInput();
145
+ // Find the shortest advance that lets the plan act again, by stepping to
146
+ // just before and just after the boundary rather than reading a private.
147
+ let waited = 0;
148
+ const step = 250;
149
+ for (;;) {
150
+ const before = stand.startedCount();
151
+ stand.made.reconcile();
152
+ if (stand.startedCount() > before) {
153
+ break;
154
+ }
155
+ stand.advance(step);
156
+ waited += step;
157
+ assert.ok(waited < 60_000, "a wait must not be unbounded");
158
+ }
159
+ waits.push(waited);
160
+ }
161
+
162
+ for (let at = 1; at < waits.length; at += 1) {
163
+ assert.ok(
164
+ waits[at] >= waits[at - 1],
165
+ `the wait must not shrink while the input stays away: ${JSON.stringify(waits)}`
166
+ );
167
+ }
168
+ assert.ok(
169
+ waits[waits.length - 1] <= 15_000,
170
+ `and it must stop growing: ${JSON.stringify(waits)}`
171
+ );
172
+ assert.ok(
173
+ waits[waits.length - 1] > waits[0],
174
+ `and it must actually have grown: ${JSON.stringify(waits)}`
175
+ );
176
+ });
177
+
178
+ test("a wake-up is asked for, because no event arrives while the data is away", async () => {
179
+ const stand = orchestrator();
180
+ stand.wants();
181
+ stand.made.reconcile();
182
+ stand.loseTheInput();
183
+ // The wake-up runs on the real clock — the orchestrator's injected `now` is
184
+ // what the DECISION reads, and a timer is not a decision. So this waits for
185
+ // the condition, with a deadline only as a backstop; a fixed pause here would
186
+ // measure the machine.
187
+ const deadline = Date.now() + 10_000;
188
+ while (stand.askedToPlanAgain() === 0) {
189
+ if (Date.now() > deadline) {
190
+ assert.fail("nothing about the state changes while the input is missing, so the plan must be recalled");
191
+ }
192
+ await new Promise((resolve) => setTimeout(resolve, 25));
193
+ }
194
+ assert.ok(stand.askedToPlanAgain() >= 1);
195
+ });
196
+
197
+ test("an ending that is not about the input clears the wait", () => {
198
+ const stand = orchestrator();
199
+ stand.wants();
200
+ stand.made.reconcile();
201
+ stand.loseTheInput();
202
+ stand.made.reconcile();
203
+ assert.equal(stand.startedCount(), 1, "held back, as it should be");
204
+
205
+ stand.advance(2_001);
206
+ stand.made.reconcile();
207
+ assert.equal(stand.startedCount(), 2);
208
+
209
+ // This one PRODUCED and was then stopped: a segment came out of the input, so
210
+ // the input was plainly there and the next attempt starts from no delay.
211
+ const newest = stand.runs[stand.runs.length - 1];
212
+ stand.made.noteEnded({
213
+ address: PICTURE,
214
+ run: newest.run,
215
+ from: newest.run.from,
216
+ to: newest.run.to,
217
+ reached: newest.run.from,
218
+ firstOutputMs: 120,
219
+ ending: ENCODE_EXIT.STOPPED,
220
+ because: "we asked it to"
221
+ });
222
+ stand.made.reconcile();
223
+ assert.equal(stand.startedCount(), 3, "a file that has just produced is not suspect");
224
+ });
225
+
226
+ test("an ending that produced NOTHING does not lift the wait", () => {
227
+ const stand = orchestrator();
228
+ stand.wants();
229
+ stand.made.reconcile();
230
+ stand.loseTheInput();
231
+
232
+ // At the moment of failure several runs end at once. One of them ending
233
+ // without having made anything proves nothing about the input, and lifting
234
+ // the wait on it is the storm again with an extra step.
235
+ const newest = stand.runs[stand.runs.length - 1];
236
+ stand.made.noteEnded({
237
+ address: PICTURE,
238
+ run: newest.run,
239
+ from: newest.run.from,
240
+ to: newest.run.to,
241
+ reached: newest.run.from - 1,
242
+ firstOutputMs: null,
243
+ ending: ENCODE_EXIT.GONE,
244
+ because: "it is no longer running, and it did not say so"
245
+ });
246
+ for (let attempt = 0; attempt < 10; attempt += 1) {
247
+ stand.made.reconcile();
248
+ }
249
+ assert.equal(stand.startedCount(), 1, "an ending with nothing produced is no evidence");
250
+ });
251
+
252
+ test("the wait is said out loud, with the attempt and how long", () => {
253
+ const stand = orchestrator();
254
+ stand.wants();
255
+ stand.made.reconcile();
256
+ stand.loseTheInput();
257
+ assert.ok(
258
+ stand.lines.some((line) => /its input was not there \(attempt 1\)/.test(line)),
259
+ `the reason nothing is being placed must be readable: ${JSON.stringify(stand.lines.slice(-4))}`
260
+ );
261
+ });
@@ -0,0 +1,134 @@
1
+ /**
2
+ * @file An established fact is said once, then with decreasing frequency.
3
+ *
4
+ * Field 2026-09-12: one absent piece produced 235 000 lines in 92 minutes —
5
+ * about 55 a second, 68.8 % of them byte-identical repeats — and it turned the
6
+ * log file over twice, so the beginning of the failure was gone before anybody
7
+ * read it. A log is not spoilt by its size; it is spoilt by uniformity.
8
+ *
9
+ * Matched verbatim, the whole line: that catches nearly all of the flood and
10
+ * cannot merge two different statements. Normalising numbers would catch a
11
+ * little more and would also merge the memory series, which exists precisely to
12
+ * catch a runaway.
13
+ */
14
+
15
+ import test from "node:test";
16
+ import assert from "node:assert/strict";
17
+ import { logger, writeAlreadyDecided } from "../utils/logger.js";
18
+
19
+ /** What reached the console while `body` ran. */
20
+ function captured(body) {
21
+ const lines = [];
22
+ const real = { log: console.log, warn: console.warn, error: console.error };
23
+ console.log = (line) => lines.push(String(line));
24
+ console.warn = (line) => lines.push(String(line));
25
+ console.error = (line) => lines.push(String(line));
26
+ try {
27
+ body();
28
+ } finally {
29
+ console.log = real.log;
30
+ console.warn = real.warn;
31
+ console.error = real.error;
32
+ }
33
+ return lines;
34
+ }
35
+
36
+ /** A line no other test in this process will have said. */
37
+ function unique(what) {
38
+ return `logger-repeats ${what} ${Math.random().toString(36).slice(2)}`;
39
+ }
40
+
41
+ test("the first time is said, and the repeats right behind it are not", () => {
42
+ const message = unique("flood");
43
+ const lines = captured(() => {
44
+ for (let at = 0; at < 500; at += 1) {
45
+ logger.info(message);
46
+ }
47
+ });
48
+ assert.equal(lines.length, 1, "five hundred identical lines are one fact");
49
+ assert.ok(lines[0].includes(message));
50
+ });
51
+
52
+ test("two different lines are both said — repeats are matched whole", () => {
53
+ const one = unique("one");
54
+ const other = unique("other");
55
+ const lines = captured(() => {
56
+ logger.info(one);
57
+ logger.info(other);
58
+ logger.info(one);
59
+ logger.info(other);
60
+ });
61
+ assert.equal(lines.length, 2, "different statements never merge");
62
+ assert.ok(lines[0].includes(one));
63
+ assert.ok(lines[1].includes(other));
64
+ });
65
+
66
+ test("a line whose numbers differ is a different line", () => {
67
+ const stem = unique("rss");
68
+ const lines = captured(() => {
69
+ logger.info(`${stem} rss=327MB`);
70
+ logger.info(`${stem} rss=726MB`);
71
+ logger.info(`${stem} rss=4616MB`);
72
+ });
73
+ assert.equal(
74
+ lines.length,
75
+ 3,
76
+ "the memory series exists to catch a runaway; suppressing it would be worse than the flood"
77
+ );
78
+ });
79
+
80
+ test("when it is said again, it says how many were held back", async () => {
81
+ const message = unique("counted");
82
+ const first = captured(() => {
83
+ logger.info(message);
84
+ for (let at = 0; at < 9; at += 1) {
85
+ logger.info(message);
86
+ }
87
+ });
88
+ assert.equal(first.length, 1);
89
+
90
+ // The first interval is a second. Waited for rather than assumed: this asks
91
+ // the logger itself when it is ready to speak again, with a deadline as a
92
+ // backstop.
93
+ const deadline = Date.now() + 10_000;
94
+ let later = [];
95
+ while (later.length === 0) {
96
+ if (Date.now() > deadline) {
97
+ assert.fail("the line should be said again once its interval has passed");
98
+ }
99
+ await new Promise((resolve) => setTimeout(resolve, 100));
100
+ later = captured(() => logger.info(message));
101
+ }
102
+ const said = later[0].match(/\[said (\d+) more time\(s\) in the last ([0-9.]+)s\]/);
103
+ assert.ok(said, `the rate is the fact here, and must be stated: ${later[0]}`);
104
+ // At least the nine held back above. Each poll that found nothing said the
105
+ // line again and was itself held back, so the exact figure belongs to how
106
+ // often this test asked — the property being pinned is that the held-back
107
+ // count is reported at all, and that it counts every one of them.
108
+ assert.ok(Number(said[1]) >= 9, `held-back count too low: ${later[0]}`);
109
+ assert.ok(Number(said[2]) > 0, `the span it covers must be stated: ${later[0]}`);
110
+ });
111
+
112
+ test("a line already decided on another thread is written as it is", () => {
113
+ const message = unique("forwarded");
114
+ const lines = captured(() => {
115
+ writeAlreadyDecided("info", message);
116
+ writeAlreadyDecided("info", message);
117
+ writeAlreadyDecided("warn", message);
118
+ });
119
+ // The worker holds the same rule and applies it before forwarding. Deciding
120
+ // again here would be one decision taken twice on two different histories,
121
+ // and the file's own promise is that a line cannot reach the console and miss
122
+ // the file.
123
+ assert.equal(lines.length, 3, "a forwarded line is not judged a second time");
124
+ });
125
+
126
+ test("every level goes through the same rule", () => {
127
+ const message = unique("levels");
128
+ const lines = captured(() => {
129
+ logger.warn(message);
130
+ logger.warn(message);
131
+ logger.error(message);
132
+ });
133
+ assert.equal(lines.length, 1, "a flood of errors is still a flood");
134
+ });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * @file A read whose piece is withdrawn under it waits, rather than failing.
3
+ *
4
+ * The store drops a piece once every reader is past it, and the claim is
5
+ * withdrawn with it, so the piece is fetched again. A read that meets the gap in
6
+ * between must therefore WAIT — until 2026-09-12 it threw, ffmpeg read the empty
7
+ * body as the end of the file, the encoder died, and the plan restarted it into
8
+ * the same emptiness: 2432 starts in 23 minutes and a viewer looking at a still
9
+ * picture for 92 minutes.
10
+ */
11
+
12
+ import test from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import { EventEmitter } from "node:events";
15
+ import os from "node:os";
16
+ import path from "node:path";
17
+ import fs from "node:fs/promises";
18
+ import { readFragments } from "../services/torrent-worker/piece-reader.js";
19
+ import { SharedPieceStore } from "../services/piece-store/shared-piece-store.js";
20
+
21
+ const PIECE = 1024;
22
+ const TOTAL = 4 * PIECE;
23
+
24
+ /**
25
+ * A torrent of four pieces over a real store, whose `reside` can be made to
26
+ * answer "gone" for a chosen piece a chosen number of times — which is what the
27
+ * store does between dropping a piece and the swarm bringing it back.
28
+ *
29
+ * @param {{ emptyFor: number, times: number }} gap
30
+ */
31
+ async function torrentWithAGap({ emptyFor, times }) {
32
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "withdrawal-read-"));
33
+ const store = new SharedPieceStore(PIECE, {
34
+ length: TOTAL,
35
+ memoryBytes: 64 * PIECE,
36
+ path: directory,
37
+ name: "test",
38
+ files: [{ offset: 0, length: TOTAL, name: "file.bin" }]
39
+ });
40
+ for (let index = 0; index < 4; index += 1) {
41
+ const piece = Buffer.alloc(PIECE);
42
+ for (let at = 0; at < PIECE; at += 1) {
43
+ piece[at] = (index * PIECE + at) % 251;
44
+ }
45
+ await new Promise((resolve, reject) => {
46
+ store.put(index, piece, (error) => (error ? reject(error) : resolve()));
47
+ });
48
+ }
49
+
50
+ const held = new Set([0, 1, 2, 3]);
51
+ let left = times;
52
+ /** How many times the piece was asked of the store at all. */
53
+ let asked = 0;
54
+ // The gap is injected at the one method that answers "can you produce this
55
+ // piece" — subclassed rather than wrapped, because `findSharedStore` walks
56
+ // the chain looking for the real class and would find the real one behind a
57
+ // facade.
58
+ store.reside = async function resideWithAGap(index) {
59
+ if (index !== emptyFor) {
60
+ return SharedPieceStore.prototype.reside.call(this, index);
61
+ }
62
+ asked += 1;
63
+ if (left > 0) {
64
+ left -= 1;
65
+ // THE CLAIM GOES WITH THE BYTES. That is what makes the wait a wait for a
66
+ // download and not a wait for nothing, and it is what the withdrawal now
67
+ // does in production.
68
+ held.delete(index);
69
+ // Back a moment later, as the swarm brings it: the reader's own wait ends
70
+ // on the torrent's `verified` event.
71
+ setImmediate(() => {
72
+ held.add(index);
73
+ torrent.emit("verified", index);
74
+ });
75
+ return null;
76
+ }
77
+ return SharedPieceStore.prototype.reside.call(this, index);
78
+ };
79
+
80
+ const torrent = Object.assign(new EventEmitter(), {
81
+ pieceLength: PIECE,
82
+ store,
83
+ bitfield: { get: (index) => held.has(index) },
84
+ files: [{ offset: 0, length: TOTAL, name: "file.bin" }],
85
+ select() {},
86
+ critical() {}
87
+ });
88
+
89
+ return {
90
+ torrent,
91
+ clean: async () => {
92
+ store.destroy(() => undefined);
93
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
94
+ },
95
+ asksFor: () => asked
96
+ };
97
+ }
98
+
99
+ /** Read a range as the worker does. */
100
+ async function readRange(torrent, start, end) {
101
+ const collected = [];
102
+ for await (const fragment of readFragments({
103
+ torrent,
104
+ fileIndex: 0,
105
+ start,
106
+ end,
107
+ cancellation: { isCancelled: () => false }
108
+ })) {
109
+ const source = fragment.buffer
110
+ ? Buffer.from(fragment.buffer, fragment.offset, fragment.length)
111
+ : Buffer.alloc(0);
112
+ collected.push(Buffer.from(source));
113
+ fragment.release();
114
+ }
115
+ return Buffer.concat(collected);
116
+ }
117
+
118
+ function expectedBytes(absoluteStart, length) {
119
+ const expected = Buffer.alloc(length);
120
+ for (let at = 0; at < length; at += 1) {
121
+ expected[at] = (absoluteStart + at) % 251;
122
+ }
123
+ return expected;
124
+ }
125
+
126
+ test("a piece withdrawn once is asked for again and the read completes", async () => {
127
+ // Piece 0 is the case the field met: an encoder restart re-opens its input at
128
+ // byte 0, and byte 0 is behind every read head by then.
129
+ const { torrent, clean, asksFor } = await torrentWithAGap({ emptyFor: 0, times: 1 });
130
+ try {
131
+ const bytes = await readRange(torrent, 0, 2 * PIECE - 1);
132
+ assert.deepEqual(bytes, expectedBytes(0, 2 * PIECE), "the read returns the film, not an empty body");
133
+ assert.equal(asksFor(), 2, "the piece is asked for a second time, not given up on");
134
+ } finally {
135
+ await clean();
136
+ }
137
+ });
138
+
139
+ test("a piece that does not come back ends the read with a named error", async () => {
140
+ const { torrent, clean } = await torrentWithAGap({ emptyFor: 0, times: 5 });
141
+ try {
142
+ await assert.rejects(
143
+ () => readRange(torrent, 0, PIECE - 1),
144
+ // NOT "verified but absent": the claim has been withdrawn, so the honest
145
+ // statement is that the bytes did not come back.
146
+ /piece 0 was withdrawn from the store and did not come back/i,
147
+ "a second emptiness is a failure the caller must hear about"
148
+ );
149
+ } finally {
150
+ await clean();
151
+ }
152
+ });
153
+
154
+ test("every piece of a long read gets its own second chance", async () => {
155
+ // The allowance is per piece: a read of many pieces may legitimately meet the
156
+ // gap more than once, and one exhausted allowance must not condemn the rest.
157
+ const { torrent, clean } = await torrentWithAGap({ emptyFor: 2, times: 1 });
158
+ try {
159
+ const bytes = await readRange(torrent, 0, 4 * PIECE - 1);
160
+ assert.deepEqual(bytes, expectedBytes(0, 4 * PIECE));
161
+ } finally {
162
+ await clean();
163
+ }
164
+ });