2026-11-22 15:28:23 -05:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
|
|
// Unit tests for the worker's command execution (worker/worker.js), with no
|
|
|
|
|
// server: results are captured from sendResult instead of a WebSocket.
|
|
|
|
|
const { PulseWorker } = require('../worker/worker');
|
|
|
|
|
|
|
|
|
|
function makeWorker(opts = {}) {
|
|
|
|
|
const w = new PulseWorker();
|
|
|
|
|
w.maxConcurrentTasks = opts.max || 5;
|
|
|
|
|
w.results = [];
|
|
|
|
|
w.sendResult = r => w.results.push(r);
|
|
|
|
|
return w;
|
|
|
|
|
}
|
|
|
|
|
const run = (w, command, extra = {}) =>
|
|
|
|
|
w.executeCommand({ command, execution_id: 'ex-1', command_id: 'cmd-1', ...extra });
|
|
|
|
|
|
|
|
|
|
beforeAll(() => {
|
|
|
|
|
jest.spyOn(console, 'log').mockImplementation(() => {});
|
|
|
|
|
jest.spyOn(console, 'error').mockImplementation(() => {});
|
|
|
|
|
});
|
|
|
|
|
afterAll(() => jest.restoreAllMocks());
|
|
|
|
|
|
|
|
|
|
test('a successful command reports stdout, stderr and duration', async () => {
|
|
|
|
|
const w = makeWorker();
|
|
|
|
|
await run(w, 'echo out; echo err >&2');
|
|
|
|
|
expect(w.results).toHaveLength(1);
|
|
|
|
|
const r = w.results[0];
|
|
|
|
|
expect(r).toMatchObject({
|
|
|
|
|
type: 'command_result', execution_id: 'ex-1', command_id: 'cmd-1',
|
|
|
|
|
worker_id: w.workerId, success: true, stdout: 'out\n', stderr: 'err\n',
|
|
|
|
|
});
|
|
|
|
|
expect(typeof r.duration).toBe('number');
|
|
|
|
|
expect(w.activeTasks).toBe(0);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('a failing command reports its exit code and output (#14)', async () => {
|
|
|
|
|
const w = makeWorker();
|
|
|
|
|
await run(w, 'echo partial; echo broke >&2; exit 7');
|
|
|
|
|
const r = w.results[0];
|
|
|
|
|
expect(r).toMatchObject({ success: false, exit_code: 7, stdout: 'partial\n', stderr: 'broke\n' });
|
|
|
|
|
expect(r.timed_out).toBeUndefined();
|
|
|
|
|
expect(r.error).toMatch(/Command failed/);
|
|
|
|
|
expect(w.activeTasks).toBe(0);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('a command that runs past its timeout is killed and reported as timed out', async () => {
|
|
|
|
|
const w = makeWorker();
|
|
|
|
|
const started = Date.now();
|
|
|
|
|
await run(w, 'sleep 5', { timeout: 300 });
|
|
|
|
|
expect(Date.now() - started).toBeLessThan(3000);
|
|
|
|
|
expect(w.results[0]).toMatchObject({ success: false, timed_out: true, signal: 'SIGTERM' });
|
|
|
|
|
expect(w.activeTasks).toBe(0);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('at capacity, extra commands get an immediate failure instead of silence (#7)', async () => {
|
|
|
|
|
const w = makeWorker({ max: 1 });
|
|
|
|
|
const first = run(w, 'sleep 0.5; echo first', { execution_id: 'ex-a', command_id: 'a' });
|
|
|
|
|
await run(w, 'echo second', { execution_id: 'ex-b', command_id: 'b' });
|
|
|
|
|
|
|
|
|
|
const rejected = w.results.find(r => r.command_id === 'b');
|
|
|
|
|
expect(rejected).toMatchObject({ success: false, execution_id: 'ex-b' });
|
|
|
|
|
expect(rejected.error).toMatch(/capacity/);
|
|
|
|
|
|
|
|
|
|
await first;
|
|
|
|
|
expect(w.results.find(r => r.command_id === 'a')).toMatchObject({ success: true, stdout: 'first\n' });
|
|
|
|
|
expect(w.activeTasks).toBe(0);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('a slot frees up again after a command fails', async () => {
|
|
|
|
|
const w = makeWorker({ max: 1 });
|
|
|
|
|
await run(w, 'exit 1');
|
|
|
|
|
await run(w, 'echo ok', { command_id: 'next' });
|
|
|
|
|
expect(w.results.find(r => r.command_id === 'next')).toMatchObject({ success: true });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('ping is answered with pong over the socket', async () => {
|
|
|
|
|
const w = makeWorker();
|
|
|
|
|
const sent = [];
|
|
|
|
|
w.ws = { readyState: 1, send: m => sent.push(JSON.parse(m)) }; // 1 = WebSocket.OPEN
|
|
|
|
|
await w.handleMessage({ type: 'ping' });
|
|
|
|
|
expect(sent).toEqual([{ type: 'pong', worker_id: w.workerId }]);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('results are not sent while disconnected', () => {
|
|
|
|
|
const w = new PulseWorker();
|
|
|
|
|
const send = jest.fn();
|
|
|
|
|
w.ws = { readyState: 3, send }; // 3 = CLOSED
|
|
|
|
|
w.sendResult({ type: 'command_result' });
|
|
|
|
|
expect(send).not.toHaveBeenCalled();
|
|
|
|
|
});
|
2026-11-22 16:51:24 -05:00
|
|
|
|
|
|
|
|
describe('detectVersion (#40)', () => {
|
|
|
|
|
const fs = require('fs');
|
|
|
|
|
const os = require('os');
|
|
|
|
|
const path = require('path');
|
|
|
|
|
const { detectVersion } = require('../worker/worker');
|
|
|
|
|
const sha = 'a'.repeat(40);
|
|
|
|
|
let dir;
|
|
|
|
|
beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-worker-version-')); });
|
|
|
|
|
afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
|
|
|
|
|
|
|
|
|
|
test('reads the VERSION file the deploy writes', () => {
|
|
|
|
|
fs.writeFileSync(path.join(dir, 'VERSION'), `${sha}\n`);
|
|
|
|
|
expect(detectVersion(dir)).toBe(sha);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('ignores a VERSION file that is not a commit sha', () => {
|
|
|
|
|
fs.writeFileSync(path.join(dir, 'VERSION'), 'v1.2.3; rm -rf /\n');
|
|
|
|
|
expect(detectVersion(dir)).toBe('unknown'); // and dir is not a git checkout
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('falls back to the git checkout it runs from', () => {
|
|
|
|
|
expect(detectVersion(path.join(__dirname, '..', 'worker'))).toMatch(/^[0-9a-f]{40}$/);
|
|
|
|
|
});
|
|
|
|
|
});
|
2026-11-22 23:59:50 -05:00
|
|
|
|
|
|
|
|
describe('cancel_command (#8)', () => {
|
|
|
|
|
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; }
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
test('cancelling stops the command and everything it started', async () => {
|
|
|
|
|
const w = makeWorker();
|
|
|
|
|
const pidFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-cancel-')), 'pid');
|
|
|
|
|
const pending = w.executeCommand({ command: `sleep 30 & echo $! > ${pidFile}; wait`, execution_id: 'ex-c', command_id: 'cmd-c' });
|
|
|
|
|
for (let i = 0; i < 50 && !fs.existsSync(pidFile); i++) await new Promise(r => setTimeout(r, 50));
|
|
|
|
|
const childPid = Number(fs.readFileSync(pidFile, 'utf8'));
|
|
|
|
|
expect(alive(childPid)).toBe(true);
|
|
|
|
|
|
|
|
|
|
w.cancelCommand({ execution_id: 'ex-c', command_id: 'cmd-c' });
|
|
|
|
|
await pending;
|
|
|
|
|
expect(w.results[0]).toMatchObject({ success: false, cancelled: true, error: 'Cancelled', command_id: 'cmd-c' });
|
|
|
|
|
for (let i = 0; i < 40 && alive(childPid); i++) await new Promise(r => setTimeout(r, 50));
|
|
|
|
|
expect(alive(childPid)).toBe(false); // the background child is gone too
|
|
|
|
|
expect(w.running.size).toBe(0);
|
|
|
|
|
expect(w.activeTasks).toBe(0);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('cancel by execution stops all of its commands, and only those', async () => {
|
|
|
|
|
const w = makeWorker();
|
|
|
|
|
const a = w.executeCommand({ command: 'sleep 30', execution_id: 'ex-1', command_id: 'a' });
|
|
|
|
|
const b = w.executeCommand({ command: 'sleep 30', execution_id: 'ex-1', command_id: 'b' });
|
|
|
|
|
const other = w.executeCommand({ command: 'sleep 0.5; echo other', execution_id: 'ex-2', command_id: 'c' });
|
|
|
|
|
await new Promise(r => setTimeout(r, 100));
|
|
|
|
|
w.handleMessage({ type: 'cancel_command', execution_id: 'ex-1' });
|
|
|
|
|
await Promise.all([a, b, other]);
|
|
|
|
|
const byId = Object.fromEntries(w.results.map(r => [r.command_id, r]));
|
|
|
|
|
expect(byId.a.cancelled).toBe(true);
|
|
|
|
|
expect(byId.b.cancelled).toBe(true);
|
|
|
|
|
expect(byId.c).toMatchObject({ success: true, stdout: 'other\n' });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('cancelling an unknown command does nothing', () => {
|
|
|
|
|
const w = makeWorker();
|
|
|
|
|
expect(() => w.cancelCommand({ execution_id: 'nope', command_id: 'nope' })).not.toThrow();
|
|
|
|
|
});
|
|
|
|
|
});
|
2026-11-23 00:08:35 -05:00
|
|
|
|
|
|
|
|
describe('connection resilience (#1, #29)', () => {
|
|
|
|
|
const { reconnectDelay } = require('../worker/worker');
|
|
|
|
|
|
|
|
|
|
test('reconnect backoff doubles from 1 s to a 60 s cap, with at most 20% jitter', () => {
|
|
|
|
|
expect([0, 1, 2, 3, 6, 10].map(a => reconnectDelay(a, () => 0))).toEqual([1000, 2000, 4000, 8000, 60000, 60000]);
|
|
|
|
|
expect(reconnectDelay(0, () => 0.999)).toBeLessThanOrEqual(1200);
|
|
|
|
|
expect(reconnectDelay(20, () => 0.999)).toBeLessThanOrEqual(72000);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('a connection that missed its pong is terminated so it reconnects', () => {
|
|
|
|
|
const w = makeWorker();
|
|
|
|
|
const ws = { isAlive: true, ping: jest.fn(), terminate: jest.fn() };
|
|
|
|
|
w.checkAlive(ws); // alive: ping and wait for the pong
|
|
|
|
|
expect(ws.ping).toHaveBeenCalledTimes(1);
|
|
|
|
|
expect(ws.terminate).not.toHaveBeenCalled();
|
|
|
|
|
w.checkAlive(ws); // no pong since: dead
|
|
|
|
|
expect(ws.terminate).toHaveBeenCalledTimes(1);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('a pong keeps the connection', () => {
|
|
|
|
|
const w = makeWorker();
|
|
|
|
|
const ws = { isAlive: true, ping: jest.fn(), terminate: jest.fn() };
|
|
|
|
|
w.checkAlive(ws);
|
|
|
|
|
ws.isAlive = true; // what the 'pong' handler does
|
|
|
|
|
w.checkAlive(ws);
|
|
|
|
|
expect(ws.terminate).not.toHaveBeenCalled();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('startup survives an unreachable server instead of crashing', async () => {
|
|
|
|
|
const w = new PulseWorker();
|
|
|
|
|
w.sendHeartbeat = jest.fn().mockRejectedValue(new Error('connect ECONNREFUSED'));
|
|
|
|
|
w.startHeartbeat = jest.fn();
|
|
|
|
|
w.connectWebSocket = jest.fn();
|
|
|
|
|
await expect(w.start()).resolves.toBeUndefined();
|
|
|
|
|
expect(w.startHeartbeat).toHaveBeenCalled();
|
|
|
|
|
expect(w.connectWebSocket).toHaveBeenCalled();
|
|
|
|
|
});
|
|
|
|
|
});
|
2026-11-23 11:55:25 -05:00
|
|
|
|
|
|
|
|
describe('availableMemory (#30)', () => {
|
|
|
|
|
const { availableMemory } = require('../worker/worker');
|
|
|
|
|
test('reads MemAvailable (page cache counts as available), in bytes', () => {
|
|
|
|
|
const meminfo = 'MemTotal: 524288 kB\nMemFree: 4460 kB\nMemAvailable: 459733 kB\n';
|
|
|
|
|
expect(availableMemory(meminfo)).toBe(459733 * 1024);
|
|
|
|
|
});
|
|
|
|
|
test('falls back to os.freemem() without a MemAvailable line', () => {
|
|
|
|
|
expect(availableMemory('MemTotal: 1 kB\n')).toBe(require('os').freemem());
|
|
|
|
|
});
|
|
|
|
|
});
|