@torrent-tv/proxy 2.9.14 → 2.9.15

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/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## 2.9.15
2
+
3
+ - **Fix**: Torrent data is now cleaned up on graceful shutdown. `TorrentPool.destroyAll()` removes every torrent **with its on-disk store** (`torrent.destroy({ destroyStore: true })`) and then tears down the WebTorrent client; it is wired into the Fastify `onClose` hook (after `hlsSessionManager.disposeAll()`, so ffmpeg readers stop before their source files are removed). Previously nothing called `client.remove()`/`torrent.destroy()` anywhere, so downloaded files accumulated under `os.tmpdir()` until the process was killed — and even a clean SIGTERM/SIGINT left them behind. (First step of disk-hygiene Level 1; refcount/TTL removal and the startup orphan sweep are separate, still pending.)
4
+
1
5
  ## 2.9.14
2
6
 
3
7
  - **New**: `GET /api/sources/:sourceKey/stats` now reports `headerBytes` / `headerDownloadedBytes` — how much of the file's header/index region (leading 256 KB + trailing 2 MB, the bytes the codec probe needs) is downloaded, counted by whole torrent pieces from the bitfield. Lets the browser show the download phase's progress and ETA toward the next (transcode) phase. Coarse by design (piece granularity).
package/CLAUDE.md CHANGED
@@ -47,6 +47,58 @@ Linux-only host (e.g. POSIX-only signals must degrade elsewhere).
47
47
  around it with `--ignore-scripts` + a targeted rebuild of `node-datachannel`;
48
48
  if you ever change install flow, keep that in mind.
49
49
 
50
+ ## Planned: public reachability (remote access)
51
+
52
+ Decided direction — full plan in the parent `../CLAUDE.md`. Proxy-side pieces:
53
+
54
+ - **Auto port mapping** at startup via UPnP IGD / NAT-PMP / PCP (`nat-api` /
55
+ `@silentbot1/nat-api`; WebTorrent already does this for the torrent port).
56
+ Always request a lease time and renew it while running; remove the mapping
57
+ on graceful shutdown — lease expiry cleans up after crashes. Zero user
58
+ action, nothing left behind on the router.
59
+ - Report the mapped external endpoint (and local addresses) to the server over
60
+ the tunnel; the server dial-back-verifies reachability before use.
61
+ - **HTTPS listener**: serve the existing routes over TLS with a per-proxy
62
+ certificate delivered by the server through the tunnel (persist cert+key
63
+ locally; ~90-day renewals are pushed the same way). Add CORS headers for the
64
+ web-app origin so hls.js / `<video>` can fetch cross-origin.
65
+ - Plain HTTPS becomes the preferred video transport; WebRTC data channel stays
66
+ as fallback for hosts where no port could be opened.
67
+ - **NAT-traversal toolbox** (staged, see parent `../CLAUDE.md`): birthday-
68
+ paradox port prediction (open ~256 UDP sockets, inject predicted-port ICE
69
+ candidates) for symmetric NAT; IPv6-first (audit the candidate filter — do
70
+ not drop *global* v6); STUN-based NAT pre-classification at startup reported
71
+ to the registry; relay-then-upgrade later.
72
+ - Future: ed25519 proxy identity (sign announcements), BEP 44 endpoint
73
+ announcements via the `bittorrent-dht` already bundled with WebTorrent.
74
+
75
+ All of this must stay deployment-agnostic (HA addon, bare npm, Docker).
76
+
77
+ ## Disk hygiene (open item — torrent data is NOT cleaned up today)
78
+
79
+ HLS segments are handled (`hls-session-manager.js`: idle TTL, `disposeSession`,
80
+ `disposeAll`). Torrent data is NOT: `new WebTorrent()` in `torrent-pool.js` uses
81
+ the default FS store under `os.tmpdir()`, there is no `client.remove()` /
82
+ `torrent.destroy()`, `deselect()` only stops further download, nothing sweeps
83
+ orphans at startup, and `TorrentPool` is not wired into the `onClose` shutdown
84
+ hook (`server.js` only disposes HLS sessions on close — see `cli.js` shutdown →
85
+ `app.close()` → `onClose`).
86
+
87
+ Level 1 (do first): `client.remove(torrent, { destroyStore: true })` on last-
88
+ file refcount 0 + idle TTL; startup sweep of orphaned store dirs; wire
89
+ `TorrentPool` teardown into the `onClose` hook so closing the proxy cleans up
90
+ (not only startup); global disk cap with LRU eviction of whole torrents.
91
+ Level 2 (research): sliding-window chunk store. Full rationale in the parent
92
+ `../CLAUDE.md` "Disk hygiene" section.
93
+
94
+ ## Cloud proxy
95
+
96
+ The same proxy code also runs as the company-hosted fallback when the user
97
+ pool can't serve a viewer. Keep the proxy host-agnostic so it runs unchanged on
98
+ rented infra (flat-rate/unmetered bandwidth — Hetzner dedicated / OVH; NOT
99
+ metered-egress clouds). Provider/economics analysis in the parent
100
+ `../CLAUDE.md` "Cloud proxy" section.
101
+
50
102
  ## Changelog
