2026-11-22 14:14:28 -05:00
|
|
|
'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 } = {}) {
|
2026-11-23 00:57:53 -05:00
|
|
|
const send = () => fetch(BASE + url, {
|
2026-11-22 14:14:28 -05:00
|
|
|
method,
|
|
|
|
|
headers: { ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers },
|
|
|
|
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
|
|
|
});
|
2026-11-23 00:57:53 -05:00
|
|
|
let res;
|
|
|
|
|
try {
|
|
|
|
|
res = await send();
|
|
|
|
|
} catch (e) {
|
|
|
|
|
// A pooled keep-alive connection can be closed by the server (5 s idle timeout) just
|
|
|
|
|
// as the client reuses it: ECONNRESET. Retry once, but only reads; a write might
|
|
|
|
|
// already have taken effect.
|
|
|
|
|
const reset = e && e.cause && e.cause.code === 'ECONNRESET';
|
|
|
|
|
if (method !== 'GET' || !reset) throw e;
|
|
|
|
|
res = await send();
|
|
|
|
|
}
|
2026-11-22 14:14:28 -05:00
|
|
|
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; });
|
2026-11-22 15:54:38 -05:00
|
|
|
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`).
|
2026-11-22 14:14:28 -05:00
|
|
|
const worker = await waitFor(async () => {
|
|
|
|
|
const w = await workerByName(name);
|
|
|
|
|
return w && w.status === 'online' ? w : null;
|
2026-11-22 15:54:38 -05:00
|
|
|
}, { 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);
|
2026-11-22 14:14:28 -05:00
|
|
|
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.
|
2026-11-22 15:54:38 -05:00
|
|
|
// 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}`));
|
2026-11-22 14:14:28 -05:00
|
|
|
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,
|
|
|
|
|
};
|