From 397f4dd778fa0ec28af6758f8f649d467e2b1c1a Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Mon, 23 Nov 2026 00:08:35 -0500 Subject: [PATCH] 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 --- tests/integration/reliability.int.js | 30 ++++++++++++-- tests/worker.test.js | 39 ++++++++++++++++++ worker/worker.js | 60 ++++++++++++++++++++++++---- 3 files changed, 119 insertions(+), 10 deletions(-) diff --git a/tests/integration/reliability.int.js b/tests/integration/reliability.int.js index 03b6425..1f2f609 100644 --- a/tests/integration/reliability.int.js +++ b/tests/integration/reliability.int.js @@ -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'); + } +}); diff --git a/tests/worker.test.js b/tests/worker.test.js index 6ff11b7..c8549a1 100644 --- a/tests/worker.test.js +++ b/tests/worker.test.js @@ -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(); + }); +}); diff --git a/worker/worker.js b/worker/worker.js index 608c07b..a5faacf 100644 --- a/worker/worker.js +++ b/worker/worker.js @@ -68,6 +68,15 @@ function detectVersion(dir = __dirname) { } } +// Reconnect delay after `attempt` consecutive failures: 1 s doubling to 60 s, with up +// to 20% jitter so a fleet of workers doesn't reconnect in lockstep (#29). +function reconnectDelay(attempt, random = Math.random) { + const base = Math.min(60_000, 1000 * 2 ** Math.max(0, attempt)); + return Math.round(base * (1 + 0.2 * random())); +} + +const KEEPALIVE_MS = 30_000; // ping the server this often; no pong by the next ping = dead (#1) + class PulseWorker { constructor() { this.workerId = crypto.randomUUID(); @@ -80,6 +89,9 @@ class PulseWorker { this.version = detectVersion(); this.activeTasks = 0; this.running = new Map(); // command_id (or execution_id) -> { execution_id, cancel } + this.reconnectAttempts = 0; + this.reconnectTimer = null; + this.stopping = false; this.ws = null; this.heartbeatTimer = null; } @@ -90,8 +102,13 @@ class PulseWorker { console.log(`[PULSE Worker] Version: ${this.version}`); console.log(`[PULSE Worker] Server: ${this.serverUrl}`); - // Send initial heartbeat - await this.sendHeartbeat(); + // Send initial heartbeat. If the server is unreachable, keep going: the heartbeat + // timer and the WebSocket reconnect retry, instead of exiting into a crash loop (#29). + try { + await this.sendHeartbeat(); + } catch (error) { + console.error(`[PULSE Worker] Server unreachable at startup (${error.message}); retrying in the background`); + } // Start heartbeat timer this.startHeartbeat(); @@ -159,6 +176,8 @@ class PulseWorker { this.ws = new WebSocket(this.wsUrl, { headers }); this.ws.on('open', () => { + this.reconnectAttempts = 0; + this.startKeepalive(this.ws); console.log('[PULSE Worker] WebSocket connected'); // Identify this worker this.ws.send(JSON.stringify({ @@ -179,9 +198,15 @@ class PulseWorker { } }); - this.ws.on('close', () => { - console.log('[PULSE Worker] WebSocket disconnected, reconnecting...'); - setTimeout(() => this.connectWebSocket(), 5000); + const ws = this.ws; + ws.on('pong', () => { ws.isAlive = true; }); + + ws.on('close', () => { + clearInterval(ws.keepalive); + if (this.stopping) return; + const delay = reconnectDelay(this.reconnectAttempts++); + console.log(`[PULSE Worker] WebSocket disconnected, reconnecting in ${Math.round(delay / 1000)}s...`); + this.reconnectTimer = setTimeout(() => this.connectWebSocket(), delay); }); this.ws.on('error', (error) => { @@ -189,6 +214,25 @@ class PulseWorker { }); } + // A connection can die without a close (server restart, network drop): ping it, and + // if the previous ping got no pong, terminate it so the close handler reconnects (#1). + startKeepalive(ws) { + ws.isAlive = true; + clearInterval(ws.keepalive); + ws.keepalive = setInterval(() => this.checkAlive(ws), KEEPALIVE_MS); + if (ws.keepalive.unref) ws.keepalive.unref(); + } + + checkAlive(ws) { + if (!ws.isAlive) { + console.warn('[PULSE Worker] No pong from the server; dropping the connection'); + ws.terminate(); + return; + } + ws.isAlive = false; + try { ws.ping(); } catch { /* the close handler takes over */ } + } + async handleMessage(message) { console.log(`[PULSE Worker] Received message:`, message.type); @@ -309,7 +353,9 @@ class PulseWorker { async stop() { console.log('[PULSE Worker] Shutting down...'); - + this.stopping = true; + clearTimeout(this.reconnectTimer); + if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); } @@ -322,7 +368,7 @@ class PulseWorker { } } -module.exports = { PulseWorker, detectVersion, runCommand }; +module.exports = { PulseWorker, detectVersion, runCommand, reconnectDelay }; // Start only when run directly (node worker.js), so tests can load the class. if (require.main === module) {