Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d5b8cdd53 | ||
|
|
8b93c88f0f | ||
|
|
5bca0cd87b | ||
|
|
f97dcc7b2a | ||
|
|
e3d09020cc | ||
|
|
be6eaad1e9 | ||
|
|
cb12fec28c | ||
|
|
b10ea154dd | ||
|
|
6da2d15397 | ||
|
|
fde2c49eca | ||
|
|
c6f6b3f842 | ||
|
|
027dce7fd5 | ||
|
|
574e7ecc4f | ||
|
|
66d5240be0 | ||
|
|
8e77c1af0a | ||
|
|
071b4072c2 |
No files matched your search
+24
-4
@@ -1,13 +1,33 @@
|
||||
{
|
||||
"env": { "node": true, "es2021": true },
|
||||
"env": {
|
||||
"node": true,
|
||||
"es2021": true
|
||||
},
|
||||
"extends": "eslint:recommended",
|
||||
"parserOptions": { "ecmaVersion": 2021, "sourceType": "commonjs" },
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 2021,
|
||||
"sourceType": "commonjs"
|
||||
},
|
||||
"rules": {
|
||||
"no-unused-vars": "warn",
|
||||
"no-empty": "warn",
|
||||
"no-constant-condition": "warn",
|
||||
"no-useless-escape": "warn",
|
||||
"semi": ["error", "always"],
|
||||
"semi": [
|
||||
"error",
|
||||
"always"
|
||||
],
|
||||
"eqeqeq": "warn"
|
||||
}
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"tests/ui/**/*.js"
|
||||
],
|
||||
"env": {
|
||||
"browser": true,
|
||||
"node": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
name: CI
|
||||
|
||||
# One pipeline: lint, test, audit and the UI tests must all pass before main deploys (#45).
|
||||
# Actions are pinned to full commit SHAs (version in the trailing comment).
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
branches: ["**"]
|
||||
schedule:
|
||||
- cron: '0 6 * * 1' # weekly dependency audit against new advisories
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
# Node comes from each job's container image, not actions/setup-node: the runner
|
||||
# shares one tool cache volume between concurrent jobs, and parallel setup-node
|
||||
# runs overwrote each other's Node install mid-job. node:20 matches production
|
||||
# (CT 122) and the worker (CT 153).
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint (eslint)
|
||||
runs-on: ubuntu-latest
|
||||
container: node:20-bookworm
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- name: Install dependencies (lockfile only)
|
||||
run: npm ci
|
||||
- name: Run ESLint
|
||||
run: npm run lint
|
||||
- name: No em or en dashes (house style)
|
||||
run: |
|
||||
# Pulse-owned files only: the vendored design system is fixed upstream.
|
||||
if git grep -nP '[\x{2013}\x{2014}]|&[mn]dash;|\\u201[34]|̵[12];|ȁ[34];' \
|
||||
-- . ':!public/web_template' ':!package-lock.json'; then
|
||||
echo "::error::Em or en dashes found (listed above). Use a hyphen, colon, comma or 'to'."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
test:
|
||||
name: Test (jest)
|
||||
runs-on: ubuntu-latest
|
||||
container: node:20-bookworm
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- name: Install dependencies (lockfile only)
|
||||
run: npm ci
|
||||
- name: Run jest with coverage
|
||||
run: npm test -- --ci
|
||||
|
||||
audit:
|
||||
name: Security (npm audit)
|
||||
runs-on: ubuntu-latest
|
||||
container: node:20-bookworm
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- name: Audit production and dev dependencies
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
ui:
|
||||
name: UI (playwright)
|
||||
runs-on: ubuntu-latest
|
||||
# Official image with Chromium and its system libraries; its version must match
|
||||
# @playwright/test in package.json.
|
||||
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 # throwaway database inside the job container
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- name: Install dependencies (lockfile only)
|
||||
run: npm ci
|
||||
- name: Start MariaDB
|
||||
# Inside the job container: the runner puts jobs on Docker's default bridge
|
||||
# network, where service containers can't be reached by name.
|
||||
run: |
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends mariadb-server >/dev/null
|
||||
mkdir -p /run/mysqld && chown mysql:mysql /run/mysqld
|
||||
(mariadbd --user=mysql --bind-address=127.0.0.1 --port=3306 >/tmp/mariadb.log 2>&1 &)
|
||||
for i in $(seq 1 30); do mariadb-admin ping --silent && break; sleep 1; done
|
||||
mariadb -e "CREATE DATABASE pulse; CREATE USER 'pulse'@'127.0.0.1' IDENTIFIED BY 'ci-only'; GRANT ALL ON pulse.* TO 'pulse'@'127.0.0.1'"
|
||||
echo "node $(node --version), $(mariadb --version)"
|
||||
- name: Start Pulse with three workers
|
||||
run: scripts/ci/ui-stack.sh start
|
||||
- name: Run Playwright (desktop and mobile)
|
||||
run: npm run test:ui
|
||||
- name: Server and worker logs
|
||||
if: always()
|
||||
run: tail -n 200 .ui-stack/*.log || true
|
||||
- name: Upload report, traces and screenshots
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@c6a3b2bd78b3985e4b2f15397fec357f0fd808de # v3.2.2-node20 (v4 is unsupported on Gitea)
|
||||
with:
|
||||
name: playwright-report
|
||||
path: |
|
||||
playwright-report/
|
||||
test-results/
|
||||
retention-days: 14
|
||||
|
||||
deploy:
|
||||
name: Deploy
|
||||
runs-on: ubuntu-latest
|
||||
needs: [lint, test, audit, ui]
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
# Never run two deploys at once; queue instead of cancelling a deploy mid-way.
|
||||
concurrency:
|
||||
group: deploy-production
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
contents: write # deploy tag
|
||||
steps:
|
||||
- name: Trigger webhook
|
||||
env:
|
||||
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
|
||||
GIT_REF: ${{ github.ref }}
|
||||
GIT_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
# sha and timestamp make every signature unique; the server starts
|
||||
# verifying them in #45 phase 2 (until then it deploys origin/main).
|
||||
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.65:9000/hooks/pulse-deploy"
|
||||
|
||||
- name: Verify production runs this commit
|
||||
env:
|
||||
GIT_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
# The webhook returns at once; the server-side deploy script checks out
|
||||
# this exact sha, runs npm ci and restarts, and rolls back if /healthz
|
||||
# never reports it. Succeed only when production reports this sha with
|
||||
# a working database (up to 4 minutes, covering npm ci).
|
||||
for i 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 -q "\"sha\":\"${GIT_SHA}\"" && echo "$body" | grep -q '"db":true'; then
|
||||
echo "Production is healthy on ${GIT_SHA}: ${body}"
|
||||
exit 0
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
echo "::error::Production never reported ${GIT_SHA} as healthy (last /healthz: ${body:-no response}). The server rolls back automatically; see /var/log/pulse-deploy.log on CT 122."
|
||||
exit 1
|
||||
|
||||
- name: Tag deployed commit
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
TAG="deploy-$(date -u +%Y.%m.%d)-${{ github.run_number }}"
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token $GITHUB_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"${TAG}\",\"target\":\"${{ github.sha }}\",\"message\":\"Deployed to production\"}" \
|
||||
"https://code.lotusguild.org/api/v1/repos/${{ github.repository }}/tags"
|
||||
|
||||
notify:
|
||||
name: Notify
|
||||
runs-on: ubuntu-latest
|
||||
needs: [lint, test, audit, ui, deploy]
|
||||
# Alert on any failure on main or in the weekly audit, and on every deploy outcome.
|
||||
if: >-
|
||||
always() && (
|
||||
(failure() && (github.ref == 'refs/heads/main' || github.event_name == 'schedule')) ||
|
||||
needs.deploy.result == 'success'
|
||||
)
|
||||
steps:
|
||||
- name: Send Matrix alert
|
||||
env:
|
||||
MATRIX_WEBHOOK_URL: ${{ secrets.MATRIX_WEBHOOK_URL }}
|
||||
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 }} ui=${{ needs.ui.result }} deploy=${{ needs.deploy.result }}"
|
||||
DEPLOYED: ${{ needs.deploy.result == 'success' }}
|
||||
run: |
|
||||
if [ -z "$MATRIX_WEBHOOK_URL" ] || [ "$MATRIX_WEBHOOK_URL" = "CONFIGURE_ME" ]; then exit 0; fi
|
||||
if [ "$DEPLOYED" = "true" ]; then MSG="DEPLOYED: ${REPO} @ ${BRANCH} (${GITHUB_SHA:0:7})"; else MSG="CI FAILED: ${REPO} @ ${BRANCH} [${RESULTS}]"; fi
|
||||
curl -sf -X POST "$MATRIX_WEBHOOK_URL" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"text\":\"${MSG}: ${RUN_URL}\"}"
|
||||
@@ -1,71 +0,0 @@
|
||||
name: Lint
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
branches: ["**"]
|
||||
|
||||
jobs:
|
||||
js-lint:
|
||||
name: JS (eslint)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Install ESLint
|
||||
run: npm install --save-dev eslint@8
|
||||
|
||||
- name: Run ESLint
|
||||
run: npx eslint --ext .js .
|
||||
|
||||
notify-failure:
|
||||
name: Notify on failure
|
||||
runs-on: ubuntu-latest
|
||||
needs: [js-lint]
|
||||
if: failure() && github.event_name == 'push'
|
||||
steps:
|
||||
- name: Send Matrix alert
|
||||
env:
|
||||
MATRIX_WEBHOOK_URL: ${{ secrets.MATRIX_WEBHOOK_URL }}
|
||||
REPO: ${{ github.repository }}
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
if [ -z "$MATRIX_WEBHOOK_URL" ] || [ "$MATRIX_WEBHOOK_URL" = "CONFIGURE_ME" ]; then exit 0; fi
|
||||
curl -sf -X POST "$MATRIX_WEBHOOK_URL" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"text\":\"CI FAILED: ${REPO} @ ${BRANCH} — ${RUN_URL}\"}"
|
||||
|
||||
deploy:
|
||||
name: Deploy
|
||||
runs-on: ubuntu-latest
|
||||
needs: [js-lint]
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Trigger webhook
|
||||
env:
|
||||
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
|
||||
GIT_REF: ${{ github.ref }}
|
||||
run: |
|
||||
PAYLOAD="{\"ref\":\"${GIT_REF}\"}"
|
||||
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.65:9000/hooks/pulse-deploy"
|
||||
|
||||
- name: Tag deployed commit
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
TAG="deploy-$(date -u +%Y.%m.%d)-${{ github.run_number }}"
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token $GITHUB_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"${TAG}\",\"target\":\"${{ github.sha }}\",\"message\":\"Deployed to production\"}" \
|
||||
"https://code.lotusguild.org/api/v1/repos/${{ github.repository }}/tags"
|
||||
@@ -1,22 +0,0 @@
|
||||
name: Security
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
branches: ["**"]
|
||||
schedule:
|
||||
- cron: '0 6 * * 1'
|
||||
|
||||
jobs:
|
||||
npm-audit:
|
||||
name: JS Security (npm audit)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Run npm audit
|
||||
run: npm audit --audit-level=high
|
||||
@@ -1,20 +0,0 @@
|
||||
name: Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
branches: ["**"]
|
||||
|
||||
jobs:
|
||||
jest:
|
||||
name: JS Tests (jest)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Run jest
|
||||
run: npm test
|
||||
@@ -35,3 +35,6 @@ Thumbs.db
|
||||
Claude.md
|
||||
coverage/
|
||||
__pycache__/
|
||||
.ui-stack/
|
||||
test-results/
|
||||
playwright-report/
|
||||
@@ -8,7 +8,7 @@ A distributed workflow orchestration platform for managing and executing complex
|
||||
|
||||
> **Security Notice:** This repository is hosted on Gitea and is version-controlled. **Never commit secrets, credentials, passwords, API keys, or any sensitive information to this repo.** All sensitive configuration belongs exclusively in `.env` files which are listed in `.gitignore` and must never be committed. This includes database passwords, worker API keys, webhook secrets, and internal IP details.
|
||||
|
||||
**Design System**: [web_template](https://code.lotusguild.org/LotusGuild/web_template) — shared CSS, JS, and layout patterns for all LotusGuild apps
|
||||
**Design System**: [web_template](https://code.lotusguild.org/LotusGuild/web_template): shared CSS, JS, and layout patterns for all LotusGuild apps
|
||||
|
||||
## Styling & Layout
|
||||
|
||||
@@ -24,17 +24,17 @@ scripts/sync-web-template.sh <path-to-web_template-checkout>
|
||||
```
|
||||
|
||||
The script copies `base.css`/`base.js` as regular files (never symlinks) and rewrites `VERSION`.
|
||||
Never hand-edit `public/web_template/` — it is excluded from ESLint and overwritten on every sync.
|
||||
Never hand-edit `public/web_template/`: it is excluded from ESLint and overwritten on every sync.
|
||||
Pulse-local gaps in the design system live in `public/assets/app.css` (currently `.lt-modal-lg`,
|
||||
`.lt-field-error`, `.is-invalid`) and are candidates for upstreaming.
|
||||
|
||||
Reference documentation:
|
||||
|
||||
- [`web_template/README.md`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/README.md) — full component reference, CSS variables, JS API
|
||||
- [`web_template/base.css`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/base.css) — unified CSS (`.lt-*` classes)
|
||||
- [`web_template/base.js`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/base.js) — `window.lt` utilities (toast, modal, WebSocket helpers, fetch)
|
||||
- [`web_template/aesthetic_diff.md`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/aesthetic_diff.md) — cross-app divergence analysis and convergence guide
|
||||
- [`web_template/node/middleware.js`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/node/middleware.js) — Express auth, CSRF, CSP nonce middleware
|
||||
- [`web_template/README.md`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/README.md): full component reference, CSS variables, JS API
|
||||
- [`web_template/base.css`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/base.css): unified CSS (`.lt-*` classes)
|
||||
- [`web_template/base.js`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/base.js): `window.lt` utilities (toast, modal, WebSocket helpers, fetch)
|
||||
- [`web_template/aesthetic_diff.md`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/aesthetic_diff.md): cross-app divergence analysis and convergence guide
|
||||
- [`web_template/node/middleware.js`](https://code.lotusguild.org/LotusGuild/web_template/src/branch/main/node/middleware.js): Express auth, CSRF, CSP nonce middleware
|
||||
|
||||

|
||||
|
||||
@@ -122,7 +122,7 @@ WebSocket, the single 30 s auto-refresh) and each page module registers itself w
|
||||
Pulse.registerPage({ name, init(), refresh(), onEvent(type, data) /* return true if handled */ });
|
||||
```
|
||||
|
||||
Page modules never attach their own listeners for UI actions — they register handlers under their
|
||||
Page modules never attach their own listeners for UI actions: they register handlers under their
|
||||
own action prefix (`dash:`, `wk:`, `wf:`, `ex:`, `qc:`, `sc:`) and the markup wires them up with
|
||||
`data-action` / `data-change-action` / `data-input-action` / `data-submit-action` attributes that
|
||||
`app.js` delegates. DOM ids are likewise prefixed per page. All dynamic strings go through
|
||||
@@ -476,7 +476,7 @@ PULSE_DEV_READONLY=1 PORT=8099 HOST=127.0.0.1 npm start
|
||||
dev instance can never mutate shared state behind your back: stale-execution recovery at startup,
|
||||
the old-execution cleanup job (startup call and interval), the scheduled-command processor
|
||||
(startup call and interval), and the stale-worker offline sweep. Each skip is logged at startup
|
||||
alongside a `PULSE_DEV_READONLY IS ON` banner. The guard covers background jobs only — API routes
|
||||
alongside a `PULSE_DEV_READONLY IS ON` banner. The guard covers background jobs only: API routes
|
||||
still write, so avoid destructive actions in the UI when you are pointed at production data.
|
||||
|
||||
**Worker (.env):**
|
||||
@@ -582,17 +582,70 @@ MIT License - See LICENSE file for details
|
||||
|
||||
## CI / CD
|
||||
|
||||
| Workflow | Purpose | Triggers |
|
||||
Everything runs from `.gitea/workflows/ci.yml`:
|
||||
|
||||
| Job | What it does | When |
|
||||
|---|---|---|
|
||||
| `lint.yml` | ESLint on all `.js` files | Every push and PR |
|
||||
| `test.yml` | Jest unit tests (`lib/utils.js`) | Every push and PR |
|
||||
| `security.yml` | `npm audit --audit-level=high` | Every push, PR, and weekly Monday 6am |
|
||||
| `deploy` job in `lint.yml` | Calls the `pulse-deploy` webhook on CT122 (10.10.10.65) to pull + restart | Push to `main` only, after lint passes |
|
||||
| `Lint (eslint)` | `npm run lint`, plus a check that fails on em or en dashes in Pulse-owned files | Every push and PR |
|
||||
| `Test (jest)` | `npm test`: unit tests for `lib/` and the deploy-script sandbox tests | Every push and PR |
|
||||
| `Security (npm audit)` | `npm audit --audit-level=high` | Every push and PR, and weekly (Monday 06:00) |
|
||||
| `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 |
|
||||
| `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 four checks pass |
|
||||
| `Notify` | Matrix alert on any failure on `main` or in the weekly audit, and on every deploy | As needed |
|
||||
|
||||
Branch protection is enabled on `main` — the `lint.yml` check must pass before any PR can merge.
|
||||
Branch protection on `main` requires `CI / Lint (eslint) (push)`, `CI / Test (jest) (push)`,
|
||||
`CI / Security (npm audit) (push)` and `CI / UI (playwright) (push)`. Actions are pinned to commit
|
||||
SHAs and builds use `npm ci`. The plan for the rest of the pipeline is tracked in #45.
|
||||
|
||||
Tests live in `tests/utils.test.js` and cover the pure utility functions in `lib/utils.js`:
|
||||
`validateWebhookUrl`, `applyParams`, `evalCondition`, `calculateNextRun`.
|
||||
### UI tests
|
||||
|
||||
The Playwright tests drive the real UI end to end: every page loads with no page errors, console
|
||||
errors or failed requests; commands typed into Quick Command run on a worker and their output appears
|
||||
in Executions; workflows are created and run from the UI; live updates arrive over the WebSocket;
|
||||
pages without an SSO identity are refused; and every page fits a phone screen. Any UI fix should come
|
||||
with a test here.
|
||||
|
||||
Run them locally against a throwaway database (see "Local development against a real database" for
|
||||
one way to start MariaDB):
|
||||
|
||||
```bash
|
||||
npx playwright install chromium # once
|
||||
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:ui # add --ui or --headed to watch
|
||||
scripts/ci/ui-stack.sh stop
|
||||
```
|
||||
|
||||
On a CI failure, the `playwright-report` artifact has the HTML report, traces and screenshots.
|
||||
|
||||
### Deploys
|
||||
|
||||
CI sends an HMAC-signed payload `{"ref", "sha", "ts"}` to the webhook on CT 122. The webhook runs
|
||||
`deploy/pulse_deploy.sh <sha> <ts>`, which:
|
||||
|
||||
1. refuses requests signed more than 5 minutes ago, or not newer than the last accepted one (replays);
|
||||
2. refuses commits that aren't on `main`;
|
||||
3. checks out exactly that commit, runs `npm ci --omit=dev` and restarts `pulse`;
|
||||
4. waits for `GET /healthz` to report that commit with a working database, and otherwise
|
||||
**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.
|
||||
|
||||
**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:
|
||||
|
||||
```bash
|
||||
install -m 755 /opt/pulse-server/deploy/pulse_deploy.sh /usr/local/bin/pulse_deploy.sh
|
||||
```
|
||||
|
||||
The `pulse-deploy` hook in `/etc/webhook/hooks.json` passes the signed values as arguments:
|
||||
|
||||
```json
|
||||
"pass-arguments-to-command": [
|
||||
{ "source": "payload", "name": "sha" },
|
||||
{ "source": "payload", "name": "ts" }
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
Executable
+96
@@ -0,0 +1,96 @@
|
||||
#!/bin/bash
|
||||
# Pulse production deploy (#45 phase 2), run by the webhook listener on CT 122.
|
||||
#
|
||||
# Source of truth: deploy/pulse_deploy.sh in the Pulse repo.
|
||||
# Installed copy: /usr/local/bin/pulse_deploy.sh (install it from the repo; see README "Deploys").
|
||||
#
|
||||
# Usage: pulse_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, so they can't be altered. The
|
||||
# timestamp makes every signature unique: stale or replayed requests are refused.
|
||||
#
|
||||
# Deploys exactly <sha>, then waits for /healthz to report that sha with a working
|
||||
# database. Otherwise it rolls back to the previous commit.
|
||||
set -euo pipefail
|
||||
|
||||
# Overridable only so tests can run the script in a sandbox.
|
||||
APP_ROOT=${PULSE_DEPLOY_APP_ROOT:-/opt/pulse-server}
|
||||
BRANCH=main
|
||||
STATE_DIR=${PULSE_DEPLOY_STATE_DIR:-/var/lib/pulse-deploy}
|
||||
LOG=${PULSE_DEPLOY_LOG:-/var/log/pulse-deploy.log}
|
||||
LOCK=${PULSE_DEPLOY_LOCK:-/run/pulse-deploy.lock}
|
||||
HEALTH_URL=${PULSE_DEPLOY_HEALTH_URL:-http://127.0.0.1:8080/healthz}
|
||||
MAX_AGE_S=300 # refuse requests signed more than 5 minutes ago
|
||||
HEALTH_TRIES=${PULSE_DEPLOY_HEALTH_TRIES:-45} # x 2 s = 90 s for the new process to report healthy
|
||||
|
||||
log() { echo "$(date '+%F %T') [pulse-deploy] $*" | tee -a "$LOG"; }
|
||||
fail() { log "REFUSED: $*"; exit 1; }
|
||||
|
||||
SHA="${1:-}"
|
||||
TS="${2:-}"
|
||||
|
||||
# One deploy at a time (CI also queues deploys, this covers manual runs).
|
||||
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"
|
||||
|
||||
cd "$APP_ROOT"
|
||||
git fetch --quiet origin "$BRANCH"
|
||||
git cat-file -e "${SHA}^{commit}" 2>/dev/null || fail "commit $SHA not found after fetch"
|
||||
git merge-base --is-ancestor "$SHA" "origin/$BRANCH" || fail "commit $SHA is not on $BRANCH"
|
||||
|
||||
PREV=$(git rev-parse HEAD)
|
||||
|
||||
deploy_to() {
|
||||
# .env and node_modules are untracked, so a forced checkout leaves .env alone.
|
||||
# Explicit returns: `set -e` does not apply inside a function used in an `if`.
|
||||
git checkout --quiet --force --detach "$1" || { log "checkout of $1 failed"; return 1; }
|
||||
npm ci --omit=dev --no-audit --no-fund >>"$LOG" 2>&1 || { log "npm ci failed for $1"; return 1; }
|
||||
systemctl restart pulse || { log "restart failed for $1"; return 1; }
|
||||
}
|
||||
|
||||
healthy() {
|
||||
local want="$1" body
|
||||
for _ in $(seq 1 "$HEALTH_TRIES"); do
|
||||
if body=$(curl -fsS --max-time 3 "$HEALTH_URL" 2>/dev/null) \
|
||||
&& grep -q "\"sha\":\"$want\"" <<<"$body" \
|
||||
&& grep -q '"db":true' <<<"$body"; then
|
||||
return 0
|
||||
fi
|
||||
sleep "${PULSE_DEPLOY_HEALTH_SLEEP:-2}"
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
if [ "$PREV" = "$SHA" ] && healthy "$SHA"; then
|
||||
log "already running $SHA and healthy; nothing to do"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "deploying $SHA (previous $PREV)"
|
||||
if deploy_to "$SHA" && healthy "$SHA"; then
|
||||
echo "$SHA" > "$STATE_DIR/current"
|
||||
log "deployed $SHA: healthy"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "FAILED: $SHA did not become healthy; rolling back to $PREV"
|
||||
if deploy_to "$PREV" && healthy "$PREV"; then
|
||||
log "rolled back to $PREV: healthy"
|
||||
else
|
||||
log "ROLLBACK FAILED: check journalctl -u pulse"
|
||||
fi
|
||||
exit 1
|
||||
+1
-1
@@ -105,7 +105,7 @@ function makeAuthenticatePage(pool) {
|
||||
|
||||
if (!identity) {
|
||||
return renderError(req, res, 401, 'Not authenticated',
|
||||
'Not authenticated — access via Authelia SSO (auth.lotusguild.org).');
|
||||
'Not authenticated. Sign in through Authelia SSO (auth.lotusguild.org).');
|
||||
}
|
||||
|
||||
const { username: remoteUser, name: remoteName, email: remoteEmail, groups } = identity;
|
||||
|
||||
+2
-2
@@ -78,14 +78,14 @@ function renderError(req, res, status, title, message) {
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>${esc(status)} — ${esc(APP_NAME)}</title>
|
||||
<title>${esc(status)} | ${esc(APP_NAME)}</title>
|
||||
<link rel="stylesheet" href="/web_template/base.css?v=${esc(assetVersion)}">
|
||||
</head>
|
||||
<body>
|
||||
<main class="lt-main lt-container">
|
||||
<div class="lt-frame">
|
||||
<div class="lt-alert lt-alert--error">
|
||||
<strong>${esc(status)} — ${esc(title)}</strong>
|
||||
<strong>${esc(status)}: ${esc(title)}</strong>
|
||||
<p>${esc(message)}</p>
|
||||
</div>
|
||||
<p><a class="lt-btn lt-btn-secondary lt-btn-sm" href="/">Return to dashboard</a></p>
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ function evalCondition(condition, state, params) {
|
||||
const context = vm.createContext({ state, params, promptResponse: state.promptResponse });
|
||||
return !!vm.runInNewContext(condition, context, { timeout: 100 });
|
||||
} catch (e) {
|
||||
console.warn(`[Workflow] evalCondition error (treated as false): ${e.message} — condition: ${condition}`);
|
||||
console.warn(`[Workflow] evalCondition error (treated as false): ${e.message} (condition: ${condition})`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
// WebSocket upgrade authentication (issue #38).
|
||||
//
|
||||
// Every connection is classified once, at the HTTP upgrade:
|
||||
// browser — came through the trusted proxy with an Authelia identity in an allowed group;
|
||||
// browser: came through the trusted proxy with an Authelia identity in an allowed group;
|
||||
// receives the live event feed.
|
||||
// worker — presented the worker key at the handshake (Authorization: Bearer <key>).
|
||||
// pending — neither, accepted only while WORKER_AUTH_ENFORCE is off so that workers
|
||||
// worker: presented the worker key at the handshake (Authorization: Bearer <key>).
|
||||
// pending: neither, accepted only while WORKER_AUTH_ENFORCE is off so that workers
|
||||
// which predate handshake auth can still identify with worker_connect.
|
||||
// Gets no events and may send nothing but worker_connect.
|
||||
// reject — refused with 401 before the upgrade completes.
|
||||
// reject: refused with 401 before the upgrade completes.
|
||||
|
||||
const crypto = require('crypto');
|
||||
const { ssoIdentity, ALLOWED_GROUPS } = require('./pageauth');
|
||||
|
||||
Generated
+83
-30
@@ -20,8 +20,12 @@
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "1.64.1",
|
||||
"eslint": "^8.57.1",
|
||||
"jest": "^30.5.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/code-frame": {
|
||||
@@ -1128,9 +1132,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@jest/reporters/node_modules/glob": {
|
||||
"version": "13.0.6",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
|
||||
"integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
|
||||
"version": "13.0.7",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.7.tgz",
|
||||
"integrity": "sha512-wfsFgXQ8A3SEI9XGf7Nl3Y9l7ffSrGh7SUCT7vU/2CzYPep9kjxAn1S40F9OPKxAMGCVl7HtNlJhrCJUeUq83g==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
@@ -1701,6 +1705,22 @@
|
||||
"url": "https://opencollective.com/pkgr"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.64.1",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz",
|
||||
"integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.64.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@sinclair/typebox": {
|
||||
"version": "0.34.52",
|
||||
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz",
|
||||
@@ -2366,9 +2386,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/babel-plugin-istanbul": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-8.0.0.tgz",
|
||||
"integrity": "sha512-18wCskrN3DgbuBmp1gr7LBGT8xdz5xhQQqFvFhVxbkl8VBCrMKQ2YtqBWtUal1Zrc1HTuX0011+Brjw78TCFkg==",
|
||||
"version": "8.0.2",
|
||||
"resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-8.0.2.tgz",
|
||||
"integrity": "sha512-bXWZeWQvvCZcD2uHLWVbitr4s1+YqILBbWB/szXKtHXt6crLlD6mqxHZ0qWy2X/Xx5RtQvqqW80JHAXMlp+y1Q==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"workspaces": [
|
||||
@@ -2461,18 +2481,18 @@
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
|
||||
"integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz",
|
||||
"integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "^3.1.2",
|
||||
"content-type": "^2.0.0",
|
||||
"content-type": "^2.1.0",
|
||||
"debug": "^4.4.3",
|
||||
"http-errors": "^2.0.1",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"iconv-lite": "^0.7.3",
|
||||
"on-finished": "^2.4.1",
|
||||
"qs": "^6.15.2",
|
||||
"qs": "^6.16.1",
|
||||
"raw-body": "^3.0.2",
|
||||
"type-is": "^2.1.0"
|
||||
},
|
||||
@@ -3528,9 +3548,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/follow-redirects": {
|
||||
"version": "1.16.1",
|
||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz",
|
||||
"integrity": "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==",
|
||||
"version": "1.16.3",
|
||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz",
|
||||
"integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
@@ -4004,9 +4024,9 @@
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ip-address": {
|
||||
"version": "10.7.3",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz",
|
||||
"integrity": "sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==",
|
||||
"version": "10.7.6",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz",
|
||||
"integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
@@ -4408,9 +4428,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/glob": {
|
||||
"version": "13.0.6",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
|
||||
"integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
|
||||
"version": "13.0.7",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.7.tgz",
|
||||
"integrity": "sha512-wfsFgXQ8A3SEI9XGf7Nl3Y9l7ffSrGh7SUCT7vU/2CzYPep9kjxAn1S40F9OPKxAMGCVl7HtNlJhrCJUeUq83g==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
@@ -4734,9 +4754,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/jest-runtime/node_modules/glob": {
|
||||
"version": "13.0.6",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
|
||||
"integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
|
||||
"version": "13.0.7",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.7.tgz",
|
||||
"integrity": "sha512-wfsFgXQ8A3SEI9XGf7Nl3Y9l7ffSrGh7SUCT7vU/2CzYPep9kjxAn1S40F9OPKxAMGCVl7HtNlJhrCJUeUq83g==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
@@ -5648,6 +5668,35 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.64.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz",
|
||||
"integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.64.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.64.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
|
||||
"integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/prelude-ls": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
|
||||
@@ -5687,9 +5736,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-addr": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
||||
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
|
||||
"version": "2.0.8",
|
||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
|
||||
"integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"forwarded": "0.2.0",
|
||||
@@ -5697,6 +5746,10 @@
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-from-env": {
|
||||
@@ -5735,9 +5788,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.16.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
|
||||
"integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
|
||||
"version": "6.17.1",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz",
|
||||
"integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"es-define-property": "^1.0.1",
|
||||
|
||||
+7
-1
@@ -2,9 +2,14 @@
|
||||
"name": "pulse-server",
|
||||
"version": "1.0.0",
|
||||
"main": "server.js",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"test": "jest --coverage"
|
||||
"test": "jest --coverage",
|
||||
"lint": "eslint --ext .js .",
|
||||
"test:ui": "playwright test"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
@@ -22,6 +27,7 @@
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "1.64.1",
|
||||
"eslint": "^8.57.1",
|
||||
"jest": "^30.5.2"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
// Playwright UI tests (#45 phase 5). They expect a running Pulse stack with three
|
||||
// workers: scripts/ci/ui-stack.sh starts one. Files are *.ui.js so jest skips them.
|
||||
const { defineConfig, devices } = require('@playwright/test');
|
||||
|
||||
const CI = !!process.env.CI;
|
||||
|
||||
module.exports = defineConfig({
|
||||
testDir: 'tests/ui',
|
||||
testMatch: '**/*.ui.js',
|
||||
// One shared database and real workers: run serially so tests can't race each other.
|
||||
workers: 1,
|
||||
fullyParallel: false,
|
||||
forbidOnly: CI,
|
||||
retries: CI ? 1 : 0,
|
||||
timeout: 30_000,
|
||||
expect: { timeout: 10_000 },
|
||||
reporter: CI ? [['list'], ['html', { open: 'never' }]] : 'list',
|
||||
use: {
|
||||
baseURL: process.env.PULSE_UI_URL || 'http://127.0.0.1:8400',
|
||||
trace: 'retain-on-failure',
|
||||
screenshot: 'only-on-failure',
|
||||
},
|
||||
projects: [
|
||||
{ name: 'desktop', use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } },
|
||||
{ name: 'mobile', use: { ...devices['Pixel 7'] }, testMatch: '**/responsive.ui.js' },
|
||||
],
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
/* =====================================================================
|
||||
PULSE — shell additions on top of /web_template/base.css
|
||||
PULSE: shell additions on top of /web_template/base.css
|
||||
---------------------------------------------------------------------
|
||||
Rules here are Pulse-specific only. No `.lt-*` base rule is redefined;
|
||||
`.lt-*` selectors appear only as ancestors/descendants of a `.pulse-*`
|
||||
@@ -8,7 +8,7 @@
|
||||
===================================================================== */
|
||||
|
||||
/* ---------------------------------------------------------------------
|
||||
1. Header right cluster — WS status, last-refreshed stamp, buttons
|
||||
1. Header right cluster: WS status, last-refreshed stamp, buttons
|
||||
--------------------------------------------------------------------- */
|
||||
.pulse-header-right,
|
||||
.lt-header-right:has(#pulse-ws-status) {
|
||||
@@ -59,7 +59,7 @@
|
||||
|
||||
/* ---------------------------------------------------------------------
|
||||
3. Compact meta line (base.css already provides .lt-kv-grid for
|
||||
key/value blocks — use that; this is only for inline meta strings)
|
||||
key/value blocks: use that; this is only for inline meta strings)
|
||||
--------------------------------------------------------------------- */
|
||||
.pulse-meta {
|
||||
display: flex;
|
||||
@@ -79,7 +79,7 @@
|
||||
.pulse-meta-val { color: var(--text-secondary); }
|
||||
|
||||
/* ---------------------------------------------------------------------
|
||||
4. Log viewer wrapper — caps the height of a long .lt-log-output run
|
||||
4. Log viewer wrapper: caps the height of a long .lt-log-output run
|
||||
--------------------------------------------------------------------- */
|
||||
.pulse-log {
|
||||
max-height: 420px;
|
||||
@@ -101,7 +101,7 @@
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------
|
||||
5. Running rows — amber left-border pulse (port of exec-running-pulse)
|
||||
5. Running rows: amber left-border pulse (port of exec-running-pulse)
|
||||
--------------------------------------------------------------------- */
|
||||
.pulse-running {
|
||||
border-left: 2px solid var(--accent-amber);
|
||||
@@ -133,13 +133,13 @@
|
||||
/* ---------------------------------------------------------------------
|
||||
7. Shared component gap-fillers (base.css does not ship these)
|
||||
---------------------------------------------------------------------
|
||||
`.lt-modal-lg` — base.css ships .lt-modal-xs/.lt-modal-sm only, but
|
||||
`.lt-modal-lg`: base.css ships .lt-modal-xs/.lt-modal-sm only, but
|
||||
several Pulse pages need a wide modal (JSON editors, log viewers,
|
||||
side-by-side compare). Sized the same way base.css sizes its own
|
||||
modifiers, and re-capped at the two breakpoints base.css caps
|
||||
`.lt-modal` at, because this selector is more specific than those.
|
||||
|
||||
`.lt-field-error` / `.is-invalid` — base.css references a field-error
|
||||
`.lt-field-error` / `.is-invalid`: base.css references a field-error
|
||||
hook but ships no visual style for it.
|
||||
Both are candidates for upstreaming into base.css.
|
||||
--------------------------------------------------------------------- */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* =====================================================================
|
||||
PULSE — shared frontend shell (WP-B)
|
||||
PULSE: shared frontend shell (WP-B)
|
||||
---------------------------------------------------------------------
|
||||
Loaded after /web_template/base.js and before /assets/pages/<page>.js.
|
||||
Exposes the frozen `window.Pulse` contract consumed by page modules.
|
||||
@@ -18,7 +18,7 @@
|
||||
const resp = await _fetch.apply(window, args);
|
||||
if (resp.status === 401) {
|
||||
window.location.reload();
|
||||
throw new Error('Session expired — reloading');
|
||||
throw new Error('Session expired, reloading');
|
||||
}
|
||||
return resp;
|
||||
};
|
||||
@@ -163,7 +163,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* Verbatim localStorage keys — `commandHistory` and `pulse_executionView`
|
||||
/* Verbatim localStorage keys: `commandHistory` and `pulse_executionView`
|
||||
must keep working across the redesign, so NO prefix is applied. */
|
||||
const storage = {
|
||||
get(key, fallback) {
|
||||
@@ -364,7 +364,7 @@
|
||||
settle(result);
|
||||
}
|
||||
/* ESC and backdrop clicks are handled globally by base.js, which fires
|
||||
lt:modalclose — treat both as a cancel. */
|
||||
lt:modalclose: treat both as a cancel. */
|
||||
el.addEventListener('lt:modalclose', () => finish(false));
|
||||
return finish;
|
||||
}
|
||||
@@ -550,7 +550,7 @@
|
||||
onMessage: handleWsMessage,
|
||||
});
|
||||
} else {
|
||||
warn('lt.ws unavailable — using raw WebSocket fallback');
|
||||
warn('lt.ws unavailable: using raw WebSocket fallback');
|
||||
_wsHandle = connectRawWs();
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -627,7 +627,7 @@
|
||||
initPage();
|
||||
|
||||
/* The ONLY autoRefresh registration in the whole app. Page modules must
|
||||
never call lt.autoRefresh — they get refreshed through page.refresh(). */
|
||||
never call lt.autoRefresh: they get refreshed through page.refresh(). */
|
||||
try {
|
||||
if (LT().autoRefresh) LT().autoRefresh.start(() => refreshNow(), 30000);
|
||||
} catch (e) { err('autoRefresh start failed', e); }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* Dashboard page (WP-C) — recent executions / workers summary layout. */
|
||||
/* Dashboard page (WP-C): recent executions / workers summary layout. */
|
||||
.dash-worker-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* =====================================================================
|
||||
PULSE — Dashboard page (WP-C)
|
||||
PULSE: Dashboard page (WP-C)
|
||||
Owns DOM id prefix `dash-` and action namespace `dash:*`.
|
||||
===================================================================== */
|
||||
'use strict';
|
||||
@@ -51,7 +51,7 @@
|
||||
const startedBy = esc(e.started_by || '');
|
||||
const startedAt = fmt.dateTime(e.started_at);
|
||||
const isRunning = String(e.status || '').toLowerCase() === 'running';
|
||||
const elapsed = isRunning ? esc(fmt.elapsed(e.started_at)) : '—';
|
||||
const elapsed = isRunning ? esc(fmt.elapsed(e.started_at)) : '-';
|
||||
return (
|
||||
'<tr data-action="dash:open-execution" data-execution-id="' + esc(e.id) + '">' +
|
||||
'<td data-label="Status"><span class="' + statusClass + '">' + statusText + '</span></td>' +
|
||||
@@ -124,7 +124,7 @@
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------
|
||||
Live tick — update elapsed times on running rows and worker last-seen
|
||||
Live tick: update elapsed times on running rows and worker last-seen
|
||||
------------------------------------------------------------------- */
|
||||
function onTick() {
|
||||
document.querySelectorAll('#dash-executions-wrap .dash-elapsed[data-started-at]').forEach(el => {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/* =====================================================================
|
||||
PULSE — Executions page (WP-E) styles
|
||||
PULSE: Executions page (WP-E) styles
|
||||
---------------------------------------------------------------------
|
||||
Only additions the design system does not already provide. Everything
|
||||
is namespaced `.ex-*` or scoped under an `#ex-*` id, except the two
|
||||
log-entry colour modifiers that extend `.lt-log-entry` (base.css ships
|
||||
.success/.warning/.error only — grey and cyan are Pulse-local).
|
||||
.success/.warning/.error only: grey and cyan are Pulse-local).
|
||||
===================================================================== */
|
||||
|
||||
/* ---------------------------------------------------------------------
|
||||
1. Modal sizing — width comes from the shared `.lt-modal-lg` rule in
|
||||
1. Modal sizing: width comes from the shared `.lt-modal-lg` rule in
|
||||
/assets/app.css; only the scroll behaviour of these two modals is
|
||||
page-specific.
|
||||
--------------------------------------------------------------------- */
|
||||
@@ -62,7 +62,7 @@
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------
|
||||
4. Log entries — extra colour semantics on top of base.css
|
||||
4. Log entries: extra colour semantics on top of base.css
|
||||
--------------------------------------------------------------------- */
|
||||
.lt-log-entry.ex-log-dim {
|
||||
border-left-color: var(--border-color);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* =====================================================================
|
||||
PULSE — Executions page (WP-E)
|
||||
PULSE: Executions page (WP-E)
|
||||
---------------------------------------------------------------------
|
||||
Owns DOM ids prefixed `ex-` and the `ex:*` action namespace.
|
||||
Loaded after /web_template/base.js and /assets/app.js.
|
||||
@@ -106,7 +106,7 @@
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
Rendering — list
|
||||
Rendering: list
|
||||
------------------------------------------------------------------ */
|
||||
function filteredRows(view) {
|
||||
const term = searchTerm();
|
||||
@@ -127,7 +127,7 @@
|
||||
if (!st.loaded) return '';
|
||||
/* Manual is a straight server-side filter, so `total` is exact.
|
||||
Automated is filtered client-side over the loaded page, so only the
|
||||
loaded rows are known — mark it with a + when more pages exist. */
|
||||
loaded rows are known: mark it with a + when more pages exist. */
|
||||
if (view === 'manual') return '(' + st.total + ')';
|
||||
return '(' + st.rows.length + (st.hasMore ? '+' : '') + ')';
|
||||
}
|
||||
@@ -150,7 +150,7 @@
|
||||
: (running
|
||||
? '<span class="ex-elapsed" data-ex-elapsed="' + esc(e.started_at) + '">' +
|
||||
esc(Pulse.fmt.elapsed(e.started_at)) + '</span>'
|
||||
: '—');
|
||||
: '-');
|
||||
|
||||
return '<tr class="' + cls.join(' ') + '" data-action="' + action + '"' +
|
||||
' data-execution-id="' + esc(e.id) + '" tabindex="0">' +
|
||||
@@ -239,7 +239,7 @@
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
Live elapsed (driven by the shared 1 s tick — never our own timer)
|
||||
Live elapsed (driven by the shared 1 s tick, never our own timer)
|
||||
------------------------------------------------------------------ */
|
||||
function tickElapsed() {
|
||||
const nodes = document.querySelectorAll('[data-ex-elapsed]');
|
||||
@@ -249,7 +249,7 @@
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
Log entry formatting — all 21 known actions plus a fallback.
|
||||
Log entry formatting: all 21 known actions plus a fallback.
|
||||
Colour semantics map onto base.css: .success (green), .warning (amber),
|
||||
.error (red), plus the page-local .ex-log-dim (grey) and .ex-log-info
|
||||
(cyan) modifiers defined in executions.css.
|
||||
@@ -427,7 +427,7 @@
|
||||
'<div class="lt-kv-key">Started</div><div class="lt-kv-val">' + esc(Pulse.fmt.dateTime(ex.started_at)) + '</div>' +
|
||||
'<div class="lt-kv-key">Completed</div><div class="lt-kv-val">' +
|
||||
(ex.completed_at ? esc(Pulse.fmt.dateTime(ex.completed_at))
|
||||
: (ex.status === 'running' ? esc(Pulse.fmt.elapsed(ex.started_at)) + ' elapsed' : '—')) +
|
||||
: (ex.status === 'running' ? esc(Pulse.fmt.elapsed(ex.started_at)) + ' elapsed' : '-')) +
|
||||
'</div>' +
|
||||
'<div class="lt-kv-key">Execution ID</div><div class="lt-kv-val ex-id-cell">' +
|
||||
'<code class="ex-code">' + esc(id) + '</code>' +
|
||||
@@ -732,7 +732,7 @@
|
||||
if (!ok) return;
|
||||
try {
|
||||
sessionStorage.setItem('pulse_rerun', JSON.stringify({ command: command, worker_id: workerId }));
|
||||
} catch (e) { /* private mode — the quick page just starts empty */ }
|
||||
} catch (e) { /* private mode: the quick page just starts empty */ }
|
||||
window.location.href = '/quick';
|
||||
},
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* PULSE — Quick Command page (WP-F) styles. Prefix: qc- */
|
||||
/* PULSE: Quick Command page (WP-F) styles. Prefix: qc- */
|
||||
|
||||
.qc-mode-row {
|
||||
display: flex;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* =====================================================================
|
||||
PULSE — Quick Command page (WP-F)
|
||||
PULSE: Quick Command page (WP-F)
|
||||
Owns DOM id prefix `qc-` and action namespace `qc:*`.
|
||||
===================================================================== */
|
||||
'use strict';
|
||||
@@ -12,7 +12,7 @@
|
||||
const RERUN_KEY = 'pulse_rerun';
|
||||
|
||||
/* Copied verbatim from the pre-redesign public/index.html commandTemplates
|
||||
array (12 templates) — kept static here since pageConfig only carries
|
||||
array (12 templates): kept static here since pageConfig only carries
|
||||
isAdmin from server.js (WP-A), not a templates list. */
|
||||
const TEMPLATES = [
|
||||
{ name: 'System Info', cmd: 'uname -a', desc: 'Show system information' },
|
||||
@@ -139,7 +139,7 @@
|
||||
list.innerHTML = history.map((item, i) =>
|
||||
'<div class="qc-list-item" data-action="qc:history-use" data-index="' + i + '">' +
|
||||
'<div class="qc-list-item-code"><code>' + esc(item.command) + '</code></div>' +
|
||||
'<div class="qc-list-item-meta">' + esc(Pulse.fmt.dateTime(item.timestamp)) + ' — ' + esc(item.worker) + '</div>' +
|
||||
'<div class="qc-list-item-meta">' + esc(Pulse.fmt.dateTime(item.timestamp)) + ' | ' + esc(item.worker) + '</div>' +
|
||||
'</div>'
|
||||
).join('');
|
||||
}
|
||||
@@ -155,7 +155,7 @@
|
||||
'<span class="lt-alert-icon">✓</span>' +
|
||||
'<div class="lt-alert-body">' +
|
||||
'<div class="lt-alert-title">Command sent successfully</div>' +
|
||||
'<div class="lt-alert-msg">Execution ID: <code>' + esc(executionId) + '</code> — ' +
|
||||
'<div class="lt-alert-msg">Execution ID: <code>' + esc(executionId) + '</code> | ' +
|
||||
'<a href="/executions?open=' + encodeURIComponent(executionId) + '">view in Executions</a>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
@@ -292,7 +292,7 @@
|
||||
if (hasWorker) {
|
||||
select.value = payload.worker_id;
|
||||
} else {
|
||||
Pulse.toast.warning('Original worker is no longer available — select a worker to run this command.');
|
||||
Pulse.toast.warning('Original worker is no longer available. Select a worker to run this command.');
|
||||
}
|
||||
}
|
||||
const commandEl = document.getElementById('qc-command');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* PULSE — Scheduler page (WP-F) styles. Prefix: sc- */
|
||||
/* PULSE: Scheduler page (WP-F) styles. Prefix: sc- */
|
||||
|
||||
.sc-row-disabled {
|
||||
opacity: 0.6;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* =====================================================================
|
||||
PULSE — Scheduler page (WP-F)
|
||||
PULSE: Scheduler page (WP-F)
|
||||
Owns DOM id prefix `sc-` and action namespace `sc:*`.
|
||||
===================================================================== */
|
||||
'use strict';
|
||||
@@ -36,7 +36,7 @@
|
||||
}
|
||||
|
||||
function workerNamesHtml(ids) {
|
||||
if (!ids.length) return '<span class="lt-text-dim">—</span>';
|
||||
if (!ids.length) return '<span class="lt-text-dim">-</span>';
|
||||
return ids.map(id => {
|
||||
const w = _workers.find(worker => worker.id === id);
|
||||
const label = w ? w.name : String(id).slice(0, 8);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* Workers page (WP-C) — grid layout for worker cards. */
|
||||
/* Workers page (WP-C): grid layout for worker cards. */
|
||||
.wk-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* =====================================================================
|
||||
PULSE — Workers page (WP-C)
|
||||
PULSE: Workers page (WP-C)
|
||||
Owns DOM id prefix `wk-` and action namespace `wk:*`.
|
||||
===================================================================== */
|
||||
'use strict';
|
||||
@@ -80,7 +80,7 @@
|
||||
return div;
|
||||
}
|
||||
|
||||
/* Update an existing card's fields in place — never replaces the card
|
||||
/* Update an existing card's fields in place: never replaces the card
|
||||
node itself, so identity is preserved across refreshes. */
|
||||
function patchCard(card, worker) {
|
||||
const meta = parseMeta(worker);
|
||||
@@ -147,7 +147,7 @@
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------
|
||||
Grid rendering — patches existing cards, adds/removes as needed.
|
||||
Grid rendering: patches existing cards, adds/removes as needed.
|
||||
------------------------------------------------------------------- */
|
||||
function renderGrid(workers) {
|
||||
const grid = document.getElementById('wk-grid');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* Workflows page (WP-D) — extends base.css, never overrides its variables. */
|
||||
/* Workflows page (WP-D): extends base.css, never overrides its variables. */
|
||||
|
||||
.wf-json-textarea {
|
||||
font-family: var(--font-mono);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* =====================================================================
|
||||
PULSE — Workflows page (WP-D)
|
||||
PULSE: Workflows page (WP-D)
|
||||
---------------------------------------------------------------------
|
||||
Owns: DOM id prefix `wf-`, action namespace `wf:*`.
|
||||
Consumes the frozen window.Pulse contract from /assets/app.js.
|
||||
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/bin/bash
|
||||
# Starts a throwaway Pulse stack for the Playwright UI tests (#45 phase 5):
|
||||
# the server on PULSE_UI_PORT plus three local workers (node-01..03) that run
|
||||
# real, harmless commands. The database must already exist; the server creates
|
||||
# its tables on start.
|
||||
#
|
||||
# Used by the CI `ui` job (MariaDB service container) and locally:
|
||||
# DB_HOST=127.0.0.1 DB_PORT=3399 DB_USER=pulse DB_PASSWORD=x DB_NAME=pulse \
|
||||
# scripts/ci/ui-stack.sh start
|
||||
# npm run test:ui
|
||||
# scripts/ci/ui-stack.sh stop
|
||||
#
|
||||
# Every setting is passed explicitly, so a developer's .env never leaks in
|
||||
# (dotenv does not override variables that are already set).
|
||||
set -euo pipefail
|
||||
|
||||
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
PORT=${PULSE_UI_PORT:-8400}
|
||||
RUN=${PULSE_UI_RUN_DIR:-$ROOT/.ui-stack}
|
||||
URL="http://127.0.0.1:$PORT"
|
||||
|
||||
export PORT HOST=127.0.0.1 NODE_ENV=test
|
||||
export TRUSTED_PROXIES=127.0.0.1 # the tests send Authelia headers themselves
|
||||
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
|
||||
|
||||
stop() {
|
||||
for f in "$RUN"/*.pid; do
|
||||
[ -e "$f" ] || continue
|
||||
kill "$(cat "$f")" 2>/dev/null || true
|
||||
rm -f "$f"
|
||||
done
|
||||
}
|
||||
|
||||
wait_for() { # wait_for <description> <seconds> <command...>
|
||||
local what=$1 secs=$2; shift 2
|
||||
for _ in $(seq 1 "$secs"); do
|
||||
if "$@" >/dev/null 2>&1; then return 0; fi
|
||||
sleep 1
|
||||
done
|
||||
echo "::error::timed out waiting for $what" >&2
|
||||
tail -n 50 "$RUN"/*.log >&2 || true
|
||||
return 1
|
||||
}
|
||||
|
||||
# Node's fetch instead of curl: the Playwright CI image has node but maybe not curl.
|
||||
healthz() { # healthz [<javascript test on the parsed body>]
|
||||
node -e 'fetch(process.argv[1]).then(r => r.json()).then(h => process.exit(h.db && eval(process.argv[2] || "true") ? 0 : 1), () => process.exit(1))' \
|
||||
"$URL/healthz" "${1:-true}"
|
||||
}
|
||||
workers_online() { healthz 'h.workers === 3'; }
|
||||
|
||||
start() {
|
||||
: "${DB_HOST:?}" "${DB_PORT:?}" "${DB_USER:?}" "${DB_PASSWORD:?}" "${DB_NAME:?}"
|
||||
export DB_HOST DB_PORT DB_USER DB_PASSWORD DB_NAME
|
||||
stop
|
||||
mkdir -p "$RUN"
|
||||
# cwd is the run dir, so dotenv finds no .env there.
|
||||
(cd "$RUN" && exec node "$ROOT/server.js" >"$RUN/server.log" 2>&1) &
|
||||
echo $! >"$RUN/server.pid"
|
||||
wait_for "the server and database" 60 healthz
|
||||
|
||||
for n in 1 2 3; do
|
||||
(cd "$RUN" && WORKER_NAME=node-0$n PULSE_SERVER="$URL" PULSE_WS="ws://127.0.0.1:$PORT" \
|
||||
HEARTBEAT_INTERVAL=5 exec node "$ROOT/worker/worker.js" >"$RUN/worker-$n.log" 2>&1) &
|
||||
echo $! >"$RUN/worker-$n.pid"
|
||||
done
|
||||
wait_for "3 workers to connect" 60 workers_online
|
||||
echo "Pulse UI stack is up at $URL with 3 workers"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
start) start ;;
|
||||
stop) stop ;;
|
||||
*) echo "usage: $0 start|stop" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -38,7 +38,7 @@ const DEV_READONLY = process.env.PULSE_DEV_READONLY === '1' || process.env.DISAB
|
||||
|
||||
// Middleware
|
||||
|
||||
// CSP nonce — must run before helmet so the directive can read it.
|
||||
// CSP nonce: must run before helmet so the directive can read it.
|
||||
app.use((req, res, next) => {
|
||||
res.locals.nonce = crypto.randomBytes(16).toString('base64');
|
||||
next();
|
||||
@@ -77,28 +77,33 @@ app.use(helmet({
|
||||
|
||||
app.use(express.json());
|
||||
|
||||
// Rate limiting
|
||||
// Rate limiting. The limits can be raised for test stacks (the UI tests make a
|
||||
// few hundred requests from one address); production uses the defaults.
|
||||
const limitFromEnv = (name, fallback) => {
|
||||
const n = parseInt(process.env[name], 10);
|
||||
return Number.isInteger(n) && n > 0 ? n : fallback;
|
||||
};
|
||||
const apiLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 300,
|
||||
max: limitFromEnv('PULSE_API_RATE_MAX', 300),
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many requests, please try again later' }
|
||||
});
|
||||
const executionLimiter = rateLimit({
|
||||
windowMs: 60 * 1000, // 1 minute
|
||||
max: 20,
|
||||
max: limitFromEnv('PULSE_EXEC_RATE_MAX', 20),
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Too many execution requests, please slow down' }
|
||||
});
|
||||
|
||||
// Named constants for timeouts and limits
|
||||
const PROMPT_TIMEOUT_MS = 60 * 60 * 1000; // 60 min — how long a prompt waits for user input
|
||||
const COMMAND_TIMEOUT_MS = 120_000; // 2 min — workflow step command timeout
|
||||
const QUICK_CMD_TIMEOUT_MS = 60_000; // 1 min — quick/direct/gandalf command timeout
|
||||
const WEBHOOK_TIMEOUT_MS = 10_000; // 10 s — outbound webhook HTTP timeout
|
||||
const WAIT_STEP_MAX_MS = 24 * 60 * 60_000; // 24 h — cap on workflow wait step
|
||||
const PROMPT_TIMEOUT_MS = 60 * 60 * 1000; // 60 min: how long a prompt waits for user input
|
||||
const COMMAND_TIMEOUT_MS = 120_000; // 2 min: workflow step command timeout
|
||||
const QUICK_CMD_TIMEOUT_MS = 60_000; // 1 min: quick/direct/gandalf command timeout
|
||||
const WEBHOOK_TIMEOUT_MS = 10_000; // 10 s: outbound webhook HTTP timeout
|
||||
const WAIT_STEP_MAX_MS = 24 * 60 * 60_000; // 24 h: cap on workflow wait step
|
||||
const GOTO_MAX_VISITS = 100; // max times a step may be revisited via goto
|
||||
const WORKER_STALE_MINUTES = 5; // minutes before a worker is marked offline
|
||||
const SERVER_VERSION = '1.0.0';
|
||||
@@ -124,7 +129,7 @@ app.post('/csp-report',
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// Static assets — the old root mount of public/ is gone on purpose.
|
||||
// Static assets: the old root mount of public/ is gone on purpose.
|
||||
app.use('/web_template', express.static(path.join(__dirname, 'public/web_template'), { maxAge: '1h' }));
|
||||
app.use('/assets', express.static(path.join(__dirname, 'public/assets'), { maxAge: '1h' }));
|
||||
|
||||
@@ -334,7 +339,7 @@ async function processScheduledCommands() {
|
||||
? JSON.parse(schedule.worker_ids)
|
||||
: schedule.worker_ids;
|
||||
} catch {
|
||||
console.error(`[Scheduler] Invalid worker_ids JSON for "${schedule.name}" — skipping`);
|
||||
console.error(`[Scheduler] Invalid worker_ids JSON for "${schedule.name}": skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -403,8 +408,35 @@ async function markStaleWorkersOffline() {
|
||||
console.error('[Worker] Stale check error:', error);
|
||||
}
|
||||
}
|
||||
// Backstop for #7: fail any execution still 'running' long past the global limit
|
||||
// that nothing in this process is tracking any more (no workflow engine loop, no
|
||||
// command awaiting a result). Restart recovery covers executions orphaned by a restart.
|
||||
async function reapOrphanedExecutions() {
|
||||
try {
|
||||
const maxMinutes = parseInt(process.env.EXECUTION_MAX_MINUTES) || 60;
|
||||
const [rows] = await pool.query(
|
||||
`SELECT id FROM executions WHERE status = 'running'
|
||||
AND started_at < DATE_SUB(NOW(), INTERVAL ? MINUTE)`,
|
||||
[maxMinutes + 10]
|
||||
);
|
||||
const tracked = new Set([..._commandTargets.values()].map(t => t.executionId));
|
||||
for (const { id } of rows) {
|
||||
if (_executionState.has(id) || tracked.has(id)) continue;
|
||||
await addExecutionLog(id, {
|
||||
action: 'execution_timeout',
|
||||
message: `Execution was still running after ${maxMinutes + 10} minutes with nothing tracking it; marked failed`,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
if (await updateExecutionStatus(id, 'failed')) console.warn(`[Reaper] Failed orphaned execution ${id}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Reaper] Error reaping orphaned executions:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!DEV_READONLY) {
|
||||
setInterval(markStaleWorkersOffline, 60_000);
|
||||
setInterval(reapOrphanedExecutions, 5 * 60_000);
|
||||
} else {
|
||||
console.log('[DEV] skipped: markStaleWorkersOffline interval');
|
||||
}
|
||||
@@ -419,15 +451,62 @@ const workers = new Map(); // Map worker_id -> WebSocket connection
|
||||
// connection are dropped, so a connection cannot forge another worker's output.
|
||||
// The DB worker id is used rather than the socket so a worker that reconnects
|
||||
// mid-command can still deliver its result.
|
||||
const _commandTargets = new Map(); // key → { dbWorkerId, sentAt }
|
||||
const _commandTargets = new Map(); // key → { dbWorkerId, ws, executionId, direct, timer, sentAt }
|
||||
const COMMAND_TARGET_TTL_MS = 25 * 60 * 60_000; // longer than any command or wait step
|
||||
const COMMAND_RESULT_GRACE_MS = 30_000; // slack on top of the command's own timeout
|
||||
|
||||
function sendCommandToWorker(workerWs, message) {
|
||||
const key = message.command_id || message.execution_id;
|
||||
_commandTargets.set(key, { dbWorkerId: workerWs.dbWorkerId, sentAt: Date.now() });
|
||||
const target = {
|
||||
dbWorkerId: workerWs.dbWorkerId,
|
||||
ws: workerWs,
|
||||
executionId: message.execution_id,
|
||||
// Workflow steps carry a command_id and time out in waitForCommandResult.
|
||||
// Direct commands (quick, scheduled, Gandalf) had no server-side timeout and
|
||||
// could stay 'running' forever when the result never came back (#7).
|
||||
direct: !message.command_id,
|
||||
timer: null,
|
||||
sentAt: Date.now()
|
||||
};
|
||||
if (target.direct) {
|
||||
const ms = (message.timeout || QUICK_CMD_TIMEOUT_MS) + COMMAND_RESULT_GRACE_MS;
|
||||
target.timer = setTimeout(() => {
|
||||
failInflightCommand(key, `No result from the worker within ${Math.round(ms / 1000)}s`)
|
||||
.catch(err => console.error('[Command] Timeout handling failed:', err));
|
||||
}, ms);
|
||||
}
|
||||
_commandTargets.set(key, target);
|
||||
workerWs.send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
// Give up on an in-flight command: the worker timed out, disconnected, or never answered.
|
||||
// Direct commands get a failed command_result log entry (rendered like any other failed
|
||||
// result, and seen by Gandalf as status 'failed'); workflow steps get their pending
|
||||
// waitForCommandResult resolved as a failure so the engine moves on immediately.
|
||||
async function failInflightCommand(key, error) {
|
||||
const t = _commandTargets.get(key);
|
||||
if (!t) return;
|
||||
_commandTargets.delete(key);
|
||||
clearTimeout(t.timer);
|
||||
console.warn(`[Command] ${t.direct ? 'Execution' : 'Workflow command'} ${key} failed: ${error}`);
|
||||
if (!t.direct) {
|
||||
const resolver = _commandResolvers.get(key);
|
||||
if (resolver) resolver({ success: false, error, stdout: '', stderr: '' });
|
||||
return;
|
||||
}
|
||||
const timestamp = new Date().toISOString();
|
||||
await addExecutionLog(t.executionId, {
|
||||
step: 'command_execution', action: 'command_result', worker_id: t.dbWorkerId,
|
||||
success: false, error, stdout: '', stderr: '', timestamp
|
||||
});
|
||||
if (await updateExecutionStatus(t.executionId, 'failed')) {
|
||||
broadcast({
|
||||
type: 'command_result', execution_id: t.executionId, worker_id: t.dbWorkerId,
|
||||
success: false, error, stdout: '', stderr: ''
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Entries for commands whose result never arrives would otherwise accumulate.
|
||||
setInterval(() => {
|
||||
const cutoff = Date.now() - COMMAND_TARGET_TTL_MS;
|
||||
@@ -460,6 +539,13 @@ wss.on('connection', (ws, req) => {
|
||||
if (message.type === 'command_result') {
|
||||
// Handle command result from worker
|
||||
const { execution_id, command_id, worker_id, success, stdout, stderr, duration, timestamp } = message;
|
||||
// Failure details from the worker (#14). Older workers send only `error`.
|
||||
const failure = success ? {} : {
|
||||
error: typeof message.error === 'string' ? message.error.slice(0, 2000) : undefined,
|
||||
exit_code: message.exit_code,
|
||||
signal: message.signal || undefined,
|
||||
timed_out: message.timed_out || undefined
|
||||
};
|
||||
|
||||
const targetKey = command_id || execution_id;
|
||||
const target = _commandTargets.get(targetKey);
|
||||
@@ -469,6 +555,7 @@ wss.on('connection', (ws, req) => {
|
||||
return;
|
||||
}
|
||||
_commandTargets.delete(targetKey);
|
||||
clearTimeout(target.timer);
|
||||
|
||||
// Add result to execution logs
|
||||
await addExecutionLog(execution_id, {
|
||||
@@ -479,6 +566,7 @@ wss.on('connection', (ws, req) => {
|
||||
success: success,
|
||||
stdout: stdout,
|
||||
stderr: stderr,
|
||||
...failure,
|
||||
duration: duration,
|
||||
timestamp: timestamp || new Date().toISOString()
|
||||
});
|
||||
@@ -498,7 +586,7 @@ wss.on('connection', (ws, req) => {
|
||||
if (command_id) {
|
||||
const resolver = _commandResolvers.get(command_id);
|
||||
if (resolver) {
|
||||
resolver({ success, stdout, stderr });
|
||||
resolver({ success, stdout, stderr, ...failure });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -516,6 +604,7 @@ wss.on('connection', (ws, req) => {
|
||||
success: success,
|
||||
stdout: stdout,
|
||||
stderr: stderr,
|
||||
...failure,
|
||||
is_automated: isAutomated,
|
||||
});
|
||||
|
||||
@@ -632,13 +721,25 @@ wss.on('connection', (ws, req) => {
|
||||
|
||||
ws.on('close', () => {
|
||||
clearTimeout(ws.identifyTimer);
|
||||
// Commands sent over this socket can no longer report back (the worker drops
|
||||
// results while disconnected), so fail them now rather than leave them 'running'.
|
||||
if (ws.isWorker) {
|
||||
for (const [key, t] of _commandTargets) {
|
||||
if (t.ws === ws) {
|
||||
failInflightCommand(key, 'Worker disconnected before returning a result')
|
||||
.catch(err => console.error('[Command] Disconnect handling failed:', err));
|
||||
}
|
||||
}
|
||||
}
|
||||
browserClients.delete(ws);
|
||||
workerClients.delete(ws);
|
||||
if (ws.workerId) {
|
||||
if (ws.workerId && workers.get(ws.workerId) === ws) {
|
||||
workers.delete(ws.workerId);
|
||||
console.log(`Worker ${ws.workerId} (runtime ID) disconnected`);
|
||||
}
|
||||
if (ws.dbWorkerId) {
|
||||
// Only if this socket is still the live connection for the worker: after a
|
||||
// reconnect, the old socket closing must not unmap the new one or mark it offline.
|
||||
if (ws.dbWorkerId && workers.get(ws.dbWorkerId) === ws) {
|
||||
workers.delete(ws.dbWorkerId);
|
||||
console.log(`Worker ${ws.dbWorkerId} (database ID) disconnected`);
|
||||
// Mark worker offline in DB
|
||||
@@ -651,7 +752,7 @@ wss.on('connection', (ws, req) => {
|
||||
|
||||
// Broadcast to browser clients only (NOT worker agents)
|
||||
function broadcast(data) {
|
||||
// Snapshot the Set before iterating — a close event during iteration would
|
||||
// Snapshot the Set before iterating: a close event during iteration would
|
||||
// otherwise modify the Set in-place, causing skipped or double-visited entries.
|
||||
const snapshot = Array.from(browserClients);
|
||||
snapshot.forEach(client => {
|
||||
@@ -661,7 +762,7 @@ function broadcast(data) {
|
||||
});
|
||||
}
|
||||
|
||||
// Helper function to add log entry to execution (atomic — no read-modify-write race condition)
|
||||
// Helper function to add log entry to execution (atomic: no read-modify-write race condition)
|
||||
async function addExecutionLog(executionId, logEntry) {
|
||||
try {
|
||||
await pool.query(
|
||||
@@ -674,12 +775,19 @@ async function addExecutionLog(executionId, logEntry) {
|
||||
}
|
||||
|
||||
// Helper function to update execution status
|
||||
// Only a running execution changes status: once failed (aborted, timed out, worker
|
||||
// gone) or completed, a late result or the workflow engine finishing can't flip it
|
||||
// back or fire a second webhook. Returns true if the status changed.
|
||||
async function updateExecutionStatus(executionId, status) {
|
||||
try {
|
||||
await pool.query(
|
||||
'UPDATE executions SET status = ?, completed_at = NOW() WHERE id = ?',
|
||||
const [result] = await pool.query(
|
||||
"UPDATE executions SET status = ?, completed_at = NOW() WHERE id = ? AND status = 'running'",
|
||||
[status, executionId]
|
||||
);
|
||||
if (!result || result.affectedRows === 0) {
|
||||
console.log(`[Workflow] Execution ${executionId} is no longer running; not changing status to ${status}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
broadcast({
|
||||
type: 'execution_status',
|
||||
@@ -695,8 +803,10 @@ async function updateExecutionStatus(executionId, status) {
|
||||
console.error(`[Webhook] Delivery error for execution ${executionId}:`, err.message);
|
||||
});
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error(`[Workflow] Error updating execution status:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -802,7 +912,7 @@ function authenticateGandalf(req, res, next) {
|
||||
// Survives across step boundaries; cleaned up when execution ends.
|
||||
const _executionState = new Map(); // executionId → { params, state }
|
||||
|
||||
// Pending prompt resolvers — set when a prompt step is waiting for user input.
|
||||
// Pending prompt resolvers: set when a prompt step is waiting for user input.
|
||||
const _executionPrompts = new Map(); // executionId → resolve fn
|
||||
const _commandResolvers = new Map(); // commandId → resolve fn (event-driven result delivery)
|
||||
|
||||
@@ -851,7 +961,7 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam
|
||||
const step = steps[currentIndex];
|
||||
const execState = _executionState.get(executionId);
|
||||
if (!execState) {
|
||||
// State was lost (server restart or bug) — fail cleanly rather than throwing TypeError
|
||||
// State was lost (server restart or bug): fail cleanly rather than throwing TypeError
|
||||
await addExecutionLog(executionId, {
|
||||
action: 'workflow_error',
|
||||
error: 'Execution state lost unexpectedly; aborting.',
|
||||
@@ -861,7 +971,7 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam
|
||||
return;
|
||||
}
|
||||
const stepLabel = step.name || step.id || `Step ${currentIndex + 1}`;
|
||||
console.log(`[Workflow] ${executionId} — step ${currentIndex + 1}: ${stepLabel}`);
|
||||
console.log(`[Workflow] ${executionId} step ${currentIndex + 1}: ${stepLabel}`);
|
||||
|
||||
await addExecutionLog(executionId, {
|
||||
step: currentIndex + 1, step_name: stepLabel, action: 'step_started',
|
||||
@@ -1198,7 +1308,7 @@ async function executeCommandStep(executionId, step, stepNumber, params = {}) {
|
||||
|
||||
// Wait for a command result using event-driven promise resolution.
|
||||
// The resolver is stored in _commandResolvers and called immediately when
|
||||
// command_result arrives via WebSocket — no DB polling required.
|
||||
// command_result arrives via WebSocket: no DB polling required.
|
||||
async function waitForCommandResult(executionId, commandId, timeout) {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
@@ -1216,6 +1326,40 @@ async function waitForCommandResult(executionId, commandId, timeout) {
|
||||
|
||||
|
||||
|
||||
// Health check for deploys and monitoring (#45 phase 2). Unauthenticated on purpose,
|
||||
// so CI and the deploy script can reach it; it reveals only the running commit,
|
||||
// whether the database answers and how many workers are connected.
|
||||
const GIT_SHA = (() => {
|
||||
try {
|
||||
return require('child_process')
|
||||
.execFileSync('git', ['rev-parse', 'HEAD'], { cwd: __dirname, timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] })
|
||||
.toString().trim();
|
||||
} catch {
|
||||
return 'unknown';
|
||||
}
|
||||
})();
|
||||
|
||||
app.get('/healthz', async (req, res) => {
|
||||
let db = false;
|
||||
try {
|
||||
await Promise.race([
|
||||
pool.query('SELECT 1'),
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 3000))
|
||||
]);
|
||||
db = true;
|
||||
} catch { /* reported as db: false */ }
|
||||
const connectedWorkers = new Set([...workers.values()].map(w => w.dbWorkerId).filter(Boolean)).size;
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.status(db ? 200 : 503).json({
|
||||
status: db ? 'ok' : 'degraded',
|
||||
version: SERVER_VERSION,
|
||||
sha: GIT_SHA,
|
||||
db,
|
||||
workers: connectedWorkers,
|
||||
uptime_s: Math.round(process.uptime())
|
||||
});
|
||||
});
|
||||
|
||||
// HTML page routes (registered before the API routes)
|
||||
const authenticatePage = makeAuthenticatePage(pool);
|
||||
PAGES.forEach((p) => {
|
||||
@@ -1261,7 +1405,7 @@ app.get('/api/workflows/:id', authenticateSSO, async (req, res) => {
|
||||
definition = typeof wf.definition === 'string'
|
||||
? JSON.parse(wf.definition || '{}')
|
||||
: (wf.definition || {});
|
||||
} catch { /* corrupt definition — return empty */ }
|
||||
} catch { /* corrupt definition: return empty */ }
|
||||
res.json({ ...wf, definition });
|
||||
} catch (error) {
|
||||
console.error('[API] GET /api/workflows/:id error:', error);
|
||||
@@ -1322,7 +1466,7 @@ app.post('/api/workers/heartbeat', async (req, res) => {
|
||||
const { worker_id, name, metadata } = req.body;
|
||||
const apiKey = req.headers['x-api-key'];
|
||||
|
||||
// Verify API key — reject missing or wrong keys
|
||||
// Verify API key: reject missing or wrong keys
|
||||
if (!checkWorkerKey(apiKey)) {
|
||||
return res.status(401).json({ error: 'Invalid API key' });
|
||||
}
|
||||
@@ -1520,6 +1664,14 @@ app.post('/api/executions/:id/abort', authenticateSSO, async (req, res) => {
|
||||
// Update execution status to failed
|
||||
await updateExecutionStatus(executionId, 'failed');
|
||||
|
||||
// Stop tracking its direct command so the result timeout doesn't fire later
|
||||
for (const [key, t] of _commandTargets) {
|
||||
if (t.direct && t.executionId === executionId) {
|
||||
clearTimeout(t.timer);
|
||||
_commandTargets.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Unblock any pending prompt so the thread can exit
|
||||
const pending = _executionPrompts.get(executionId);
|
||||
if (pending) pending.resolve(null);
|
||||
@@ -1879,7 +2031,7 @@ app.post('/api/workers/:id/command', authenticateSSO, requireJSON, async (req, r
|
||||
}
|
||||
});
|
||||
|
||||
// 404 — JSON under /api/, themed HTML elsewhere
|
||||
// 404: JSON under /api/, themed HTML elsewhere
|
||||
app.use((req, res) => {
|
||||
if (req.path.startsWith('/api/')) {
|
||||
return res.status(404).json({ error: 'Not found' });
|
||||
@@ -1920,7 +2072,7 @@ initDatabase().then(() => {
|
||||
console.log(`Worker auth enforcement: ${workerAuthEnforced() ? 'ON (keyless workers refused)' : 'OFF (keyless workers allowed with a warning; set WORKER_AUTH_ENFORCE=1 once all workers send their key)'}`);
|
||||
if (DEV_READONLY) {
|
||||
console.warn('************************************************************');
|
||||
console.warn('* PULSE_DEV_READONLY IS ON — background jobs are disabled *');
|
||||
console.warn('* PULSE_DEV_READONLY IS ON - background jobs are disabled *');
|
||||
console.warn('* No cleanup, scheduler, stale-worker or recovery writes. *');
|
||||
console.warn('************************************************************');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
'use strict';
|
||||
|
||||
// Runs deploy/pulse_deploy.sh in a sandbox: a throwaway git origin and checkout,
|
||||
// with fake systemctl/npm/curl on PATH. "Production" health is simulated by the
|
||||
// fake curl, which reports whatever commit the fake systemctl last started; a
|
||||
// commit containing a BROKEN file reports db:false (an unhealthy build).
|
||||
|
||||
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_deploy.sh');
|
||||
let root, app, bin, 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.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 head = () => sh(app, 'rev-parse', 'HEAD');
|
||||
const running = () => fs.readFileSync(path.join(root, 'running'), 'utf8').trim();
|
||||
|
||||
beforeAll(() => {
|
||||
root = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-deploy-'));
|
||||
const work = path.join(root, 'work');
|
||||
const origin = path.join(root, 'origin.git');
|
||||
app = path.join(root, 'app');
|
||||
bin = path.join(root, 'bin');
|
||||
fs.mkdirSync(work); fs.mkdirSync(bin);
|
||||
|
||||
sh(root, 'init', '-q', '--bare', '-b', 'main', origin);
|
||||
sh(root, 'init', '-q', '-b', 'main', work);
|
||||
commits = {};
|
||||
commits.a = commit(work, 'a', { 'server.js': 'a' });
|
||||
sh(work, 'remote', 'add', 'origin', origin);
|
||||
sh(work, 'push', '-q', 'origin', 'main');
|
||||
sh(root, 'clone', '-q', origin, app);
|
||||
fs.writeFileSync(path.join(app, '.env'), 'SECRET=keep-me\n'); // untracked, must survive
|
||||
|
||||
commits.b = commit(work, 'b', { 'server.js': 'b' });
|
||||
commits.broken = commit(work, 'broken', { 'server.js': 'c', BROKEN: '1' });
|
||||
commits.fixed = commit(work, 'fixed', { 'server.js': 'd' });
|
||||
fs.unlinkSync(path.join(work, 'BROKEN'));
|
||||
commits.fixed = commit(work, 'fixed2', { 'server.js': 'e' });
|
||||
sh(work, 'push', '-q', 'origin', 'main');
|
||||
sh(work, 'checkout', '-q', '-b', 'side', commits.a);
|
||||
commits.side = commit(work, 'side', { 'server.js': 'side' });
|
||||
sh(work, 'push', '-q', 'origin', 'side');
|
||||
|
||||
const fake = (name, body) => fs.writeFileSync(path.join(bin, name), `#!/bin/bash\n${body}\n`, { mode: 0o755 });
|
||||
fake('npm', 'exit 0');
|
||||
fake('systemctl', `git -C "${app}" rev-parse HEAD > "${root}/running"`);
|
||||
fake('curl', `s=$(cat "${root}/running" 2>/dev/null) || exit 7
|
||||
if [ -e "${app}/BROKEN" ]; then db=false; else db=true; fi
|
||||
echo "{\\"status\\":\\"ok\\",\\"sha\\":\\"$s\\",\\"db\\":$db}"`);
|
||||
fs.writeFileSync(path.join(root, 'running'), commits.a);
|
||||
|
||||
env = {
|
||||
...process.env,
|
||||
PATH: `${bin}:${process.env.PATH}`,
|
||||
PULSE_DEPLOY_APP_ROOT: app,
|
||||
PULSE_DEPLOY_STATE_DIR: path.join(root, 'state'),
|
||||
PULSE_DEPLOY_LOG: path.join(root, 'deploy.log'),
|
||||
PULSE_DEPLOY_LOCK: path.join(root, 'lock'),
|
||||
PULSE_DEPLOY_HEALTH_TRIES: '3',
|
||||
PULSE_DEPLOY_HEALTH_SLEEP: '0'
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
|
||||
// Order matters: each test builds on the state the previous one left.
|
||||
test('deploys exactly the requested commit, not just the tip of main', () => {
|
||||
const r = deploy(commits.b);
|
||||
expect(r.code).toBe(0);
|
||||
expect(head()).toBe(commits.b);
|
||||
expect(running()).toBe(commits.b);
|
||||
expect(fs.readFileSync(path.join(app, '.env'), 'utf8')).toBe('SECRET=keep-me\n');
|
||||
});
|
||||
|
||||
test('a replayed request (same or older timestamp) 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(head()).toBe(commits.fixed);
|
||||
});
|
||||
|
||||
test('a stale request is refused', () => {
|
||||
const r = deploy(commits.b, Math.floor(Date.now() / 1000) - 3600);
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toMatch(/old \(limit 300s\)/);
|
||||
});
|
||||
|
||||
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);
|
||||
// Only main is fetched, so a commit from another branch is unknown or not an ancestor.
|
||||
expect(r.out).toMatch(/is not on main|not found after fetch/);
|
||||
expect(head()).toBe(commits.fixed);
|
||||
});
|
||||
|
||||
test('malformed input is refused', () => {
|
||||
expect(deploy('abc', Math.floor(Date.now() / 1000) + 11).out).toMatch(/invalid sha/);
|
||||
expect(deploy(commits.b, 'x').out).toMatch(/invalid timestamp/);
|
||||
});
|
||||
|
||||
test('an unhealthy build is rolled back to the previous commit', () => {
|
||||
const r = deploy(commits.broken, Math.floor(Date.now() / 1000) + 20);
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toMatch(/rolling back/);
|
||||
expect(r.out).toMatch(/rolled back to .*healthy/);
|
||||
expect(head()).toBe(commits.fixed);
|
||||
expect(running()).toBe(commits.fixed);
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
// Pages and the API require an Authelia identity in an allowed group (#37).
|
||||
const { test, expect, SSO } = require('./fixtures');
|
||||
|
||||
test.describe('without an SSO identity', () => {
|
||||
test.use({ extraHTTPHeaders: {} });
|
||||
|
||||
test('pages show the sign-in error', async ({ page, problems }) => {
|
||||
const res = await page.goto('/');
|
||||
expect(res.status()).toBe(401);
|
||||
await expect(page.getByText(/Sign in through Authelia SSO/)).toBeVisible();
|
||||
problems.length = 0; // the 401 itself is the expected outcome
|
||||
});
|
||||
|
||||
test('the API refuses requests', async ({ request }) => {
|
||||
expect((await request.get('/api/workers')).status()).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('signed in outside the allowed groups', () => {
|
||||
test.use({ extraHTTPHeaders: { ...SSO, 'Remote-Groups': 'guests' } });
|
||||
|
||||
test('the API refuses requests', async ({ request }) => {
|
||||
expect((await request.get('/api/workers')).status()).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
// Shared fixture: every test gets a page signed in as an Authelia admin, and fails
|
||||
// if the page throws, logs a console error, or any Pulse request returns >= 400.
|
||||
const { test: base, expect } = require('@playwright/test');
|
||||
|
||||
const SSO = {
|
||||
'Remote-User': 'ci.tester',
|
||||
'Remote-Name': 'CI Tester',
|
||||
'Remote-Email': 'ci@example.invalid',
|
||||
'Remote-Groups': 'admin,employee',
|
||||
};
|
||||
|
||||
const isLocal = url => /^(https?|wss?):\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(url);
|
||||
|
||||
const test = base.extend({
|
||||
// extraHTTPHeaders also covers the WebSocket upgrade, which page.route can't see.
|
||||
extraHTTPHeaders: [SSO, { option: true }],
|
||||
|
||||
// Problems seen on the page; tests that expect one can clear the list.
|
||||
// eslint-disable-next-line no-empty-pattern -- Playwright requires the destructuring
|
||||
problems: async ({}, use) => { await use([]); },
|
||||
|
||||
page: async ({ page, problems }, use) => {
|
||||
// Nothing leaves the machine: no SSO headers to third parties, and no flaky
|
||||
// dependence on Google Fonts. The fallback fonts are fine for assertions.
|
||||
await page.route(url => !isLocal(url.href), route => route.abort());
|
||||
|
||||
page.on('pageerror', e => problems.push(`page error: ${e.message}`));
|
||||
page.on('console', m => {
|
||||
if (m.type() !== 'error') return;
|
||||
const src = (m.location() && m.location().url) || '';
|
||||
if (src && !isLocal(src)) return; // the blocked external requests
|
||||
if (/Failed to load resource: net::ERR_FAILED/.test(m.text())) return;
|
||||
problems.push(`console error: ${m.text()}`);
|
||||
});
|
||||
page.on('response', r => {
|
||||
if (isLocal(r.url()) && r.status() >= 400) problems.push(`HTTP ${r.status()} ${r.request().method()} ${r.url()}`);
|
||||
});
|
||||
|
||||
await page.addInitScript(() => {
|
||||
try { sessionStorage.setItem('lt_boot', '1'); } catch (e) { /* boot animation off */ }
|
||||
});
|
||||
|
||||
await use(page);
|
||||
expect(problems, 'page errors, console errors or failed requests').toEqual([]);
|
||||
},
|
||||
});
|
||||
|
||||
module.exports = { test, expect, SSO };
|
||||
@@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
|
||||
const { test, expect } = require('./fixtures');
|
||||
|
||||
const PAGES = [
|
||||
{ path: '/', title: 'Dashboard', heading: 'Dashboard' },
|
||||
{ path: '/workers', title: 'Workers', heading: 'Workers' },
|
||||
{ path: '/workflows', title: 'Workflows', heading: 'Workflows' },
|
||||
{ path: '/executions', title: 'Executions', heading: 'Executions' },
|
||||
{ path: '/quick', title: 'Quick Command', heading: 'Quick Command' },
|
||||
{ path: '/scheduler', title: 'Scheduler', heading: 'Scheduler' },
|
||||
];
|
||||
|
||||
for (const p of PAGES) {
|
||||
test(`${p.path} loads without errors`, async ({ page }) => {
|
||||
await page.goto(p.path);
|
||||
await expect(page).toHaveTitle(`${p.title} | PULSE`);
|
||||
await expect(page.getByRole('heading', { level: 1, name: p.heading })).toBeVisible();
|
||||
await page.waitForLoadState('networkidle');
|
||||
});
|
||||
}
|
||||
|
||||
test('dashboard counts the three online workers', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await expect(page.locator('#dash-stat-total-val')).toHaveText('3');
|
||||
await expect(page.locator('#dash-stat-online-val')).toHaveText('3');
|
||||
await expect(page.locator('#dash-stat-offline-val')).toHaveText('0');
|
||||
for (const n of ['node-01', 'node-02', 'node-03']) {
|
||||
await expect(page.locator('#dash-workers-wrap').getByText(n, { exact: true })).toBeVisible();
|
||||
}
|
||||
});
|
||||
|
||||
test('workers page lists each worker as online', async ({ page }) => {
|
||||
await page.goto('/workers');
|
||||
const grid = page.locator('#wk-grid');
|
||||
for (const n of ['node-01', 'node-02', 'node-03']) {
|
||||
await expect(grid.getByText(n, { exact: true })).toBeVisible();
|
||||
}
|
||||
await expect(grid.getByText(/^online$/i)).toHaveCount(3);
|
||||
});
|
||||
|
||||
test('quick command offers every online worker', async ({ page }) => {
|
||||
await page.goto('/quick');
|
||||
await expect(page.locator('#qc-worker option', { hasText: 'online' })).toHaveCount(3);
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
'use strict';
|
||||
|
||||
// End to end: browser -> server -> a real worker over the authenticated
|
||||
// WebSocket -> result stored -> shown in the UI.
|
||||
const { test, expect } = require('./fixtures');
|
||||
|
||||
const token = () => `ui-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
|
||||
test('a quick command runs on a worker and its output shows in Executions', async ({ page }) => {
|
||||
const marker = token();
|
||||
await page.goto('/quick');
|
||||
await page.locator('#qc-worker').selectOption({ label: 'node-02 (online)' });
|
||||
await page.locator('#qc-command').fill(`echo ${marker}`);
|
||||
await page.locator('#qc-execute-btn').click();
|
||||
|
||||
const result = page.locator('#qc-result');
|
||||
await expect(result).toContainText('Command sent successfully');
|
||||
await result.getByRole('link', { name: 'view in Executions' }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/executions/);
|
||||
const detail = page.locator('#ex-detail-body');
|
||||
await expect(detail).toContainText(marker);
|
||||
await expect(detail).toContainText(/completed/i);
|
||||
});
|
||||
|
||||
test('a failing command is reported as failed with its stderr', async ({ page }) => {
|
||||
const marker = token();
|
||||
await page.goto('/quick');
|
||||
await page.locator('#qc-worker').selectOption({ label: 'node-01 (online)' });
|
||||
await page.locator('#qc-command').fill(`echo ${marker} >&2; exit 3`);
|
||||
await page.locator('#qc-command').press('Control+Enter'); // the documented shortcut
|
||||
|
||||
await page.locator('#qc-result').getByRole('link', { name: 'view in Executions' }).click();
|
||||
const detail = page.locator('#ex-detail-body');
|
||||
await expect(detail).toContainText(marker);
|
||||
await expect(detail).toContainText(/failed/i);
|
||||
});
|
||||
|
||||
test('multi-worker mode sends the command to every selected worker', async ({ page }) => {
|
||||
await page.goto('/quick');
|
||||
await page.locator('label[for="qc-mode-multi"], #qc-mode-multi').first().click();
|
||||
await page.getByRole('button', { name: /select all/i }).click();
|
||||
await page.locator('#qc-command').fill(`echo ${token()}`);
|
||||
await page.locator('#qc-execute-btn').click();
|
||||
|
||||
const result = page.locator('#qc-result');
|
||||
await expect(result).toContainText('Success: 3');
|
||||
await expect(result).toContainText('Failed: 0');
|
||||
await expect(result.locator('tbody tr')).toHaveCount(3);
|
||||
});
|
||||
|
||||
test('Executions updates live when a command starts elsewhere', async ({ page, request }) => {
|
||||
await page.goto('/executions');
|
||||
await page.waitForLoadState('networkidle');
|
||||
const rows = page.locator('#ex-list-manual .ex-row');
|
||||
const before = await rows.count();
|
||||
|
||||
// Start a command through the API, not this page: only the WebSocket can tell it.
|
||||
const workers = await (await request.get('/api/workers')).json();
|
||||
const node3 = workers.find(w => w.name === 'node-03');
|
||||
const res = await request.post(`/api/workers/${node3.id}/command`, { data: { command: `echo ${token()}` } });
|
||||
expect(res.ok()).toBeTruthy();
|
||||
|
||||
await expect(rows).toHaveCount(before + 1);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
|
||||
// Runs in the `mobile` project (Pixel 7). Every page must fit the phone width:
|
||||
// no horizontal page scroll, and the heading on screen.
|
||||
const { test, expect } = require('./fixtures');
|
||||
|
||||
const PATHS = ['/', '/workers', '/workflows', '/executions', '/quick', '/scheduler'];
|
||||
|
||||
for (const path of PATHS) {
|
||||
test(`${path} fits a phone screen`, async ({ page }) => {
|
||||
await page.goto(path);
|
||||
await page.waitForLoadState('networkidle');
|
||||
await expect(page.getByRole('heading', { level: 1 })).toBeInViewport();
|
||||
const overflow = await page.evaluate(() => {
|
||||
const doc = document.documentElement;
|
||||
const wide = [...document.querySelectorAll('body *')]
|
||||
.filter(el => el.getBoundingClientRect().right > doc.clientWidth + 1 && el.getClientRects().length)
|
||||
.slice(0, 5)
|
||||
.map(el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (el.className && typeof el.className === 'string' ? '.' + el.className.trim().split(/\s+/).join('.') : ''));
|
||||
return { scrollWidth: doc.scrollWidth, clientWidth: doc.clientWidth, wide };
|
||||
});
|
||||
expect(overflow.scrollWidth, `wider than the screen: ${overflow.wide.join(', ')}`).toBeLessThanOrEqual(overflow.clientWidth);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
|
||||
const { test, expect } = require('./fixtures');
|
||||
|
||||
test('create a workflow in the UI, run it on all workers, and see it complete', async ({ page }) => {
|
||||
const id = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
const name = `UI test ${id}`;
|
||||
const definition = {
|
||||
steps: [
|
||||
{ id: 'hello', name: 'Say hello', type: 'execute', command: `echo wf-${id}`, targets: ['all'] },
|
||||
{ id: 'host', name: 'Hostname', type: 'execute', command: 'hostname', targets: ['all'] },
|
||||
],
|
||||
};
|
||||
|
||||
await page.goto('/workflows');
|
||||
await page.getByRole('button', { name: '+ Create Workflow' }).click();
|
||||
await page.locator('#wf-create-name').fill(name);
|
||||
await page.locator('#wf-create-description').fill('Created by the Playwright UI tests');
|
||||
await page.locator('#wf-create-definition').fill(JSON.stringify(definition, null, 2));
|
||||
await page.locator('#wf-create-form').getByRole('button', { name: 'Create' }).click();
|
||||
|
||||
const row = page.locator('#wf-list tr', { hasText: name });
|
||||
await expect(row).toBeVisible();
|
||||
await row.getByRole('button', { name: 'Execute' }).click();
|
||||
await page.locator('#wf-run-form').getByRole('button', { name: /Run/ }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/executions\?open=|\/executions$/);
|
||||
const detail = page.locator('#ex-detail-body');
|
||||
// Both steps ran on all three workers, and the execution finished.
|
||||
await expect(detail).toContainText(`wf-${id}`);
|
||||
await expect(detail).toContainText(/completed/i, { timeout: 20_000 });
|
||||
});
|
||||
|
||||
test('an invalid workflow definition is rejected with a message', async ({ page, problems }) => {
|
||||
await page.goto('/workflows');
|
||||
await page.getByRole('button', { name: '+ Create Workflow' }).click();
|
||||
await page.locator('#wf-create-name').fill('Broken definition');
|
||||
await page.locator('#wf-create-definition').fill('{ not json');
|
||||
await page.locator('#wf-create-form').getByRole('button', { name: 'Create' }).click();
|
||||
|
||||
await expect(page.locator('#wf-create-error')).toBeVisible();
|
||||
await expect(page.locator('#wf-list tr', { hasText: 'Broken definition' })).toHaveCount(0);
|
||||
expect(problems).toEqual([]); // rejected in the browser, so no failed request either
|
||||
});
|
||||
+1
-1
@@ -46,7 +46,7 @@ describe('validateWebhookUrl', () => {
|
||||
expect(validateWebhookUrl('http://127.0.0.1/hook')).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
test('172.16.x.x – 172.31.x.x private range is rejected', () => {
|
||||
test('172.16.x.x to 172.31.x.x private range is rejected', () => {
|
||||
expect(validateWebhookUrl('http://172.16.0.1/hook')).toMatchObject({ ok: false });
|
||||
expect(validateWebhookUrl('http://172.31.255.255/hook')).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
+4
-4
@@ -1,5 +1,5 @@
|
||||
<%#
|
||||
PULSE — LotusGuild Terminal Design System base layout.
|
||||
PULSE: LotusGuild Terminal Design System base layout.
|
||||
|
||||
Vendored from web_template/node/layout.ejs (bbec859) and extended for Pulse:
|
||||
fixed comment delimiters, skip link, mobile drawer, theme button, command
|
||||
@@ -30,7 +30,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="theme-color" content="#030508">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title><%= pageTitle ? pageTitle + ' — ' : '' %><%= appName %></title>
|
||||
<title><%= pageTitle ? pageTitle + ' | ' : '' %><%= appName %></title>
|
||||
|
||||
<!-- Fonts -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
@@ -154,13 +154,13 @@
|
||||
<span class="lt-footer-sep">|</span>
|
||||
<button type="button" class="lt-footer-hint" data-action="app:keys-help"><span class="lt-footer-key">[ ? ]</span> HELP</button>
|
||||
</nav>
|
||||
<span><%= appName.toUpperCase() %> — TDS v1.2</span>
|
||||
<span><%= appName.toUpperCase() %> | TDS v1.2</span>
|
||||
</footer>
|
||||
|
||||
<%- include('partials/keys-help') %>
|
||||
|
||||
<!-- =========================================================
|
||||
SCRIPTS — all tags carry the CSP nonce
|
||||
SCRIPTS: all tags carry the CSP nonce
|
||||
========================================================= -->
|
||||
|
||||
<!-- Runtime globals (the only inline script on the page) -->
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
<span class="lt-alert-icon">▤</span>
|
||||
<div class="lt-alert-body">
|
||||
<div class="lt-alert-title">Compare mode</div>
|
||||
<div class="lt-alert-msg">Select 2–5 executions to compare their outputs. Click a row to toggle selection.</div>
|
||||
<div class="lt-alert-msg">Select 2 to 5 executions to compare their outputs. Click a row to toggle selection.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -147,6 +147,18 @@ class PulseWorker {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -183,6 +195,11 @@ class PulseWorker {
|
||||
command_id,
|
||||
success: false,
|
||||
error: error.message,
|
||||
// exec() errors: code is the exit status (number) or a Node error code (string);
|
||||
// killed is set when the timeout fired; signal names what terminated the process.
|
||||
exit_code: typeof error.code === 'number' ? error.code : undefined,
|
||||
signal: error.signal || undefined,
|
||||
timed_out: error.killed && !!error.signal ? true : undefined,
|
||||
stdout: error.stdout || '',
|
||||
stderr: error.stderr || '',
|
||||
timestamp: new Date().toISOString()
|
||||
|
||||
Reference in new issue
Block a user