'use strict'; // Executions always reach a final state (#7), and a final state is final. const { api, sso, gandalf, startWorker, waitForExecution, commandResult, sleep, waitFor, workerByName } = require('./helpers'); const unique = () => `int-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`; test('a worker that dies mid-command fails the execution at once, not hours later', async () => { const w = await startWorker(unique()); try { const submit = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'sleep 30' }); expect(submit.status).toBe(200); await sleep(500); w.child.kill('SIGKILL'); const ex = await waitForExecution(submit.json.execution_id, { timeout: 15_000 }); expect(ex.status).toBe('failed'); expect(commandResult(ex).error).toMatch(/disconnected/i); } finally { await w.stop(); } }); test('a worker that disconnects shows offline at once', async () => { const name = unique(); const w = await startWorker(name); try { w.child.kill('SIGKILL'); // Not after the stale-heartbeat sweep: the socket close marks it offline. await waitFor(async () => (await workerByName(name))?.status === 'offline', { timeout: 3_000, what: 'offline status' }); } finally { await w.stop(); } }); test('a worker at capacity answers with a failure instead of staying silent', async () => { const w = await startWorker(unique(), { MAX_CONCURRENT_TASKS: '1' }); try { const first = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'sleep 3; echo first' }); await sleep(300); const second = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'echo second' }); const ex2 = await waitForExecution(second.json.execution_id, { timeout: 10_000 }); expect(ex2.status).toBe('failed'); expect(commandResult(ex2).error).toMatch(/capacity/i); const ex1 = await waitForExecution(first.json.execution_id); expect(ex1.status).toBe('completed'); } finally { await w.stop(); } }); test('an aborted execution stays failed when the worker reports back later', async () => { const w = await startWorker(unique()); try { const submit = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'sleep 2; echo late' }); const id = submit.json.execution_id; await sleep(300); expect((await sso('POST', `/api/executions/${id}/abort`)).status).toBe(200); await sleep(3500); // the command finishes and the worker sends its result const ex = await waitForExecution(id); expect(ex.status).toBe('failed'); expect((ex.logs || []).some(l => l.action === 'execution_aborted')).toBe(true); expect((ex.logs || []).some(l => l.action === 'command_result' && l.success)).toBe(false); } finally { await w.stop(); } }); test('/healthz reports the commit each connected worker runs (#40)', async () => { const head = require('child_process').execFileSync('git', ['rev-parse', 'HEAD'], { cwd: __dirname }).toString().trim(); const { json } = await api('GET', '/healthz'); // The stack's workers run from this checkout, so they report its HEAD. expect(json.worker_versions).toEqual([head]); }); test('aborting a command kills its process on the worker (#8)', async () => { const fs = require('fs'); const os = require('os'); const path = require('path'); // Running, not merely a zombie waiting to be reaped (kill(pid, 0) succeeds on zombies). const alive = pid => { try { return !/^\S+ \(.*\) Z/.test(fs.readFileSync(`/proc/${pid}/stat`, 'utf8')); } catch { return false; } }; const pidFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-abort-')), 'pid'); const w = await startWorker(unique()); try { const submit = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: `sleep 30 & echo $! > ${pidFile}; wait` }); const id = submit.json.execution_id; await waitFor(() => fs.existsSync(pidFile) && fs.readFileSync(pidFile, 'utf8').trim(), { what: 'the command to start' }); const pid = Number(fs.readFileSync(pidFile, 'utf8')); expect(alive(pid)).toBe(true); expect((await sso('POST', `/api/executions/${id}/abort`)).status).toBe(200); await waitFor(() => !alive(pid), { timeout: 8000, what: 'the process to be killed' }); expect((await waitForExecution(id)).status).toBe('failed'); } finally { await w.stop(); } }); test('a quick command to an offline worker is refused without leaving a running execution (#6)', async () => { const mysql = require('mysql2/promise'); const marker = `offline-${unique()}`; const name = unique(); const w = await startWorker(name); w.child.kill('SIGKILL'); try { await waitFor(async () => (await workerByName(name))?.status === 'offline', { what: 'the worker to show offline' }); const r = await sso('POST', `/api/workers/${w.id}/command`, { command: `echo ${marker}` }); expect(r.status).toBe(400); expect(r.json.error).toBe('Worker not connected'); const db = await mysql.createConnection({ host: process.env.DB_HOST || '127.0.0.1', port: Number(process.env.DB_PORT || 3306), user: process.env.DB_USER || 'pulse', password: process.env.DB_PASSWORD || 'ci-only', database: process.env.DB_NAME || 'pulse', }); try { const [rows] = await db.query('SELECT id FROM executions WHERE logs LIKE ?', [`%${marker}%`]); expect(rows).toEqual([]); } finally { await db.end(); } } finally { await w.stop(); } }); test('a connected worker cannot be deleted; it would re-register on its next heartbeat (#34)', async () => { const node1 = await workerByName('node-01'); const r = await sso('DELETE', `/api/workers/${node1.id}`); expect(r.status).toBe(409); expect((await workerByName('node-01'))?.id).toBe(node1.id); }); test('a worker started while the server is unreachable keeps running and retries (#29)', async () => { const { spawn } = require('child_process'); const path = require('path'); const child = spawn(process.execPath, [path.join(__dirname, '..', '..', 'worker', 'worker.js')], { cwd: __dirname, env: { ...process.env, WORKER_NAME: unique(), PULSE_SERVER: 'http://127.0.0.1:9', PULSE_WS: 'ws://127.0.0.1:9', WORKER_API_KEY: 'x' }, stdio: ['ignore', 'pipe', 'pipe'], }); let log = ''; child.stdout.on('data', d => { log += d; }); child.stderr.on('data', d => { log += d; }); try { await sleep(4000); expect(child.exitCode).toBeNull(); // no crash loop expect(log).toMatch(/unreachable at startup/); expect(log).toMatch(/reconnecting in \d+s/); } finally { child.kill('SIGKILL'); } });