@torrent-tv/proxy 2.83.4 → 2.83.5

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,120 @@
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 } 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("every level goes through the same rule", () => {
113
+ const message = unique("levels");
114
+ const lines = captured(() => {
115
+ logger.warn(message);
116
+ logger.warn(message);
117
+ logger.error(message);
118
+ });
119
+ assert.equal(lines.length, 1, "a flood of errors is still a flood");
120
+ });
@@ -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
+ });
@@ -0,0 +1,212 @@
1
+ /**
2
+ * @file One owner of the fact "this proxy has piece N".
3
+ *
4
+ * The store holds the bytes, so it owns the fact. The library keeps a second
5
+ * copy of it in its completion bitfield, and until 2026-09-12 nothing
6
+ * reconciled them: the disk tier dropped a piece once every reader was past it
7
+ * — correctly, that is what bounds the spill — and the bitfield went on saying
8
+ * the piece was verified. A read then concluded the piece was had, asked for it,
9
+ * was told it was absent, and failed; nothing fetched it again either, because
10
+ * the library does not download what it believes it owns. Field: a film played
11
+ * 80 seconds and then answered `Piece 0 is verified but absent from the store`
12
+ * for 92 minutes.
13
+ *
14
+ * Pinned here: the announcement and its one rule — said when the piece has gone
15
+ * from EVERYWHERE, never when one tier alone lost it — and the withdrawal.
16
+ */
17
+
18
+ import test from "node:test";
19
+ import assert from "node:assert/strict";
20
+ import os from "node:os";
21
+ import path from "node:path";
22
+ import fs from "node:fs/promises";
23
+ import { SharedPieceStore } from "../services/piece-store/shared-piece-store.js";
24
+ import { withdrawClaim } from "../services/download/withdraw-claim.js";
25
+
26
+ const PIECE = 1024;
27
+
28
+ /**
29
+ * A store of four pieces with room for one, so every admission spills the last,
30
+ * plus the announcements it made.
31
+ */
32
+ async function storeWithGone(extras = {}) {
33
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "withdraw-test-"));
34
+ /** @type {number[]} */
35
+ const gone = [];
36
+ const store = new SharedPieceStore(PIECE, {
37
+ length: 4 * PIECE,
38
+ memoryBytes: PIECE,
39
+ path: directory,
40
+ name: "test",
41
+ files: [{ offset: 0, length: 4 * PIECE, name: "file.bin" }],
42
+ onPieceGone: ({ index }) => gone.push(index),
43
+ ...extras
44
+ });
45
+ const put = (index) => new Promise((resolve, reject) => {
46
+ store.put(index, Buffer.alloc(PIECE, index + 1), (error) => (error ? reject(error) : resolve()));
47
+ });
48
+ const clean = async () => {
49
+ store.destroy(() => undefined);
50
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 });
51
+ };
52
+ return { store, gone, put, clean };
53
+ }
54
+
55
+ /**
56
+ * Wait for the CONDITION, with a deadline only as a backstop. A fixed pause
57
+ * here would measure the machine rather than the store.
58
+ *
59
+ * @param {() => boolean} ready
60
+ * @param {string} what
61
+ */
62
+ async function until(ready, what) {
63
+ const deadline = Date.now() + 5_000;
64
+ while (!ready()) {
65
+ if (Date.now() > deadline) {
66
+ throw new Error(`timed out waiting for ${what}`);
67
+ }
68
+ await new Promise((resolve) => setImmediate(resolve));
69
+ }
70
+ }
71
+
72
+ test("a piece left behind every reader is dropped AND the claim withdrawn", async () => {
73
+ const { store, gone, put, clean } = await storeWithGone();
74
+ try {
75
+ await put(0);
76
+ await put(1);
77
+ await put(2);
78
+ // WHERE THE READERS STAND, which is the whole trigger: the encoder ran
79
+ // ahead, so pieces 0-1 are behind every one of them. This is the production
80
+ // path — `reviseSpillCeiling` asks `forgetBehind(readHeads)` — and it is
81
+ // what dropped 565 pieces in the field.
82
+ store.protectRange("reader", 2, 3, 0);
83
+ const revision = store.reviseSpillCeiling(null);
84
+
85
+ assert.ok(revision.behind >= 1, `something should have been dropped, got ${revision.behind}`);
86
+ assert.ok(gone.includes(0), `piece 0 has gone and should say so, got ${JSON.stringify(gone)}`);
87
+ assert.ok(
88
+ gone.every((index) => index < 2),
89
+ `nothing a reader still wants may be announced, got ${JSON.stringify(gone)}`
90
+ );
91
+ } finally {
92
+ await clean();
93
+ }
94
+ });
95
+
96
+ test("a piece dropped as a duplicate of a file held whole is NOT announced", async () => {
97
+ const { store, gone, put, clean } = await storeWithGone({
98
+ // Every piece can be had from the assembled file, which is exactly why the
99
+ // spilled copy is being dropped. Nothing has been lost, so nothing is said.
100
+ isPieceElsewhere: () => true
101
+ });
102
+ try {
103
+ await put(0);
104
+ await put(1);
105
+ await put(2);
106
+ // The spill is what puts a piece on disk, and it finishes on its own time;
107
+ // dropping duplicates deliberately leaves a piece whose spill is still in
108
+ // flight alone, so the precondition is waited for rather than assumed.
109
+ await until(() => store.stats().spilled >= 1, "a piece to reach the disk");
110
+ const dropped = store.dropDuplicatesHeldElsewhere();
111
+ assert.ok(dropped >= 1, "the spilled duplicate should have been dropped");
112
+ assert.deepEqual(gone, [], "a piece still readable from a whole file has not gone");
113
+ } finally {
114
+ await clean();
115
+ }
116
+ });
117
+
118
+ test("a closing store announces nothing, because its torrent is going too", async () => {
119
+ const { store, gone, put, clean } = await storeWithGone();
120
+ try {
121
+ await put(0);
122
+ await put(1);
123
+ store.protectRange("reader", 2, 3, 0);
124
+ store.close(() => undefined);
125
+ store.reviseSpillCeiling(null);
126
+ assert.deepEqual(gone, [], "a claim withdrawn against a dying torrent reaches nothing useful");
127
+ } finally {
128
+ await clean();
129
+ }
130
+ });
131
+
132
+ test("the withdrawal is counted in the store's own figures", async () => {
133
+ const { store, put, clean } = await storeWithGone();
134
+ try {
135
+ await put(0);
136
+ await put(1);
137
+ await put(2);
138
+ store.protectRange("reader", 2, 3, 0);
139
+ store.reviseSpillCeiling(null);
140
+ assert.ok(
141
+ store.stats().withdrawn >= 1,
142
+ "the figure that makes the eviction's bargain checkable must move"
143
+ );
144
+ } finally {
145
+ await clean();
146
+ }
147
+ });
148
+
149
+ test("a piece the library thinks it has is withdrawn", () => {
150
+ const asked = [];
151
+ const torrent = {
152
+ name: "film.mkv",
153
+ destroyed: false,
154
+ bitfield: { get: () => true },
155
+ _markUnverified: (index) => asked.push(index)
156
+ };
157
+ assert.equal(withdrawClaim({ index: 3, files: [{ _torrent: torrent }] }), "withdrawn");
158
+ assert.deepEqual(asked, [3]);
159
+ });
160
+
161
+ test("a piece the library already knows is missing is left alone", () => {
162
+ let touched = 0;
163
+ const torrent = {
164
+ destroyed: false,
165
+ bitfield: { get: () => false },
166
+ _markUnverified: () => { touched += 1; }
167
+ };
168
+ assert.equal(
169
+ withdrawClaim({ index: 7, torrent }),
170
+ "nothing-to-withdraw",
171
+ "re-creating a piece the library is already fetching would discard its blocks in flight"
172
+ );
173
+ assert.equal(touched, 0);
174
+ });
175
+
176
+ test("a destroyed torrent is left alone", () => {
177
+ let touched = 0;
178
+ const torrent = {
179
+ destroyed: true,
180
+ bitfield: { get: () => true },
181
+ _markUnverified: () => { touched += 1; }
182
+ };
183
+ assert.equal(withdrawClaim({ index: 1, torrent }), "no-torrent");
184
+ assert.equal(touched, 0);
185
+ });
186
+
187
+ test("a library that refuses says so instead of failing the eviction", () => {
188
+ const said = [];
189
+ const torrent = {
190
+ name: "film.mkv",
191
+ destroyed: false,
192
+ bitfield: { get: () => true },
193
+ _markUnverified: () => { throw new Error("no such method any more"); }
194
+ };
195
+ assert.equal(withdrawClaim({ index: 2, torrent, warn: (line) => said.push(line) }), "refused");
196
+ assert.equal(said.length, 1);
197
+ assert.match(said[0], /piece 2 of film\.mkv/);
198
+ });
199
+
200
+ test("a store with nobody listening evicts exactly as it did before", async () => {
201
+ const { store, put, clean } = await storeWithGone({ onPieceGone: undefined });
202
+ try {
203
+ await put(0);
204
+ await put(1);
205
+ await put(2);
206
+ store.protectRange("reader", 2, 3, 0);
207
+ const revision = store.reviseSpillCeiling(null);
208
+ assert.ok(revision.behind >= 1, "the eviction does not depend on anybody listening");
209
+ } finally {
210
+ await clean();
211
+ }
212
+ });
package/utils/logger.js CHANGED
@@ -27,11 +27,18 @@ const PREFIX = "[proxy-client]";
27
27
  /**
28
28
  * When the file is rotated, and how many turns are kept.
29
29
  *
30
- * One turn holds a few hours of a busy session at the current rate; two turns
31
- * therefore cover a night's worth of restarts, which is the span a morning
32
- * report asks about. Bounded because the addon's `/data` is the owner's disk.
30
+ * **Why it is this large.** It was 32 MiB, and that erased the beginning of
31
+ * the very failure it was needed for. Field 2026-09-12: a session froze at
32
+ * 17:20 and printed one established fact about 55 times a second, so the file
33
+ * turned over twice before the session ended — 159 000 lines covering
34
+ * 17:51-18:29, then 76 385 covering 18:29-18:52. Sixty-one minutes was all
35
+ * that survived of ninety-two, and the second rotation overwrote the turn that
36
+ * held the onset. The disk it is bounded for had 91.4 GB free at the time.
37
+ *
38
+ * The repetition is a separate fault and is being fixed separately; a log that
39
+ * cannot hold a session either way is the one that has to go first.
33
40
  */
