From ea939d4430bbb781e755b73b47aea2d6346fb0de Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sun, 22 Nov 2026 16:51:24 -0500 Subject: [PATCH] Worker deploys from CI, with version reporting (#40) - The worker reports its commit (VERSION file, or git rev-parse in a checkout) in worker_connect and heartbeat metadata. The server keeps it per live socket and /healthz lists worker_versions. - deploy/pulse_worker_deploy.sh , for the webhook on a worker host: replay and age checks, commit must be on main, installs worker.js and the npm manifests from exactly that commit, writes VERSION, npm ci, restarts, waits until /healthz lists the sha, else restores the previous files. Sandbox tests cover deploy, replay, stale and malformed input, off-main commits, no-op redeploys and rollback. - New CI job Deploy worker after Deploy: only when worker/ or the npm manifests changed since the commit the workers report, so unrelated merges don't restart the worker; then waits for the worker to reconnect on the new commit. - README: Worker deploys (install, hook definition, adding a worker host). Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 69 +++++++++++++- README.md | 52 ++++++++++- deploy/pulse_worker_deploy.sh | 122 +++++++++++++++++++++++++ server.js | 12 ++- tests/integration/auth.int.js | 2 +- tests/integration/reliability.int.js | 9 +- tests/worker-deploy-script.test.js | 130 +++++++++++++++++++++++++++ tests/worker.test.js | 25 ++++++ worker/worker.js | 28 +++++- 9 files changed, 439 insertions(+), 10 deletions(-) create mode 100755 deploy/pulse_worker_deploy.sh create mode 100644 tests/worker-deploy-script.test.js diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index f01c8ac..b12927a 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -226,10 +226,75 @@ jobs: -d "{\"tag_name\":\"${TAG}\",\"target\":\"${{ github.sha }}\",\"message\":\"Deployed to production\"}" \ "https://code.lotusguild.org/api/v1/repos/${{ github.repository }}/tags" + deploy-worker: + name: Deploy worker + runs-on: ubuntu-latest + container: node:20-bookworm + needs: [deploy] # the server first: it must understand anything new the worker sends + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + concurrency: + group: deploy-worker + cancel-in-progress: false + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + fetch-depth: 0 # to compare against the commit the worker runs now + - name: Did the worker change since the running version? + id: changed + env: + GIT_SHA: ${{ github.sha }} + run: | + # Restarting the worker briefly interrupts Gandalf's commands, so only + # deploy when worker code or its dependencies changed (#40). + running=$(curl -fsS --max-time 5 http://10.10.10.65:8080/healthz \ + | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log((JSON.parse(s).worker_versions||[]).join(" ")))') + echo "Workers run: ${running:-none}" + deploy=false + [ -n "$running" ] || deploy=true + for v in $running; do + if ! git cat-file -e "${v}^{commit}" 2>/dev/null \ + || ! git diff --quiet "$v" "$GIT_SHA" -- worker/ package.json package-lock.json; then + deploy=true + fi + done + echo "deploy=$deploy" >> "$GITHUB_OUTPUT" + echo "Deploy the worker: $deploy" + - name: Trigger worker webhook + if: steps.changed.outputs.deploy == 'true' + env: + WEBHOOK_SECRET: ${{ secrets.WORKER_WEBHOOK_SECRET }} + GIT_REF: ${{ github.ref }} + GIT_SHA: ${{ github.sha }} + run: | + PAYLOAD="{\"ref\":\"${GIT_REF}\",\"sha\":\"${GIT_SHA}\",\"ts\":$(date +%s)}" + SIG=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | awk '{print $2}') + curl -sf --connect-timeout 10 -X POST \ + -H "Content-Type: application/json" \ + -H "X-Gitea-Signature: ${SIG}" \ + -d "$PAYLOAD" \ + "http://10.10.10.151:9000/hooks/pulse-worker-deploy" + - name: Verify the worker reconnected on this commit + if: steps.changed.outputs.deploy == 'true' + env: + GIT_SHA: ${{ github.sha }} + run: | + # deploy/pulse_worker_deploy.sh on CT 153 installs this sha, restarts the + # worker, and restores the previous files if it never reconnects. + for _ in $(seq 1 48); do + body=$(curl -fsS --connect-timeout 5 --max-time 5 http://10.10.10.65:8080/healthz || true) + if echo "$body" | grep -Eq "\"worker_versions\":\[[^]]*\"${GIT_SHA}\""; then + echo "Worker connected on ${GIT_SHA}: ${body}" + exit 0 + fi + sleep 5 + done + echo "::error::The worker never reconnected on ${GIT_SHA} (last /healthz: ${body:-no response}). See /var/log/pulse-worker-deploy.log on CT 153." + exit 1 + notify: name: Notify runs-on: ubuntu-latest - needs: [lint, test, audit, scan, integration, ui, deploy] + needs: [lint, test, audit, scan, integration, ui, deploy, deploy-worker] # Alert on any failure on main or in the weekly audit, and on every deploy outcome. if: >- always() && ( @@ -243,7 +308,7 @@ jobs: REPO: ${{ github.repository }} BRANCH: ${{ github.ref_name }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - RESULTS: "lint=${{ needs.lint.result }} test=${{ needs.test.result }} audit=${{ needs.audit.result }} scan=${{ needs.scan.result }} integration=${{ needs.integration.result }} ui=${{ needs.ui.result }} deploy=${{ needs.deploy.result }}" + RESULTS: "lint=${{ needs.lint.result }} test=${{ needs.test.result }} audit=${{ needs.audit.result }} scan=${{ needs.scan.result }} integration=${{ needs.integration.result }} ui=${{ needs.ui.result }} deploy=${{ needs.deploy.result }} worker=${{ needs.deploy-worker.result }}" DEPLOYED: ${{ needs.deploy.result == 'success' }} run: | if [ -z "$MATRIX_WEBHOOK_URL" ] || [ "$MATRIX_WEBHOOK_URL" = "CONFIGURE_ME" ]; then exit 0; fi diff --git a/README.md b/README.md index 65b8132..2d72f19 100644 --- a/README.md +++ b/README.md @@ -645,7 +645,8 @@ CI sends an HMAC-signed payload `{"ref", "sha", "ts"}` to the webhook on CT 122. **rolls back** to the previous commit. It logs to `/var/log/pulse-deploy.log`. `GET /healthz` (unauthenticated) returns -`{status, version, sha, db, workers, uptime_s}` with 200, or 503 when the database is unreachable. +`{status, version, sha, db, workers, worker_versions, uptime_s}` with 200, or 503 when the database is +unreachable. `worker_versions` lists the commit each connected worker reports. **Installing or updating the deploy script** (on CT 122, as root). The webhook runs the installed copy, not the one in the checkout, so a bad commit can't replace the code that rolls it back: @@ -663,6 +664,55 @@ The `pulse-deploy` hook in `/etc/webhook/hooks.json` passes the signed values as ] ``` +### Worker deploys + +The only worker today is `pulse-worker-01` (LXC CT 153 on monitor-01, 10.10.10.151), installed in +`/opt/pulse-worker` (`worker.js`, the npm manifests, `node_modules`, and its own `.env`), run by +`pulse-worker.service`. The unit file itself is deployed from `jared/pve-infra`. + +After the server deploys, the `Deploy worker` job checks the commit the connected workers report +(`worker_versions` in `/healthz`). Only if `worker/` or the npm manifests changed since then does it +call the HMAC-signed `pulse-worker-deploy` hook on CT 153, so unrelated merges don't restart the +worker mid-command. The hook runs `deploy/pulse_worker_deploy.sh `, which: + +1. refuses stale or replayed requests, and commits that aren't on `main`; +2. reads `worker/worker.js`, `package.json` and `package-lock.json` at exactly that commit from a + local clone of the repo, installs them, writes the sha to `VERSION`, runs `npm ci --omit=dev` and + restarts the worker (`.env` is never touched); +3. waits until `/healthz` lists that sha among the connected workers, and otherwise **restores** the + previous files. + +CI then waits for the same thing before the job passes. The script logs to +`/var/log/pulse-worker-deploy.log`. + +**Installing it on a worker host** (as root; CT 153 already runs `webhook`): + +```bash +install -m 755 pulse_worker_deploy.sh /usr/local/bin/pulse_worker_deploy.sh # from deploy/ in this repo +``` + +and add a hook to `/etc/webhook/hooks.json`, with the same secret as the repo's +`WORKER_WEBHOOK_SECRET` Actions secret: + +```json +{ + "id": "pulse-worker-deploy", + "execute-command": "/usr/local/bin/pulse_worker_deploy.sh", + "pass-arguments-to-command": [ + { "source": "payload", "name": "sha" }, + { "source": "payload", "name": "ts" } + ], + "trigger-rule": { + "match": { "type": "payload-hmac-sha256", "secret": "", + "parameter": { "source": "header", "name": "X-Gitea-Signature" } } + } +} +``` + +To add a worker host, install Node 20 and the worker as above, give it a `.env` with `WORKER_NAME`, +`PULSE_SERVER`, `PULSE_WS` and `WORKER_API_KEY`, and add its hook (one hook URL per host in the +`Deploy worker` job). + --- **PULSE** - Orchestrating your infrastructure, one heartbeat at a time. ⚡ diff --git a/deploy/pulse_worker_deploy.sh b/deploy/pulse_worker_deploy.sh new file mode 100755 index 0000000..07de7f7 --- /dev/null +++ b/deploy/pulse_worker_deploy.sh @@ -0,0 +1,122 @@ +#!/bin/bash +# Pulse worker deploy (#40), run by the webhook listener on a worker host (CT 153). +# +# Source of truth: deploy/pulse_worker_deploy.sh in the Pulse repo. +# Installed copy: /usr/local/bin/pulse_worker_deploy.sh (see README "Worker deploys"). +# +# Usage: pulse_worker_deploy.sh +# sha full 40-char commit CI tested; must be on origin/main +# ts unix time CI signed the request at +# Both come from the HMAC-signed webhook payload. The timestamp makes every +# signature unique: stale or replayed requests are refused. +# +# Installs worker/worker.js and the npm manifests from exactly , records the +# sha in VERSION (the worker reports it), restarts the worker and waits until the +# server's /healthz lists that sha among the connected workers. Otherwise it puts +# the previous files back. +set -euo pipefail + +# Overridable only so tests can run the script in a sandbox. +APP_DIR=${PULSE_WORKER_APP_DIR:-/opt/pulse-worker} +REPO_URL=${PULSE_WORKER_REPO_URL:-https://code.lotusguild.org/LotusGuild/pulse.git} +STATE_DIR=${PULSE_WORKER_STATE_DIR:-/var/lib/pulse-worker-deploy} +LOG=${PULSE_WORKER_LOG:-/var/log/pulse-worker-deploy.log} +LOCK=${PULSE_WORKER_LOCK:-/run/pulse-worker-deploy.lock} +HEALTH_URL=${PULSE_WORKER_HEALTH_URL:-http://10.10.10.65:8080/healthz} +SERVICE=${PULSE_WORKER_SERVICE:-pulse-worker} +BRANCH=main +MAX_AGE_S=300 +HEALTH_TRIES=${PULSE_WORKER_HEALTH_TRIES:-45} # x 2 s = 90 s to reconnect +FILES=(worker.js package.json package-lock.json) + +log() { echo "$(date '+%F %T') [pulse-worker-deploy] $*" | tee -a "$LOG"; } +fail() { log "REFUSED: $*"; exit 1; } + +SHA="${1:-}" +TS="${2:-}" + +exec 9>"$LOCK" +flock -w 600 9 || fail "timed out waiting for another deploy" + +[[ "$SHA" =~ ^[0-9a-f]{40}$ ]] || fail "missing or invalid sha" +[[ "$TS" =~ ^[0-9]+$ ]] || fail "missing or invalid timestamp" + +now=$(date +%s) +age=$(( now - TS )) +(( age >= -60 && age <= MAX_AGE_S )) || fail "request is ${age}s old (limit ${MAX_AGE_S}s)" + +mkdir -p "$STATE_DIR" +chmod 700 "$STATE_DIR" +last_ts=$(cat "$STATE_DIR/last_ts" 2>/dev/null || echo 0) +(( TS > last_ts )) || fail "timestamp $TS is not newer than the last accepted request ($last_ts): replay or out of order" +echo "$TS" > "$STATE_DIR/last_ts" + +# A local clone of the (public) repo, used only to read files at . +REPO="$STATE_DIR/repo" +if [ ! -d "$REPO/.git" ]; then + git clone --quiet --no-checkout "$REPO_URL" "$REPO" +fi +git -C "$REPO" fetch --quiet origin "$BRANCH" +git -C "$REPO" cat-file -e "${SHA}^{commit}" 2>/dev/null || fail "commit $SHA not found after fetch" +git -C "$REPO" merge-base --is-ancestor "$SHA" "origin/$BRANCH" || fail "commit $SHA is not on $BRANCH" + +PREV=$(cat "$APP_DIR/VERSION" 2>/dev/null || echo unknown) + +healthy() { # healthy : the server lists among connected worker versions + local want="$1" body + for _ in $(seq 1 "$HEALTH_TRIES"); do + if body=$(curl -fsS --max-time 3 "$HEALTH_URL" 2>/dev/null) \ + && grep -Eq "\"worker_versions\":\[[^]]*\"$want\"" <<<"$body"; then + return 0 + fi + sleep "${PULSE_WORKER_HEALTH_SLEEP:-2}" + done + return 1 +} + +if [ "$PREV" = "$SHA" ] && healthy "$SHA"; then + log "already running $SHA and connected; nothing to do" + exit 0 +fi + +# Keep the current files so a failed deploy can be undone. +BACKUP="$STATE_DIR/previous" +rm -rf "$BACKUP" && mkdir -p "$BACKUP" +for f in "${FILES[@]}" VERSION; do + if [ -e "$APP_DIR/$f" ]; then cp -p "$APP_DIR/$f" "$BACKUP/$f"; fi +done + +restart() { + # Explicit returns: `set -e` does not apply inside a function used in an `if`. + (cd "$APP_DIR" && npm ci --omit=dev --no-audit --no-fund >>"$LOG" 2>&1) || { log "npm ci failed"; return 1; } + systemctl restart "$SERVICE" || { log "restart failed"; return 1; } +} + +install_sha() { + local src + for f in "${FILES[@]}"; do + case "$f" in worker.js) src="worker/worker.js" ;; *) src="$f" ;; esac + git -C "$REPO" show "$SHA:$src" > "$APP_DIR/$f.new" || { log "could not read $src at $SHA"; return 1; } + done + for f in "${FILES[@]}"; do mv -f "$APP_DIR/$f.new" "$APP_DIR/$f"; done + echo "$SHA" > "$APP_DIR/VERSION" + restart +} + +log "deploying worker $SHA (previous $PREV)" +if install_sha && healthy "$SHA"; then + log "deployed worker $SHA: connected" + exit 0 +fi + +log "FAILED: worker $SHA did not reconnect; restoring $PREV" +rm -f "$APP_DIR"/*.new "$APP_DIR/VERSION" +for f in "${FILES[@]}" VERSION; do + if [ -e "$BACKUP/$f" ]; then cp -p "$BACKUP/$f" "$APP_DIR/$f"; fi +done +if restart && { [ "$PREV" = unknown ] || healthy "$PREV"; }; then + log "restored $PREV" +else + log "RESTORE FAILED: check journalctl -u $SERVICE" +fi +exit 1 diff --git a/server.js b/server.js index 8537461..d18ae93 100644 --- a/server.js +++ b/server.js @@ -656,10 +656,13 @@ wss.on('connection', (ws, req) => { } clearTimeout(ws.identifyTimer); ws.isWorker = true; + // Reported by the worker (#40); only a commit sha is accepted, anything else is 'unknown'. + ws.workerVersion = typeof message.version === 'string' && /^[0-9a-f]{40}$/.test(message.version) + ? message.version : 'unknown'; // Move from browser set to worker set browserClients.delete(ws); workerClients.add(ws); - console.log(`Worker connected: ${worker_name} (${worker_id})`); + console.log(`Worker connected: ${worker_name} (${worker_id}), version ${ws.workerVersion}`); // Find the database worker ID by name const [dbWorkers] = await pool.query( @@ -1352,7 +1355,11 @@ app.get('/healthz', async (req, res) => { ]); db = true; } catch { /* reported as db: false */ } - const connectedWorkers = new Set([...workers.values()].map(w => w.dbWorkerId).filter(Boolean)).size; + const live = [...new Set([...workers.values()].filter(w => w.dbWorkerId))]; + const connectedWorkers = new Set(live.map(w => w.dbWorkerId)).size; + // Commits of the connected workers (public repo, so not sensitive): lets the + // worker deploy confirm the new code is the one that reconnected (#40). + const workerVersions = [...new Set(live.map(w => w.workerVersion || 'unknown'))].sort(); res.set('Cache-Control', 'no-store'); res.status(db ? 200 : 503).json({ status: db ? 'ok' : 'degraded', @@ -1360,6 +1367,7 @@ app.get('/healthz', async (req, res) => { sha: GIT_SHA, db, workers: connectedWorkers, + worker_versions: workerVersions, uptime_s: Math.round(process.uptime()) }); }); diff --git a/tests/integration/auth.int.js b/tests/integration/auth.int.js index fe7b8d3..2922159 100644 --- a/tests/integration/auth.int.js +++ b/tests/integration/auth.int.js @@ -25,7 +25,7 @@ describe('HTTP', () => { test('the public health check reveals no detail beyond status', async () => { const r = await api('GET', '/healthz'); expect(r.status).toBe(200); - expect(Object.keys(r.json).sort()).toEqual(['db', 'sha', 'status', 'uptime_s', 'version', 'workers']); + expect(Object.keys(r.json).sort()).toEqual(['db', 'sha', 'status', 'uptime_s', 'version', 'worker_versions', 'workers']); }); }); diff --git a/tests/integration/reliability.int.js b/tests/integration/reliability.int.js index 8259745..ed35145 100644 --- a/tests/integration/reliability.int.js +++ b/tests/integration/reliability.int.js @@ -1,7 +1,7 @@ 'use strict'; // Executions always reach a final state (#7), and a final state is final. -const { sso, gandalf, startWorker, waitForExecution, commandResult, sleep, waitFor, workerByName } = require('./helpers'); +const { api, sso, gandalf, startWorker, waitForExecution, commandResult, sleep, waitFor, workerByName } = require('./helpers'); const unique = () => `int-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`; @@ -60,3 +60,10 @@ test('an aborted execution stays failed when the worker reports back later', asy expect((ex.logs || []).some(l => l.action === 'command_result' && l.success)).toBe(false); } finally { await w.stop(); } }); + +test('/healthz reports the commit each connected worker runs (#40)', async () => { + const head = require('child_process').execFileSync('git', ['rev-parse', 'HEAD'], { cwd: __dirname }).toString().trim(); + const { json } = await api('GET', '/healthz'); + // The stack's workers run from this checkout, so they report its HEAD. + expect(json.worker_versions).toEqual([head]); +}); diff --git a/tests/worker-deploy-script.test.js b/tests/worker-deploy-script.test.js new file mode 100644 index 0000000..88c6a97 --- /dev/null +++ b/tests/worker-deploy-script.test.js @@ -0,0 +1,130 @@ +'use strict'; + +// Runs deploy/pulse_worker_deploy.sh in a sandbox: a throwaway git origin, an app +// directory, and fake systemctl/npm/curl on PATH. The fake systemctl "starts" the +// worker by recording the VERSION it would report; a worker.js containing BROKEN +// never reconnects, so the fake /healthz lists no version for it. + +const { execFileSync, spawnSync } = require('child_process'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const SCRIPT = path.join(__dirname, '..', 'deploy', 'pulse_worker_deploy.sh'); +let root, app, env, commits; + +function sh(cwd, ...args) { + return execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim(); +} +function commit(repo, name, files) { + for (const [f, c] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(repo, f)), { recursive: true }); + fs.writeFileSync(path.join(repo, f), c); + } + sh(repo, 'add', '-A'); + sh(repo, '-c', 'user.name=t', '-c', 'user.email=t@example.invalid', 'commit', '-qm', name); + return sh(repo, 'rev-parse', 'HEAD'); +} +function deploy(sha, ts = Math.floor(Date.now() / 1000)) { + const r = spawnSync('bash', [SCRIPT, sha, String(ts)], { env, encoding: 'utf8' }); + return { code: r.status, out: r.stdout + r.stderr }; +} +const read = f => fs.readFileSync(path.join(app, f), 'utf8'); +const running = () => fs.readFileSync(path.join(root, 'running'), 'utf8').trim(); +const manifests = { 'package.json': '{"name":"pulse-server"}', 'package-lock.json': '{}' }; + +beforeAll(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-worker-deploy-')); + const work = path.join(root, 'work'); + const origin = path.join(root, 'origin.git'); + app = path.join(root, 'app'); + const bin = path.join(root, 'bin'); + [work, app, bin].forEach(d => fs.mkdirSync(d)); + + sh(root, 'init', '-q', '--bare', '-b', 'main', origin); + sh(root, 'init', '-q', '-b', 'main', work); + sh(work, 'remote', 'add', 'origin', origin); + commits = {}; + commits.a = commit(work, 'a', { 'worker/worker.js': 'v-a', 'server.js': 's', ...manifests }); + commits.b = commit(work, 'b', { 'worker/worker.js': 'v-b' }); + commits.broken = commit(work, 'broken', { 'worker/worker.js': 'v-c BROKEN' }); + commits.fixed = commit(work, 'fixed', { 'worker/worker.js': 'v-d' }); + sh(work, 'push', '-q', 'origin', 'main'); + sh(work, 'checkout', '-q', '-b', 'side', commits.a); + commits.side = commit(work, 'side', { 'worker/worker.js': 'v-side' }); + sh(work, 'push', '-q', 'origin', 'side'); + + // The hand-installed worker before the first automated deploy: no VERSION file. + fs.writeFileSync(path.join(app, 'worker.js'), 'hand-installed'); + fs.writeFileSync(path.join(app, '.env'), 'WORKER_API_KEY=keep-me\n'); + fs.writeFileSync(path.join(root, 'running'), ''); + + const fake = (name, body) => fs.writeFileSync(path.join(bin, name), `#!/bin/bash\n${body}\n`, { mode: 0o755 }); + fake('npm', 'exit 0'); + fake('systemctl', `if grep -q BROKEN "${app}/worker.js"; then : > "${root}/running"; else cat "${app}/VERSION" > "${root}/running" 2>/dev/null || : > "${root}/running"; fi`); + fake('curl', `v=$(cat "${root}/running"); if [ -n "$v" ]; then echo "{\\"workers\\":1,\\"worker_versions\\":[\\"$v\\"]}"; else echo '{"workers":0,"worker_versions":[]}'; fi`); + + env = { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + PULSE_WORKER_APP_DIR: app, + PULSE_WORKER_REPO_URL: origin, + PULSE_WORKER_STATE_DIR: path.join(root, 'state'), + PULSE_WORKER_LOG: path.join(root, 'deploy.log'), + PULSE_WORKER_LOCK: path.join(root, 'lock'), + PULSE_WORKER_HEALTH_TRIES: '3', + PULSE_WORKER_HEALTH_SLEEP: '0', + }; +}); + +afterAll(() => { if (process.env.KEEP) console.log(fs.readFileSync(path.join(root, 'deploy.log'), 'utf8')); fs.rmSync(root, { recursive: true, force: true }); }); + +// Order matters: each test builds on the state the previous one left. +test('replaces a hand-installed worker with exactly the requested commit', () => { + const r = deploy(commits.b); + expect(r.code).toBe(0); + expect(r.out).toMatch(/previous unknown/); + expect(read('worker.js')).toBe('v-b'); + expect(read('VERSION').trim()).toBe(commits.b); + expect(read('package-lock.json')).toBe('{}'); + expect(read('.env')).toBe('WORKER_API_KEY=keep-me\n'); // config is never touched + expect(running()).toBe(commits.b); +}); + +test('a replayed request is refused', () => { + const ts = Math.floor(Date.now() / 1000) + 5; + expect(deploy(commits.fixed, ts).code).toBe(0); + const r = deploy(commits.b, ts); + expect(r.code).toBe(1); + expect(r.out).toMatch(/replay or out of order/); + expect(read('VERSION').trim()).toBe(commits.fixed); +}); + +test('a stale request and malformed input are refused', () => { + expect(deploy(commits.b, Math.floor(Date.now() / 1000) - 3600).out).toMatch(/old \(limit 300s\)/); + expect(deploy('abc', Math.floor(Date.now() / 1000) + 6).out).toMatch(/invalid sha/); + expect(deploy(commits.b, 'x').out).toMatch(/invalid timestamp/); +}); + +test('a commit that is not on main is refused', () => { + const r = deploy(commits.side, Math.floor(Date.now() / 1000) + 10); + expect(r.code).toBe(1); + expect(r.out).toMatch(/is not on main|not found after fetch/); + expect(read('worker.js')).toBe('v-d'); +}); + +test('redeploying the running commit does nothing', () => { + const r = deploy(commits.fixed, Math.floor(Date.now() / 1000) + 15); + expect(r.code).toBe(0); + expect(r.out).toMatch(/nothing to do/); +}); + +test('a worker that never reconnects is rolled back to the previous files', () => { + const r = deploy(commits.broken, Math.floor(Date.now() / 1000) + 20); + expect(r.code).toBe(1); + expect(r.out).toMatch(/did not reconnect; restoring/); + expect(r.out).toMatch(/restored /); + expect(read('worker.js')).toBe('v-d'); + expect(read('VERSION').trim()).toBe(commits.fixed); + expect(running()).toBe(commits.fixed); +}); diff --git a/tests/worker.test.js b/tests/worker.test.js index f3a4b28..c6a9970 100644 --- a/tests/worker.test.js +++ b/tests/worker.test.js @@ -88,3 +88,28 @@ test('results are not sent while disconnected', () => { w.sendResult({ type: 'command_result' }); expect(send).not.toHaveBeenCalled(); }); + +describe('detectVersion (#40)', () => { + const fs = require('fs'); + const os = require('os'); + const path = require('path'); + const { detectVersion } = require('../worker/worker'); + const sha = 'a'.repeat(40); + let dir; + beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-worker-version-')); }); + afterEach(() => fs.rmSync(dir, { recursive: true, force: true })); + + test('reads the VERSION file the deploy writes', () => { + fs.writeFileSync(path.join(dir, 'VERSION'), `${sha}\n`); + expect(detectVersion(dir)).toBe(sha); + }); + + test('ignores a VERSION file that is not a commit sha', () => { + fs.writeFileSync(path.join(dir, 'VERSION'), 'v1.2.3; rm -rf /\n'); + expect(detectVersion(dir)).toBe('unknown'); // and dir is not a git checkout + }); + + test('falls back to the git checkout it runs from', () => { + expect(detectVersion(path.join(__dirname, '..', 'worker'))).toMatch(/^[0-9a-f]{40}$/); + }); +}); diff --git a/worker/worker.js b/worker/worker.js index 4f86a85..764e26e 100644 --- a/worker/worker.js +++ b/worker/worker.js @@ -8,6 +8,24 @@ require('dotenv').config(); const execAsync = promisify(exec); +// 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'; + } +} + class PulseWorker { constructor() { this.workerId = crypto.randomUUID(); @@ -17,6 +35,7 @@ class PulseWorker { 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.ws = null; this.heartbeatTimer = null; @@ -25,6 +44,7 @@ class PulseWorker { 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 @@ -60,7 +80,8 @@ class PulseWorker { uptime: os.uptime(), loadavg: os.loadavg(), activeTasks: this.activeTasks, - maxConcurrentTasks: this.maxConcurrentTasks + maxConcurrentTasks: this.maxConcurrentTasks, + version: this.version }; try { @@ -101,7 +122,8 @@ class PulseWorker { type: 'worker_connect', worker_id: this.workerId, worker_name: this.workerName, - api_key: this.apiKey + api_key: this.apiKey, + version: this.version })); }); @@ -256,7 +278,7 @@ class PulseWorker { } } -module.exports = { PulseWorker }; +module.exports = { PulseWorker, detectVersion }; // Start only when run directly (node worker.js), so tests can load the class. if (require.main === module) {