@torrent-tv/proxy 2.90.0 → 2.91.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/bin/cli.js CHANGED
@@ -559,6 +559,8 @@ try {
559
559
  proxyId: clientId,
560
560
  token,
561
561
  proxyPort: actualPort,
562
+ name: clientName,
563
+ baseUrl: directBaseUrl,
562
564
  onSignal(sessionId, signal) {
563
565
  webRtcManager?.handleSignal(sessionId, signal);
564
566
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.90.0",
3
+ "version": "2.91.0",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -9,6 +9,13 @@
9
9
  *
10
10
  * The tunnel reconnects automatically with a fixed back-off after any
11
11
  * unexpected close.
12
+ *
13
+ * A server being replaced by a release asks its proxies to move
14
+ * (`server-moving`). The proxy then opens a second connection, which reaches the
15
+ * new server, and keeps the old one until the old server closes it. While both
16
+ * are open each reply goes over the connection its request arrived on: a
17
+ * browser that signalled through the old server is answered there, because the
18
+ * new one does not know that browser.
12
19
  */
13
20
 
14
21
  import { WebSocket } from "ws";
@@ -27,6 +34,11 @@ import { WebSocket } from "ws";
27
34
  * Auth token sent as the `x-proxy-id` / `x-proxy-token` headers during the WS handshake.
28
35
  * @property {number} proxyPort
29
36
  * Local port the proxy's Fastify server is listening on.
37
+ * @property {string} [name]
38
+ * Display name, sent with every connection so that whichever server instance
39
+ * the connection reaches knows it without a separate registration request.
40
+ * @property {string} [baseUrl]
41
+ * Advertised direct URL, sent with every connection for the same reason.
30
42
  * @property {(sessionId: string, signal: WebRtcSignal) => void} [onSignal]
31
43
  * Called when the server forwards a WebRTC signal (SDP offer or ICE candidate)
32
44
  * from a browser to this proxy. `sessionId` scopes the signal to a P2P session.
@@ -120,6 +132,8 @@ export function createTunnelClient({
120
132
  proxyId,
121
133
  token,
122
134
  proxyPort,
135
+ name = "",
136
+ baseUrl = "",
123
137
  onSignal,
124
138
  onConnect,
125
139
  onHealthRequest,
@@ -141,6 +155,21 @@ export function createTunnelClient({
141
155
  */
142
156
  let renewalTimer = null;
143
157
  let stopped = false;
158
+ /**
159
+ * Every connection that is open now. Usually one; two while a renewal or a
160
+ * move to a new server is under way.
161
+ *
162
+ * @type {Set<WebSocket>}
163
+ */
164
+ const openConnections = new Set();
165
+ /**
166
+ * The connection each browser session signalled through. The proxy's answer
167
+ * and its ICE candidates go back the same way, because only the server
168
+ * instance that holds that browser's signalling socket can deliver them.
169
+ *
170
+ * @type {Map<string, WebSocket>}
171
+ */
172
+ const signalRoutes = new Map();
144
173
 
145
174
  /**
146
175
  * Write a message to the log sink if one was provided.
@@ -174,6 +203,14 @@ export function createTunnelClient({
174
203
  headers: {
175
204
  "x-proxy-id": proxyId,
176
205
  "x-proxy-token": token,
206
+ // Who this proxy is, on the connection itself: a separate registration
207
+ // request may reach a different server instance during a release.
208
+ "x-proxy-name": encodeURIComponent(name),
209
+ "x-proxy-base-url": baseUrl,
210
+ // This proxy answers on the connection a request arrived on and opens a
211
+ // new connection when the server says `server-moving`, so the server
212
+ // may wait for it to arrive at the new instance.
213
+ "x-proxy-follows-moves": "1",
177
214
  "user-agent": "torrent-tv-proxy/1.0"
178
215
  }
179
216
  });
@@ -182,6 +219,7 @@ export function createTunnelClient({
182
219
  socket = connection;
183
220
 
184
221
  connection.addEventListener("open", () => {
222
+ openConnections.add(connection);
185
223
  log("Tunnel connected.");
186
224
  // Start keepalive pings to prevent Cloudflare's idle WebSocket timeout.
187
225
  keepaliveTimer = setInterval(() => {
@@ -213,8 +251,19 @@ export function createTunnelClient({
213
251
  return;
214
252
  }
215
253
 
254
+ // The server is being replaced. A new connection reaches its successor;
255
+ // this one stays open until the old server has finished with the
256
+ // browsers it is still signalling for, and then it closes it.
257
+ if (message.type === "server-moving") {
258
+ if (connection === socket && !stopped) {
259
+ log("Tunnel: the server is being replaced; connecting to its successor before this connection closes.");
260
+ connect();
261
+ }
262
+ return;
263
+ }
264
+
216
265
  if (message.type === "request") {
217
- void handleRelayRequest(message).catch((error) => {
266
+ void handleRelayRequest(message, connection).catch((error) => {
218
267
  log(`Tunnel relay error: ${error?.message ?? error}`);
219
268
  });
220
269
  return;
@@ -223,6 +272,7 @@ export function createTunnelClient({
223
272
  // WebRTC signalling: server forwards a signal from a browser session.
224
273
  if (message.type === "signal") {
225
274
  if (typeof message.sessionId === "string" && message.signal && typeof onSignal === "function") {
275
+ signalRoutes.set(message.sessionId, connection);
226
276
  onSignal(message.sessionId, message.signal);
227
277
  }
228
278
  return;
@@ -244,7 +294,7 @@ export function createTunnelClient({
244
294
  // silent-ok: an unanswerable question is answered "no", which is what
245
295
  // a null offer means to the caller.
246
296
  }
247
- send({ type: "can-serve-response", requestId: message.requestId, offer });
297
+ send({ type: "can-serve-response", requestId: message.requestId, offer }, connection);
248
298
  return;
249
299
  }
250
300
 
@@ -266,7 +316,7 @@ export function createTunnelClient({
266
316
  requestId: message.requestId,
267
317
  metrics: answer?.metrics ?? answer ?? {},
268
318
  holds: Array.isArray(answer?.holds) ? answer.holds : []
269
- });
319
+ }, connection);
270
320
  })();
271
321
  return;
272
322
  }
@@ -277,6 +327,12 @@ export function createTunnelClient({
277
327
  clearInterval(keepaliveTimer);
278
328
  keepaliveTimer = null;
279
329
  }
330
+ openConnections.delete(connection);
331
+ for (const [sessionId, route] of signalRoutes) {
332
+ if (route === connection) {
333
+ signalRoutes.delete(sessionId);
334
+ }
335
+ }
280
336
  // A connection this one replaced. The server closes it as soon as the
281
337
  // replacement registers, which is the whole point of renewing early —
282
338
  // there is nothing to report and nothing to reconnect, because the tunnel
@@ -285,15 +341,24 @@ export function createTunnelClient({
285
341
  log(`Tunnel handed over (code=${event.code}); the replacement is already carrying it.`);
286
342
  return;
287
343
  }
344
+ // The newest connection ended while an older one is still open: a move
345
+ // whose new connection did not get through. The older one goes on
346
+ // carrying the tunnel until its server closes it, and the move is tried
347
+ // again meanwhile.
348
+ const survivor = [...openConnections].at(-1);
349
+ if (survivor) {
350
+ socket = survivor;
351
+ log(`Tunnel connection ended (code=${event.code}) while the previous one is still open; it carries the tunnel, and a new connection is tried in ${RECONNECT_DELAY_MS}ms.`);
352
+ scheduleReconnect();
353
+ return;
354
+ }
288
355
  log(`Tunnel disconnected (code=${event.code}). Reconnecting in ${RECONNECT_DELAY_MS}ms...`);
289
356
  socket = null;
290
357
  if (renewalTimer !== null) {
291
358
  clearTimeout(renewalTimer);
292
359
  renewalTimer = null;
293
360
  }
294
- if (!stopped) {
295
- reconnectTimer = setTimeout(connect, RECONNECT_DELAY_MS);
296
- }
361
+ scheduleReconnect();
297
362
  });
298
363
 
299
364
  connection.addEventListener("error", (event) => {
@@ -301,14 +366,31 @@ export function createTunnelClient({
301
366
  });
302
367
  }
303
368
 
369
+ /**
370
+ * Connect again after a fixed back-off, unless a reconnect is already due.
371
+ *
372
+ * @returns {void}
373
+ */
374
+ function scheduleReconnect() {
375
+ if (stopped || reconnectTimer !== null) {
376
+ return;
377
+ }
378
+ reconnectTimer = setTimeout(() => {
379
+ reconnectTimer = null;
380
+ connect();
381
+ }, RECONNECT_DELAY_MS);
382
+ }
383
+
304
384
  /**
305
385
  * Fetch a resource from the local Fastify server and stream the response
306
386
  * back to the registry server chunk-by-chunk over the WebSocket.
307
387
  *
308
388
  * @param {TunnelRelayRequest} relayRequest
389
+ * @param {WebSocket} over - The connection the request arrived on, which
390
+ * the response goes back over.
309
391
  * @returns {Promise<void>}
310
392
  */
311
- async function handleRelayRequest(relayRequest) {
393
+ async function handleRelayRequest(relayRequest, over) {
312
394
  const { requestId, method, path, query, headers: forwardedHeaders, body } = relayRequest;
313
395
  const targetUrl = `http://127.0.0.1:${proxyPort}${path}` + (query ? `?${query}` : "");
314
396
  const requestHeaders = { ...(forwardedHeaders ?? {}), host: `127.0.0.1:${proxyPort}` };
@@ -322,7 +404,7 @@ export function createTunnelClient({
322
404
  redirect: "manual"
323
405
  });
324
406
  } catch (fetchError) {
325
- sendError(requestId, fetchError?.message ?? String(fetchError));
407
+ sendError(requestId, fetchError?.message ?? String(fetchError), over);
326
408
  return;
327
409
  }
328
410
 
@@ -332,10 +414,10 @@ export function createTunnelClient({
332
414
  responseHeaders[headerName] = headerValue;
333
415
  }
334
416
 
335
- send({ type: "response-start", requestId, status: response.status, headers: responseHeaders });
417
+ send({ type: "response-start", requestId, status: response.status, headers: responseHeaders }, over);
336
418
 
337
419
  if (!response.body) {
338
- send({ type: "response-chunk", requestId, data: "", done: true });
420
+ send({ type: "response-chunk", requestId, data: "", done: true }, over);
339
421
  return;
340
422
  }
341
423
 
@@ -344,7 +426,7 @@ export function createTunnelClient({
344
426
  while (true) {
345
427
  const { done, value } = await reader.read();
346
428
  if (done) {
347
- send({ type: "response-chunk", requestId, data: "", done: true });
429
+ send({ type: "response-chunk", requestId, data: "", done: true }, over);
348
430
  break;
349
431
  }
350
432
  send({
@@ -352,10 +434,10 @@ export function createTunnelClient({
352
434
  requestId,
353
435
  data: Buffer.from(value).toString("base64"),
354
436
  done: false
355
- });
437
+ }, over);
356
438
  }
357
439
  } catch {
358
- send({ type: "response-chunk", requestId, data: "", done: true });
440
+ send({ type: "response-chunk", requestId, data: "", done: true }, over);
359
441
  }
360
442
  }
361
443
 
@@ -363,13 +445,15 @@ export function createTunnelClient({
363
445
  * Serialise a message to JSON and send it through the WebSocket if open.
364
446
  *
365
447
  * @param {object} message
448
+ * @param {WebSocket | null} [over]
366
449
  * @returns {void}
367
450
  */
368
451
  function send(message, over = null) {
369
- // Everything the proxy has to say goes over the LIVE connection. `over` is
370
- // for the one thing that belongs to a particular socket rather than to the
371
- // tunnel — its own keepalive — which must not be sent over a replacement
372
- // that has already taken over.
452
+ // What the proxy says on its own goes over the LIVE connection. `over` is
453
+ // for what belongs to a particular socket rather than to the tunnel: its
454
+ // own keepalive, and every reply, which goes back over the connection its
455
+ // request arrived on — during a move that is the old server, the only one
456
+ // still waiting for it.
373
457
  const target = over ?? socket;
374
458
  if (target && target.readyState === WebSocket.OPEN) {
375
459
  target.send(JSON.stringify(message));
@@ -381,10 +465,11 @@ export function createTunnelClient({
381
465
  *
382
466
  * @param {string} requestId
383
467
  * @param {string} errorMessage
468
+ * @param {WebSocket} over - The connection the request arrived on.
384
469
  * @returns {void}
385
470
  */
386
- function sendError(requestId, errorMessage) {
387
- send({ type: "response-error", requestId, error: errorMessage });
471
+ function sendError(requestId, errorMessage, over) {
472
+ send({ type: "response-error", requestId, error: errorMessage }, over);
388
473
  }
389
474
 
390
475
  return {
@@ -414,6 +499,9 @@ export function createTunnelClient({
414
499
  clearTimeout(reconnectTimer);
415
500
  reconnectTimer = null;
416
501
  }
502
+ for (const connection of openConnections) {
503
+ connection.close(1000, "shutdown");
504
+ }
417
505
  if (socket) {
418
506
  socket.close(1000, "shutdown");
419
507
  socket = null;
@@ -429,7 +517,10 @@ export function createTunnelClient({
429
517
  * @returns {void}
430
518
  */
431
519
  sendSignal(sessionId, signal) {
432
- send({ type: "signal", sessionId, signal });
520
+ // Back over the connection this session signalled through, while it is
521
+ // open; the server instance at the other end holds that browser.
522
+ const route = signalRoutes.get(sessionId);
523
+ send({ type: "signal", sessionId, signal }, route?.readyState === WebSocket.OPEN ? route : null);
433
524
  },
434
525
 
435
526
  /**