@torrent-tv/proxy 2.69.2 → 2.71.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.
@@ -62,11 +62,13 @@ async function recordingTorrent({ pieceCount, present = () => true }) {
62
62
  bitfield: { get: (index) => present(index) },
63
63
  files: [{ offset: 0, length: totalLength, name: "file.bin" }],
64
64
  _critical: [],
65
+ _selections: { _items: [] },
65
66
  calls,
66
67
  held,
67
68
  _select(from, to, _priority, _notify, isStreamSelection) {
68
69
  calls.push({ call: "select", from, to, stream: isStreamSelection === true });
69
70
  held.push(`${from}-${to}`);
71
+ this._selections._items.push({ from, to });
70
72
  },
71
73
  _deselect(from, to, isStreamSelection) {
72
74
  calls.push({ call: "deselect", from, to, stream: isStreamSelection === true });
@@ -74,6 +76,10 @@ async function recordingTorrent({ pieceCount, present = () => true }) {
74
76
  if (at >= 0) {
75
77
  held.splice(at, 1);
76
78
  }
79
+ const item = this._selections._items.findIndex((one) => one.from === from && one.to === to);
80
+ if (item >= 0) {
81
+ this._selections._items.splice(item, 1);
82
+ }
77
83
  },
78
84
  critical(from, to) {
79
85
  calls.push({ call: "critical", from, to });
@@ -181,7 +187,7 @@ test("an abandoned read leaves nothing selected", async () => {
181
187
  }
182
188
  });
183
189
 
184
- test("two readers add up, and one leaving takes only its own window", async () => {
190
+ test("two readers add up, and one leaving takes only its own", async () => {
185
191
  const { torrent, store, directory } = await recordingTorrent({ pieceCount: 8000 });
186
192
  try {
187
193
  const head = readFragments({
@@ -195,18 +201,24 @@ test("two readers add up, and one leaving takes only its own window", async () =
195
201
  (await head.next()).value.release();
196
202
  (await tail.next()).value.release();
197
203
 
198
- assert.equal(torrent.held.length, 2, "the two readers did not both hold a window");
199
- const [headWindow, tailWindow] = torrent.held;
204
+ // Not a count: each reader states several bands by level, and two readers
205
+ // wanting the same pieces are one instruction. What matters is that both
206
+ // are represented and that leaving removes only what leaving should.
207
+ const pieceOf = (range) => Number(range.split("-")[0]);
208
+ const held = [...torrent.held];
209
+ assert.ok(held.some((range) => pieceOf(range) < 4000), "the head reader holds nothing");
210
+ assert.ok(held.some((range) => pieceOf(range) >= 4000), "the tail reader holds nothing");
200
211
 
201
212
  await tail.return();
202
- assert.deepEqual(
203
- torrent.held,
204
- [headWindow],
205
- `leaving reader took the wrong window (expected to remove ${tailWindow})`
213
+ const after = [...torrent.held];
214
+ assert.ok(
215
+ after.some((range) => pieceOf(range) < 4000),
216
+ "the head reader's window went with the tail reader"
206
217
  );
218
+ assert.ok(after.length < held.length, "the tail reader took nothing away when it left");
207
219
 
208
220
  await head.return();
209
- assert.deepEqual(torrent.held, []);
221
+ assert.deepEqual(torrent.held, [], "the last reader left something behind");
210
222
  } finally {
211
223
  store.destroy(() => undefined);
212
224
  await fs.rm(directory, { recursive: true, force: true });
@@ -0,0 +1,191 @@
1
+ /**
2
+ * @file The one place that speaks to WebTorrent.
3
+ *
4
+ * Driven against a stub torrent shaped like the vendored 2.8.5: a selection
5
+ * list it can be asked about, a bitfield saying what has arrived, and the
6
+ * private `_select`/`_deselect` the real one exposes.
7
+ */
8
+
9
+ import test from "node:test";
10
+ import assert from "node:assert/strict";
11
+
12
+ import { DemandRegister } from "../services/demand/DemandRegister.js";
13
+ import { Urgency } from "../services/demand/Urgency.js";
14
+ import { SwarmSelection } from "../services/download/SwarmSelection.js";
15
+
16
+ const PIECE = 1024;
17
+
18
+ /**
19
+ * @param {object} [params]
20
+ * @param {number[]} [params.have] - Pieces that have arrived.
21
+ * @param {number} [params.files] - How many files, each ten pieces long.
22
+ * @returns {object}
23
+ */
24
+ function stubTorrent({ have = [], files = 1 } = {}) {
25
+ const arrived = new Set(have);
26
+ const items = [];
27
+ return {
28
+ pieceLength: PIECE,
29
+ files: Array.from({ length: files }, (unused, index) => ({
30
+ offset: index * 10 * PIECE,
31
+ length: 10 * PIECE
32
+ })),
33
+ bitfield: { get: (index) => arrived.has(index) },
34
+ _critical: [],
35
+ _selections: { _items: items },
36
+ calls: { select: [], deselect: [], critical: [] },
37
+ _select(from, to, priority, notify, isStream) {
38
+ this.calls.select.push({ from, to, priority, isStream });
39
+ items.push({ from, to, priority });
40
+ },
41
+ _deselect(from, to) {
42
+ this.calls.deselect.push({ from, to });
43
+ const at = items.findIndex((item) => item.from === from && item.to === to);
44
+ if (at >= 0) {
45
+ items.splice(at, 1);
46
+ }
47
+ },
48
+ critical(from, to) {
49
+ this.calls.critical.push({ from, to });
50
+ for (let index = from; index <= to; index += 1) {
51
+ this._critical[index] = true;
52
+ }
53
+ },
54
+ /** Pretend the library dropped a satisfied selection, which it does. */
55
+ forget(from, to) {
56
+ const at = items.findIndex((item) => item.from === from && item.to === to);
57
+ if (at >= 0) {
58
+ items.splice(at, 1);
59
+ }
60
+ }
61
+ };
62
+ }
63
+
64
+ test("nothing is asked of the swarm until somebody states a need", () => {
65
+ const torrent = stubTorrent();
66
+ const selection = new SwarmSelection({ torrent, register: new DemandRegister() });
67
+
68
+ assert.deepEqual(selection.reconcile(), { stated: 0, withdrawn: 0 });
69
+ assert.equal(torrent.calls.select.length, 0);
70
+ });
71
+
72
+ test("two viewers of one film are two instructions, and both are urgent", () => {
73
+ const torrent = stubTorrent();
74
+ const register = new DemandRegister();
75
+ const selection = new SwarmSelection({ torrent, register });
76
+
77
+ // One stopped at the start, one stopped further in. Both pictures are still.
78
+ register.state({ claimant: "v1", fileIndex: 0, byteStart: 0, byteEnd: PIECE - 1, urgency: Urgency.BLOCKED });
79
+ register.state({ claimant: "v2", fileIndex: 0, byteStart: 5 * PIECE, byteEnd: 6 * PIECE - 1, urgency: Urgency.BLOCKED });
80
+ selection.reconcile();
81
+
82
+ assert.deepEqual(torrent.calls.select, [
83
+ { from: 0, to: 0, priority: 1, isStream: true },
84
+ { from: 5, to: 5, priority: 1, isStream: true }
85
+ ]);
86
+ // Both may take a block from a slow peer, and the mark spans both.
87
+ assert.deepEqual(torrent.calls.critical, [{ from: 0, to: 5 }]);
88
+ });
89
+
90
+ test("the same pieces wanted by two claimants are one instruction", () => {
91
+ const torrent = stubTorrent();
92
+ const register = new DemandRegister();
93
+ const selection = new SwarmSelection({ torrent, register });
94
+
95
+ // Picture and sound of one viewer read the same file and overlap.
96
+ register.state({ claimant: "video", fileIndex: 0, byteStart: 0, byteEnd: PIECE - 1, urgency: Urgency.NEAR });
97
+ register.state({ claimant: "audio", fileIndex: 0, byteStart: 0, byteEnd: PIECE - 1, urgency: Urgency.NEAR });
98
+ const first = selection.reconcile();
99
+
100
+ assert.equal(first.stated, 1, "one range, told once");
101
+ assert.equal(torrent.calls.select.length, 1);
102
+ });
103
+
104
+ test("the speculative levels are withdrawn whole the moment something urgent is missing", () => {
105
+ const torrent = stubTorrent({ have: [0] });
106
+ const register = new DemandRegister();
107
+ const selection = new SwarmSelection({ torrent, register });
108
+
109
+ register.state({ claimant: "video", fileIndex: 0, byteStart: 0, byteEnd: PIECE - 1, urgency: Urgency.NEAR });
110
+ register.state({ claimant: "fill", fileIndex: 0, byteStart: 5 * PIECE, byteEnd: 9 * PIECE - 1, urgency: Urgency.TAIL });
111
+ selection.reconcile();
112
+
113
+ assert.equal(selection.statedRanges().length, 2, "nothing urgent is missing, so the tail is stated");
114
+ assert.ok(torrent.calls.select.some((call) => call.priority === 0), "and it is stated as zero");
115
+
116
+ // The viewer moves on to a piece that has not arrived.
117
+ register.state({ claimant: "video", fileIndex: 0, byteStart: PIECE, byteEnd: 2 * PIECE - 1, urgency: Urgency.NEAR });
118
+ selection.reconcile();
119
+
120
+ assert.deepEqual(
121
+ selection.statedRanges().map((range) => range.priority),
122
+ [1],
123
+ "the tail is out of the download set entirely, not lowered — a peer with nothing urgent to give must not be able to fall through to it"
124
+ );
125
+ assert.ok(torrent.calls.deselect.length > 0);
126
+ });
127
+
128
+ test("a selection the library drops once satisfied is stated again", () => {
129
+ const torrent = stubTorrent();
130
+ const register = new DemandRegister();
131
+ const selection = new SwarmSelection({ torrent, register });
132
+
133
+ register.state({ claimant: "video", fileIndex: 0, byteStart: 0, byteEnd: PIECE - 1, urgency: Urgency.NEAR });
134
+ selection.reconcile();
135
+ assert.equal(torrent.calls.select.length, 1);
136
+
137
+ // Nothing changed: no second instruction.
138
+ selection.reconcile();
139
+ assert.equal(torrent.calls.select.length, 1);
140
+
141
+ // WebTorrent removes a selection once every piece in it has arrived, and says
142
+ // nothing about having done so. The window is still wanted.
143
+ torrent.forget(0, 0);
144
+ selection.reconcile();
145
+ assert.equal(torrent.calls.select.length, 2, "stated again, because the library had let it go");
146
+ });
147
+
148
+ test("a claimant that withdraws takes its instruction with it", () => {
149
+ const torrent = stubTorrent();
150
+ const register = new DemandRegister();
151
+ const selection = new SwarmSelection({ torrent, register });
152
+
153
+ register.state({ claimant: "video", fileIndex: 0, byteStart: 0, byteEnd: PIECE - 1, urgency: Urgency.BLOCKED });
154
+ selection.reconcile();
155
+ register.withdraw("video");
156
+ const after = selection.reconcile();
157
+
158
+ assert.equal(after.withdrawn, 1);
159
+ assert.equal(selection.statedRanges().length, 0);
160
+ // And the displacement mark goes with it: WebTorrent never clears it itself,
161
+ // so a reader walking a film would leave every piece of it marked.
162
+ assert.equal(torrent._critical.some((marked) => marked === true), false);
163
+ });
164
+
165
+ test("a window is bounded by its own file, so it cannot claim the next one", () => {
166
+ const torrent = stubTorrent({ files: 3 });
167
+ const register = new DemandRegister();
168
+ const selection = new SwarmSelection({ torrent, register });
169
+
170
+ // Asking past the end of file 1. File 1 occupies pieces 10-19.
171
+ register.state({
172
+ claimant: "video", fileIndex: 1, byteStart: 0, byteEnd: 100 * PIECE, urgency: Urgency.NEAR
173
+ });
174
+ selection.reconcile();
175
+
176
+ assert.deepEqual(torrent.calls.select, [{ from: 10, to: 19, priority: 1, isStream: true }]);
177
+ });
178
+
179
+ test("releasing everything leaves the library holding nothing of ours", () => {
180
+ const torrent = stubTorrent();
181
+ const register = new DemandRegister();
182
+ const selection = new SwarmSelection({ torrent, register });
183
+
184
+ register.state({ claimant: "video", fileIndex: 0, byteStart: 0, byteEnd: 3 * PIECE, urgency: Urgency.BLOCKED });
185
+ selection.reconcile();
186
+ selection.releaseAll();
187
+
188
+ assert.equal(torrent._selections._items.length, 0);
189
+ assert.equal(selection.statedRanges().length, 0);
190
+ assert.equal(torrent._critical.some((marked) => marked === true), false);
191
+ });
package/utils/logger.js CHANGED
@@ -38,6 +38,40 @@ let fileStream = null;
38
38
  /** @type {string} */
39
39
  let filePath = "";
40
40
  let writtenBytes = 0;
41
+ /**
42
+ * Where lines go when this module is running in a worker thread.
43
+ *
44
+ * A worker thread is a separate instance of the runtime: it loads its own copy
45
+ * of every module, so `fileStream` above is a DIFFERENT variable there, and
46
+ * `logToFile` is only ever called on the main thread. The result was silent:
47
+ * measured 2026-09-02 over a whole log file of 49 938 lines, every line the
48
+ * torrent thread wrote through this module — the piece reader's, including the
49
+ * comparison of the two claim strategies that had been awaited for weeks, and
50
+ * the torrent pool's — was absent, while the same lines were visible in the
51
+ * container's output, which is destroyed by every release.
52
+ *
53
+ * Two threads cannot both write the file: they would race on the rotation and
54
+ * could interleave mid-line. So there is one writer, and a worker sends its
55
+ * lines to it. Set by the worker at startup; unset on the main thread, where
56
+ * the file is written directly.
57
+ *
58
+ * @type {((level: string, message: string) => void) | null}
59
+ */
60
+ let forward = null;
61
+
62
+ /**
63
+ * Send this thread's log lines to the thread that owns the file.
64
+ *
65
+ * Called by a worker at startup. Until it is, a worker's lines reach the
66
+ * console and nothing else — which is what they did for as long as this module
67
+ * has existed.
68
+ *
69
+ * @param {((level: string, message: string) => void) | null} sink
70
+ * @returns {void}
71
+ */
72
+ export function forwardLogsTo(sink) {
73
+ forward = typeof sink === "function" ? sink : null;
74
+ }
41
75
 
42
76
  /**
43
77
  * Return the current time as a compact ISO-8601 (UTC) string, e.g.
@@ -119,24 +153,32 @@ function toFile(line) {
119
153
  * @type {ProxyLogger}
120
154
  */
121
155
  export const logger = {
122
- info: (message) => {
123
- const line = `${PREFIX} [${ts()}] ${message}`;
124
- console.log(chalk.cyan(line));
125
- toFile(line);
126
- },
127
- success: (message) => {
128
- const line = `${PREFIX} [${ts()}] ${message}`;
129
- console.log(chalk.green(line));
130
- toFile(line);
131
- },
132
- warn: (message) => {
133
- const line = `${PREFIX} [${ts()}] ${message}`;
134
- console.warn(chalk.yellow(line));
135
- toFile(line);
136
- },
137
- error: (message) => {
138
- const line = `${PREFIX} [${ts()}] ${message}`;
139
- console.error(chalk.red(line));
140
- toFile(line);
141
- }
156
+ info: (message) => write("info", message, chalk.cyan, console.log),
157
+ success: (message) => write("success", message, chalk.green, console.log),
158
+ warn: (message) => write("warn", message, chalk.yellow, console.warn),
159
+ error: (message) => write("error", message, chalk.red, console.error)
142
160
  };
161
+
162
+ /**
163
+ * One path for every level, so a line cannot reach the console and miss the
164
+ * file depending on which method was called or which thread called it.
165
+ *
166
+ * @param {string} level
167
+ * @param {string} message
168
+ * @param {(text: string) => string} colour
169
+ * @param {(text: string) => void} toConsole
170
+ * @returns {void}
171
+ */
172
+ function write(level, message, colour, toConsole) {
173
+ toConsole(colour(`${PREFIX} [${ts()}] ${message}`));
174
+ if (forward) {
175
+ try {
176
+ forward(level, message);
177
+ } catch {
178
+ // silent-ok: a thread whose channel has closed is shutting down, and a
179
+ // failed log line must not be what ends it.
180
+ }
181
+ return;
182
+ }
183
+ toFile(`${PREFIX} [${ts()}] ${message}`);
184
+ }