Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5a4333a8e | ||
|
|
a34867af92 | ||
|
|
4459ce46cc | ||
|
|
783d6db160 | ||
|
|
c35eb82631 | ||
|
|
9980663f83 | ||
|
|
41480bf30a | ||
|
|
57a6cf72ce | ||
|
|
74eb525413 |
No files matched your search
+52
-5
@@ -9,15 +9,62 @@
|
||||
"sourceType": "commonjs"
|
||||
},
|
||||
"rules": {
|
||||
"no-unused-vars": "warn",
|
||||
"no-empty": "warn",
|
||||
"no-constant-condition": "warn",
|
||||
"no-useless-escape": "warn",
|
||||
"semi": [
|
||||
"error",
|
||||
"always"
|
||||
],
|
||||
"eqeqeq": "warn"
|
||||
"no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
"args": "after-used",
|
||||
"argsIgnorePattern": "^_",
|
||||
"caughtErrors": "none"
|
||||
}
|
||||
],
|
||||
"no-empty": [
|
||||
"error",
|
||||
{
|
||||
"allowEmptyCatch": true
|
||||
}
|
||||
],
|
||||
"no-constant-condition": [
|
||||
"error",
|
||||
{
|
||||
"checkLoops": false
|
||||
}
|
||||
],
|
||||
"no-useless-escape": "error",
|
||||
"eqeqeq": [
|
||||
"error",
|
||||
"always",
|
||||
{
|
||||
"null": "ignore"
|
||||
}
|
||||
],
|
||||
"prefer-const": "error",
|
||||
"curly": [
|
||||
"error",
|
||||
"multi-line"
|
||||
],
|
||||
"no-eval": "error",
|
||||
"no-implied-eval": "error",
|
||||
"no-new-func": "error",
|
||||
"no-throw-literal": "error",
|
||||
"no-useless-catch": "error",
|
||||
"no-prototype-builtins": "error",
|
||||
"no-shadow": [
|
||||
"error",
|
||||
{
|
||||
"builtinGlobals": false
|
||||
}
|
||||
],
|
||||
"no-unused-expressions": [
|
||||
"error",
|
||||
{
|
||||
"allowShortCircuit": true,
|
||||
"allowTernary": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
|
||||
+65
-3
@@ -61,7 +61,17 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- name: Audit production and dev dependencies
|
||||
run: npm audit --audit-level=high
|
||||
run: |
|
||||
# Retry only when the registry itself fails (it has returned spurious 400s);
|
||||
# a real advisory fails at once.
|
||||
for attempt in 1 2 3; do
|
||||
if out=$(npm audit --audit-level=high 2>&1); then echo "$out"; exit 0; fi
|
||||
echo "$out"
|
||||
echo "$out" | grep -q "audit endpoint returned an error" || exit 1
|
||||
echo "npm registry error (attempt $attempt); retrying in 20s"
|
||||
sleep 20
|
||||
done
|
||||
exit 1
|
||||
- name: Software bill of materials (production dependencies)
|
||||
run: npm sbom --sbom-format cyclonedx --omit dev --package-lock-only > sbom.cdx.json
|
||||
- name: Keep the SBOM for each main build
|
||||
@@ -121,6 +131,8 @@ jobs:
|
||||
run: actionlint .gitea/workflows/*.yml
|
||||
- name: Shell scripts (shellcheck)
|
||||
run: git ls-files -z '*.sh' | xargs -0 shellcheck
|
||||
- name: Vendored design system matches upstream
|
||||
run: scripts/ci/check-web-template.sh
|
||||
- name: Code patterns (semgrep)
|
||||
# Rule packs come from the semgrep registry, so new rules can surface new
|
||||
# findings: fix them, or suppress one line with `nosemgrep: <rule id>` and a reason.
|
||||
@@ -167,6 +179,55 @@ jobs:
|
||||
test-results/
|
||||
retention-days: 14
|
||||
|
||||
ui-screenshots:
|
||||
name: UI screenshots (before/after)
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'pull_request'
|
||||
container: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||
env:
|
||||
DB_HOST: 127.0.0.1
|
||||
DB_PORT: '3306'
|
||||
DB_NAME: pulse
|
||||
DB_USER: pulse
|
||||
DB_PASSWORD: ci-only
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Did this PR change the UI?
|
||||
id: ui
|
||||
run: |
|
||||
if git diff --quiet "$BASE_SHA" HEAD -- public/ views/ lib/render.js lib/nav.js; then
|
||||
echo "No UI files changed; no screenshots needed."
|
||||
else
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Start MariaDB
|
||||
if: steps.ui.outputs.changed == 'true'
|
||||
run: |
|
||||
scripts/ci/mariadb.sh
|
||||
mariadb -e "CREATE DATABASE pulse_base; GRANT ALL ON pulse_base.* TO 'pulse'@'127.0.0.1';"
|
||||
- name: Start this PR's Pulse (port 8400)
|
||||
if: steps.ui.outputs.changed == 'true'
|
||||
run: npm ci && scripts/ci/ui-stack.sh start
|
||||
- name: Start the base branch's Pulse (port 8401)
|
||||
if: steps.ui.outputs.changed == 'true'
|
||||
run: |
|
||||
git worktree add /tmp/base "$BASE_SHA"
|
||||
cd /tmp/base && npm ci
|
||||
DB_NAME=pulse_base PULSE_UI_PORT=8401 scripts/ci/ui-stack.sh start
|
||||
- name: Capture before/after screenshots
|
||||
if: steps.ui.outputs.changed == 'true'
|
||||
run: node scripts/ci/screenshots.js ui-screenshots before=http://127.0.0.1:8401 after=http://127.0.0.1:8400
|
||||
- name: Upload screenshots
|
||||
if: steps.ui.outputs.changed == 'true'
|
||||
uses: actions/upload-artifact@c6a3b2bd78b3985e4b2f15397fec357f0fd808de # v3.2.2-node20 (v4 is unsupported on Gitea)
|
||||
with:
|
||||
name: ui-screenshots
|
||||
path: ui-screenshots/
|
||||
retention-days: 30
|
||||
|
||||
deploy:
|
||||
name: Deploy
|
||||
runs-on: ubuntu-latest
|
||||
@@ -245,7 +306,8 @@ jobs:
|
||||
GIT_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
# Restarting the worker briefly interrupts Gandalf's commands, so only
|
||||
# deploy when worker code or its dependencies changed (#40).
|
||||
# deploy when worker code or its dependencies changed (#40). The lockfile
|
||||
# changes with every dependency change; package.json alone (scripts) doesn't matter.
|
||||
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}"
|
||||
@@ -253,7 +315,7 @@ jobs:
|
||||
[ -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
|
||||
|| ! git diff --quiet "$v" "$GIT_SHA" -- worker/ package-lock.json; then
|
||||
deploy=true
|
||||
fi
|
||||
done
|
||||
|
||||
@@ -586,12 +586,13 @@ Everything runs from `.gitea/workflows/ci.yml`:
|
||||
|
||||
| Job | What it does | When |
|
||||
|---|---|---|
|
||||
| `Lint (eslint)` | `npm run lint`, plus a check that fails on em or en dashes anywhere in the repo, including the vendored design system | Every push and PR |
|
||||
| `Lint (eslint)` | `npm run lint` (errors on bugs-in-waiting such as `==`, shadowed or unused variables and `eval`; no warnings allowed), plus a check that fails on em or en dashes anywhere in the repo, including the vendored design system | Every push and PR |
|
||||
| `Test (jest)` | `npm test`: unit tests for `lib/` and the worker, and the deploy-script sandbox tests. Fails if coverage drops below the floors in `package.json` (`lib/` 90% lines, `worker/` 40%) | Every push and PR |
|
||||
| `Security (npm audit)` | `npm audit --audit-level=high`, plus a CycloneDX SBOM of production dependencies (kept 90 days as the `sbom-cyclonedx` artifact of each `main` build) | Every push and PR, and weekly (Monday 06:00) |
|
||||
| `Scan (secrets, workflows, shell)` | gitleaks over the whole git history, actionlint on the workflow files (with shellcheck on their scripts), shellcheck on every `*.sh`, and semgrep (JavaScript, Node.js, Express, secrets and security-audit rule packs). Suppress a reviewed false positive on its line with `nosemgrep: <rule id>` and a comment saying why | Every push and PR |
|
||||
| `Scan (secrets, workflows, shell)` | gitleaks over the whole git history, actionlint on the workflow files (with shellcheck on their scripts), shellcheck on every `*.sh`, a check that `public/web_template` is byte-identical to upstream at the commit in its `VERSION`, and semgrep (JavaScript, Node.js, Express, secrets and security-audit rule packs). Suppress a reviewed false positive on its line with `nosemgrep: <rule id>` and a comment saying why | Every push and PR |
|
||||
| `Integration (api)` | Starts the real server and three workers on Node 20 against MariaDB, then runs `tests/integration/` over HTTP and WebSocket: the Gandalf API contract, HTTP and WebSocket auth, and execution reliability (worker crash, capacity, abort) | Every push and PR |
|
||||
| `UI (playwright)` | Starts the real server and three workers against a MariaDB service container, then runs the Playwright tests in `tests/ui/` (desktop and phone) | Every push and PR |
|
||||
| `UI screenshots (before/after)` | On PRs that touch `public/`, `views/` or the render/nav code: runs the base branch and the PR side by side with the same seeded data and uploads a `ui-screenshots` artifact with one before/after image per page (desktop and phone). Pages that came out identical are listed in `unchanged.txt`. Not a required check; attach the relevant images to the PR for review | Pull requests |
|
||||
| `Deploy` | Calls the `pulse-deploy` webhook on CT 122, waits until `/healthz` reports the tested commit, then tags it `deploy-*` | Push to `main`, only after all six checks pass |
|
||||
| `Notify` | Matrix alert on any failure on `main` or in the weekly audit, and on every deploy | As needed |
|
||||
|
||||
@@ -607,12 +608,26 @@ use it: Gandalf's submit-and-poll contract (`/api/internal/command`, `/api/inter
|
||||
SSO and worker-key auth on HTTP and on the WebSocket upgrade, forged results from a browser socket,
|
||||
and that executions always finish (a worker killed mid-command, a worker at capacity, an abort
|
||||
followed by a late result). Tests that need to kill or limit a worker start their own.
|
||||
The workflow engine (execute, parse, route, prompt, params, dry run, loop detection, abort) and the
|
||||
scheduler are covered too; the scheduler tests make a schedule due by setting `next_run` in the
|
||||
database, and the stack ticks the scheduler every second (`PULSE_SCHEDULER_TICK_MS`). Known bugs are
|
||||
written as `test.failing` with their issue number: when a fix lands, the test starts failing until
|
||||
the marker is removed.
|
||||
|
||||
```bash
|
||||
DB_HOST=127.0.0.1 DB_PORT=3399 DB_USER=pulse DB_PASSWORD=... DB_NAME=pulse scripts/ci/ui-stack.sh start
|
||||
npm run test:integration
|
||||
```
|
||||
|
||||
### Design system
|
||||
|
||||
`public/web_template/` is vendored from LotusGuild/web_template; never edit it here (CI checks it is
|
||||
byte-identical to upstream). Change the design system upstream, then vendor it:
|
||||
|
||||
```bash
|
||||
scripts/sync-web-template.sh <path-to-web_template-checkout>
|
||||
```
|
||||
|
||||
### UI tests
|
||||
|
||||
The Playwright tests drive the real UI end to end: every page loads with no page errors, console
|
||||
@@ -671,7 +686,7 @@ The only worker today is `pulse-worker-01` (LXC CT 153 on monitor-01, 10.10.10.1
|
||||
`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
|
||||
(`worker_versions` in `/healthz`). Only if `worker/` or `package-lock.json` (any dependency change) 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:
|
||||
|
||||
@@ -703,12 +718,19 @@ and add a hook to `/etc/webhook/hooks.json`, with the same secret as the repo's
|
||||
{ "source": "payload", "name": "ts" }
|
||||
],
|
||||
"trigger-rule": {
|
||||
"match": { "type": "payload-hmac-sha256", "secret": "<WORKER_WEBHOOK_SECRET>",
|
||||
"parameter": { "source": "header", "name": "X-Gitea-Signature" } }
|
||||
"and": [
|
||||
{ "match": { "type": "payload-hmac-sha256", "secret": "<WORKER_WEBHOOK_SECRET>",
|
||||
"parameter": { "source": "header", "name": "X-Gitea-Signature" } } },
|
||||
{ "match": { "type": "ip-whitelist", "ip-range": "10.10.10.70/32" } }
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Both Pulse hooks (`pulse-deploy` on CT 122 and `pulse-worker-deploy` on CT 153) only accept requests
|
||||
from the CI runner, 10.10.10.70, as well as requiring the signature. If the runner's address changes,
|
||||
deploys fail in CI (the verify step times out) until the `ip-range` is updated on both hosts.
|
||||
|
||||
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).
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"test": "jest --coverage",
|
||||
"lint": "eslint --ext .js .",
|
||||
"lint": "eslint --ext .js --max-warnings 0 .",
|
||||
"test:ui": "playwright test",
|
||||
"test:integration": "jest --config tests/integration/jest.config.js"
|
||||
},
|
||||
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# Fails if public/web_template/{base.css,base.js} differ from LotusGuild/web_template at
|
||||
# the commit recorded in public/web_template/VERSION. Change the design system upstream,
|
||||
# then vendor it with scripts/sync-web-template.sh; never edit the copies here.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
DEST="$ROOT/public/web_template"
|
||||
UPSTREAM=${WEB_TEMPLATE_RAW_URL:-https://code.lotusguild.org/LotusGuild/web_template/raw/commit}
|
||||
|
||||
sha=$(awk '{print $2}' "$DEST/VERSION")
|
||||
[[ "$sha" =~ ^[0-9a-f]{7,40}$ ]] || { echo "::error::public/web_template/VERSION has no commit sha"; exit 1; }
|
||||
|
||||
tmp=$(mktemp -d)
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
status=0
|
||||
for f in base.css base.js; do
|
||||
curl -fsS --retry 2 --max-time 30 -o "$tmp/$f" "$UPSTREAM/$sha/$f"
|
||||
if cmp -s "$tmp/$f" "$DEST/$f"; then
|
||||
echo "$f matches web_template@$sha"
|
||||
else
|
||||
echo "::error::public/web_template/$f differs from web_template@$sha. Change it upstream and resync with scripts/sync-web-template.sh."
|
||||
diff -u "$tmp/$f" "$DEST/$f" | head -40 || true
|
||||
status=1
|
||||
fi
|
||||
done
|
||||
exit $status
|
||||
@@ -0,0 +1,126 @@
|
||||
'use strict';
|
||||
/* eslint-env node, browser */
|
||||
|
||||
// Before/after screenshots for UI pull requests (#45 phase 5).
|
||||
//
|
||||
// node scripts/ci/screenshots.js <out-dir> before=<url> after=<url>
|
||||
//
|
||||
// Seeds the same demo data into each running Pulse stack (scripts/ci/ui-stack.sh),
|
||||
// captures every page on desktop and on a phone, then composes one side-by-side
|
||||
// image per page and viewport (<page>-<viewport>.png), rendered in the browser so
|
||||
// no image tooling is needed. Pages that look identical are listed in unchanged.txt.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { chromium, devices } = require('@playwright/test');
|
||||
|
||||
const SSO = {
|
||||
'Remote-User': 'ci.screens',
|
||||
'Remote-Name': 'CI Screens',
|
||||
'Remote-Email': 'ci@example.invalid',
|
||||
'Remote-Groups': 'admin,employee',
|
||||
};
|
||||
const PAGES = ['/', '/workers', '/workflows', '/executions', '/quick', '/scheduler'];
|
||||
const VIEWPORTS = {
|
||||
desktop: { viewport: { width: 1440, height: 900 } },
|
||||
phone: { ...devices['Pixel 7'] },
|
||||
};
|
||||
const isLocal = url => /^(https?|wss?):\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(url);
|
||||
|
||||
async function api(base, method, url, body) {
|
||||
const res = await fetch(base + url, {
|
||||
method,
|
||||
headers: { ...SSO, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
return res.ok ? res.json().catch(() => ({})) : null;
|
||||
}
|
||||
|
||||
// The same data on both sides, so differences come from the code, not the data.
|
||||
async function seed(base) {
|
||||
const workers = (await api(base, 'GET', '/api/workers')) || [];
|
||||
for (const w of workers) {
|
||||
await api(base, 'POST', `/api/workers/${w.id}/command`, { command: `echo hello from ${w.name}` });
|
||||
}
|
||||
if (workers[0]) await api(base, 'POST', `/api/workers/${workers[0].id}/command`, { command: 'echo oops >&2; exit 2' });
|
||||
await api(base, 'POST', '/api/workflows', {
|
||||
name: 'Node health check',
|
||||
description: 'Uptime and disk on every worker',
|
||||
definition: { steps: [
|
||||
{ id: 'uptime', name: 'Uptime', type: 'execute', command: 'uptime', targets: ['all'] },
|
||||
{ id: 'disk', name: 'Disk', type: 'execute', command: 'df -h / | tail -1', targets: ['all'] },
|
||||
] },
|
||||
});
|
||||
await new Promise(r => setTimeout(r, 3000)); // let the commands finish
|
||||
}
|
||||
|
||||
async function capture(browser, label, base, dir) {
|
||||
const shots = {};
|
||||
for (const [vp, opts] of Object.entries(VIEWPORTS)) {
|
||||
// reducedMotion instead of injected CSS: Pulse's CSP rightly blocks inline styles.
|
||||
const ctx = await browser.newContext({ ...opts, extraHTTPHeaders: SSO, reducedMotion: 'reduce' });
|
||||
await ctx.route(u => !isLocal(u.href), r => r.abort());
|
||||
await ctx.addInitScript(() => {
|
||||
try { localStorage.setItem('lt_theme', 'dark'); sessionStorage.setItem('lt_boot', '1'); } catch (e) { /* ignore */ }
|
||||
});
|
||||
const page = await ctx.newPage();
|
||||
for (const p of PAGES) {
|
||||
await page.goto(base + p);
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.waitForTimeout(500);
|
||||
const name = (p === '/' ? 'dashboard' : p.slice(1)) + '-' + vp;
|
||||
const file = path.join(dir, `${label}-${name}.png`);
|
||||
await page.screenshot({ path: file, fullPage: true });
|
||||
shots[name] = file;
|
||||
}
|
||||
await ctx.close();
|
||||
}
|
||||
return shots;
|
||||
}
|
||||
|
||||
async function compose(browser, name, before, after, out) {
|
||||
const b64 = f => 'data:image/png;base64,' + fs.readFileSync(f).toString('base64');
|
||||
const html = `<!doctype html><meta charset="utf-8"><style>
|
||||
body{margin:0;background:#0b0e14;color:#ddd;font:16px monospace}
|
||||
.row{display:flex;gap:16px;padding:16px;align-items:flex-start}
|
||||
.col{flex:1;min-width:0} h2{margin:0 0 8px;font-size:16px}
|
||||
.b h2{color:#ff7878}.a h2{color:#78ffa0} img{width:100%;border:1px solid #333}
|
||||
</style><div class="row">
|
||||
<div class="col b"><h2>BEFORE (base) ${name}</h2><img src="${b64(before)}"></div>
|
||||
<div class="col a"><h2>AFTER (this PR) ${name}</h2><img src="${b64(after)}"></div>
|
||||
</div>`;
|
||||
const page = await browser.newPage({ viewport: { width: 1600, height: 800 } });
|
||||
await page.setContent(html);
|
||||
await page.screenshot({ path: out, fullPage: true });
|
||||
await page.close();
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const [outDir, ...targets] = process.argv.slice(2);
|
||||
const urls = Object.fromEntries(targets.map(t => t.split('=')));
|
||||
if (!outDir || !urls.before || !urls.after) {
|
||||
console.error('usage: screenshots.js <out-dir> before=<url> after=<url>');
|
||||
process.exit(2);
|
||||
}
|
||||
const raw = path.join(outDir, 'raw');
|
||||
fs.mkdirSync(raw, { recursive: true });
|
||||
|
||||
await Promise.all([seed(urls.before), seed(urls.after)]);
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
const before = await capture(browser, 'before', urls.before, raw);
|
||||
const after = await capture(browser, 'after', urls.after, raw);
|
||||
const unchanged = [];
|
||||
for (const name of Object.keys(after)) {
|
||||
if (before[name] && fs.readFileSync(before[name]).equals(fs.readFileSync(after[name]))) {
|
||||
unchanged.push(name);
|
||||
continue;
|
||||
}
|
||||
await compose(browser, name, before[name], after[name], path.join(outDir, `${name}.png`));
|
||||
console.log(`changed: ${name}`);
|
||||
}
|
||||
fs.writeFileSync(path.join(outDir, 'unchanged.txt'), unchanged.join('\n') + '\n');
|
||||
console.log(`unchanged: ${unchanged.length ? unchanged.join(', ') : 'none'}`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -25,6 +25,7 @@ export WORKER_API_KEY=ui-test-worker-key WORKER_AUTH_ENFORCE=1
|
||||
export GANDALF_API_KEY=ui-test-gandalf-key
|
||||
export SECRET_KEY=ui-test-secret EXECUTION_RETENTION_DAYS=30
|
||||
export PULSE_API_RATE_MAX=100000 PULSE_EXEC_RATE_MAX=100000 # one test client makes many requests
|
||||
export PULSE_SCHEDULER_TICK_MS=1000 # scheduler tests shouldn't wait a minute
|
||||
|
||||
stop() {
|
||||
for f in "$RUN"/*.pid; do
|
||||
|
||||
@@ -3,9 +3,7 @@ const http = require('http');
|
||||
const WebSocket = require('ws');
|
||||
const mysql = require('mysql2/promise');
|
||||
const crypto = require('crypto');
|
||||
const vm = require('vm');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const cronParser = require('cron-parser');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const helmet = require('helmet');
|
||||
@@ -383,8 +381,9 @@ async function processScheduledCommands() {
|
||||
|
||||
|
||||
if (!DEV_READONLY) {
|
||||
// Run scheduler every minute
|
||||
setInterval(processScheduledCommands, 60 * 1000);
|
||||
// Run scheduler every minute (tests shorten it with PULSE_SCHEDULER_TICK_MS, minimum 1 s)
|
||||
const tick = parseInt(process.env.PULSE_SCHEDULER_TICK_MS, 10);
|
||||
setInterval(processScheduledCommands, Number.isInteger(tick) && tick >= 1000 ? tick : 60 * 1000);
|
||||
// Initial run on startup
|
||||
setTimeout(processScheduledCommands, 5000);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
'use strict';
|
||||
|
||||
// The scheduler (processScheduledCommands in server.js). The test stack ticks every
|
||||
// second (PULSE_SCHEDULER_TICK_MS); a schedule is made due at once by setting its
|
||||
// next_run in the database, the one place these tests reach past the API.
|
||||
const mysql = require('mysql2/promise');
|
||||
const { api, sso, SSO, waitFor, waitForExecution, workerByName, commandResult, startWorker, sleep } = require('./helpers');
|
||||
|
||||
const unique = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
let db;
|
||||
|
||||
beforeAll(async () => {
|
||||
db = await mysql.createConnection({
|
||||
host: process.env.DB_HOST || '127.0.0.1',
|
||||
port: Number(process.env.DB_PORT || 3306),
|
||||
user: process.env.DB_USER || 'pulse',
|
||||
password: process.env.DB_PASSWORD || 'ci-only',
|
||||
database: process.env.DB_NAME || 'pulse',
|
||||
});
|
||||
});
|
||||
afterAll(() => db && db.end());
|
||||
|
||||
async function createSchedule(fields) {
|
||||
const r = await sso('POST', '/api/scheduled-commands', {
|
||||
name: `int ${unique()}`, schedule_type: 'interval', schedule_value: '60', ...fields,
|
||||
});
|
||||
return r;
|
||||
}
|
||||
const makeDue = id => db.query('UPDATE scheduled_commands SET next_run = NOW() - INTERVAL 1 SECOND WHERE id = ?', [id]);
|
||||
async function executionsOf(name) {
|
||||
const [rows] = await db.query('SELECT id, status FROM executions WHERE started_by = ? ORDER BY started_at', [`scheduler:${name}`]);
|
||||
return rows;
|
||||
}
|
||||
|
||||
test('a due schedule runs its command on its worker and moves next_run forward', async () => {
|
||||
const worker = await workerByName('node-02');
|
||||
const name = `int ${unique()}`;
|
||||
const created = await createSchedule({ name, command: 'echo scheduled-ok', worker_ids: [worker.id] });
|
||||
expect(created.status).toBe(200);
|
||||
await makeDue(created.json.id);
|
||||
|
||||
const [run] = await waitFor(async () => { const r = await executionsOf(name); return r.length ? r : null; },
|
||||
{ what: 'the scheduled execution' });
|
||||
const ex = await waitForExecution(run.id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(commandResult(ex).stdout.trim()).toBe('scheduled-ok');
|
||||
|
||||
const [[row]] = await db.query('SELECT next_run, last_run FROM scheduled_commands WHERE id = ?', [created.json.id]);
|
||||
expect(row.last_run).not.toBeNull();
|
||||
expect(new Date(row.next_run).getTime()).toBeGreaterThan(Date.now() + 50 * 60_000); // about 60 min ahead
|
||||
});
|
||||
|
||||
test('a disabled schedule does not run', async () => {
|
||||
const worker = await workerByName('node-02');
|
||||
const name = `int ${unique()}`;
|
||||
const created = await createSchedule({ name, command: 'echo nope', worker_ids: [worker.id] });
|
||||
const toggled = await sso('PUT', `/api/scheduled-commands/${created.json.id}/toggle`);
|
||||
expect(toggled.json.enabled).toBe(false);
|
||||
await makeDue(created.json.id);
|
||||
await sleep(3500); // several scheduler ticks
|
||||
expect(await executionsOf(name)).toEqual([]);
|
||||
});
|
||||
|
||||
test('only admins can create schedules, and bad input is refused', async () => {
|
||||
const worker = await workerByName('node-01');
|
||||
const asEmployee = await api('POST', '/api/scheduled-commands', {
|
||||
headers: { ...SSO, 'Remote-Groups': 'employee' },
|
||||
body: { name: 'x', command: 'true', worker_ids: [worker.id], schedule_type: 'interval', schedule_value: '5' },
|
||||
});
|
||||
expect(asEmployee.status).toBe(403);
|
||||
expect((await createSchedule({ command: 'true' })).status).toBe(400); // no workers
|
||||
expect((await createSchedule({ command: 'true', worker_ids: [worker.id], schedule_value: '-5' })).status).toBe(400);
|
||||
});
|
||||
|
||||
// Known bug: calculateNextRun throws on a bad cron expression, and the route answers 500.
|
||||
test.failing('an invalid cron expression is a 400, not a server error', async () => {
|
||||
const worker = await workerByName('node-01');
|
||||
const r = await createSchedule({ command: 'true', worker_ids: [worker.id], schedule_type: 'cron', schedule_value: 'not a cron' });
|
||||
expect(r.status).toBe(400);
|
||||
});
|
||||
|
||||
// Known bug #9: a schedule whose worker is offline is skipped silently, leaving no trace.
|
||||
test.failing('a schedule whose worker is offline records a failed run (#9)', async () => {
|
||||
const workerName = `int-sched-${unique()}`;
|
||||
const w = await startWorker(workerName);
|
||||
const name = `int ${unique()}`;
|
||||
try {
|
||||
const created = await createSchedule({ name, command: 'echo unreachable', worker_ids: [w.id] });
|
||||
w.child.kill('SIGKILL');
|
||||
await waitFor(async () => (await workerByName(workerName))?.status === 'offline', { what: 'the worker to go offline' });
|
||||
await makeDue(created.json.id);
|
||||
await sleep(3500);
|
||||
const runs = await executionsOf(name);
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs[0].status).toBe('failed');
|
||||
} finally { await w.stop(); }
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
'use strict';
|
||||
|
||||
// The workflow engine (executeWorkflowSteps in server.js), driven through the API
|
||||
// with real workers. Known bugs are written as test.failing: they document today's
|
||||
// behaviour and start failing (so the marker must be removed) once the bug is fixed.
|
||||
const { sso, waitFor, waitForExecution, sleep } = require('./helpers');
|
||||
|
||||
const unique = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
|
||||
async function createWorkflow(steps, extra = {}) {
|
||||
const r = await sso('POST', '/api/workflows', { name: `int ${unique()}`, definition: { steps, ...extra } });
|
||||
expect(r.status).toBe(200);
|
||||
return r.json.id;
|
||||
}
|
||||
async function start(workflowId, body = {}) {
|
||||
const r = await sso('POST', '/api/executions', { workflow_id: workflowId, ...body });
|
||||
expect(r.status).toBe(200);
|
||||
return r.json.id;
|
||||
}
|
||||
const logs = (ex, action) => (ex.logs || []).filter(l => l.action === action);
|
||||
const outputs = ex => logs(ex, 'command_result').map(l => (l.stdout || '').trim());
|
||||
|
||||
test('an execute step on all workers runs everywhere and completes', async () => {
|
||||
const marker = `all-${unique()}`;
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'hello', name: 'Hello', type: 'execute', command: `echo ${marker}`, targets: ['all'] },
|
||||
]));
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(outputs(ex).filter(o => o === marker)).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('a failing step fails the execution and stops the workflow', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'bad', type: 'execute', command: 'exit 3', targets: ['node-01'] },
|
||||
{ id: 'never', type: 'execute', command: 'echo should-not-run', targets: ['node-01'] },
|
||||
]));
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('failed');
|
||||
expect(outputs(ex)).not.toContain('should-not-run');
|
||||
});
|
||||
|
||||
test('parse reads KEY=VALUE output and route jumps on it', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'probe', type: 'execute', command: 'echo STATUS=degraded', targets: ['node-01'] },
|
||||
{ id: 'parse', type: 'parse' },
|
||||
{ id: 'decide', type: 'route', conditions: [
|
||||
{ if: "state.status === 'degraded'", goto: 'fix', label: 'needs fixing' },
|
||||
{ default: true, goto: 'end' },
|
||||
] },
|
||||
{ id: 'skipped', type: 'execute', command: 'echo not-me', targets: ['node-01'] },
|
||||
{ id: 'fix', type: 'execute', command: 'echo fixed', targets: ['node-01'] },
|
||||
]));
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(logs(ex, 'parse_complete')[0].parsed).toEqual({ status: 'degraded' });
|
||||
expect(logs(ex, 'route_taken')[0]).toMatchObject({ goto: 'fix', label: 'needs fixing' });
|
||||
expect(outputs(ex)).toContain('fixed');
|
||||
expect(outputs(ex)).not.toContain('not-me');
|
||||
});
|
||||
|
||||
test('a false condition skips the step', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'prod-only', type: 'execute', command: 'echo prod', targets: ['node-01'], condition: "params.env === 'prod'" },
|
||||
{ id: 'always', type: 'execute', command: 'echo always', targets: ['node-01'] },
|
||||
], { params: [{ name: 'env' }] }), { params: { env: 'staging' } });
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(logs(ex, 'step_skipped')).toHaveLength(1);
|
||||
expect(outputs(ex)).toEqual(['always']);
|
||||
});
|
||||
|
||||
test('a prompt waits for an answer, rejects invalid options, and routes on the answer', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'ask', type: 'prompt', message: 'Restart?', options: ['Yes', 'No'], key: 'answer', routes: { No: 'end' } },
|
||||
{ id: 'restart', type: 'execute', command: 'echo restarted', targets: ['node-02'] },
|
||||
]));
|
||||
await waitFor(async () => logs((await sso('GET', `/api/executions/${id}`)).json || {}, 'prompt').length > 0,
|
||||
{ what: 'the prompt to be asked' });
|
||||
|
||||
expect((await sso('POST', `/api/executions/${id}/respond`, { response: 'Maybe' })).status).toBe(400);
|
||||
expect((await sso('POST', `/api/executions/${id}/respond`, { response: 'Yes' })).status).toBe(200);
|
||||
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(logs(ex, 'prompt_response')[0]).toMatchObject({ response: 'Yes', responded_by: 'int.tester' });
|
||||
expect(outputs(ex)).toEqual(['restarted']);
|
||||
});
|
||||
|
||||
test('parameters are substituted, and unsafe values are refused', async () => {
|
||||
const wf = await createWorkflow([
|
||||
{ id: 'greet', type: 'execute', command: 'echo host={{host}}', targets: ['node-03'] },
|
||||
], { params: [{ name: 'host', required: true }] });
|
||||
|
||||
expect((await sso('POST', '/api/executions', { workflow_id: wf })).status).toBe(400); // required
|
||||
|
||||
const ok = await waitForExecution(await start(wf, { params: { host: 'db-01.lan' } }));
|
||||
expect(ok.status).toBe('completed');
|
||||
expect(outputs(ok)).toEqual(['host=db-01.lan']);
|
||||
|
||||
const bad = await waitForExecution(await start(wf, { params: { host: 'x; reboot' } }));
|
||||
expect(bad.status).toBe('failed');
|
||||
expect(outputs(bad)).toEqual([]);
|
||||
});
|
||||
|
||||
test('a dry run logs the commands without running them', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'danger', type: 'execute', command: 'echo would-run', targets: ['all'] },
|
||||
]), { dry_run: true });
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(logs(ex, 'dry_run_skipped')).toHaveLength(1);
|
||||
expect(logs(ex, 'command_result')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('an endless goto loop is detected and fails the execution', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'loop', type: 'route', conditions: [{ default: true, goto: 'loop' }] },
|
||||
]));
|
||||
const ex = await waitForExecution(id, { timeout: 60_000 });
|
||||
expect(ex.status).toBe('failed');
|
||||
expect(logs(ex, 'workflow_error')[0].error).toMatch(/Infinite loop/);
|
||||
});
|
||||
|
||||
test('an aborted execution stays failed', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'pause', type: 'wait', duration: 2 },
|
||||
{ id: 'after', type: 'execute', command: 'echo after-abort', targets: ['node-01'] },
|
||||
]));
|
||||
await sleep(500);
|
||||
expect((await sso('POST', `/api/executions/${id}/abort`)).status).toBe(200);
|
||||
await sleep(4000);
|
||||
const ex = (await sso('GET', `/api/executions/${id}`)).json;
|
||||
expect(ex.status).toBe('failed');
|
||||
});
|
||||
|
||||
// Known bug #8: abort marks the execution failed but the engine keeps going.
|
||||
test.failing('abort stops the workflow before its next step (#8)', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'pause', type: 'wait', duration: 2 },
|
||||
{ id: 'after', type: 'execute', command: 'echo after-abort', targets: ['node-01'] },
|
||||
]));
|
||||
await sleep(500);
|
||||
await sso('POST', `/api/executions/${id}/abort`);
|
||||
await sleep(5000);
|
||||
const ex = (await sso('GET', `/api/executions/${id}`)).json;
|
||||
expect(logs(ex, 'step_started').map(l => l.step)).toEqual([1]);
|
||||
});
|
||||
|
||||
// Known bug #20: a goto to a step that doesn't exist ends as 'completed'.
|
||||
test.failing('a goto to a missing step fails the execution (#20)', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
{ id: 'jump', type: 'route', conditions: [{ default: true, goto: 'no-such-step' }] },
|
||||
]));
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('failed');
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
jest.mock('../lib/render', () => ({
|
||||
renderError: jest.fn((req, res, status) => res.status(status).send('error page'))
|
||||
renderError: jest.fn((_req, response, status) => response.status(status).send('error page'))
|
||||
}));
|
||||
|
||||
const {
|
||||
|
||||
Reference in new issue
Block a user