@torrent-tv/proxy 2.56.0 → 2.57.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.
@@ -1,78 +1,124 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
-
4
- import { readProbeState, MISSES_FOR_VERDICT, UNRELIABLE_LABEL } from "../services/delivery-probe.js";
5
-
6
- const ORDERED = ["proxy", "proxy-control"];
7
- const ALL = [...ORDERED, UNRELIABLE_LABEL];
8
-
9
- /**
10
- * @param {Record<string, number>} seen
11
- * @param {object} [overrides]
12
- */
13
- function state(seen, overrides = {}) {
14
- return {
15
- seq: 100,
16
- seen,
17
- labels: ALL,
18
- echoes: 5,
19
- echoAgeMs: 400,
20
- ...overrides
21
- };
22
- }
23
-
24
- test("every channel current reads as flowing", () => {
25
- const { verdict } = readProbeState(state({ proxy: 100, "proxy-control": 99, "proxy-fast": 100 }));
26
- assert.equal(verdict, "flowing");
27
- });
28
-
29
- test("a lag shorter than the verdict window is still flowing", () => {
30
- const behind = 100 - (MISSES_FOR_VERDICT - 1);
31
- const { verdict } = readProbeState(
32
- state({ proxy: behind, "proxy-control": behind, "proxy-fast": 100 })
33
- );
34
- assert.equal(verdict, "flowing");
35
- });
36
-
37
- test("ordered channels behind while the unordered one keeps up names a stuck stream", () => {
38
- const { verdict, detail } = readProbeState(
39
- state({ proxy: 40, "proxy-control": 41, "proxy-fast": 100 })
40
- );
41
- assert.equal(verdict, "stream-stuck");
42
- // The numbers that produced the verdict must be in the line beside it.
43
- assert.match(detail, /proxy=40\(gap 60\)/);
44
- });
45
-
46
- test("every channel behind names the association", () => {
47
- const { verdict } = readProbeState(
48
- state({ proxy: 40, "proxy-control": 41, "proxy-fast": 42 })
49
- );
50
- assert.equal(verdict, "association-stopped");
51
- });
52
-
53
- test("without the unordered channel the verdict says it cannot compare", () => {
54
- const { verdict } = readProbeState(
55
- state({ proxy: 40, "proxy-control": 41 }, { labels: ORDERED })
56
- );
57
- assert.equal(verdict, "ordered-behind-no-comparison");
58
- });
59
-
60
- test("a stale echo means the reverse direction went too", () => {
61
- const { verdict } = readProbeState(
62
- state({ proxy: 40, "proxy-control": 41, "proxy-fast": 42 }, { echoAgeMs: 30_000 })
63
- );
64
- assert.equal(verdict, "reverse-direction-gone");
65
- });
66
-
67
- test("before the first echo nothing is claimed", () => {
68
- const { verdict } = readProbeState(state({}, { echoes: 0, echoAgeMs: null }));
69
- assert.equal(verdict, "no-echo-yet");
70
- });
71
-
72
- test("a channel that has never reported counts as behind, not as unknown", () => {
73
- const { verdict, detail } = readProbeState(
74
- state({ "proxy-fast": 100 })
75
- );
76
- assert.equal(verdict, "stream-stuck");
77
- assert.match(detail, /proxy=\?\(gap \?\)/);
78
- });
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+
4
+ import { allowedGap, readProbeState, PROBE_INTERVAL_MS, UNRELIABLE_LABEL } from "../services/delivery-probe.js";
5
+
6
+ const ORDERED = ["proxy", "proxy-control"];
7
+ const ALL = [...ORDERED, UNRELIABLE_LABEL];
8
+
9
+ /**
10
+ * @param {Record<string, number>} seen
11
+ * @param {object} [overrides]
12
+ */
13
+ function state(seen, overrides = {}) {
14
+ const allowed = {};
15
+ for (const label of overrides.labels ?? ALL) {
16
+ allowed[label] = 3;
17
+ }
18
+ return {
19
+ seq: 100,
20
+ seen,
21
+ labels: ALL,
22
+ echoes: 5,
23
+ echoAgeMs: 400,
24
+ allowed,
25
+ ...overrides
26
+ };
27
+ }
28
+
29
+ test("every channel current reads as flowing", () => {
30
+ const { verdict } = readProbeState(state({ proxy: 100, "proxy-control": 99, "proxy-fast": 100 }));
31
+ assert.equal(verdict, "flowing");
32
+ });
33
+
34
+ test("a lag shorter than the verdict window is still flowing", () => {
35
+ const behind = 100 - 3;
36
+ const { verdict } = readProbeState(
37
+ state({ proxy: behind, "proxy-control": behind, "proxy-fast": 100 })
38
+ );
39
+ assert.equal(verdict, "flowing");
40
+ });
41
+
42
+ test("ordered channels behind while the unordered one keeps up names a stuck stream", () => {
43
+ const { verdict, detail } = readProbeState(
44
+ state({ proxy: 40, "proxy-control": 41, "proxy-fast": 100 })
45
+ );
46
+ assert.equal(verdict, "stream-stuck");
47
+ // The numbers that produced the verdict must be in the line beside it.
48
+ assert.match(detail, /proxy=40\(gap 60 of 3\)/);
49
+ });
50
+
51
+ test("every channel behind names the association", () => {
52
+ const { verdict } = readProbeState(
53
+ state({ proxy: 40, "proxy-control": 41, "proxy-fast": 42 })
54
+ );
55
+ assert.equal(verdict, "association-stopped");
56
+ });
57
+
58
+ test("without the unordered channel the verdict says it cannot compare", () => {
59
+ const { verdict } = readProbeState(
60
+ state({ proxy: 40, "proxy-control": 41 }, { labels: ORDERED })
61
+ );
62
+ assert.equal(verdict, "ordered-behind-no-comparison");
63
+ });
64
+
65
+ test("a stale echo means the reverse direction went too", () => {
66
+ const { verdict } = readProbeState(
67
+ state({ proxy: 40, "proxy-control": 41, "proxy-fast": 42 }, { echoAgeMs: 30_000 })
68
+ );
69
+ assert.equal(verdict, "reverse-direction-gone");
70
+ });
71
+
72
+ test("before the first echo nothing is claimed", () => {
73
+ const { verdict } = readProbeState(state({}, { echoes: 0, echoAgeMs: null }));
74
+ assert.equal(verdict, "no-echo-yet");
75
+ });
76
+
77
+ test("a channel that has never reported counts as behind, not as unknown", () => {
78
+ const { verdict, detail } = readProbeState(
79
+ state({ "proxy-fast": 100 })
80
+ );
81
+ assert.equal(verdict, "stream-stuck");
82
+ assert.match(detail, /proxy=\?\(gap \? of 3\)/);
83
+ });
84
+
85
+ test("the allowance is the queue's own drain time, not a chosen number", () => {
86
+ // 8 MB queued at 8 MB/s is one second of draining; probes go twice a second,
87
+ // so two of them may legitimately be outstanding, plus the round trip.
88
+ assert.equal(
89
+ allowedGap({ queuedBytes: 8 * 1024 * 1024, bytesPerSecond: 8 * 1024 * 1024, rttMs: 0 }),
90
+ Math.ceil(1000 / PROBE_INTERVAL_MS)
91
+ );
92
+ // An empty queue still allows the one probe that is always in flight.
93
+ assert.equal(allowedGap({ queuedBytes: 0, bytesPerSecond: 8 * 1024 * 1024, rttMs: 0 }), 1);
94
+ // The round trip counts: the echo has to come back too.
95
+ assert.ok(
96
+ allowedGap({ queuedBytes: 0, bytesPerSecond: 1024, rttMs: 2000 }) >
97
+ allowedGap({ queuedBytes: 0, bytesPerSecond: 1024, rttMs: 0 })
98
+ );
99
+ });
100
+
101
+ test("with no rate measured nothing is claimed", () => {
102
+ assert.equal(allowedGap({ queuedBytes: 1024, bytesPerSecond: 0, rttMs: 10 }), null);
103
+ const { verdict } = readProbeState(
104
+ state({ proxy: 40, "proxy-control": 41, "proxy-fast": 42 }, { allowed: {} })
105
+ );
106
+ assert.equal(verdict, "no-rate-yet");
107
+ });
108
+
109
+ test("a burst big enough to explain the lag is not called a stopped association", () => {
110
+ // The 2026-08-26 false positive: all three channels at gap 7 while 150 Mbps
111
+ // crossed the association. 64 MB queued at 18 MB/s is three and a half
112
+ // seconds of draining, which is seven probe intervals.
113
+ const allowance = allowedGap({
114
+ queuedBytes: 64 * 1024 * 1024,
115
+ bytesPerSecond: 18 * 1024 * 1024,
116
+ rttMs: 16
117
+ });
118
+ assert.ok(allowance >= 7);
119
+ const allowed = Object.fromEntries(ALL.map((label) => [label, allowance]));
120
+ const { verdict } = readProbeState(
121
+ state({ proxy: 93, "proxy-control": 93, "proxy-fast": 93 }, { allowed })
122
+ );
123
+ assert.equal(verdict, "flowing");
124
+ });
@@ -0,0 +1,236 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { EventEmitter } from "node:events";
4
+ import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+
8
+ import {
9
+ adoptOrphanRingFiles,
10
+ createPacketWitness,
11
+ WITNESS_RING_BASENAME
12
+ } from "../services/packet-witness.js";
13
+
14
+ /**
15
+ * A stand-in for a spawned tcpdump: it records how it was called and stays
16
+ * "running" until something kills it.
17
+ */
18
+ class FakeChild extends EventEmitter {
19
+ constructor(command, args) {
20
+ super();
21
+ this.command = command;
22
+ this.args = args;
23
+ this.killed = false;
24
+ this.signals = [];
25
+ }
26
+
27
+ kill(signal) {
28
+ this.signals.push(signal);
29
+ if (!this.killed) {
30
+ this.killed = true;
31
+ // A real child exits asynchronously, which is what the code must wait for.
32
+ setImmediate(() => this.emit("close", 0, signal));
33
+ }
34
+ return true;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * @returns {{ spawnProcess: Function, children: FakeChild[], rings: FakeChild[] }}
40
+ */
41
+ function makeSpawn() {
42
+ const children = [];
43
+ const spawnProcess = (command, args) => {
44
+ const child = new FakeChild(command, args);
45
+ children.push(child);
46
+ if (args.includes("--version")) {
47
+ // The availability probe: answer at once, like a present tcpdump.
48
+ setImmediate(() => child.emit("spawn"));
49
+ }
50
+ return child;
51
+ };
52
+ return {
53
+ spawnProcess,
54
+ children,
55
+ get rings() {
56
+ return children.filter((child) => !child.args.includes("--version"));
57
+ }
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Wait until `check` holds, rather than for a chosen interval.
63
+ *
64
+ * A fixed sleep passes alone and fails in a full run — the defect roadmap item
65
+ * 51 names — and the work here is several awaits deep (probe, stop, readdir,
66
+ * copy, restart), so its duration is whatever the machine is busy with.
67
+ *
68
+ * @param {() => boolean | Promise<boolean>} check
69
+ * @param {string} what
70
+ * @returns {Promise<void>}
71
+ */
72
+ async function waitFor(check, what) {
73
+ const deadline = Date.now() + 10_000;
74
+ for (;;) {
75
+ if (await check()) {
76
+ return;
77
+ }
78
+ if (Date.now() > deadline) {
79
+ throw new Error(`timed out waiting for ${what}`);
80
+ }
81
+ await new Promise((resolve) => setTimeout(resolve, 5));
82
+ }
83
+ }
84
+
85
+ /** Let every already-queued microtask and immediate run. */
86
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 20));
87
+
88
+ async function withDir(run) {
89
+ const dir = await mkdtemp(path.join(os.tmpdir(), "witness-ring-"));
90
+ try {
91
+ await run(dir);
92
+ } finally {
93
+ await rm(dir, { recursive: true, force: true });
94
+ }
95
+ }
96
+
97
+ test("the ring runs while a channel is open and stops with the last one", async () => {
98
+ await withDir(async (dir) => {
99
+ const spawn = makeSpawn();
100
+ const witness = createPacketWitness({
101
+ log: () => {},
102
+ dir,
103
+ port: 9090,
104
+ spawnProcess: spawn.spawnProcess
105
+ });
106
+
107
+ witness.holdRing();
108
+ witness.holdRing();
109
+ await waitFor(() => spawn.rings.length === 1, "the ring to start");
110
+ assert.equal(spawn.rings.length, 1, "a second channel must not start a second ring");
111
+ assert.equal(spawn.rings[0].killed, false);
112
+
113
+ witness.releaseRing();
114
+ await settle();
115
+ assert.equal(spawn.rings[0].killed, false, "one channel left still wants the ring");
116
+
117
+ witness.releaseRing();
118
+ await waitFor(() => spawn.rings[0].killed, "the ring to stop");
119
+ });
120
+ });
121
+
122
+ test("a channel that opens and closes while the ring is starting leaves nothing running", async () => {
123
+ await withDir(async (dir) => {
124
+ const spawn = makeSpawn();
125
+ const witness = createPacketWitness({
126
+ log: () => {},
127
+ dir,
128
+ port: 9090,
129
+ spawnProcess: spawn.spawnProcess
130
+ });
131
+ // Release before the availability probe has resolved — the start is still
132
+ // in flight. Without the second look after the await this leaves a tcpdump
133
+ // nobody holds and nobody will ever stop.
134
+ witness.holdRing();
135
+ witness.releaseRing();
136
+ await waitFor(
137
+ () => spawn.rings.every((child) => child.killed),
138
+ "any ring started mid-flight to be stopped"
139
+ );
140
+ const alive = spawn.rings.filter((child) => !child.killed);
141
+ assert.deepEqual(alive, [], "no ring may outlive the channels that wanted it");
142
+ });
143
+ });
144
+
145
+ test("the ring's files are removed once nobody is being served", async () => {
146
+ await withDir(async (dir) => {
147
+ const spawn = makeSpawn();
148
+ const witness = createPacketWitness({
149
+ log: () => {},
150
+ dir,
151
+ port: 9090,
152
+ spawnProcess: spawn.spawnProcess
153
+ });
154
+ witness.holdRing();
155
+ await waitFor(() => spawn.rings.length === 1, "the ring to start");
156
+ await writeFile(path.join(dir, `${WITNESS_RING_BASENAME}0`), "pcap");
157
+ witness.releaseRing();
158
+ await waitFor(async () => (await readdir(dir)).length === 0, "the ring files to be removed");
159
+ });
160
+ });
161
+
162
+ test("a wedge keeps the ring's history, and the ring keeps recording afterwards", async () => {
163
+ await withDir(async (dir) => {
164
+ const spawn = makeSpawn();
165
+ const lines = [];
166
+ const witness = createPacketWitness({
167
+ log: (message) => lines.push(message),
168
+ dir,
169
+ port: 9090,
170
+ spawnProcess: spawn.spawnProcess
171
+ });
172
+ witness.holdRing();
173
+ await waitFor(() => spawn.rings.length === 1, "the ring to start");
174
+ await writeFile(path.join(dir, `${WITNESS_RING_BASENAME}0`), "before-the-freeze");
175
+ await writeFile(path.join(dir, `${WITNESS_RING_BASENAME}1`), "also-before");
176
+
177
+ const started = witness.maybeCapture({
178
+ sessionId: "68296f7d-0000-0000-0000-000000000000",
179
+ tag: "68296f7d",
180
+ label: "proxy",
181
+ remote: { address: "2001:db8::1", port: 61649 },
182
+ queuedBytes: 67_372_267,
183
+ stuckForMs: 4000
184
+ });
185
+ assert.equal(started, true);
186
+ await waitFor(
187
+ async () => (await readdir(dir)).filter((name) => name.includes(".before")).length === 2,
188
+ "both ring files to be copied aside"
189
+ );
190
+
191
+ const kept = (await readdir(dir)).filter((name) => name.includes(".before"));
192
+ assert.equal(kept.length, 2, "both ring files must be kept, not just the finished one");
193
+ assert.ok(kept.every((name) => name.startsWith("packet-witness.68296f7d.")));
194
+ // Stopped to flush, then started again: two ring processes over the episode.
195
+ await waitFor(() => spawn.rings.length >= 2, "the ring to resume after the copy");
196
+ assert.equal(spawn.rings.at(-1).killed, false);
197
+ assert.ok(lines.some((line) => line.includes("kept 2 ring file(s)")));
198
+
199
+ // End the tail capture: it would otherwise sit out its whole window, and
200
+ // its timer would hold this process open.
201
+ for (const child of spawn.children) {
202
+ child.kill("SIGTERM");
203
+ }
204
+ await settle();
205
+ });
206
+ });
207
+
208
+ test("dispose stops the ring and clears its files", async () => {
209
+ await withDir(async (dir) => {
210
+ const spawn = makeSpawn();
211
+ const witness = createPacketWitness({
212
+ log: () => {},
213
+ dir,
214
+ port: 9090,
215
+ spawnProcess: spawn.spawnProcess
216
+ });
217
+ witness.holdRing();
218
+ await waitFor(() => spawn.rings.length === 1, "the ring to start");
219
+ await writeFile(path.join(dir, `${WITNESS_RING_BASENAME}0`), "pcap");
220
+ await witness.dispose();
221
+ assert.equal(spawn.rings.at(-1).killed, true);
222
+ assert.deepEqual(await readdir(dir), []);
223
+ });
224
+ });
225
+
226
+ test("ring files left by a killed process are kept, not deleted by the next one", async () => {
227
+ await withDir(async (dir) => {
228
+ await writeFile(path.join(dir, `${WITNESS_RING_BASENAME}0`), "the seconds before the crash");
229
+ await writeFile(path.join(dir, `${WITNESS_RING_BASENAME}2`), "and these");
230
+ const adopted = await adoptOrphanRingFiles(dir);
231
+ assert.equal(adopted.length, 2);
232
+ const left = await readdir(dir);
233
+ assert.equal(left.filter((name) => name.startsWith(WITNESS_RING_BASENAME)).length, 0);
234
+ assert.ok(left.every((name) => name.startsWith("packet-witness.orphan.")));
235
+ });
236
+ });