@torrent-tv/proxy 2.46.0 → 2.48.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,13 @@
1
+ ## 2.48.0
2
+
3
+ - **Fix**: A copied picture now begins where it was asked to, so its cuts land on the times its playlist names. ffmpeg's own CLI moves an input seek back by `3*AV_TIME_BASE / 23` — **130.435 ms** — whenever the container does not declare `AVFMT_SEEK_TO_PTS` (Matroska does not) and a stream carries B-frames, which is sound in itself: such containers seek in decode order while the caller asks in presentation order. The consequence for a copy is that asking for a keyframe lands on the one BEFORE it, deterministically; and since `-segment_times` is measured from where the run really began while this code computed those offsets from the time it asked for, every cut of the run inherited one whole keyframe interval. Field 2026-08-20: 119 of 125 segments arriving a uniform 2.002 s early against the 0.5 s hls.js bridges, so every fragment was refused and re-fetched — on 2026-08-17 two of them 1908 times each. The request is now made that much later, bounded by half the distance to the next keyframe. Measured 2026-08-21 on Matroska with keyframes every 2 s: `-ss 10` produced a first segment starting at 8.000, `-ss 10.130435` one starting at 10.000; on MP4, where the heuristic does not fire, 10, 10.130435 and 10.2 all produced 10.000 — right in one case and harmless in the other. Not applied when the picture is re-encoded: a re-encode discards frames up to the requested time and already begins exactly there (`-ss 11` copied starts at 10.000, re-encoded at 11.000).
4
+ - **New**: A run that did not begin where it was asked to says so. The first piece a run produces is the only statement of its real origin that exists, and nothing compared the two — which is why the fault above stayed silent through two releases that touched the same grid. Said once per run, and only past what a player bridges.
5
+ - **Chore**: The tunnel-renewal test shuts its stand-in registry down deterministically. `WebSocketServer.close` waits for every connection to end and a renewal can leave one still closing, so a full suite run could hang for nine minutes on it.
6
+
7
+ ## 2.47.0
8
+
9
+ - **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.
10
+
1
11
  ## 2.46.0
2
12
 
3
13
  - **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.48.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": {
@@ -568,6 +568,36 @@ const SEGMENT_READ_HIGH_WATER_MARK = 4 * 1024 * 1024;
568
568
  // second is below any drift a viewer could notice, so anything above it is the
569
569
  // index being wrong about where a keyframe is rather than rounding.
570
570
  const SEGMENT_START_DISAGREEMENT_SEC = 0.25;
571
+ /**
572
+ * What ffmpeg's own CLI subtracts from an input seek, and therefore what has to
573
+ * be added back to land where we asked.
574
+ *
575
+ * `fftools/ffmpeg_demux.c`, in `ifile_open`: when the container does not
576
+ * declare `AVFMT_SEEK_TO_PTS` — Matroska does not — and any stream carries
577
+ * B-frames, the seek target is moved back by `3*AV_TIME_BASE / 23` before
578
+ * `avformat_seek_file` is called. Its purpose is sound: such containers seek in
579
+ * decode order while the caller asks in presentation order, and with B-frames
580
+ * the two differ, so it backs off far enough to be sure of reaching the frame
581
+ * asked for.
582
+ *
583
+ * The consequence for a COPY is that asking for a keyframe lands on the one
584
+ * BEFORE it — deterministically, every time. Measured 2026-08-21 on a Matroska
585
+ * file with keyframes every 2 s: `-ss 10` produced a first segment starting at
586
+ * 8.000; `-ss 10.130435` produced one starting at 10.000. On MP4, where the
587
+ * heuristic does not fire, all of 10, 10.130435 and 10.2 produced 10.000 — so
588
+ * adding this is right in one case and harmless in the other.
589
+ *
590
+ * That landing is what `-segment_times` is measured from, while this code
591
+ * computes those offsets from the time it ASKED for. One keyframe interval
592
+ * apart, inherited by every cut of the run: 119 of 125 segments arriving a
593
+ * uniform 2.002 s early in the field, four times what a player bridges.
594
+ *
595
+ * Not applied when the picture is re-encoded: a re-encode decodes from the
596
+ * keyframe and discards frames up to the requested time, so its output already
597
+ * begins exactly where asked (measured the same day: `-ss 11` copied starts at
598
+ * 10.000, re-encoded at 11.000).
599
+ */
600
+ const SEEK_LANDING_OFFSET_SEC = 3 / 23;
571
601
 
