@torrent-tv/proxy 2.46.0 → 2.47.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## 2.47.0
2
+
3
+ - **Fix**: The tunnel is replaced before anything upstream ends it, so a viewer no longer arrives to find no proxy. Something between the proxy and the server closes the socket after exactly **100 min 15 s** — measured across a day of logs 2026-08-20, three intervals of 100:15 wherever a restart did not reset the clock, `code=1006` each time, and with the 30 s keepalive running throughout, so it is a lifetime cap and not an idle timeout. Reconnecting afterwards takes five seconds during which this proxy does not exist as far as the registry is concerned. The connection is now replaced at ninety minutes and the replacement takes over FIRST: the new socket registers itself, the server atomically supersedes the old one, and only then does the old one close — so there is no instant with nothing registered. A socket that finds itself superseded says so rather than reporting the tunnel as down, and an abrupt close nobody asked for still reconnects as before. Pinned by a test against a real WebSocket server.
4
+
1
5
  ## 2.46.0
2
6
 
3
7
  - **New**: The cost of DECODING is measured per codec family, not once on H.264. A video that has to be re-encoded is by definition one the browser could not play — HEVC, 10-bit — so the one model the host had was fitted on the codec it is least often asked about, and those decode dearer per pixel on the same box. There are now sets for HEVC 8-bit and HEVC Main 10 beside the H.264 one (`assets/calibration/`, four clips each: two sizes at two bitrates, the smallest grid that keeps the axes independent and still leaves a spare), the source's own codec and bit depth choose the constants, and a family with no set of its own is priced as H.264 — said in the log rather than left to be inferred. Measured on a desktop 2026-08-20, the same 1080p picture at ~5.8 Mbit/s: 7.7x as 8-bit HEVC against 6.3x as 10-bit, which is why ten bits is its own family and not a multiplier. AV1 has no set yet; the release survey of 2026-07-10 found it rare where HEVC was 18 %.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.46.0",
