Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

api: the server names the port it bound, so a test never has to pick one

Boris 'B' Kurktchievb429a240b463
diff --git a/api/server.js b/api/server.js
index c02b3fa7a..04e2e5a8a 100644
--- a/api/server.js
+++ b/api/server.js
@@ -1248,7 +1248,7 @@ coachJobs.setProposalHook((uid, pending) => {
startCadence({ users: () => db.users, userNow });
startWarmup();
-http.createServer(async (req, res) => {
+const server = http.createServer(async (req, res) => {
// Same-origin (the deployed nginx-proxied web app) never triggers CORS, so this only matters
// for the paired mobile app calling in from its own WebView origin. It carries no cookie
// (auth is the Authorization header instead), so Allow-Credentials is deliberately never set —
@@ -1288,4 +1288,9 @@ http.createServer(async (req, res) => {
console.error(key, e);
if (!res.headersSent) json(res, 500, { error: 'server error' });
}
-}).listen(PORT, () => console.log(`gym-api on :${PORT} (rpID=${RP_ID}, origin=${ORIGIN})`));
+});
+// The port is read back off the listener rather than echoed from PORT, so the line states the
+// port that was actually bound: with PORT=0 the OS picks one, and a caller that did not choose it
+// (the tests spawn the server that way, and so does anyone running two instances on one box) has
+// no other way to learn it.
+server.listen(PORT, () => console.log(`gym-api on :${server.address().port} (rpID=${RP_ID}, origin=${ORIGIN})`));
diff --git a/api/test/server-data-rev-endpoint.test.js b/api/test/server-data-rev-endpoint.test.js
index e1df73ba3..e1a07e14e 100644
--- a/api/test/server-data-rev-endpoint.test.js
+++ b/api/test/server-data-rev-endpoint.test.js
@@ -1,4 +1,12 @@
// GET /api/data/rev hands out the revision alone — what a signed-in client polls.
+//
+// The child picks its own port (PORT=0) and announces it, rather than the test picking a free
+// one and handing it over: between `listen(0)`, the close that frees it and the child's own bind
+// there is a window of one process start, and the kernel hands the same ephemeral port back out
+// inside it (measured: 8 repeats in 400 open/close rounds on this box). Eight test files spawn
+// servers this way at once, so the loser of that race got EADDRINUSE and this test then talked to
+// another file's server — a db.json without its user, and `{"error":"not signed in"}` where the
+// revision should have been. Once at baseline, never again on a re-run.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
@@ -12,21 +20,31 @@ const API = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const SECRET = 'test-secret-rev-endpoint';
const uid = 'u_rev_1';
const cookie = () => { const p = `${uid}:${Date.now() + 86400000}:0`; return `gymsid=${p}.${crypto.createHmac('sha256', SECRET).update(p).digest('base64url')}`; };
-const freePort = () => new Promise(r => { const s = require_net().createServer(); s.listen(0, () => { const p = s.address().port; s.close(() => r(p)); }); });
-import net from 'node:net';
-function require_net() { return net; }
test('GET /api/data/rev tracks PUT /api/data', async t => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-rev-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: uid, name: 'R', created: new Date().toISOString() }], creds: [], subs: [], invites: [] }));
- const port = await freePort();
- const child = spawn(process.execPath, ['server.js'], { cwd: API, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } });
+ const child = spawn(process.execPath, ['server.js'], { cwd: API, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } });
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
+
+ // The boot line carries the port the listener actually bound, so there is no window in which
+ // anything else could be holding it — the server is listening by the time it is printed.
+ let log = '';
+ const port = await new Promise((resolve, reject) => {
+ const give = setTimeout(() => reject(new Error(`server never announced a port:\n${log}`)), 20000);
+ const look = d => {
+ log += d;
+ const m = /gym-api on :(\d+)/.exec(log);
+ if (m) { clearTimeout(give); resolve(+m[1]); }
+ };
+ child.stdout.on('data', look);
+ child.stderr.on('data', d => { log += d; });
+ child.on('exit', c => { clearTimeout(give); reject(new Error(`server exited (${c}):\n${log}`)); });
+ });
const base = `http://127.0.0.1:${port}`;
- let up = false;
- for (let i = 0; i < 100 && !up; i++) { try { up = (await fetch(`${base}/api/health`)).ok; } catch {} if (!up) await new Promise(r => setTimeout(r, 100)); }
- assert.ok(up);
+ assert.equal((await fetch(`${base}/api/health`)).status, 200);
+
const h = { cookie: cookie(), origin: 'http://localhost:8080', 'content-type': 'application/json' };
assert.equal((await fetch(`${base}/api/data/rev`)).status, 401);
assert.deepEqual(await (await fetch(`${base}/api/data/rev`, { headers: h })).json(), { rev: 0 });