572
602
  /**
573
603
  * How far a fragment may land from where the playlist put it before the player
@@ -1146,6 +1176,34 @@ export function segmentCutTimesFrom(boundaries, startIndex) {
1146
1176
  return times;
1147
1177
  }
1148
1178
 
1179
+ /**
1180
+ * How much later than a keyframe to ASK, so that ffmpeg lands on that keyframe.
1181
+ *
1182
+ * Bounded by half the distance to the next keyframe, which matters only where
1183
+ * keyframes stand closer together than twice the offset. There no single value
1184
+ * can satisfy both worlds — asking too little lands a keyframe early when the
1185
+ * heuristic fires, asking too much lands a keyframe late when it does not — and
1186
+ * the bound picks the smaller error, which is then under one keyframe interval
1187
+ * and therefore under what a player bridges.
1188
+ *
1189
+ * @param {HlsSession} session
1190
+ * @param {number} keyframe - A real keyframe time the run is to begin at.
1191
+ * @returns {number} Seconds to add to the request.
1192
+ */
1193
+ export function seekLandingOffsetFor(session, keyframe) {
1194
+ // A re-encode trims to the requested time itself, so it needs no help and
1195
+ // must not be pushed past what it was asked for.
1196
+ if (session?.transcodeVideo === true) {
1197
+ return 0;
1198
+ }
1199
+ const times = Array.isArray(session?.keyframeTimes) ? session.keyframeTimes : [];
1200
+ const next = times.find((time) => time > keyframe + 0.001);
1201
+ if (next === undefined) {
1202
+ return SEEK_LANDING_OFFSET_SEC;
1203
+ }
1204
+ return Math.min(SEEK_LANDING_OFFSET_SEC, (next - keyframe) / 2);
1205
+ }
1206
+
1149
1207
  /**
1150
1208
  * The largest keyframe time that does not exceed `target`, from a SORTED
1151
1209
  * (ascending) array of keyframe times such as {@link probeVideoKeyframeTimes}
@@ -3932,7 +3990,7 @@ export class HlsSessionManager {
3932
3990
  if (snappedKeyframe !== null) {
3933
3991
  const residualSeconds = Math.max(0, seekSeconds - snappedKeyframe);
3934
3992
  if (snappedKeyframe > 0) {
3935
- args.push("-ss", ffmpegSeconds(snappedKeyframe));
3993
+ args.push("-ss", ffmpegSeconds(snappedKeyframe + seekLandingOffsetFor(session, snappedKeyframe)));
3936
3994
  }
3937
3995
  args.push("-i", session.inputUrl);
3938
3996
  if (residualSeconds > 0) {
@@ -5124,6 +5182,41 @@ export class HlsSessionManager {
5124
5182
  * @param {number} declaredStart - Seconds, from the playlist.
5125
5183
  * @returns {void}
5126
5184
  */
5185
+ /**
5186
+ * Where the run REALLY began, against where it was asked to begin.
5187
+ *
5188
+ * The first piece a run produces is the only statement of this that exists,
5189
+ * and until now nothing compared the two. They disagree whenever the seek
5190
+ * lands somewhere other than the time asked for — which, before the landing
5191
+ * offset, was every run on a Matroska source with B-frames, by exactly one
5192
+ * keyframe interval. Every cut of the run then inherits it, because
5193
+ * `-segment_times` is measured from the landing.
5194
+ *
5195
+ * Said once per run, and only when it matters: within what a player bridges
5196
+ * there is nothing to report.
5197
+ *
5198
+ * @param {HlsSession} session
5199
+ * @param {number} index
5200
+ * @param {number} trueStart
5201
+ * @returns {void}
5202
+ */
5203
+ #noteRunLanding(session, index, trueStart) {
5204
+ if (session.encodeStartIndex !== index || session.landingReportedForRun === index) {
5205
+ return;
5206
+ }
5207
+ session.landingReportedForRun = index;
5208
+ const asked = this.#segmentStartTime(session, index);
5209
+ const drift = trueStart - asked;
5210
+ if (!Number.isFinite(drift) || Math.abs(drift) <= PLAYER_BUFFER_HOLE_SEC) {
5211
+ return;
5212
+ }
5213
+ logger.warn(
5214
+ `transcode ${session.id} run began at ${trueStart.toFixed(3)}s but was asked for ` +
5215
+ `${asked.toFixed(3)}s — ${drift > 0 ? "+" : ""}${drift.toFixed(3)}s, and every cut of this ` +
5216
+ "run is measured from where it began, so the whole run is that far from its playlist"
5217
+ );
5218
+ }
5219
+
5127
5220
  #noteIndexAccuracy(session, index, trueStart, declaredStart) {
