@torrent-tv/proxy 2.69.0 → 2.69.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.69.0",
3
+ "version": "2.69.1",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "publishConfig": {
@@ -291,6 +291,12 @@ function megabytes(bytes) {
291
291
  * @param {ReturnType<typeof summariseMappings> | null} [reading.mappings]
292
292
  * @param {number | null} [reading.diskFreeBytes]
293
293
  * @param {{ name: string, residentBytes: number, committedBytes: number, spilledBytes: number, budgetBytes: number }[]} [reading.stores]
294
+ * @param {string} [reading.extra] - Figures the caller wants on the same line
295
+ * rather than on one of its own. The piece-buffer counters are read here so
296
+ * that the number of buffers alive and the off-heap mass they should account
297
+ * for are the SAME instant: printed on separate timers they were up to a
298
+ * minute apart, and 950 MB of `arrayBuffers` could not be checked against the
299
+ * 62 buffers a reading half a minute away said were alive (roadmap item 2).
294
300
  * @returns {string}
295
301
  */
296
302
  export function describeMemory({
@@ -302,7 +308,8 @@ export function describeMemory({
302
308
  anonymousBytes = null,
303
309
  mappings = null,
304
310
  diskFreeBytes = null,
305
- stores = []
311
+ stores = [],
312
+ extra = ""
306
313
  }) {
307
314
  const total = (field) => stores.reduce((sum, store) => sum + (store[field] || 0), 0);
308
315
  const storeResident = total("residentBytes");
@@ -321,8 +328,9 @@ export function describeMemory({
321
328
  `heap=${megabytes(usage.heapUsed)}/${megabytes(usage.heapTotal)}` +
322
329
  `${usage.heapLimit ? ` of ${megabytes(usage.heapLimit)} allowed` : ""} ` +
323
330
  `external=${megabytes(usage.external)} arrayBuffers=${megabytes(usage.arrayBuffers)}`;
331
+ const tail = extra ? `; ${extra}` : "";
324
332
  if (scope === "thread") {
325
- return `memory (${label || "thread"}): ${isolate}; ${storesPart}`;
333
+ return `memory (${label || "thread"}): ${isolate}; ${storesPart}${tail}`;
326
334
  }
327
335
  const shape = mappings === null
328
336
  ? ""
@@ -337,10 +345,41 @@ export function describeMemory({
337
345
  `${storesPart}; ` +
338
346
  `machine has ${megabytes(availableBytes ?? 0)} available` +
339
347
  `${availableMeasured ? "" : " (estimated — /proc/meminfo could not be read)"}` +
340
- `${diskFreeBytes === null ? "" : `, ${megabytes(diskFreeBytes)} free on disk`}`
348
+ `${diskFreeBytes === null ? "" : `, ${megabytes(diskFreeBytes)} free on disk`}` +
349
+ tail
341
350
  );
342
351
  }
343
352
 
353
+ /**
354
+ * The figures whose movement earns a line, each under its own name.
355
+ *
356
+ * Not the same question as what the scope WATCHES for a heap snapshot. A
357
+ * thread's heap is only one of the three ways its isolate holds memory, and on
358
+ * 2026-09-02 it was the one that did not move: `heapTotal` stayed at 31-173 MB
359
+ * through a session where `arrayBuffers` swung between 130 and 950 MB, so the
360
+ * change trigger was watching the one quantity that stood still and every
361
+ * reading of the one that grew came out on the quiet interval, a minute apart.
362
+ *
363
+ * Each figure is compared against its own last written value and any one of
364
+ * them moving is enough. Nothing is added together, because `arrayBuffers` is
365
+ * documented as part of `external` and reads larger than it on this runtime —
366
+ * a contradiction this code has no business resolving.
367
+ *
368
+ * @param {"process" | "thread"} scope
369
+ * @param {{ rss: number, heapTotal: number, external: number, arrayBuffers: number }} memory
370
+ * @returns {Record<string, number>}
371
+ */
372
+ export function watchedFigures(scope, memory) {
373
+ if (scope === "thread") {
374
+ return {
375
+ heap: memory.heapTotal ?? 0,
376
+ external: memory.external ?? 0,
377
+ buffers: memory.arrayBuffers ?? 0
378
+ };
379
+ }
380
+ return { rss: memory.rss ?? 0 };
381
+ }
382
+
344
383
  /**
345
384
  * Whether this reading is worth writing down, and why.
346
385
  *
@@ -397,11 +436,14 @@ export function readingIsWorthWriting({
397
436
  * @param {number} [options.snapshotFloorBytes]
398
437
  * @param {number} [options.snapshotGrowthBytes]
399
438
  * @param {number} [options.keepSnapshots] - Newest to keep; zero keeps all.
439
+ * @param {() => string} [options.readExtra] - Figures to append to the line,
440
+ * read at the same instant as the memory itself.
400
441
  * @returns {{ stop: () => void }}
401
442
  */
402
443
  export function startMemoryReport({
403
444
  log,
404
445
  readStores,
446
+ readExtra,
405
447
  scope = "process",
406
448
  label = "",
407
449
  diskPath = "",
@@ -414,7 +456,8 @@ export function startMemoryReport({
414
456
  keepSnapshots = 0
415
457
  }) {
416
458
  let highWater = 0;
417
- let lastWrittenBytes = 0;
459
+ /** @type {Record<string, number>} */
460
+ let lastWritten = {};
418
461
  let lastWrittenAt = 0;
419
462
  // The process watches what the kernel kills it for; a thread watches what the
420
463
  // runtime kills IT for, which is its own heap and not the process's resident
@@ -472,25 +515,35 @@ export function startMemoryReport({
472
515
  }
473
516
  const processMemory = readProcessMemory();
474
517
  const watched = watchedOf(processMemory);
518
+ const figures = watchedFigures(scope, processMemory);
475
519
  const now = Date.now();
476
- const write = readingIsWorthWriting({
477
- watchedBytes: watched,
478
- lastWrittenBytes,
479
- sinceWrittenMs: lastWrittenAt === 0 ? Number.POSITIVE_INFINITY : now - lastWrittenAt,
520
+ const sinceWrittenMs = lastWrittenAt === 0 ? Number.POSITIVE_INFINITY : now - lastWrittenAt;
521
+ const write = Object.entries(figures).some(([name, bytes]) => readingIsWorthWriting({
522
+ watchedBytes: bytes,
523
+ lastWrittenBytes: lastWritten[name] ?? 0,
524
+ sinceWrittenMs,
480
525
  changeBytes,
481
526
  quietMs
482
- });
527
+ }));
483
528
 
484
529
  let anonymousBytes = null;
485
- if (scope === "thread") {
486
- if (write) {
487
- log(describeMemory({ scope, label, process: processMemory, stores }));
530
+ if (write) {
531
+ let extra = "";
532
+ try {
533
+ extra = typeof readExtra === "function" ? readExtra() ?? "" : "";
534
+ } catch {
535
+ // silent-ok: a caller's own figures are worth less than the line they
536
+ // would have taken down with them.
488
537
  }
489
- } else {
490
- const { bytes, measured } = await availableMemory();
491
- anonymousBytes = await readAnonymousMemory();
492
- const diskFreeBytes = diskPath ? await readDiskFree(diskPath) : null;
493
- if (write) {
538
+ if (scope === "thread") {
539
+ log(describeMemory({ scope, label, process: processMemory, stores, extra }));
540
+ } else {
541
+ // Read only when the line is written. `smaps` is one entry per
542
+ // mapping and a busy process has thousands; the rollup and
543
+ // `/proc/meminfo` are single lines but still walk page tables, and
544
+ // the reading now happens once a second rather than once a minute.
545
+ const { bytes, measured } = await availableMemory();
546
+ anonymousBytes = await readAnonymousMemory();
494
547
  log(describeMemory({
495
548
  scope,
496
549
  label,
@@ -498,17 +551,13 @@ export function startMemoryReport({
498
551
  availableBytes: bytes,
499
552
  availableMeasured: measured,
500
553
  anonymousBytes,
501
- // Read only when the line is written: `smaps` is one entry per
502
- // mapping and a busy process has thousands, which is a different
503
- // cost from the rollup's single line.
504
554
  mappings: await readMappingSummary(),
505
- diskFreeBytes,
506
- stores
555
+ diskFreeBytes: diskPath ? await readDiskFree(diskPath) : null,
556
+ stores,
557
+ extra
507
558
  }));
508
559
  }
509
- }
510
- if (write) {
511
- lastWrittenBytes = watched;
560
+ lastWritten = figures;
512
561
  lastWrittenAt = now;
513
562
  }
514
563
 
@@ -524,6 +573,9 @@ export function startMemoryReport({
524
573
  highWater = watched;
525
574
  await takeSnapshot(watched, "a new high-water");
526
575
  }
576
+ // Under `write` by construction: `anonymousBytes` is only read when the
577
+ // line is, and at one reading a second an unconditional warning would be
578
+ // a line a second for as long as the process stayed large.
527
579
  if (scope !== "thread" && anonymousBytes !== null && processMemory.rss > 800 * 1024 * 1024) {
528
580
  log(`memory: high rss=${megabytes(processMemory.rss)} anon=${megabytes(anonymousBytes)} heap=${megabytes(processMemory.heapUsed)} — watch for OOM`);
529
581
  }
@@ -522,6 +522,12 @@ parentPort.on("message", async (message) => {
522
522
  startMemoryReport({
523
523
  log,
524
524
  readStores: collectStoreStats,
525
+ // Beside the isolate's own figures, and on the SAME line, because the
526
+ // question they answer together is whether the off-heap mass is buffers this
527
+ // thread still refers to or buffers the collector has not reached yet. On
528
+ // separate timers the two were up to a minute apart and could not be
529
+ // compared at all (roadmap item 2).
530
+ readExtra: describePieceBuffers,
525
531
  scope: "thread",
526
532
  label: "torrent worker",
527
533
  intervalMs: WORKER_MEMORY_SAMPLE_MS,
@@ -581,22 +587,30 @@ setInterval(() => {
581
587
  (stats.outstanding > 0 ? ` outstanding=${stats.outstanding}` : "")
582
588
  );
583
589
  }
584
- // Not per store: the collector is per thread, and the question it answers —
585
- // is anything of ours outliving a piece — is about the thread. Printed
586
- // whenever the two disagree by more than the pieces actually held, which is
587
- // the only shape worth looking at (roadmap item 2).
590
+ }, STORE_REPORT_INTERVAL_MS).unref();
591
+
592
+ /**
593
+ * The piece buffers this thread has let go of against the ones it still holds.
594
+ *
595
+ * Not per store: the collector is per thread, and the question is about the
596
+ * thread. A gap that keeps widening means a reference of ours outlives the
597
+ * piece; a gap that does not means whatever grows is below us, in the
598
+ * allocator or in buffers the collector has not reached.
599
+ *
600
+ * @returns {string}
601
+ */
602
+ function describePieceBuffers() {
588
603
  const collection = pieceBufferCollection();
589
- const outstandingBuffers = collection.released - collection.collected;
590
- const heldNow = collectStoreStats().reduce((sum, stats) => sum + (stats.resident || 0), 0);
591
- if (outstandingBuffers > heldNow) {
592
- log(
593
- `piece buffers: ${collection.released} let go, ${collection.collected} collected — ` +
594
- `${outstandingBuffers} still alive against ${heldNow} the store holds. ` +
595
- "A gap that keeps widening means a reference of ours outlives the piece; " +
596
- "a gap that does not means whatever grows is below us, in the allocator"
597
- );
604
+ if (collection.released === 0) {
605
+ return "";
598
606
  }
599
- }, STORE_REPORT_INTERVAL_MS).unref();
607
+ const alive = collection.released - collection.collected;
608
+ const held = collectStoreStats().reduce((sum, stats) => sum + (stats.resident || 0), 0);
609
+ return (
610
+ `piece buffers ${collection.released} let go, ${collection.collected} collected, ` +
611
+ `${alive} still alive against ${held} the store holds`
612
+ );
613
+ }
600
614
 
601
615
  /**
602
616
  * Walk subtitle cues for every actively-read file of one torrent, and PUSH
@@ -1,7 +1,12 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
 
4
- import { describeMemory, readingIsWorthWriting, summariseMappings } from "../services/memory-report.js";
4
+ import {
5
+ describeMemory,
6
+ readingIsWorthWriting,
7
+ summariseMappings,
8
+ watchedFigures
9
+ } from "../services/memory-report.js";
5
10
  import {
6
11
  budgetForNewStore,
7
12
  SharedPieceStore,
@@ -287,3 +292,55 @@ test("the mapping shape is said in the line, and left out when it is not known",
287
292
  });
288
293
  assert.ok(!withoutShape.includes("mappings="), "an unread breakdown is absent, not zeroed");
289
294
  });
295
+
296
+ test("a thread's line is earned by any of its three figures, not by the heap alone", () => {
297
+ // 2026-09-02, the session that ended in two out-of-memory kills: the worker's
298
+ // heap stood at 33-45 MB for the whole of it while its buffers went from 130
299
+ // to 950 MB. Watching the heap alone, nothing ever earned a line and every
300
+ // reading of the quantity that grew came out on the quiet minute.
301
+ const before = watchedFigures("thread", {
302
+ rss: 0, heapTotal: 38 * MEGABYTE, external: 14 * MEGABYTE, arrayBuffers: 130 * MEGABYTE
303
+ });
304
+ const after = watchedFigures("thread", {
305
+ rss: 0, heapTotal: 38 * MEGABYTE, external: 14 * MEGABYTE, arrayBuffers: 515 * MEGABYTE
306
+ });
307
+ assert.equal(before.heap, after.heap, "the heap is what did NOT move");
308
+
309
+ const moved = Object.entries(after).some(([name, bytes]) => readingIsWorthWriting({
310
+ watchedBytes: bytes,
311
+ lastWrittenBytes: before[name],
312
+ sinceWrittenMs: 1_000,
313
+ changeBytes: 25 * MEGABYTE,
314
+ quietMs: 60_000
315
+ }));
316
+ assert.equal(moved, true, "buffers growing by 385 MB earns a line of its own");
317
+
318
+ assert.deepEqual(
319
+ Object.keys(watchedFigures("process", { rss: 5, heapTotal: 1, external: 2, arrayBuffers: 3 })),
320
+ ["rss"],
321
+ "a process is killed for its resident memory and watches that"
322
+ );
323
+ });
324
+
325
+ test("figures a caller reads for itself land on the same line as the memory", () => {
326
+ const line = describeMemory({
327
+ scope: "thread",
328
+ label: "torrent worker",
329
+ process: {
330
+ rss: 0, heapUsed: 34 * MEGABYTE, heapTotal: 46 * MEGABYTE,
331
+ external: 54 * MEGABYTE, arrayBuffers: 393 * MEGABYTE, heapLimit: 0
332
+ },
333
+ stores: [],
334
+ extra: "piece buffers 21544 let go, 21482 collected, 62 still alive against 53 the store holds"
335
+ });
336
+ assert.match(line, /arrayBuffers=393MB/);
337
+ assert.match(line, /62 still alive against 53 the store holds$/);
338
+ assert.doesNotMatch(
339
+ describeMemory({
340
+ scope: "thread",
341
+ process: { rss: 0, heapUsed: 1, heapTotal: 2, external: 3, arrayBuffers: 4, heapLimit: 0 }
342
+ }),
343
+ /;\s*$/,
344
+ "nothing to add leaves no dangling separator"
345
+ );
346
+ });