@torrent-tv/proxy 2.84.0 → 2.85.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.
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @file The route that hands a browser bytes to time its link with.
3
+ *
4
+ * Only this end's half. How big an ask should be is derived on the page, from
5
+ * what its last ask measured, and is checked where that function lives — a copy
6
+ * of it here would be two owners of one rule, which is the fault this
7
+ * repository keeps recording.
8
+ */
9
+
10
+ import assert from "node:assert/strict";
11
+ import test from "node:test";
12
+
13
+ import { handleApiLinkProbeGet, MAX_LINK_PROBE_BYTES } from "../routes/api/link-probe/get.js";
14
+
15
+ /**
16
+ * A reply that records what it was given.
17
+ *
18
+ * @returns {{ code: (n: number) => object, header: () => object, send: (b: unknown) => object, status: number | null, body: unknown }}
19
+ */
20
+ function fakeReply() {
21
+ const reply = {
22
+ status: /** @type {number | null} */ (null),
23
+ body: /** @type {unknown} */ (null),
24
+ code(n) {
25
+ reply.status = n;
26
+ return reply;
27
+ },
28
+ header() {
29
+ return reply;
30
+ },
31
+ send(body) {
32
+ reply.body = body;
33
+ return reply;
34
+ }
35
+ };
36
+ return reply;
37
+ }
38
+
39
+
40
+
41
+ test("the route answers exactly what was asked for, up to its own ceiling", async () => {
42
+ const small = fakeReply();
43
+ await handleApiLinkProbeGet({ query: { bytes: "65536" } }, small);
44
+ assert.equal(small.status, 200);
45
+ assert.equal(/** @type {Buffer} */ (small.body).length, 65536);
46
+
47
+ const huge = fakeReply();
48
+ await handleApiLinkProbeGet({ query: { bytes: "999999999" } }, huge);
49
+ assert.equal(/** @type {Buffer} */ (huge.body).length, MAX_LINK_PROBE_BYTES);
50
+ });
51
+
52
+ test("the route refuses an ask that is not a size", async () => {
53
+ const reply = fakeReply();
54
+ await handleApiLinkProbeGet({ query: { bytes: "none" } }, reply);
55
+ assert.equal(reply.status, 400);
56
+ });
@@ -1,223 +1,225 @@
1
- /**
2
- * @file The placement must not move while the facts do not.
3
- *
4
- * This is the check the field failure of 2026-09-13 had no equivalent of. Two
5
- * browsers on one torrent: 77 encoder starts and 141 stops in six minutes
6
- * against ONE normal end, both viewers frozen — one at 170.8 s with
7
- * `bufferedAhead=0.1s`, the other at 1673.6 s with an empty buffer — while the
8
- * swarm delivered 3 MB/s from 129 peers. Nothing was produced because no run
9
- * lived long enough to close a piece.
10
- *
11
- * The plan itself was not at fault and was measured not to be: given a settled
12
- * map it returns the same arrangement however often it is asked. What moved was
13
- * its INPUT. A viewer's position had two writers — a seek wrote one field, a
14
- * segment request wrote another, and the reading preferred whichever was set —
15
- * so the priority map jumped backwards and forwards by one or two segments
16
- * several times a second:
17
- *
18
- * 19:58:00.283 p100:#9..#10 p100:#160..#162
19
- * 19:58:00.496 p100:#18..#20 p100:#161..#163
20
- * 19:58:00.574 p100:#16..#18 p100:#161..#163
21
- * 19:58:00.696 p100:#16..#18 p100:#160..#162
22
- * 19:58:01.231 p100:#18..#20 p100:#160..#162
23
- *
24
- * So the property to hold is about the whole chain and not about one function:
25
- * what a viewer states must produce a map that only moves the way film moves,
26
- * and a plan asked repeatedly against unchanged facts must answer identically.
27
- */
28
-
29
- import test from "node:test";
30
- import assert from "node:assert/strict";
31
- import { CoverageMap } from "../services/encode/CoverageMap.js";
32
- import { planEncoders } from "../services/encode/EncodePlan.js";
33
- import { contentionPenalty, penaltiesFrom } from "../services/encode/contention.js";
34
- import { mapForViewer, mergeMaps, runsOf } from "../services/priority/PriorityMap.js";
35
- import { Viewer } from "../services/viewer/Viewer.js";
36
-
37
- // Measured on the addon host 2026-09-03: 7.12x alone, 4.18x with a second.
38
- const PENALTIES = penaltiesFrom(7.12, [{ others: 1, speed: 4.18 }]);
39
- const penaltyFor = (others) => contentionPenalty(others, PENALTIES).penalty;
40
-
41
- const HOST = {
42
- contentionPenaltyFor: penaltyFor,
43
- speedX: 2,
44
- segmentSeconds: 8,
45
- killCostSec: 0.5,
46
- firstByteWaitSec: 1,
47
- refetchSecPerFilmSecond: 0.25
48
- };
49
-
50
- const DURATION = 2896;
51
- const ALLOWANCE = 30;
52
-
53
- /**
54
- * The map two viewers produce, exactly as `PriorityOrchestrator` builds it.
55
- *
56
- * @param {Viewer[]} viewers
57
- * @param {number} now
58
- * @returns {{ from: number, to: number, priority: number }[]}
59
- */
60
- function zonesFor(viewers, now) {
61
- const merged = mergeMaps(
62
- viewers.map((viewer) =>
63
- mapForViewer({
64
- atSeconds: viewer.positionSeconds(now) ?? 0,
65
- durationSeconds: DURATION,
66
- allowanceSeconds: ALLOWANCE,
67
- playing: viewer.consumesFilm()
68
- })
69
- )
70
- );
71
- return runsOf(merged).map((zone) => ({
72
- from: Math.floor(zone.from / HOST.segmentSeconds),
73
- to: Math.floor((zone.to - 1) / HOST.segmentSeconds),
74
- priority: zone.priority
75
- }));
76
- }
77
-
78
- test("a viewer's position only ever moves the way film moves", () => {
79
- const viewer = new Viewer("one", 1_000_000);
80
- viewer.moveTo(170.8, 1_000_000);
81
- viewer.playing = true;
82
-
83
- let previous = viewer.positionSeconds(1_000_000);
84
- for (let tick = 1; tick <= 200; tick += 1) {
85
- const now = 1_000_000 + tick * 50;
86
- const seconds = viewer.positionSeconds(now);
87
- assert.ok(seconds >= previous, `position went backwards at tick ${tick}: ${seconds} < ${previous}`);
88
- previous = seconds;
89
- }
90
- // Fifty ticks of 50 ms is ten seconds of wall clock, and a playing viewer
91
- // covers ten seconds of film in it.
92
- assert.ok(Math.abs(previous - (170.8 + 10)) < 0.001, `expected 180.8s, got ${previous}`);
93
- });
94
-
95
- test("a segment request does not move a viewer, and a stopped picture does not either", () => {
96
- const viewer = new Viewer("one", 1_000_000);
97
- viewer.moveTo(170.8, 1_000_000);
98
- viewer.playing = false;
99
-
100
- // Whatever else happens, only a statement from the viewer moves them. There
101
- // is no method here a request could call: `seen` is presence and nothing more.
102
- viewer.seen(1_000_500);
103
- viewer.seen(1_001_000);
104
- assert.equal(viewer.positionSeconds(1_010_000), 170.8);
105
- });
106
-
107
- test("the priority map of two viewers is the same whenever it is asked", () => {
108
- const at = 1_000_000;
109
- const one = new Viewer("one", at);
110
- one.moveTo(170.8, at);
111
- one.playing = false;
112
- const two = new Viewer("two", at);
113
- two.moveTo(1673.6, at);
114
- two.playing = false;
115
-
116
- const first = JSON.stringify(zonesFor([one, two], at));
117
- for (let tick = 1; tick <= 40; tick += 1) {
118
- // Nothing changes: both pictures are stopped, so no time passes for them.
119
- assert.equal(JSON.stringify(zonesFor([one, two], at + tick * 100)), first, `map moved at tick ${tick}`);
120
- }
121
- });
122
-
123
- test("two viewers far apart settle on one arrangement and stay on it", () => {
124
- const at = 1_000_000;
125
- const one = new Viewer("one", at);
126
- one.moveTo(170.8, at);
127
- one.playing = false;
128
- const two = new Viewer("two", at);
129
- two.moveTo(1673.6, at);
130
- two.playing = false;
131
-
132
- const coverage = new CoverageMap({ segmentCount: 362 });
133
- /** @type {{ from: number, to: number, head: number, speedX: number, startedAt: number }[]} */
134
- let live = [];
135
- let started = 0;
136
- let stopped = 0;
137
-
138
- for (let tick = 0; tick < 60; tick += 1) {
139
- const now = at + tick * 100;
140
- const actions = planEncoders({
141
- coverage,
142
- windows: zonesFor([one, two], now),
143
- runs: live,
144
- maxRuns: 2,
145
- now,
146
- ...HOST
147
- });
148
- for (const action of actions) {
149
- if (action.type === "start") {
150
- live.push({ from: action.from, to: action.to, head: action.from, speedX: 2, startedAt: now });
151
- started += 1;
152
- } else if (action.type === "stop") {
153
- live = live.filter((run) => run !== action.run);
154
- stopped += 1;
155
- } else if (action.type === "move") {
156
- live = live.filter((run) => run !== action.run);
157
- live.push({ from: action.from, to: action.to, head: action.from, speedX: 2, startedAt: now });
158
- started += 1;
159
- stopped += 1;
160
- }
161
- }
162
- }
163
-
164
- // One encoder per viewer, placed once. Anything above this is the plan
165
- // arguing with itself: in the field the same six minutes cost 77 and 141.
166
- assert.equal(started, 2, `expected two starts, got ${started}`);
167
- assert.equal(stopped, 0, `expected no stops, got ${stopped}`);
168
- assert.equal(live.length, 2);
169
- });
170
-
171
- test("an encoder keeping ahead of a playing viewer is left alone", () => {
172
- const at = 1_000_000;
173
- const one = new Viewer("one", at);
174
- one.moveTo(0, at);
175
- one.playing = true;
176
-
177
- const coverage = new CoverageMap({ segmentCount: 362 });
178
- const ready = new Set();
179
- /** @type {{ from: number, to: number, head: number, speedX: number, startedAt: number, made: number }[]} */
180
- let live = [];
181
- let moves = 0;
182
- let starts = 0;
183
-
184
- for (let tick = 0; tick < 120; tick += 1) {
185
- const now = at + tick * 1000;
186
- const actions = planEncoders({
187
- coverage,
188
- windows: zonesFor([one], now),
189
- runs: live,
190
- maxRuns: 1,
191
- now,
192
- ...HOST
193
- });
194
- for (const action of actions) {
195
- if (action.type === "start") {
196
- live.push({ from: action.from, to: action.to, head: action.from, speedX: 2, startedAt: now, made: 0 });
197
- starts += 1;
198
- } else if (action.type === "move") {
199
- live = live.filter((run) => run !== action.run);
200
- live.push({ from: action.from, to: action.to, head: action.from, speedX: 2, startedAt: now, made: 0 });
201
- moves += 1;
202
- } else if (action.type === "stop") {
203
- live = live.filter((run) => run !== action.run);
204
- }
205
- }
206
- // The encoder works: at 2x, one 8-second piece every four seconds of clock.
207
- for (const run of live) {
208
- run.made += 1000 * 2;
209
- while (run.made >= HOST.segmentSeconds * 1000 && run.head <= run.to) {
210
- run.made -= HOST.segmentSeconds * 1000;
211
- ready.add(run.head);
212
- run.head += 1;
213
- }
214
- }
215
- coverage.setReady(ready);
216
- }
217
-
218
- // One encoder, placed once, running twice as fast as the viewer plays: it
219
- // stays in front of them for the whole two minutes, so there is nothing to
220
- // decide again.
221
- assert.equal(starts, 1, `expected one start, got ${starts}`);
222
- assert.equal(moves, 0, `expected no moves, got ${moves}`);
223
- });
1
+ /**
2
+ * @file The placement must not move while the facts do not.
3
+ *
4
+ * This is the check the field failure of 2026-09-13 had no equivalent of. Two
5
+ * browsers on one torrent: 77 encoder starts and 141 stops in six minutes
6
+ * against ONE normal end, both viewers frozen — one at 170.8 s with
7
+ * `bufferedAhead=0.1s`, the other at 1673.6 s with an empty buffer — while the
8
+ * swarm delivered 3 MB/s from 129 peers. Nothing was produced because no run
9
+ * lived long enough to close a piece.
10
+ *
11
+ * The plan itself was not at fault and was measured not to be: given a settled
12
+ * map it returns the same arrangement however often it is asked. What moved was
13
+ * its INPUT. A viewer's position had two writers — a seek wrote one field, a
14
+ * segment request wrote another, and the reading preferred whichever was set —
15
+ * so the priority map jumped backwards and forwards by one or two segments
16
+ * several times a second:
17
+ *
18
+ * 19:58:00.283 p100:#9..#10 p100:#160..#162
19
+ * 19:58:00.496 p100:#18..#20 p100:#161..#163
20
+ * 19:58:00.574 p100:#16..#18 p100:#161..#163
21
+ * 19:58:00.696 p100:#16..#18 p100:#160..#162
22
+ * 19:58:01.231 p100:#18..#20 p100:#160..#162
23
+ *
24
+ * So the property to hold is about the whole chain and not about one function:
25
+ * what a viewer states must produce a map that only moves the way film moves,
26
+ * and a plan asked repeatedly against unchanged facts must answer identically.
27
+ */
28
+
29
+ import test from "node:test";
30
+ import assert from "node:assert/strict";
31
+ import { CoverageMap } from "../services/encode/CoverageMap.js";
32
+ import { planEncoders } from "../services/encode/EncodePlan.js";
33
+ import { contentionPenalty, penaltiesFrom } from "../services/encode/contention.js";
34
+ import { mapForViewer, mergeMaps, runsOf } from "../services/priority/PriorityMap.js";
35
+ import { Viewer } from "../services/viewer/Viewer.js";
36
+
37
+ // Measured on the addon host 2026-09-03: 7.12x alone, 4.18x with a second.
38
+ const PENALTIES = penaltiesFrom(7.12, [{ others: 1, speed: 4.18 }]);
39
+ const penaltyFor = (others) => contentionPenalty(others, PENALTIES).penalty;
40
+
41
+ const HOST = {
42
+ contentionPenaltyFor: penaltyFor,
43
+ speedX: 2,
44
+ segmentSeconds: 8,
45
+ killCostSec: 0.5,
46
+ firstByteWaitSec: 1,
47
+ refetchSecPerFilmSecond: 0.25
48
+ };
49
+
50
+ const DURATION = 2896;
51
+ const ALLOWANCE = 30;
52
+
53
+ /**
54
+ * The map two viewers produce, exactly as `PriorityOrchestrator` builds it.
55
+ *
56
+ * @param {Viewer[]} viewers
57
+ * @param {number} now
58
+ * @returns {{ from: number, to: number, priority: number }[]}
59
+ */
60
+ function zonesFor(viewers, now) {
61
+ const merged = mergeMaps(
62
+ viewers.map((viewer) =>
63
+ mapForViewer({
64
+ atSeconds: viewer.positionSeconds(now) ?? 0,
65
+ durationSeconds: DURATION,
66
+ allowanceSeconds: ALLOWANCE,
67
+ playing: viewer.wantsFilmNow()
68
+ })
69
+ )
70
+ );
71
+ return runsOf(merged).map((zone) => ({
72
+ from: Math.floor(zone.from / HOST.segmentSeconds),
73
+ to: Math.floor((zone.to - 1) / HOST.segmentSeconds),
74
+ priority: zone.priority
75
+ }));
76
+ }
77
+
78
+ test("a viewer's position only ever moves the way film moves", () => {
79
+ const viewer = new Viewer("one", 1_000_000);
80
+ // Stated the way a page states it: where they are, what they hold, and that
81
+ // the picture is advancing. The cushion is what bounds the extrapolation, so
82
+ // a viewer who has stated none cannot move at all.
83
+ viewer.report(
84
+ { bufferedAheadSec: 120, positionSeconds: 170.8, playing: true, waiting: false },
85
+ 1_000_000
86
+ );
87
+
88
+ let previous = viewer.positionSeconds(1_000_000);
89
+ for (let tick = 1; tick <= 200; tick += 1) {
90
+ const now = 1_000_000 + tick * 50;
91
+ const seconds = viewer.positionSeconds(now);
92
+ assert.ok(seconds >= previous, `position went backwards at tick ${tick}: ${seconds} < ${previous}`);
93
+ previous = seconds;
94
+ }
95
+ // Fifty ticks of 50 ms is ten seconds of wall clock, and a playing viewer
96
+ // covers ten seconds of film in it.
97
+ assert.ok(Math.abs(previous - (170.8 + 10)) < 0.001, `expected 180.8s, got ${previous}`);
98
+ });
99
+
100
+ test("a segment request does not move a viewer, and a stopped picture does not either", () => {
101
+ const viewer = new Viewer("one", 1_000_000);
102
+ viewer.report(
103
+ { bufferedAheadSec: 120, positionSeconds: 170.8, playing: false, waiting: false },
104
+ 1_000_000
105
+ );
106
+
107
+ // Whatever else happens, only a statement from the viewer moves them. There
108
+ // is no method here a request could call: `seen` is presence and nothing more.
109
+ viewer.seen(1_000_500);
110
+ viewer.seen(1_001_000);
111
+ assert.equal(viewer.positionSeconds(1_010_000), 170.8);
112
+ });
113
+
114
+ test("the priority map of two viewers is the same whenever it is asked", () => {
115
+ const at = 1_000_000;
116
+ const one = new Viewer("one", at);
117
+ one.report({ bufferedAheadSec: 120, positionSeconds: 170.8, playing: false, waiting: false }, at);
118
+ const two = new Viewer("two", at);
119
+ two.report({ bufferedAheadSec: 120, positionSeconds: 1673.6, playing: false, waiting: false }, at);
120
+
121
+ const first = JSON.stringify(zonesFor([one, two], at));
122
+ for (let tick = 1; tick <= 40; tick += 1) {
123
+ // Nothing changes: both pictures are stopped, so no time passes for them.
124
+ assert.equal(JSON.stringify(zonesFor([one, two], at + tick * 100)), first, `map moved at tick ${tick}`);
125
+ }
126
+ });
127
+
128
+ test("two viewers far apart settle on one arrangement and stay on it", () => {
129
+ const at = 1_000_000;
130
+ const one = new Viewer("one", at);
131
+ one.report({ bufferedAheadSec: 120, positionSeconds: 170.8, playing: false, waiting: false }, at);
132
+ const two = new Viewer("two", at);
133
+ two.report({ bufferedAheadSec: 120, positionSeconds: 1673.6, playing: false, waiting: false }, at);
134
+
135
+ const coverage = new CoverageMap({ segmentCount: 362 });
136
+ /** @type {{ from: number, to: number, head: number, speedX: number, startedAt: number }[]} */
137
+ let live = [];
138
+ let started = 0;
139
+ let stopped = 0;
140
+
141
+ for (let tick = 0; tick < 60; tick += 1) {
142
+ const now = at + tick * 100;
143
+ const actions = planEncoders({
144
+ coverage,
145
+ windows: zonesFor([one, two], now),
146
+ runs: live,
147
+ maxRuns: 2,
148
+ now,
149
+ ...HOST
150
+ });
151
+ for (const action of actions) {
152
+ if (action.type === "start") {
153
+ live.push({ from: action.from, to: action.to, head: action.from, speedX: 2, startedAt: now });
154
+ started += 1;
155
+ } else if (action.type === "stop") {
156
+ live = live.filter((run) => run !== action.run);
157
+ stopped += 1;
158
+ } else if (action.type === "move") {
159
+ live = live.filter((run) => run !== action.run);
160
+ live.push({ from: action.from, to: action.to, head: action.from, speedX: 2, startedAt: now });
161
+ started += 1;
162
+ stopped += 1;
163
+ }
164
+ }
165
+ }
166
+
167
+ // One encoder per viewer, placed once. Anything above this is the plan
168
+ // arguing with itself: in the field the same six minutes cost 77 and 141.
169
+ assert.equal(started, 2, `expected two starts, got ${started}`);
170
+ assert.equal(stopped, 0, `expected no stops, got ${stopped}`);
171
+ assert.equal(live.length, 2);
172
+ });
173
+
174
+ test("an encoder keeping ahead of a playing viewer is left alone", () => {
175
+ const at = 1_000_000;
176
+ const one = new Viewer("one", at);
177
+ one.report({ bufferedAheadSec: 120, positionSeconds: 0, playing: true, waiting: false }, at);
178
+
179
+ const coverage = new CoverageMap({ segmentCount: 362 });
180
+ const ready = new Set();
181
+ /** @type {{ from: number, to: number, head: number, speedX: number, startedAt: number, made: number }[]} */
182
+ let live = [];
183
+ let moves = 0;
184
+ let starts = 0;
185
+
186
+ for (let tick = 0; tick < 120; tick += 1) {
187
+ const now = at + tick * 1000;
188
+ const actions = planEncoders({
189
+ coverage,
190
+ windows: zonesFor([one], now),
191
+ runs: live,
192
+ maxRuns: 1,
193
+ now,
194
+ ...HOST
195
+ });
196
+ for (const action of actions) {
197
+ if (action.type === "start") {
198
+ live.push({ from: action.from, to: action.to, head: action.from, speedX: 2, startedAt: now, made: 0 });
199
+ starts += 1;
200
+ } else if (action.type === "move") {
201
+ live = live.filter((run) => run !== action.run);
202
+ live.push({ from: action.from, to: action.to, head: action.from, speedX: 2, startedAt: now, made: 0 });
203
+ moves += 1;
204
+ } else if (action.type === "stop") {
205
+ live = live.filter((run) => run !== action.run);
206
+ }
207
+ }
208
+ // The encoder works: at 2x, one 8-second piece every four seconds of clock.
209
+ for (const run of live) {
210
+ run.made += 1000 * 2;
211
+ while (run.made >= HOST.segmentSeconds * 1000 && run.head <= run.to) {
212
+ run.made -= HOST.segmentSeconds * 1000;
213
+ ready.add(run.head);
214
+ run.head += 1;
215
+ }
216
+ }
217
+ coverage.setReady(ready);
218
+ }
219
+
220
+ // One encoder, placed once, running twice as fast as the viewer plays: it
221
+ // stays in front of them for the whole two minutes, so there is nothing to
222
+ // decide again.
223
+ assert.equal(starts, 1, `expected one start, got ${starts}`);
224
+ assert.equal(moves, 0, `expected no moves, got ${moves}`);
225
+ });
@@ -22,8 +22,6 @@ import { TorrentPool } from "../services/torrent-pool.js";
22
22
  import { demandFor, forgetTorrent } from "../services/download/registry.js";
23
23
  import { Urgency } from "../services/demand/index.js";
24
24
 
25
- const STALE_AFTER_MS = 60_000;
26
-
27
25
  /**
28
26
  * A session, as much of one as the orchestrator reads.
29
27
  *