Worker: keepalive, reconnect backoff, no crash loop at startup (#1, #29)

- #1: the worker pings the server every 30 s over the WebSocket; if the
  previous ping got no pong, the connection is dead (server restart or
  network drop without a close) and is terminated so it reconnects. The
  ws server answers pings itself, so the server needs no change.
- #29: reconnects back off from 1 s doubling to 60 s with up to 20%
  jitter, reset on a successful connection; a failed first heartbeat is
  logged and retried instead of exiting into a systemd crash loop.
- stop() no longer schedules a reconnect.
- Tests: backoff bounds, missed pong terminates, pong keeps, startup with
  an unreachable server (unit and end to end). The #6 test now waits for
  the worker to show offline before sending one command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-23 00:08:35 -05:00
1 parent d517cae7e6
commit 397f4dd778
3 files changed
+119 -10

No files matched your search

+27 -3
View File
@@ -94,11 +94,14 @@ test('aborting a command kills its process on the worker (#8)', async () => {
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 w = await startWorker(unique());
const name = unique();
const w = await startWorker(name);
w.child.kill('SIGKILL');
try {
await waitFor(async () => (await sso('POST', `/api/workers/${w.id}/command`, { command: `echo ${marker}` })).status === 400,
{ timeout: 5000, what: 'the server to notice the worker is gone' });
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',
@@ -116,3 +119,24 @@ test('a connected worker cannot be deleted; it would re-register on its next hea
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');
}
});
+39
View File
@@ -159,3 +159,42 @@ describe('cancel_command (#8)', () => {
expect(() => w.cancelCommand({ execution_id: 'nope', command_id: 'nope' })).not.toThrow();
});
});
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();
});
});