51
103
 
52
104
  Every behavioural change must be recorded in `CHANGELOG.md` — add an entry under
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.9.14",
3
+ "version": "2.9.15",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "publishConfig": {
package/server.js CHANGED
@@ -154,7 +154,10 @@ export async function startProxyServer({ host, port, transcodeAudio, ffmpegBin }
154
154
  });
155
155
 
156
156
  app.addHook("onClose", async () => {
157
+ // Order matters: stop the ffmpeg readers (HLS sessions) before destroying
158
+ // the torrents whose files they read from, then remove the torrent data.
157
159
  await hlsSessionManager.disposeAll();
160
+ await torrentPool.destroyAll();
158
161
  });
159
162
 
160
163
  await app.listen({ host, port: selectedPort });
@@ -423,4 +423,56 @@ export class TorrentPool {
423
423
  // Best effort — never break streaming because prioritization failed.
424
424
  }
425
425
  }
426
+
427
+ /**
428
+ * Destroy every torrent together with its on-disk store, then tear down the
429
+ * WebTorrent client. Called from the proxy's graceful-shutdown `onClose`
430
+ * hook so downloaded torrent data does not linger under `os.tmpdir()` after
431
+ * the process stops.
432
+ *
433
+ * `client.destroy()` on its own destroys the torrents but only *closes* their
434
+ * stores (data stays on disk), so each torrent is removed explicitly with
435
+ * `{ destroyStore: true }` first. Best-effort: never rejects and never hangs
436
+ * on a single store-removal error during shutdown.
437
+ *
438
+ * @returns {Promise<void>}
439
+ */
440
+ async destroyAll() {
441
+ if (!this.client || this.client.destroyed) {
442
+ return;
443
+ }
444
+
445
+ // Destroy each torrent with its store so downloaded pieces are removed
446
+ // from disk. This also removes the torrent from `client.torrents`, so the
447
+ // subsequent `client.destroy()` only tears down the client internals.
448
+ const torrents = [...this.client.torrents];
449
+ await Promise.all(
450
+ torrents.map(
451
+ (torrent) =>
452
+ new Promise((resolve) => {
453
+ try {
454
+ torrent.destroy({ destroyStore: true }, () => resolve());
455
+ } catch (error) {
456
+ const message = error instanceof Error ? error.message : String(error);
457
+ logger.warn(`failed to destroy torrent store: ${message}`);
458
+ resolve();
459
+ }
460
+ })
461
+ )
462
+ );
463
+
464
+ // Tear down the client itself (DHT, connection pool, TCP server).
465
+ await new Promise((resolve) => {
466
+ try {
467
+ this.client.destroy(() => resolve());
468
+ } catch (error) {
469
+ const message = error instanceof Error ? error.message : String(error);
470
+ logger.warn(`failed to destroy WebTorrent client: ${message}`);
471
+ resolve();
472
+ }
473
+ });
474
+
475
+ this.torrents.clear();
476
+ this.#pending.clear();
477
+ }
426
478
  }