Files
pulse/tests/integration/helpers.js
T
jaredandClaude Opus 5.5 67a9e1c009
CI / Security (npm audit) (push) Successful in 21s
CI / Test (jest) (push) Successful in 23s
CI / Scan (secrets, workflows, shell) (push) Successful in 14s
CI / Integration (api) (push) Successful in 1m58s
CI / Lint (eslint) (pull_request) Successful in 44s
CI / UI (playwright) (push) Successful in 3m9s
CI / Test (jest) (pull_request) Successful in 42s
CI / Security (npm audit) (pull_request) Successful in 30s
CI / Scan (secrets, workflows, shell) (pull_request) Successful in 11s
CI / Integration (api) (pull_request) Successful in 1m44s
CI / Lint (eslint) (push) Successful in 13s
CI / Deploy (push) Skipped
CI / Notify (push) Skipped
CI / UI (playwright) (pull_request) Successful in 1m45s
CI / Deploy (pull_request) Skipped
CI / Notify (pull_request) Skipped
Integration tests: wait for a worker's WebSocket, not just its heartbeat
Under load a new worker's first heartbeat marked it online before its
WebSocket had connected, so a test's first command was refused, and the
cleanup in finally then threw its own error and hid the real one.
startWorker now waits until the server accepts a probe command for the
worker, and cleanup never throws (offline status has its own test).
Reproduced 1 in 6 under UI-test load before; 0 in 10 after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:54:38 -05:00

124 lines
5.0 KiB
JavaScript

'use strict';
const { spawn } = require('child_process');
const path = require('path');
const WebSocket = require('ws');
// Matches scripts/ci/ui-stack.sh.
const BASE = process.env.PULSE_URL || 'http://127.0.0.1:8400';
const WS_BASE = BASE.replace(/^http/, 'ws');
const WORKER_KEY = process.env.PULSE_TEST_WORKER_KEY || 'ui-test-worker-key';
const GANDALF_KEY = process.env.PULSE_TEST_GANDALF_KEY || 'ui-test-gandalf-key';
const SSO = {
'Remote-User': 'int.tester',
'Remote-Name': 'Integration Tester',
'Remote-Email': 'int@example.invalid',
'Remote-Groups': 'admin',
};
async function api(method, url, { headers = {}, body } = {}) {
const res = await fetch(BASE + url, {
method,
headers: { ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json = null;
try { json = JSON.parse(text); } catch { /* not JSON */ }
return { status: res.status, json, text };
}
const sso = (method, url, body) => api(method, url, { headers: SSO, body });
const gandalf = (method, url, body, key = GANDALF_KEY) =>
api(method, url, { headers: key === null ? {} : { 'X-Gandalf-API-Key': key }, body });
async function waitFor(fn, { timeout = 20_000, interval = 250, what = 'condition' } = {}) {
const end = Date.now() + timeout;
let last;
while (Date.now() < end) {
last = await fn();
if (last) return last;
await new Promise(r => setTimeout(r, interval));
}
throw new Error(`timed out waiting for ${what} (last value: ${JSON.stringify(last)})`);
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function workerByName(name) {
const { json } = await sso('GET', '/api/workers');
return (json || []).find(w => w.name === name);
}
// Polls the Gandalf endpoint the way Gandalf does, until the execution leaves 'running'.
async function waitForExecution(id, opts = {}) {
return waitFor(async () => {
const r = await gandalf('GET', `/api/internal/executions/${id}`);
return r.json && r.json.status !== 'running' ? r.json : null;
}, { what: `execution ${id} to finish`, ...opts });
}
const commandResult = ex => (ex.logs || []).find(l => l.action === 'command_result');
// An extra worker process owned by one test, so it can be killed or limited.
async function startWorker(name, env = {}) {
const child = spawn(process.execPath, [path.join(__dirname, '..', '..', 'worker', 'worker.js')], {
cwd: __dirname, // no .env here
env: {
...process.env,
WORKER_NAME: name, PULSE_SERVER: BASE, PULSE_WS: WS_BASE,
WORKER_API_KEY: WORKER_KEY, HEARTBEAT_INTERVAL: '5', ...env,
},
stdio: ['ignore', 'pipe', 'pipe'],
});
let log = '';
child.stdout.on('data', d => { log += d; });
child.stderr.on('data', d => { log += d; });
const fail = e => { child.kill('SIGKILL'); throw new Error(`${e.message}\n${log}`); };
// The first heartbeat marks the worker 'online' before its WebSocket is connected,
// so wait until the server actually accepts a command for it (a harmless `true`).
const worker = await waitFor(async () => {
const w = await workerByName(name);
return w && w.status === 'online' ? w : null;
}, { what: `worker ${name} to register` }).catch(fail);
const probe = await waitFor(async () => {
const r = await gandalf('POST', '/api/internal/command', { worker_id: worker.id, command: 'true' });
return r.status === 200 ? r.json.execution_id : null;
}, { what: `worker ${name} to connect its WebSocket` }).catch(fail);
await waitForExecution(probe).catch(fail);
return {
id: worker.id,
child,
log: () => log,
async stop() {
if (child.exitCode === null && child.signalCode === null) {
child.kill('SIGKILL');
await new Promise(r => child.once('exit', r));
}
// Remove it so other suites (and the UI tests' worker counts) don't see it.
// Never throws: cleanup must not hide the test's own failure. The offline
// status itself is asserted by its own test in reliability.int.js.
await waitFor(async () => (await workerByName(name))?.status === 'offline', { timeout: 5_000, what: `${name} offline` })
.catch(e => console.warn(`cleanup: ${e.message}`));
await sso('DELETE', `/api/workers/${worker.id}`);
},
};
}
// Opens a WebSocket and resolves once open, or rejects with the HTTP status if refused.
function openWs(headers = {}) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(WS_BASE, { headers });
const messages = [];
ws.on('message', d => { try { messages.push(JSON.parse(d)); } catch { /* ignore */ } });
ws.once('open', () => resolve(Object.assign(ws, { messages })));
ws.once('unexpected-response', (req, res) => reject(Object.assign(new Error(`HTTP ${res.statusCode}`), { status: res.statusCode })));
ws.once('error', reject);
});
}
module.exports = {
BASE, SSO, GANDALF_KEY, WORKER_KEY, api, sso, gandalf, waitFor, sleep,
workerByName, waitForExecution, commandResult, startWorker, openWs,
};