34
- const MAX_FILE_BYTES = 32 * 1024 * 1024;
41
+ const MAX_FILE_BYTES = 1024 * 1024 * 1024;
35
42
 
36
43
  /** @type {import("node:fs").WriteStream | null} */
37
44
  let fileStream = null;
@@ -159,6 +166,92 @@ export const logger = {
159
166
  error: (message) => write("error", message, chalk.red, console.error)
160
167
  };
161
168
 
169
+ /**
170
+ * An established fact is said once, then with decreasing frequency.
171
+ *
172
+ * **Why.** A failure that establishes itself and does not change is printed by
173
+ * whatever loop meets it, at that loop's own rate. Field 2026-09-12: one
174
+ * absent piece produced 235 000 lines in 92 minutes — `Error opening input
175
+ * file …` 8514 times, `Error opening input files: End of file` 5712, the same
176
+ * `run-state` transition 2892, the same read failure 2884 — about 55 lines a
177
+ * second, and it turned the log over twice so the beginning of the failure was
178
+ * gone before anyone read it. A log is not vitiated by its size alone; it is
179
+ * vitiated by uniformity, and a bigger file does not fix that.
180
+ *
181
+ * **Matched VERBATIM — the whole line, no normalisation of numbers.** Measured
182
+ * on that log: exact repeats are 52 567 of 76 385 lines, 68.8 %, which is
183
+ * nearly all of the flood and carries no risk at all of merging two different
184
+ * statements. Normalising digits would catch a little more and would also merge
185
+ * the memory series — `rss=327MB`, `rss=726MB` — which exists precisely to
186
+ * catch a runaway, and suppressing it would be worse than the flood.
187
+ */
188
+ const REPEAT_FIRST_MS = 1_000;
189
+ const REPEAT_MAX_MS = 60_000;
190
+ /**
191
+ * How many distinct lines are tracked. Bounded because it is keyed by the full
192
+ * text: a process that logs unique lines for ever must not grow a map of them.
193
+ */
194
+ const REPEAT_KEYS = 512;
195
+ /** @type {Map<string, { suppressed: number, printedAt: number, interval: number }>} */
196
+ const recent = new Map();
197
+
198
+ /**
199
+ * Whether this line is a repeat to hold back, and what to say if it is not.
200
+ *
201
+ * @param {string} message
202
+ * @returns {{ hold: true } | { hold: false, suffix: string }}
203
+ */
204
+ function repeatCheck(message) {
205
+ const now = Date.now();
206
+ const seen = recent.get(message);
207
+ // Unseen, or not seen for longer than the longest interval — which makes it
208
+ // news again rather than a continuing fact.
209
+ if (!seen || now - seen.printedAt > REPEAT_MAX_MS) {
210
+ // WHAT WAS HELD BACK IS STILL SAID. A stale entry can carry repeats that
211
+ // were never reported — a line said just under its interval and then not
212
+ // again for a while — and dropping the count here would be the quiet lie
213
+ // this whole rule exists to avoid.
214
+ const heldBack = seen?.suppressed ?? 0;
215
+ const overMs = seen ? now - seen.printedAt : 0;
216
+ recent.delete(message);
217
+ if (recent.size >= REPEAT_KEYS) {
218
+ // The least recently printed goes: `Map` keeps insertion order and every
219
+ // print re-inserts, so the first key is the oldest.
220
+ const oldest = recent.keys().next();
221
+ if (!oldest.done) {
222
+ recent.delete(oldest.value);
223
+ }
224
+ }
225
+ recent.set(message, { suppressed: 0, printedAt: now, interval: REPEAT_FIRST_MS });
226
+ return {
227
+ hold: false,
228
+ suffix: heldBack > 0
229
+ ? ` [said ${heldBack} more time(s) in the last ${(overMs / 1000).toFixed(1)}s]`
230
+ : ""
231
+ };
232
+ }
233
+ if (now - seen.printedAt < seen.interval) {
234
+ seen.suppressed += 1;
235
+ return { hold: true };
236
+ }
237
+ const heldBack = seen.suppressed;
238
+ const overMs = now - seen.printedAt;
239
+ recent.delete(message);
240
+ recent.set(message, {
241
+ suppressed: 0,
242
+ printedAt: now,
243
+ interval: Math.min(REPEAT_MAX_MS, seen.interval * 2)
244
+ });
245
+ return {
246
+ hold: false,
247
+ // SAID, not merely hidden: the rate is the fact here, and a log that quietly
248
+ // drops repeats reports a healthy proxy where a loop was spinning.
249
+ suffix: heldBack > 0
250
+ ? ` [said ${heldBack} more time(s) in the last ${(overMs / 1000).toFixed(1)}s]`
251
+ : ""
252
+ };
253
+ }
254
+
162
255
  /**
163
256
  * One path for every level, so a line cannot reach the console and miss the
164
257
  * file depending on which method was called or which thread called it.
@@ -170,15 +263,20 @@ export const logger = {
170
263
  * @returns {void}
171
264
  */
172
265
  function write(level, message, colour, toConsole) {
173
- toConsole(colour(`${PREFIX} [${ts()}] ${message}`));
266
+ const repeat = repeatCheck(message);
267
+ if (repeat.hold) {
268
+ return;
269
+ }
270
+ const line = `${message}${repeat.suffix}`;
271
+ toConsole(colour(`${PREFIX} [${ts()}] ${line}`));
174
272
  if (forward) {
175
273
  try {
176
- forward(level, message);
274
+ forward(level, line);
177
275
  } catch {
178
276
  // silent-ok: a thread whose channel has closed is shutting down, and a
179
277
  // failed log line must not be what ends it.
180
278
  }
181
279
  return;
182
280
  }
183
- toFile(`${PREFIX} [${ts()}] ${message}`);
281
+ toFile(`${PREFIX} [${ts()}] ${line}`);
184
282
  }