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

+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();
});
});