3
+ "version": "2.47.0",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "publishConfig": {
@@ -80,6 +80,28 @@ import { WebSocket } from "ws";
80
80
  const RECONNECT_DELAY_MS = 5_000;
81
81
  /** Send a keepalive ping every 30 s to prevent Cloudflare's idle WebSocket timeout (~100 s). */
82
82
  const KEEPALIVE_INTERVAL_MS = 30_000;
83
+ /**
84
+ * Replace the connection before anything upstream ends it for us.
85
+ *
86
+ * Something between this process and the server closes the socket after
87
+ * exactly **100 min 15 s**, whatever is flowing over it. It is not an idle
88
+ * timeout — the keepalive above has been running for months — it is a lifetime
89
+ * cap. Measured across one day of logs (2026-08-20): 01:54:12 → 03:34:27 →
90
+ * ... the same 100:15 apart wherever a restart did not reset the clock, and
91
+ * with `code=1006`, an abrupt close with no closing handshake, which is what an
92
+ * intermediary killing a connection looks like.
93
+ *
94
+ * Reconnecting after the fact costs 5 s during which this proxy does not exist
95
+ * as far as the registry is concerned, and a viewer arriving in that window is
96
+ * told there is no proxy. So the connection is replaced BEFORE the cap, and the
97
+ * replacement is seamless: the new socket registers itself with the server,
98
+ * which atomically supersedes the old one, and only then does the old one
99
+ * close. There is no moment with nothing registered.
100
+ *
101
+ * Ninety minutes leaves ten minutes of margin against a cap that has been
102
+ * exact, and makes the replacement a quiet event rather than a race.
103
+ */
104
+ const CONNECTION_LIFETIME_MS = 90 * 60_000;
83
105
 
84
106
  /**
85
107
  * Create and manage the outbound WebSocket tunnel to the registry server.
@@ -87,15 +109,30 @@ const KEEPALIVE_INTERVAL_MS = 30_000;
87
109
  * @param {TunnelClientOptions} options
88
110
  * @returns {TunnelClient}
89
111
  */
90
- export function createTunnelClient({ serverUrl, proxyId, token, proxyPort, onSignal, onConnect, onHealthRequest, onLog }) {
112
+ export function createTunnelClient({
113
+ serverUrl,
114
+ proxyId,
115
+ token,
116
+ proxyPort,
117
+ onSignal,
118
+ onConnect,
119
+ onHealthRequest,
120
+ onLog,
121
+ connectionLifetimeMs = CONNECTION_LIFETIME_MS
122
+ }) {
91
123
  const wsUrl = serverUrl.replace(/^http/, "ws").replace(/\/+$/, "") + "/ws/proxy-tunnel";
92
124
 
93
125
  /** @type {WebSocket | null} */
94
126
  let socket = null;
95
127
  /** @type {ReturnType<typeof setTimeout> | null} */
96
128
  let reconnectTimer = null;
97
- /** @type {ReturnType<typeof setInterval> | null} */
98
- let keepaliveTimer = null;
129
+ /**
130
+ * The renewal that will replace the live connection before the upstream cap
131
+ * ends it. Owned by the connection it belongs to, and cancelled with it.
132
+ *
133
+ * @type {ReturnType<typeof setTimeout> | null}
134
+ */
135
+ let renewalTimer = null;
99
136
  let stopped = false;
100
137
 
101
138
  /**
@@ -122,28 +159,46 @@ export function createTunnelClient({ serverUrl, proxyId, token, proxyPort, onSig
122
159
  }
123
160
  log(`Connecting tunnel to ${wsUrl}`);
124
161
 
125
- socket = new WebSocket(wsUrl, {
162
+ // The connection being opened, held separately from `socket` so that a
163
+ // socket which has been SUPERSEDED can still recognise itself. During a
164
+ // renewal two exist for a moment, and the old one's close must not be
165
+ // mistaken for the tunnel going down.
166
+ const connection = new WebSocket(wsUrl, {
126
167
  headers: {
127
168
  "x-proxy-id": proxyId,
128
169
  "x-proxy-token": token,
129
170
  "user-agent": "torrent-tv-proxy/1.0"
130
171
  }
131
172
  });
173
+ /** @type {ReturnType<typeof setInterval> | null} */
174
+ let keepaliveTimer = null;
175
+ socket = connection;
132
176
 
133
- socket.addEventListener("open", () => {
177
+ connection.addEventListener("open", () => {
134
178
  log("Tunnel connected.");
135
179
  // Start keepalive pings to prevent Cloudflare's idle WebSocket timeout.
136
180
  keepaliveTimer = setInterval(() => {
137
- if (socket && socket.readyState === WebSocket.OPEN) {
138
- send({ type: "ping" });
181
+ if (connection.readyState === WebSocket.OPEN) {
182
+ send({ type: "ping" }, connection);
139
183
  }
140
184
  }, KEEPALIVE_INTERVAL_MS);
185
+ // And replace this connection before the upstream lifetime cap does.
186
+ if (renewalTimer !== null) {
187
+ clearTimeout(renewalTimer);
188
+ }
189
+ renewalTimer = setTimeout(() => {
190
+ if (stopped || socket !== connection) {
191
+ return;
192
+ }
193
+ log("Tunnel renewing before the upstream lifetime cap; the replacement takes over first.");
194
+ connect();
195
+ }, connectionLifetimeMs);
141
196
  if (typeof onConnect === "function") {
142
197
  onConnect();
143
198
  }
144
199
  });
145
200
 
146
- socket.addEventListener("message", (event) => {
201
+ connection.addEventListener("message", (event) => {
147
202
  let message;
148
203
  try {
149
204
  message = JSON.parse(event.data);
@@ -174,19 +229,31 @@ export function createTunnelClient({ serverUrl, proxyId, token, proxyPort, onSig
174
229
  }
175
230
  });
176
231
 
177
- socket.addEventListener("close", (event) => {
178
- log(`Tunnel disconnected (code=${event.code}). Reconnecting in ${RECONNECT_DELAY_MS}ms...`);
179
- socket = null;
232
+ connection.addEventListener("close", (event) => {
180
233
  if (keepaliveTimer !== null) {
181
234
  clearInterval(keepaliveTimer);
182
235
  keepaliveTimer = null;
183
236
  }
237
+ // A connection this one replaced. The server closes it as soon as the
238
+ // replacement registers, which is the whole point of renewing early —
239
+ // there is nothing to report and nothing to reconnect, because the tunnel
240
+ // never went down.
241
+ if (socket !== connection) {
242
+ log(`Tunnel handed over (code=${event.code}); the replacement is already carrying it.`);
243
+ return;
244
+ }
245
+ log(`Tunnel disconnected (code=${event.code}). Reconnecting in ${RECONNECT_DELAY_MS}ms...`);
246
+ socket = null;
247
+ if (renewalTimer !== null) {
248
+ clearTimeout(renewalTimer);
249
+ renewalTimer = null;
250
+ }
184
251
  if (!stopped) {
185
252
  reconnectTimer = setTimeout(connect, RECONNECT_DELAY_MS);
186
253
  }
187
254
  });
188
255
 
189
- socket.addEventListener("error", (event) => {
256
+ connection.addEventListener("error", (event) => {
190
257
  log(`Tunnel WebSocket error: ${event.message ?? "unknown"}`);
191
258
  });
192
259
  }
@@ -255,9 +322,14 @@ export function createTunnelClient({ serverUrl, proxyId, token, proxyPort, onSig
255
322
  * @param {object} message
256
323
  * @returns {void}
257
324
  */
258
- function send(message) {
259
- if (socket && socket.readyState === WebSocket.OPEN) {
260
- socket.send(JSON.stringify(message));
325
+ function send(message, over = null) {
326
+ // Everything the proxy has to say goes over the LIVE connection. `over` is
327
+ // for the one thing that belongs to a particular socket rather than to the
328
+ // tunnel — its own keepalive — which must not be sent over a replacement
329
+ // that has already taken over.
330
+ const target = over ?? socket;
331
+ if (target && target.readyState === WebSocket.OPEN) {
332
+ target.send(JSON.stringify(message));
261
333
  }
262
334
  }
263
335
 
@@ -291,9 +363,9 @@ export function createTunnelClient({ serverUrl, proxyId, token, proxyPort, onSig
291
363
  */
292
364
  disconnect() {
293
365
  stopped = true;
294
- if (keepaliveTimer !== null) {
295
- clearInterval(keepaliveTimer);
296
- keepaliveTimer = null;
366
+ if (renewalTimer !== null) {
367
+ clearTimeout(renewalTimer);
368
+ renewalTimer = null;
297
369
  }
298
370
  if (reconnectTimer != null) {
299
371
  clearTimeout(reconnectTimer);
@@ -0,0 +1,126 @@
1
+ /**
2
+ * @file The tunnel is replaced before anything upstream ends it, and the
3
+ * replacement takes over first.
4
+ *
5
+ * Something between the proxy and the server closes the socket after exactly
6
+ * 100 min 15 s whatever is flowing over it — measured across a day of logs on
7
+ * 2026-08-20, `code=1006` each time, with a 30 s keepalive running throughout,
8
+ * so it is a lifetime cap and not an idle timeout. Reconnecting afterwards
9
+ * costs five seconds in which the proxy does not exist as far as the registry
10
+ * is concerned, and a viewer arriving then is told there is no proxy.
11
+ *
12
+ * What is pinned here is the property that removes that window: at no instant
13
+ * is the server without a registered connection for this proxy.
14
+ */
15
+
16
+ import assert from "node:assert/strict";
17
+ import test from "node:test";
18
+ import { WebSocketServer } from "ws";
19
+
20
+ import { createTunnelClient } from "../services/tunnel-client.js";
21
+
22
+ /**
23
+ * A stand-in for the registry's tunnel endpoint, with the one behaviour that
24
+ * matters here: a new connection for a proxy REPLACES the previous one, which
25
+ * is what `registerConnection` does in `server/services/proxy-tunnel-server.js`.
26
+ *
27
+ * @returns {Promise<{ url: string, close: () => Promise<void>, registered: () => number, opened: () => number, everEmpty: () => boolean }>}
28
+ */
29
+ async function startRegistry() {
30
+ const server = new WebSocketServer({ port: 0 });
31
+ await new Promise((resolve) => { server.on("listening", resolve); });
32
+ /** @type {import("ws").WebSocket | null} */
33
+ let current = null;
34
+ let opened = 0;
35
+ let everEmpty = false;
36
+ server.on("connection", (socket) => {
37
+ opened += 1;
38
+ const previous = current;
39
+ current = socket;
40
+ // The replacement is registered BEFORE the old one is closed, so a reader
41
+ // of `current` never sees nothing.
42
+ if (previous && previous.readyState < 2) {
43
+ previous.close(1000, "replaced");
44
+ }
45
+ socket.on("close", () => {
46
+ if (current === socket) {
47
+ current = null;
48
+ everEmpty = true;
49
+ }
50
+ });
51
+ });
52
+ const { port } = server.address();
53
+ return {
54
+ url: `http://127.0.0.1:${port}`,
55
+ close: () => new Promise((resolve) => { server.close(resolve); }),
56
+ registered: () => (current && current.readyState === 1 ? 1 : 0),
57
+ killCurrent: () => { current?.terminate(); },
58
+ opened: () => opened,
59
+ everEmpty: () => everEmpty
60
+ };
61
+ }
62
+
63
+ test("the connection is replaced before its lifetime runs out, without a gap", async (t) => {
64
+ const registry = await startRegistry();
65
+ /** @type {string[]} */
66
+ const lines = [];
67
+ const client = createTunnelClient({
68
+ serverUrl: registry.url,
69
+ proxyId: "p1",
70
+ token: "t",
71
+ proxyPort: 9090,
72
+ onLog: (line) => lines.push(line),
73
+ // The real cap is 100 min 15 s and the real renewal is at 90 min; the
74
+ // ratio is what matters, not the magnitude.
75
+ connectionLifetimeMs: 150
76
+ });
77
+ t.after(async () => {
78
+ client.disconnect();
79
+ await registry.close();
80
+ });
81
+
82
+ client.connect();
83
+ // Long enough for several renewals at 150 ms each.
84
+ await new Promise((resolve) => { setTimeout(resolve, 700); });
85
+
86
+ assert.ok(registry.opened() >= 3, `expected several renewals, saw ${registry.opened()}`);
87
+ // The property this exists for: the registry was never left with nothing.
88
+ assert.equal(registry.everEmpty(), false, "the registry lost its connection at some point");
89
+ assert.equal(registry.registered(), 1);
90
+ // And the proxy knows the difference between a handover and going down. A
91
+ // "Reconnecting in" line here would mean it had treated its own renewal as a
92
+ // failure and waited five seconds before coming back.
93
+ assert.ok(lines.some((line) => line.includes("Tunnel renewing")), lines.join("\n"));
94
+ assert.ok(lines.some((line) => line.includes("Tunnel handed over")), lines.join("\n"));
95
+ assert.equal(lines.filter((line) => line.includes("Reconnecting in")).length, 0, lines.join("\n"));
96
+ });
97
+
98
+ test("a connection killed from outside is still reconnected", async (t) => {
99
+ const registry = await startRegistry();
100
+ /** @type {string[]} */
101
+ const lines = [];
102
+ const client = createTunnelClient({
103
+ serverUrl: registry.url,
104
+ proxyId: "p2",
105
+ token: "t",
106
+ proxyPort: 9090,
107
+ onLog: (line) => lines.push(line),
108
+ // Far longer than this test runs, so nothing renews and the only close is
109
+ // the one forced below — which is what the upstream cap looks like from
110
+ // here: an abrupt end nobody asked for.
111
+ connectionLifetimeMs: 60_000
112
+ });
113
+ t.after(async () => {
114
+ client.disconnect();
115
+ await registry.close();
116
+ });
117
+
118
+ client.connect();
119
+ await new Promise((resolve) => { setTimeout(resolve, 200); });
120
+ assert.equal(registry.opened(), 1);
121
+
122
+ registry.killCurrent();
123
+ await new Promise((resolve) => { setTimeout(resolve, 300); });
124
+ // The renewal must not have taken the ordinary reconnect away with it.
125
+ assert.ok(lines.some((line) => line.includes("Reconnecting in")), lines.join("\n"));
126
+ });