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: no test picks a port for the server any more

Boris 'B' Kurktchiev7ca9349eb0ec
diff --git a/api/test/helpers.mjs b/api/test/helpers.mjs
index 55ea3138c..418380719 100644
--- a/api/test/helpers.mjs
+++ b/api/test/helpers.mjs
@@ -9,6 +9,39 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+/* The port a spawned server.js actually bound.
+ *
+ * Never pick one for it. Opening a listener on 0, reading the port, closing it and handing the
+ * number to a child that binds it a process start later leaves a window the kernel re-issues
+ * ephemeral ports inside -- 8 repeats in 400 open/close rounds on this box -- and a dozen test
+ * files spawn servers at once, so two draw the same number, one child loses the bind and dies,
+ * and the other file's server answers on it: a different data dir, a db.json without the test's
+ * user, and a 401 where the answer belongs. It cost one unreproducible failure before anyone
+ * looked.
+ *
+ * So the child picks its own port (PORT=0) and says which on its boot line. That line cannot be
+ * printed before the socket is bound, which makes it the readiness signal as well -- no polling
+ * /api/health, and no waiting on a server that died at boot either.
+ *
+ * `tail` supplies whatever the caller has collected of the child's output, for the message.
+ */
+export function boundPort(child, tail = () => '') {
+ return new Promise((resolve, reject) => {
+ let seen = '';
+ const give = setTimeout(() => reject(new Error(`server never announced a port:\n${tail() || seen}`)), 20000);
+ const look = d => {
+ seen += d;
+ const m = /gym-api on :(\d+)/.exec(seen);
+ if (!m) return;
+ clearTimeout(give);
+ child.stdout.off('data', look);
+ resolve(+m[1]);
+ };
+ child.stdout.on('data', look);
+ child.once('exit', code => { clearTimeout(give); reject(new Error(`server exited (${code}):\n${tail() || seen}`)); });
+ });
+}
+
export function tempData() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'coach-test-'));
fs.writeFileSync(path.join(dir, 'secret'), 'a'.repeat(64), { mode: 0o600 });
diff --git a/api/test/server-body-errors.test.js b/api/test/server-body-errors.test.js
index 414c69c97..f8ca0663f 100644
--- a/api/test/server-body-errors.test.js
+++ b/api/test/server-body-errors.test.js
@@ -14,6 +14,7 @@ import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -23,32 +24,25 @@ function mintSession(uid) {
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
}
-const freePort = () => new Promise(r => {
- const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
-});
-
async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-bodyerr-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
users: [{ id: 'u_body_1', name: 'One', 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' }
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
});
- const h = { api: `http://127.0.0.1:${port}`, port, dataDir, log: '', exited: null };
+ const h = { api: '', port: 0, dataDir, log: '', exited: null };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
child.on('exit', (code, signal) => { h.exited = { code, signal }; });
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
- let up = false;
- for (let i = 0; i < 100 && !up; i++) {
- try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
- if (!up) await new Promise(r => setTimeout(r, 100));
- }
- assert.ok(up, `server never came up:\n${h.log}`);
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
h.cookie = `gymsid=${mintSession('u_body_1')}`;
return h;
}
diff --git a/api/test/server-config-session.test.js b/api/test/server-config-session.test.js
index 9d498626c..e4b2a7fc5 100644
--- a/api/test/server-config-session.test.js
+++ b/api/test/server-config-session.test.js
@@ -11,6 +11,7 @@ import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -36,12 +37,9 @@ async function startServer(t, env = {}) {
});
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
let log = '';
- const port = await new Promise((resolve, reject) => {
- const give = setTimeout(() => reject(new Error(`server never announced a port:\n${log}`)), 20000);
- child.stdout.on('data', d => { log += d; const m = /gym-api on :(\d+)/.exec(log); if (m) { clearTimeout(give); resolve(+m[1]); } });
- child.stderr.on('data', d => { log += d; });
- child.on('exit', c => { clearTimeout(give); reject(new Error(`server exited (${c}):\n${log}`)); });
- });
+ child.stdout.on('data', d => { log += d; });
+ child.stderr.on('data', d => { log += d; });
+ const port = await boundPort(child, () => log);
return { api: `http://127.0.0.1:${port}`, dataDir };
}
diff --git a/api/test/server-data-rev-endpoint.test.js b/api/test/server-data-rev-endpoint.test.js
index e1a07e14e..2fd313cab 100644
--- a/api/test/server-data-rev-endpoint.test.js
+++ b/api/test/server-data-rev-endpoint.test.js
@@ -15,6 +15,7 @@ import path from 'node:path';
import crypto from 'node:crypto';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const SECRET = 'test-secret-rev-endpoint';
@@ -31,17 +32,9 @@ test('GET /api/data/rev tracks PUT /api/data', async t => {
// 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}`)); });
- });
+ child.stdout.on('data', d => { log += d; });
+ child.stderr.on('data', d => { log += d; });
+ const port = await boundPort(child, () => log);
const base = `http://127.0.0.1:${port}`;
assert.equal((await fetch(`${base}/api/health`)).status, 200);
diff --git a/api/test/server-data-rev.test.js b/api/test/server-data-rev.test.js
index e7b73f6c5..c702da6bd 100644
--- a/api/test/server-data-rev.test.js
+++ b/api/test/server-data-rev.test.js
@@ -4,12 +4,12 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
-import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -20,31 +20,24 @@ function mintSession(uid, sv = 0) {
}
const headers = uid => ({ Cookie: `gymsid=${mintSession(uid)}`, 'Content-Type': 'application/json' });
-const freePort = () => new Promise(r => {
- const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
-});
-
async function startServer(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: 'u_rev_1', name: 'One', 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' }
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
});
- const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir };
+ const h = { api: '', log: '', dataDir };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
- let up = false;
- for (let i = 0; i < 100 && !up; i++) {
- try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
- if (!up) await new Promise(r => setTimeout(r, 100));
- }
- assert.ok(up, `server never came up:\n${h.log}`);
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
return h;
}
diff --git a/api/test/server-pairing.test.js b/api/test/server-pairing.test.js
index 0507ee044..c69f9d1e3 100644
--- a/api/test/server-pairing.test.js
+++ b/api/test/server-pairing.test.js
@@ -5,12 +5,12 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
-import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -22,10 +22,6 @@ function mintSession(uid, sv = 0) {
}
const cookie = (uid, sv) => ({ Cookie: `gymsid=${mintSession(uid, sv)}` });
-const freePort = () => new Promise(r => {
- const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
-});
-
const USERS = [
{ id: 'u_test_1', name: 'One', created: new Date().toISOString() },
{ id: 'u_test_2', name: 'Two', created: new Date().toISOString() }
@@ -35,21 +31,18 @@ async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pair-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, 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' }
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
});
- const h = { api: `http://127.0.0.1:${port}`, log: '' };
+ const h = { api: '', log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
- let up = false;
- for (let i = 0; i < 100 && !up; i++) {
- try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
- if (!up) await new Promise(r => setTimeout(r, 100));
- }
- assert.ok(up, `server never came up:\n${h.log}`);
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
return h;
}
diff --git a/api/test/server-push-filter.test.js b/api/test/server-push-filter.test.js
index c212f2172..f0551411d 100644
--- a/api/test/server-push-filter.test.js
+++ b/api/test/server-push-filter.test.js
@@ -13,6 +13,7 @@ import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -30,31 +31,24 @@ const keys = {
auth: crypto.randomBytes(16).toString('base64url')
};
-const freePort = () => new Promise(r => {
- const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
-});
-
async function startServer(t, subs = []) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-push-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
users: [{ id: 'u_test_1', name: 'One', 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' }
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
});
- const h = { api: `http://127.0.0.1:${port}`, dataDir, log: '' };
+ const h = { api: '', dataDir, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
- let up = false;
- for (let i = 0; i < 100 && !up; i++) {
- try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
- if (!up) await new Promise(r => setTimeout(r, 100));
- }
- assert.ok(up, `server never came up:\n${h.log}`);
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
return h;
}
diff --git a/api/test/server-push-prune-save.test.js b/api/test/server-push-prune-save.test.js
index 6826b2561..fac09d441 100644
--- a/api/test/server-push-prune-save.test.js
+++ b/api/test/server-push-prune-save.test.js
@@ -10,12 +10,12 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
-import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -26,10 +26,6 @@ function mintSession(uid) {
}
const cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };
-const freePort = () => new Promise(r => {
- const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
-});
-
async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pushprune-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
@@ -40,16 +36,15 @@ async function startServer(t) {
subs: [{ userId: 'u_test_1', endpoint: 'https://10.1.2.3/push/abc', keys: { p256dh: 'p', auth: 'a' }, created: new Date().toISOString() }]
}));
fs.writeFileSync(path.join(dataDir, 'state-u_test_1.json'), JSON.stringify({ _rev: 1, lang: 'en', workouts: [], routines: [] }));
- const port = await freePort();
const child = spawn(process.execPath, ['server.js'], {
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
// AUDIT_LOG off and the reminder tick parked: the only write this test wants to fail is the prune's
env: {
- ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost',
+ ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost',
AUDIT_LOG: '0', REMINDER_TICK_MS: '100000'
}
});
- const h = { api: `http://127.0.0.1:${port}`, dataDir, log: '', exited: null };
+ const h = { api: '', dataDir, log: '', exited: null };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
child.on('exit', (code, signal) => { h.exited = { code, signal }; });
@@ -58,12 +53,10 @@ async function startServer(t) {
child.kill('SIGKILL');
fs.rmSync(dataDir, { recursive: true, force: true });
});
- let up = false;
- for (let i = 0; i < 100 && !up; i++) {
- try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
- if (!up) await new Promise(r => setTimeout(r, 100));
- }
- assert.ok(up, `server never came up:\n${h.log}`);
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
return h;
}
const unwritable = h => fs.chmodSync(h.dataDir, 0o500);
diff --git a/api/test/server-push-status.test.js b/api/test/server-push-status.test.js
index 459d4e82d..ce6c7d58e 100644
--- a/api/test/server-push-status.test.js
+++ b/api/test/server-push-status.test.js
@@ -6,12 +6,12 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
-import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -24,10 +24,6 @@ const cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };
const other = { Cookie: `gymsid=${mintSession('u_test_2')}` };
const keys = { p256dh: 'p', auth: 'a' };
-const freePort = () => new Promise(r => {
- const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
-});
-
async function startServer(t, subs = []) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pushstatus-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
@@ -35,21 +31,18 @@ async function startServer(t, subs = []) {
users: [{ id: 'u_test_1', name: 'One', created: new Date().toISOString() }, { id: 'u_test_2', name: 'Two', 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' }
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
});
- const h = { api: `http://127.0.0.1:${port}`, dataDir, log: '' };
+ const h = { api: '', dataDir, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
- let up = false;
- for (let i = 0; i < 100 && !up; i++) {
- try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
- if (!up) await new Promise(r => setTimeout(r, 100));
- }
- assert.ok(up, `server never came up:\n${h.log}`);
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
return h;
}
const readDb = h => JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
diff --git a/api/test/server-reminder.test.js b/api/test/server-reminder.test.js
index d17f88973..28135fbf8 100644
--- a/api/test/server-reminder.test.js
+++ b/api/test/server-reminder.test.js
@@ -9,12 +9,12 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
-import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -26,10 +26,6 @@ function mintSession(uid) {
}
const cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };
-const freePort = () => new Promise(r => {
- const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
-});
-
const USERS = [
{ id: 'u_test_1', name: 'One', created: new Date().toISOString() },
{ id: 'u_test_2', name: 'Two', created: new Date().toISOString() }
@@ -39,21 +35,18 @@ async function startServer(t, subs = []) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-reminder-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, 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', REMINDER_TICK_MS: '300' }
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', REMINDER_TICK_MS: '300' }
});
- const h = { api: `http://127.0.0.1:${port}`, dataDir, child, log: '' };
+ const h = { api: '', dataDir, child, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
- let up = false;
- for (let i = 0; i < 100 && !up; i++) {
- try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
- if (!up) await new Promise(r => setTimeout(r, 100));
- }
- assert.ok(up, `server never came up:\n${h.log}`);
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
return h;
}
diff --git a/api/test/server-state-cache-bounds.test.js b/api/test/server-state-cache-bounds.test.js
index 0819cafd2..30cb6ac1b 100644
--- a/api/test/server-state-cache-bounds.test.js
+++ b/api/test/server-state-cache-bounds.test.js
@@ -16,6 +16,7 @@ import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -42,12 +43,9 @@ async function startServer(t, env = {}) {
});
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
let log = '';
- const port = await new Promise((resolve, reject) => {
- const give = setTimeout(() => reject(new Error(`server never announced a port:\n${log}`)), 20000);
- child.stdout.on('data', d => { log += d; const m = /gym-api on :(\d+)/.exec(log); if (m) { clearTimeout(give); resolve(+m[1]); } });
- child.stderr.on('data', d => { log += d; });
- child.on('exit', c => { clearTimeout(give); reject(new Error(`server exited (${c}):\n${log}`)); });
- });
+ child.stdout.on('data', d => { log += d; });
+ child.stderr.on('data', d => { log += d; });
+ const port = await boundPort(child, () => log);
return { api: `http://127.0.0.1:${port}`, dataDir };
}
diff --git a/api/test/server-state-read-cost.test.js b/api/test/server-state-read-cost.test.js
index b210eb430..9701fa227 100644
--- a/api/test/server-state-read-cost.test.js
+++ b/api/test/server-state-read-cost.test.js
@@ -26,6 +26,7 @@ import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
@@ -36,31 +37,24 @@ function mintSession(uid) {
}
const headers = { Cookie: `gymsid=${mintSession('u_cost_1')}`, 'Content-Type': 'application/json' };
-const freePort = () => new Promise(r => {
- const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
-});
-
async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-statecost-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
users: [{ id: 'u_cost_1', name: 'One', 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' }
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
});
- const h = { api: `http://127.0.0.1:${port}`, port, dataDir, log: '' };
+ const h = { api: '', port: 0, dataDir, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
- let up = false;
- for (let i = 0; i < 100 && !up; i++) {
- try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
- if (!up) await new Promise(r => setTimeout(r, 100));
- }
- assert.ok(up, `server never came up:\n${h.log}`);
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
return h;
}
diff --git a/api/test/server-url.test.js b/api/test/server-url.test.js
index 514bfc40a..95b46ef71 100644
--- a/api/test/server-url.test.js
+++ b/api/test/server-url.test.js
@@ -11,32 +11,26 @@ import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
-const freePort = () => new Promise(r => {
- const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
-});
-
async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-url-'));
fs.writeFileSync(path.join(dataDir, 'secret'), crypto.randomBytes(32).toString('hex'), { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [], 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' }
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
});
- const h = { api: `http://127.0.0.1:${port}`, port, child, log: '' };
+ const h = { api: '', port: 0, child, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
- let up = false;
- for (let i = 0; i < 100 && !up; i++) {
- try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
- if (!up) await new Promise(r => setTimeout(r, 100));
- }
- assert.ok(up, `server never came up:\n${h.log}`);
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
return h;
}