5128
5221
  const deviation = Math.abs(trueStart - declaredStart);
5129
5222
  session.indexCheck ??= newIndexCheck();
@@ -7719,6 +7812,7 @@ export class HlsSessionManager {
7719
7812
  : null;
7720
7813
  const declaredStart = this.#segmentStartTime(session, index);
7721
7814
  if (trueStart !== null) {
7815
+ this.#noteRunLanding(session, index, trueStart);
7722
7816
  this.#noteIndexAccuracy(session, index, trueStart, declaredStart);
7723
7817
  }
7724
7818
  // WHERE THE PLAYER WAS TOLD THIS SEGMENT BEGINS, which is the playlist
@@ -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,50 @@
1
+ /**
2
+ * @file Ask ffmpeg late enough that it lands where we meant.
3
+ *
4
+ * `fftools/ffmpeg_demux.c` moves an input seek back by `3*AV_TIME_BASE / 23` —
5
+ * 130.435 ms — whenever the container does not declare `AVFMT_SEEK_TO_PTS` and
6
+ * a stream carries B-frames. So asking for a keyframe lands on the one before
7
+ * it, and since `-segment_times` is measured from where the run really began,
8
+ * every cut of that run inherits the shift.
9
+ *
10
+ * Measured 2026-08-21 on Matroska with keyframes every 2 s: `-ss 10` produced a
11
+ * first segment starting at 8.000, `-ss 10.130435` one starting at 10.000. On
12
+ * MP4, where the heuristic does not fire, 10, 10.130435 and 10.2 all produced
13
+ * 10.000 — right in one case, harmless in the other.
14
+ */
15
+
16
+ import assert from "node:assert/strict";
17
+ import test from "node:test";
18
+
19
+ import { seekLandingOffsetFor } from "../services/hls-session-manager.js";
20
+
21
+ const OFFSET = 3 / 23;
22
+
23
+ test("a copied picture is asked for one heuristic later than the keyframe", () => {
24
+ const session = { transcodeVideo: false, keyframeTimes: [0, 2.002, 4.004, 6.006] };
25
+ assert.equal(seekLandingOffsetFor(session, 2.002), OFFSET);
26
+ });
27
+
28
+ test("a re-encode is asked for exactly what it should produce", () => {
29
+ // It decodes from the keyframe and discards frames up to the requested time,
30
+ // so pushing the request later would start its output late.
31
+ const session = { transcodeVideo: true, keyframeTimes: [0, 2.002, 4.004] };
32
+ assert.equal(seekLandingOffsetFor(session, 2.002), 0);
33
+ });
34
+
35
+ test("the offset never reaches the next keyframe", () => {
36
+ // Keyframes 0.1 s apart: half of that is the most that can be added without
37
+ // risking a landing on the NEXT one where the heuristic does not fire.
38
+ const session = { transcodeVideo: false, keyframeTimes: [0, 0.1, 0.2, 0.3] };
39
+ assert.equal(seekLandingOffsetFor(session, 0.1), 0.05);
40
+ });
41
+
42
+ test("the last keyframe has nothing after it to collide with", () => {
43
+ const session = { transcodeVideo: false, keyframeTimes: [0, 2.002, 4.004] };
44
+ assert.equal(seekLandingOffsetFor(session, 4.004), OFFSET);
45
+ });
46
+
47
+ test("no keyframe list is still answered", () => {
48
+ assert.equal(seekLandingOffsetFor({ transcodeVideo: false }, 5), OFFSET);
49
+ assert.equal(seekLandingOffsetFor(null, 5), OFFSET);
50
+ });
@@ -0,0 +1,138 @@
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
+ /** Every socket ever accepted, so the server can be shut without waiting. */
37
+ const accepted = new Set();
38
+ server.on("connection", (socket) => {
39
+ opened += 1;
40
+ accepted.add(socket);
41
+ socket.on("close", () => { accepted.delete(socket); });
42
+ const previous = current;
43
+ current = socket;
44
+ // The replacement is registered BEFORE the old one is closed, so a reader
45
+ // of `current` never sees nothing.
46
+ if (previous && previous.readyState < 2) {
47
+ previous.close(1000, "replaced");
48
+ }
49
+ socket.on("close", () => {
50
+ if (current === socket) {
51
+ current = null;
52
+ everEmpty = true;
53
+ }
54
+ });
55
+ });
56
+ const { port } = server.address();
57
+ return {
58
+ url: `http://127.0.0.1:${port}`,
59
+ // `close` waits for every connection to end, and a renewal can leave one
60
+ // still closing, so they are ended here rather than waited on.
61
+ close: () => new Promise((resolve) => {
62
+ for (const socket of accepted) {
63
+ socket.terminate();
64
+ }
65
+ accepted.clear();
66
+ server.close(() => resolve());
67
+ }),
68
+ registered: () => (current && current.readyState === 1 ? 1 : 0),
69
+ killCurrent: () => { current?.terminate(); },
70
+ opened: () => opened,
71
+ everEmpty: () => everEmpty
72
+ };
73
+ }
74
+
75
+ test("the connection is replaced before its lifetime runs out, without a gap", async (t) => {
76
+ const registry = await startRegistry();
77
+ /** @type {string[]} */
78
+ const lines = [];
79
+ const client = createTunnelClient({
80
+ serverUrl: registry.url,
81
+ proxyId: "p1",
82
+ token: "t",
83
+ proxyPort: 9090,
84
+ onLog: (line) => lines.push(line),
85
+ // The real cap is 100 min 15 s and the real renewal is at 90 min; the
86
+ // ratio is what matters, not the magnitude.
87
+ connectionLifetimeMs: 150
88
+ });
89
+ t.after(async () => {
90
+ client.disconnect();
91
+ await registry.close();
92
+ });
93
+
94
+ client.connect();
95
+ // Long enough for several renewals at 150 ms each.
96
+ await new Promise((resolve) => { setTimeout(resolve, 700); });
97
+
98
+ assert.ok(registry.opened() >= 3, `expected several renewals, saw ${registry.opened()}`);
99
+ // The property this exists for: the registry was never left with nothing.
100
+ assert.equal(registry.everEmpty(), false, "the registry lost its connection at some point");
101
+ assert.equal(registry.registered(), 1);
102
+ // And the proxy knows the difference between a handover and going down. A
103
+ // "Reconnecting in" line here would mean it had treated its own renewal as a
104
+ // failure and waited five seconds before coming back.
105
+ assert.ok(lines.some((line) => line.includes("Tunnel renewing")), lines.join("\n"));
106
+ assert.ok(lines.some((line) => line.includes("Tunnel handed over")), lines.join("\n"));
107
+ assert.equal(lines.filter((line) => line.includes("Reconnecting in")).length, 0, lines.join("\n"));
108
+ });
109
+
110
+ test("a connection killed from outside is still reconnected", async (t) => {
111
+ const registry = await startRegistry();
112
+ /** @type {string[]} */
113
+ const lines = [];
114
+ const client = createTunnelClient({
115
+ serverUrl: registry.url,
116
+ proxyId: "p2",
117
+ token: "t",
118
+ proxyPort: 9090,
119
+ onLog: (line) => lines.push(line),
120
+ // Far longer than this test runs, so nothing renews and the only close is
121
+ // the one forced below — which is what the upstream cap looks like from
122
+ // here: an abrupt end nobody asked for.
123
+ connectionLifetimeMs: 60_000
124
+ });
125
+ t.after(async () => {
126
+ client.disconnect();
127
+ await registry.close();
128
+ });
129
+
130
+ client.connect();
131
+ await new Promise((resolve) => { setTimeout(resolve, 200); });
132
+ assert.equal(registry.opened(), 1);
133
+
134
+ registry.killCurrent();
135
+ await new Promise((resolve) => { setTimeout(resolve, 300); });
136
+ // The renewal must not have taken the ordinary reconnect away with it.
137
+ assert.ok(lines.some((line) => line.includes("Reconnecting in")), lines.join("\n"));
138
+ });