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

+53 -7
View File
@@ -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) {