Merge pull request 'Worker deploys from CI, with version reporting' (#54) from worker-deploy into main
CI / Test (jest) (push) Successful in 53s
CI / Security (npm audit) (push) Successful in 53s
CI / Integration (api) (push) Successful in 1m46s
CI / Scan (secrets, workflows, shell) (push) Successful in 1m50s
CI / Lint (eslint) (push) Successful in 40s
CI / UI (playwright) (push) Successful in 2m4s
CI / Deploy (push) Successful in 25s
CI / Deploy worker (push) Successful in 31s
CI / Notify (push) Successful in 4s

This commit was merged in pull request #54.
This commit is contained in:
jared committed 2026-11-22 18:58:06 -05:00
commit e167e2f3b8
9 files changed
+439 -10

No files matched your search

+67 -2
View File
@@ -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
+51 -1
View File
@@ -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 <sha> <ts>`, 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": "<WORKER_WEBHOOK_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. ⚡
+122
View File
@@ -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> <ts>
# 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 <sha>, 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 <sha>.
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 <sha>: the server lists <sha> 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
+10 -2
View File
@@ -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())
});
});
+1 -1
View File
@@ -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']);
});
});
+8 -1
View File
@@ -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]);
});
+130
View File
@@ -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);
});
+25
View File
@@ -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}$/);
});
});
+25 -3
View File
@@ -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) {