@torrent-tv/proxy 2.56.0 → 2.57.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.
@@ -95,7 +95,20 @@ export function mergeContainerSubtitleFlags(bannerTracks, declared) {
95
95
  const banner = Array.isArray(bannerTracks) ? bannerTracks : [];
96
96
  const container = Array.isArray(declared) ? declared : [];
97
97
  const undecided = () => ({
98
- tracks: banner.map((track) => ({ ...track, declaresDefault: false }))
98
+ // The container reading could not be lined up, so nothing of it is used —
99
+ // including the flags, which would otherwise be attributed to the wrong
100
+ // track.
101
+ tracks: banner.map((track) => ({
102
+ ...track,
103
+ declaresDefault: false,
104
+ isForced: false,
105
+ isHearingImpaired: false,
106
+ // Not "the container says this track is unusable" — nothing of the
107
+ // container is being used here. A track is offered unless it was read to
108
+ // say otherwise.
109
+ isEnabled: true,
110
+ languageBcp47: ""
111
+ }))
99
112
  });
100
113
  if (container.length === 0) {
101
114
  return { ...undecided(), aligned: false, reason: "the container declares no subtitle track" };
@@ -123,7 +136,20 @@ export function mergeContainerSubtitleFlags(bannerTracks, declared) {
123
136
  tracks: banner.map((track, order) => ({
124
137
  ...track,
125
138
  isDefault: container[order].isDefault === true,
126
- declaresDefault: container[order].declaresDefault === true
139
+ declaresDefault: container[order].declaresDefault === true,
140
+ // Read from the file rather than guessed from the track's name. Both are
141
+ // stated by the container itself (RFC 9559 §5.1.4.1) and neither reaches
142
+ // ffmpeg's `-i` banner, which is where every other field here comes from.
143
+ isForced: container[order].isForced === true,
144
+ isHearingImpaired: container[order].isHearingImpaired === true,
145
+ // FlagEnabled, so the browser can leave an unusable track out of the
146
+ // menu. It stays in this list and keeps its number: ffmpeg creates a
147
+ // stream for it either way.
148
+ isEnabled: container[order].isEnabled !== false,
149
+ // The RFC 5646 tag, where the file writes one. Kept beside the code
150
+ // rather than replacing it: what this list is aligned against is ffmpeg's
151
+ // banner, which prints the three-letter form.
152
+ languageBcp47: typeof container[order].languageBcp47 === "string" ? container[order].languageBcp47 : ""
127
153
  })),
128
154
  aligned: true,
129
155
  reason: ""
@@ -1,78 +1,158 @@
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
+ });
125
+
126
+ test("the peer's own answering cadence counts toward the allowance", () => {
127
+ // Field case 2026-08-27: queues empty, 3.4 MB/s crossing, tab hidden so the
128
+ // browser echoed about once a second. Without the peer's cadence the
129
+ // allowance is one probe and every other line read `association-stopped`.
130
+ const withoutCadence = allowedGap({
131
+ queuedBytes: 0,
132
+ bytesPerSecond: 3.4 * 1024 * 1024,
133
+ rttMs: 9
134
+ });
135
+ assert.equal(withoutCadence, 1);
136
+ const withCadence = allowedGap({
137
+ queuedBytes: 0,
138
+ bytesPerSecond: 3.4 * 1024 * 1024,
139
+ rttMs: 9,
140
+ echoIntervalMs: 1000
141
+ });
142
+ assert.ok(withCadence >= 3, `a second of cadence must allow more than ${withCadence}`);
143
+ const allowed = Object.fromEntries(ALL.map((label) => [label, withCadence]));
144
+ const { verdict } = readProbeState(
145
+ state({ proxy: 98, "proxy-control": 98, "proxy-fast": 98 }, { allowed, echoAgeMs: 977 })
146
+ );
147
+ assert.equal(verdict, "flowing");
148
+ });
149
+
150
+ test("a stale echo is judged against the peer's cadence, not a fixed half second", () => {
151
+ // The same numbers with the cadence unknown must still be able to say the
152
+ // reverse direction is gone — the bound rises with the cadence, it does not
153
+ // disappear.
154
+ const { verdict } = readProbeState(
155
+ state({ proxy: 99, "proxy-control": 99, "proxy-fast": 99 }, { echoAgeMs: 60_000, echoStaleMs: 2000 })
156
+ );
157
+ assert.equal(verdict, "reverse-direction-gone");
158
+ });
@@ -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
+ });