- #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>
393 lines
13 KiB
JavaScript
393 lines
13 KiB
JavaScript
const axios = require('axios');
|
|
const WebSocket = require('ws');
|
|
const { spawn } = require('child_process');
|
|
const os = require('os');
|
|
const crypto = require('crypto');
|
|
require('dotenv').config();
|
|
|
|
const MAX_OUTPUT = 10 * 1024 * 1024; // per stream, like exec's maxBuffer
|
|
const KILL_GRACE_MS = 5000; // SIGTERM, then SIGKILL after this
|
|
|
|
// Runs a shell command in its own process group, so a timeout or a cancel can stop
|
|
// the whole tree (sh and everything it started). Resolves with the outcome; the
|
|
// error message matches what child_process.exec reported.
|
|
function runCommand(command, { timeout = 300000, onSpawn } = {}) {
|
|
return new Promise(resolve => {
|
|
const child = spawn('/bin/sh', ['-c', command], { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
let stdout = '';
|
|
let stderr = '';
|
|
let timedOut = false;
|
|
let cancelled = false;
|
|
let overflow = false;
|
|
let killTimer = null;
|
|
const kill = () => {
|
|
try { process.kill(-child.pid, 'SIGTERM'); } catch { /* already gone */ }
|
|
killTimer = setTimeout(() => { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* gone */ } }, KILL_GRACE_MS);
|
|
killTimer.unref();
|
|
};
|
|
const collect = which => chunk => {
|
|
if (which === 'out') stdout += chunk; else stderr += chunk;
|
|
if (!overflow && (stdout.length > MAX_OUTPUT || stderr.length > MAX_OUTPUT)) { overflow = true; kill(); }
|
|
};
|
|
child.stdout.setEncoding('utf8').on('data', collect('out'));
|
|
child.stderr.setEncoding('utf8').on('data', collect('err'));
|
|
const timer = setTimeout(() => { timedOut = true; kill(); }, timeout);
|
|
if (onSpawn) onSpawn({ cancel: () => { cancelled = true; kill(); } });
|
|
child.on('error', err => {
|
|
clearTimeout(timer);
|
|
resolve({ ok: false, stdout, stderr, code: undefined, signal: undefined, timedOut, cancelled, message: err.message });
|
|
});
|
|
child.on('close', (code, signal) => {
|
|
clearTimeout(timer);
|
|
if (killTimer) clearTimeout(killTimer);
|
|
const ok = code === 0 && !timedOut && !cancelled && !overflow;
|
|
let message;
|
|
if (cancelled) message = 'Cancelled';
|
|
else if (overflow) message = 'Output exceeded 10 MB';
|
|
else if (!ok) message = `Command failed: ${command}\n${stderr}`;
|
|
resolve({ ok, stdout, stderr, code, signal: signal || undefined, timedOut, cancelled, message });
|
|
});
|
|
});
|
|
}
|
|
|
|
// The commit this worker runs (#40): the VERSION file written by
|
|
// deploy/pulse_worker_deploy.sh, or the git checkout it runs from.
|
|
function detectVersion(dir = __dirname) {
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
try {
|
|
const v = fs.readFileSync(path.join(dir, 'VERSION'), 'utf8').trim();
|
|
if (/^[0-9a-f]{40}$/.test(v)) return v;
|
|
} catch { /* no VERSION file */ }
|
|
try {
|
|
return require('child_process')
|
|
.execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] })
|
|
.toString().trim();
|
|
} catch {
|
|
return 'unknown';
|
|
}
|
|
}
|
|
|
|
// 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();
|
|
this.workerName = process.env.WORKER_NAME || os.hostname();
|
|
this.serverUrl = process.env.PULSE_SERVER || 'http://localhost:8080';
|
|
this.wsUrl = process.env.PULSE_WS || 'ws://localhost:8080';
|
|
this.apiKey = process.env.WORKER_API_KEY;
|
|
this.heartbeatInterval = parseInt(process.env.HEARTBEAT_INTERVAL || '30') * 1000;
|
|
this.maxConcurrentTasks = parseInt(process.env.MAX_CONCURRENT_TASKS || '5');
|
|
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;
|
|
}
|
|
|
|
async start() {
|
|
console.log(`[PULSE Worker] Starting worker: ${this.workerName}`);
|
|
console.log(`[PULSE Worker] Worker ID: ${this.workerId}`);
|
|
console.log(`[PULSE Worker] Version: ${this.version}`);
|
|
console.log(`[PULSE Worker] Server: ${this.serverUrl}`);
|
|
|
|
// 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();
|
|
|
|
// Connect to WebSocket for real-time commands
|
|
this.connectWebSocket();
|
|
|
|
console.log(`[PULSE Worker] Worker started successfully`);
|
|
}
|
|
|
|
startHeartbeat() {
|
|
this.heartbeatTimer = setInterval(async () => {
|
|
try {
|
|
await this.sendHeartbeat();
|
|
} catch (error) {
|
|
console.error('[PULSE Worker] Heartbeat failed:', error.message);
|
|
}
|
|
}, this.heartbeatInterval);
|
|
}
|
|
|
|
async sendHeartbeat() {
|
|
const metadata = {
|
|
hostname: os.hostname(),
|
|
platform: os.platform(),
|
|
arch: os.arch(),
|
|
cpus: os.cpus().length,
|
|
totalMem: os.totalmem(),
|
|
freeMem: os.freemem(),
|
|
uptime: os.uptime(),
|
|
loadavg: os.loadavg(),
|
|
activeTasks: this.activeTasks,
|
|
maxConcurrentTasks: this.maxConcurrentTasks,
|
|
version: this.version
|
|
};
|
|
|
|
try {
|
|
const response = await axios.post(
|
|
`${this.serverUrl}/api/workers/heartbeat`,
|
|
{
|
|
worker_id: this.workerId,
|
|
name: this.workerName,
|
|
metadata: metadata
|
|
},
|
|
{
|
|
headers: {
|
|
'X-API-Key': this.apiKey,
|
|
'Content-Type': 'application/json'
|
|
}
|
|
}
|
|
);
|
|
|
|
console.log(`[PULSE Worker] Heartbeat sent - Status: online`);
|
|
return response.data;
|
|
} catch (error) {
|
|
console.error('[PULSE Worker] Heartbeat error:', error.message);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
connectWebSocket() {
|
|
console.log(`[PULSE Worker] Connecting to WebSocket...`);
|
|
|
|
// The server authenticates the WebSocket upgrade with the worker key (issue #38).
|
|
const headers = this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {};
|
|
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({
|
|
type: 'worker_connect',
|
|
worker_id: this.workerId,
|
|
worker_name: this.workerName,
|
|
api_key: this.apiKey,
|
|
version: this.version
|
|
}));
|
|
});
|
|
|
|
this.ws.on('message', async (data) => {
|
|
try {
|
|
const message = JSON.parse(data.toString());
|
|
await this.handleMessage(message);
|
|
} catch (error) {
|
|
console.error('[PULSE Worker] Message handling error:', error);
|
|
}
|
|
});
|
|
|
|
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) => {
|
|
console.error('[PULSE Worker] WebSocket error:', error.message);
|
|
});
|
|
}
|
|
|
|
// 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);
|
|
|
|
switch (message.type) {
|
|
case 'execute_command':
|
|
await this.executeCommand(message);
|
|
break;
|
|
case 'execute_workflow':
|
|
await this.executeWorkflow(message);
|
|
break;
|
|
case 'cancel_command':
|
|
this.cancelCommand(message);
|
|
break;
|
|
case 'ping':
|
|
this.sendPong();
|
|
break;
|
|
default:
|
|
console.log(`[PULSE Worker] Unknown message type: ${message.type}`);
|
|
}
|
|
}
|
|
|
|
async executeCommand(message) {
|
|
const { command, execution_id, command_id, timeout = 300000 } = message;
|
|
|
|
if (this.activeTasks >= this.maxConcurrentTasks) {
|
|
console.log(`[PULSE Worker] Max concurrent tasks reached, rejecting command`);
|
|
// Tell the server, or the execution would wait for a result that never comes (#7).
|
|
this.sendResult({
|
|
type: 'command_result',
|
|
execution_id,
|
|
worker_id: this.workerId,
|
|
command_id,
|
|
success: false,
|
|
error: `Worker at capacity (${this.maxConcurrentTasks} commands already running)`,
|
|
stdout: '',
|
|
stderr: '',
|
|
timestamp: new Date().toISOString()
|
|
});
|
|
return;
|
|
}
|
|
|
|
this.activeTasks++;
|
|
console.log(`[PULSE Worker] Executing command (active tasks: ${this.activeTasks})`);
|
|
const key = command_id || execution_id;
|
|
const startTime = Date.now();
|
|
try {
|
|
const r = await runCommand(command, {
|
|
timeout,
|
|
onSpawn: handle => this.running.set(key, { execution_id, ...handle }),
|
|
});
|
|
const duration = Date.now() - startTime;
|
|
const base = { type: 'command_result', execution_id, worker_id: this.workerId, command_id, timestamp: new Date().toISOString() };
|
|
if (r.ok) {
|
|
this.sendResult({ ...base, success: true, stdout: r.stdout, stderr: r.stderr, duration });
|
|
console.log(`[PULSE Worker] Command completed in ${duration}ms`);
|
|
} else {
|
|
this.sendResult({
|
|
...base,
|
|
success: false,
|
|
error: r.message,
|
|
exit_code: typeof r.code === 'number' ? r.code : undefined,
|
|
signal: r.signal,
|
|
timed_out: r.timedOut || undefined,
|
|
cancelled: r.cancelled || undefined,
|
|
stdout: r.stdout,
|
|
stderr: r.stderr,
|
|
});
|
|
console.error('[PULSE Worker] Command failed:', r.message.split('\n')[0]);
|
|
}
|
|
} finally {
|
|
this.running.delete(key);
|
|
this.activeTasks--;
|
|
}
|
|
}
|
|
|
|
// Stops a running command and everything it started (#8): by command_id, or every
|
|
// command of an execution. Its result is then reported with cancelled: true.
|
|
cancelCommand(message) {
|
|
const { execution_id, command_id } = message;
|
|
let n = 0;
|
|
for (const [key, run] of this.running) {
|
|
if ((command_id && key === command_id) || (!command_id && run.execution_id === execution_id)) {
|
|
run.cancel();
|
|
n++;
|
|
}
|
|
}
|
|
console.log(`[PULSE Worker] Cancel for ${command_id || execution_id}: ${n} command(s) stopped`);
|
|
}
|
|
|
|
async executeWorkflow(message) {
|
|
const { workflow, execution_id } = message;
|
|
|
|
console.log(`[PULSE Worker] Executing workflow: ${workflow.name}`);
|
|
|
|
// Workflow execution will be implemented in phase 2
|
|
// For now, just acknowledge receipt
|
|
this.sendResult({
|
|
type: 'workflow_result',
|
|
execution_id,
|
|
worker_id: this.workerId,
|
|
success: true,
|
|
message: 'Workflow execution not yet implemented',
|
|
timestamp: new Date().toISOString()
|
|
});
|
|
}
|
|
|
|
sendResult(result) {
|
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
this.ws.send(JSON.stringify(result));
|
|
}
|
|
}
|
|
|
|
sendPong() {
|
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
this.ws.send(JSON.stringify({ type: 'pong', worker_id: this.workerId }));
|
|
}
|
|
}
|
|
|
|
async stop() {
|
|
console.log('[PULSE Worker] Shutting down...');
|
|
this.stopping = true;
|
|
clearTimeout(this.reconnectTimer);
|
|
|
|
if (this.heartbeatTimer) {
|
|
clearInterval(this.heartbeatTimer);
|
|
}
|
|
|
|
if (this.ws) {
|
|
this.ws.close();
|
|
}
|
|
|
|
console.log('[PULSE Worker] Shutdown complete');
|
|
}
|
|
}
|
|
|
|
module.exports = { PulseWorker, detectVersion, runCommand, reconnectDelay };
|
|
|
|
// Start only when run directly (node worker.js), so tests can load the class.
|
|
if (require.main === module) {
|
|
const worker = new PulseWorker();
|
|
|
|
// Handle graceful shutdown
|
|
process.on('SIGTERM', async () => {
|
|
await worker.stop();
|
|
process.exit(0);
|
|
});
|
|
|
|
process.on('SIGINT', async () => {
|
|
await worker.stop();
|
|
process.exit(0);
|
|
});
|
|
|
|
worker.start().catch((error) => {
|
|
console.error('[PULSE Worker] Fatal error:', error);
|
|
process.exit(1);
|
|
});
|
|
}
|