Integration tests for the Gandalf contract, auth and reliability; fix worker offline status
CI / Lint (eslint) (push) Successful in 46s
CI / Security (npm audit) (push) Successful in 26s
CI / Integration (api) (push) Successful in 1m31s
CI / Test (jest) (pull_request) Successful in 50s
CI / UI (playwright) (push) Successful in 2m31s
CI / Integration (api) (pull_request) Successful in 1m58s
CI / Test (jest) (push) Successful in 13s
CI / Deploy (push) Skipped
CI / Notify (push) Skipped
CI / UI (playwright) (pull_request) Successful in 2m16s
CI / Lint (eslint) (pull_request) Successful in 15s
CI / Security (npm audit) (pull_request) Successful in 15s
CI / Deploy (pull_request) Skipped
CI / Notify (pull_request) Skipped
CI / Lint (eslint) (push) Successful in 46s
CI / Security (npm audit) (push) Successful in 26s
CI / Integration (api) (push) Successful in 1m31s
CI / Test (jest) (pull_request) Successful in 50s
CI / UI (playwright) (push) Successful in 2m31s
CI / Integration (api) (pull_request) Successful in 1m58s
CI / Test (jest) (push) Successful in 13s
CI / Deploy (push) Skipped
CI / Notify (push) Skipped
CI / UI (playwright) (pull_request) Successful in 2m16s
CI / Lint (eslint) (pull_request) Successful in 15s
CI / Security (npm audit) (pull_request) Successful in 15s
CI / Deploy (pull_request) Skipped
CI / Notify (pull_request) Skipped
New CI job `Integration (api)` (#45 phase 3) runs the real server and three workers on Node 20 against MariaDB and tests them as a black box over HTTP and WebSocket (20 tests, about 12 s): - Gandalf contract: submit and poll, stdout from command_result, failures with exit code and stderr, 401 for wrong or missing key, 400 for missing fields or an unknown worker, 404 for an unknown execution - Auth: SSO identity, 401/403, heartbeat key, /healthz exposes only status; WebSocket upgrade refused without credentials, with a wrong key or a wrong group; live events reach a signed-in browser; a browser socket cannot forge a command result - Reliability: a worker killed mid-command fails the execution at once; a worker at capacity answers with a failure; an aborted execution stays failed when the late result arrives; a disconnected worker shows offline The last test found a bug from #42: the close handler deleted the worker's runtime-id entry before checking whether the socket was still live under its database id, and the two ids are normally the same key. So a disconnected worker was never marked offline and showed 'online' until the stale heartbeat sweep. Gandalf was unaffected (it checks live sockets). MariaDB setup for CI moves to scripts/ci/mariadb.sh, shared by both jobs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1d5b8cdd53
commit
def926d41e
11 files changed
+391
-21
No files matched your search
+29
-14
@@ -1,6 +1,6 @@
|
||||
name: CI
|
||||
|
||||
# One pipeline: lint, test, audit and the UI tests must all pass before main deploys (#45).
|
||||
# One pipeline: lint, unit tests, audit, integration and UI tests must all pass before main deploys (#45).
|
||||
# Actions are pinned to full commit SHAs (version in the trailing comment).
|
||||
|
||||
on:
|
||||
@@ -63,6 +63,30 @@ jobs:
|
||||
- name: Audit production and dev dependencies
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
integration:
|
||||
name: Integration (api)
|
||||
runs-on: ubuntu-latest
|
||||
container: node:20-bookworm # the server and workers on production's Node
|
||||
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
|
||||
run: scripts/ci/mariadb.sh
|
||||
- name: Start Pulse with three workers
|
||||
run: scripts/ci/ui-stack.sh start
|
||||
- name: Run integration tests (Gandalf contract, auth, reliability)
|
||||
run: npm run test:integration -- --ci
|
||||
- name: Server and worker logs
|
||||
if: always()
|
||||
run: tail -n 200 .ui-stack/*.log || true
|
||||
|
||||
ui:
|
||||
name: UI (playwright)
|
||||
runs-on: ubuntu-latest
|
||||
@@ -80,16 +104,7 @@ jobs:
|
||||
- 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)"
|
||||
run: scripts/ci/mariadb.sh
|
||||
- name: Start Pulse with three workers
|
||||
run: scripts/ci/ui-stack.sh start
|
||||
- name: Run Playwright (desktop and mobile)
|
||||
@@ -110,7 +125,7 @@ jobs:
|
||||
deploy:
|
||||
name: Deploy
|
||||
runs-on: ubuntu-latest
|
||||
needs: [lint, test, audit, ui]
|
||||
needs: [lint, test, audit, integration, 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:
|
||||
@@ -169,7 +184,7 @@ jobs:
|
||||
notify:
|
||||
name: Notify
|
||||
runs-on: ubuntu-latest
|
||||
needs: [lint, test, audit, ui, deploy]
|
||||
needs: [lint, test, audit, integration, ui, deploy]
|
||||
# Alert on any failure on main or in the weekly audit, and on every deploy outcome.
|
||||
if: >-
|
||||
always() && (
|
||||
@@ -183,7 +198,7 @@ jobs:
|
||||
REPO: ${{ github.repository }}
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
RESULTS: "lint=${{ needs.lint.result }} test=${{ needs.test.result }} audit=${{ needs.audit.result }} ui=${{ needs.ui.result }} deploy=${{ needs.deploy.result }}"
|
||||
RESULTS: "lint=${{ needs.lint.result }} test=${{ needs.test.result }} audit=${{ needs.audit.result }} integration=${{ needs.integration.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
|
||||
|
||||
@@ -589,14 +589,28 @@ Everything runs from `.gitea/workflows/ci.yml`:
|
||||
| `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) |
|
||||
| `Integration (api)` | Starts the real server and three workers on Node 20 against MariaDB, then runs `tests/integration/` over HTTP and WebSocket: the Gandalf API contract, HTTP and WebSocket auth, and execution reliability (worker crash, capacity, abort) | Every push and PR |
|
||||
| `UI (playwright)` | Starts the real server and three workers against a MariaDB service container, then runs the Playwright tests in `tests/ui/` (desktop and phone) | Every push and PR |
|
||||
| `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 |
|
||||
| `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 five checks pass |
|
||||
| `Notify` | Matrix alert on any failure on `main` or in the weekly audit, and on every deploy | As needed |
|
||||
|
||||
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
|
||||
`CI / Security (npm audit) (push)`, `CI / Integration (api) (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.
|
||||
|
||||
### Integration tests
|
||||
|
||||
`tests/integration/` tests the running server as a black box, the way Gandalf and the workers
|
||||
use it: Gandalf's submit-and-poll contract (`/api/internal/command`, `/api/internal/executions/:id`),
|
||||
SSO and worker-key auth on HTTP and on the WebSocket upgrade, forged results from a browser socket,
|
||||
and that executions always finish (a worker killed mid-command, a worker at capacity, an abort
|
||||
followed by a late result). Tests that need to kill or limit a worker start their own.
|
||||
|
||||
```bash
|
||||
DB_HOST=127.0.0.1 DB_PORT=3399 DB_USER=pulse DB_PASSWORD=... DB_NAME=pulse scripts/ci/ui-stack.sh start
|
||||
npm run test:integration
|
||||
```
|
||||
|
||||
### UI tests
|
||||
|
||||
The Playwright tests drive the real UI end to end: every page loads with no page errors, console
|
||||
|
||||
+2
-1
@@ -9,7 +9,8 @@
|
||||
"start": "node server.js",
|
||||
"test": "jest --coverage",
|
||||
"lint": "eslint --ext .js .",
|
||||
"test:ui": "playwright test"
|
||||
"test:ui": "playwright test",
|
||||
"test:integration": "jest --config tests/integration/jest.config.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/bin/bash
|
||||
# Installs and starts a throwaway MariaDB inside a CI job container (Debian or
|
||||
# Ubuntu, as root) and creates the database and user from DB_NAME, DB_USER and
|
||||
# DB_PASSWORD. Used instead of a service container: the Gitea runner puts jobs on
|
||||
# Docker's default bridge network, where services can't be reached by name.
|
||||
set -euo pipefail
|
||||
: "${DB_NAME:?}" "${DB_USER:?}" "${DB_PASSWORD:?}"
|
||||
|
||||
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
|
||||
if ! mariadb-admin ping --silent 2>/dev/null; then
|
||||
(mariadbd --user=mysql --bind-address=127.0.0.1 --port=3306 >/tmp/mariadb.log 2>&1 &)
|
||||
fi
|
||||
for _ in $(seq 1 30); do mariadb-admin ping --silent 2>/dev/null && break; sleep 1; done
|
||||
mariadb -e "CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\`;
|
||||
CREATE USER IF NOT EXISTS '${DB_USER}'@'127.0.0.1' IDENTIFIED BY '${DB_PASSWORD}';
|
||||
GRANT ALL ON \`${DB_NAME}\`.* TO '${DB_USER}'@'127.0.0.1';"
|
||||
echo "node $(node --version), $(mariadb --version)"
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/bash
|
||||
# Starts a throwaway Pulse stack for the Playwright UI tests (#45 phase 5):
|
||||
# Starts a throwaway Pulse stack for the integration and Playwright UI tests (#45):
|
||||
# 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.
|
||||
|
||||
@@ -733,13 +733,17 @@ wss.on('connection', (ws, req) => {
|
||||
}
|
||||
browserClients.delete(ws);
|
||||
workerClients.delete(ws);
|
||||
// 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.
|
||||
// Decide before unmapping anything: the runtime and database ids are usually the
|
||||
// same key, so deleting one first made the database check always fail and left
|
||||
// disconnected workers 'online'.
|
||||
const liveForDb = !!ws.dbWorkerId && workers.get(ws.dbWorkerId) === ws;
|
||||
if (ws.workerId && workers.get(ws.workerId) === ws) {
|
||||
workers.delete(ws.workerId);
|
||||
console.log(`Worker ${ws.workerId} (runtime ID) disconnected`);
|
||||
}
|
||||
// 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) {
|
||||
if (liveForDb) {
|
||||
workers.delete(ws.dbWorkerId);
|
||||
console.log(`Worker ${ws.dbWorkerId} (database ID) disconnected`);
|
||||
// Mark worker offline in DB
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
'use strict';
|
||||
|
||||
// HTTP and WebSocket authentication (#37, #38).
|
||||
const { api, sso, SSO, WORKER_KEY, openWs, workerByName, waitFor, gandalf, waitForExecution, commandResult } = require('./helpers');
|
||||
|
||||
describe('HTTP', () => {
|
||||
test('a trusted SSO identity in an allowed group is signed in', async () => {
|
||||
const r = await sso('GET', '/api/user');
|
||||
expect(r.status).toBe(200);
|
||||
expect(r.json.username).toBe('int.tester');
|
||||
});
|
||||
|
||||
test('no identity is 401, and a group outside the allowed list is 403', async () => {
|
||||
expect((await api('GET', '/api/user')).status).toBe(401);
|
||||
expect((await api('GET', '/api/user', { headers: { ...SSO, 'Remote-Groups': 'guests' } })).status).toBe(403);
|
||||
});
|
||||
|
||||
test('worker heartbeats need the worker key', async () => {
|
||||
const r = await api('POST', '/api/workers/heartbeat', {
|
||||
headers: { 'X-API-Key': 'wrong' }, body: { worker_id: 'x', name: 'x' },
|
||||
});
|
||||
expect(r.status).toBe(401);
|
||||
});
|
||||
|
||||
test('the public health check reveals no detail beyond status', async () => {
|
||||
const r = await api('GET', '/healthz');
|
||||
expect(r.status).toBe(200);
|
||||
expect(Object.keys(r.json).sort()).toEqual(['db', 'sha', 'status', 'uptime_s', 'version', 'workers']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('WebSocket upgrade', () => {
|
||||
test('is refused with no credentials (worker auth is enforced)', async () => {
|
||||
await expect(openWs()).rejects.toMatchObject({ status: 401 });
|
||||
});
|
||||
|
||||
test('is refused with a wrong worker key', async () => {
|
||||
await expect(openWs({ Authorization: 'Bearer wrong-key' })).rejects.toMatchObject({ status: 401 });
|
||||
});
|
||||
|
||||
test('is refused for an SSO identity outside the allowed groups', async () => {
|
||||
await expect(openWs({ ...SSO, 'Remote-Groups': 'guests' })).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
test('accepts the worker key', async () => {
|
||||
const ws = await openWs({ Authorization: `Bearer ${WORKER_KEY}` });
|
||||
ws.close();
|
||||
});
|
||||
|
||||
test('a signed-in browser receives live execution events', async () => {
|
||||
const ws = await openWs(SSO);
|
||||
try {
|
||||
const workerId = (await workerByName('node-02')).id;
|
||||
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'echo live' });
|
||||
const id = submit.json.execution_id;
|
||||
await waitFor(() => ws.messages.some(m => m.type === 'command_result' && m.execution_id === id),
|
||||
{ what: 'a command_result broadcast' });
|
||||
} finally { ws.close(); }
|
||||
});
|
||||
|
||||
test('a browser connection cannot forge a command result', async () => {
|
||||
const ws = await openWs(SSO);
|
||||
try {
|
||||
const workerId = (await workerByName('node-03')).id;
|
||||
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'sleep 1; echo genuine' });
|
||||
const id = submit.json.execution_id;
|
||||
ws.send(JSON.stringify({
|
||||
type: 'command_result', execution_id: id, worker_id: workerId, command_id: id,
|
||||
success: true, stdout: 'forged', stderr: '',
|
||||
}));
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(commandResult(ex).stdout.trim()).toBe('genuine');
|
||||
expect((ex.logs || []).filter(l => l.action === 'command_result')).toHaveLength(1);
|
||||
} finally { ws.close(); }
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
// The contract Gandalf depends on (gandalf/monitor.py PulseClient.run_command):
|
||||
// POST /api/internal/command -> {execution_id}; poll GET /api/internal/executions/:id
|
||||
// until status is 'completed' (stdout read from the command_result log) or 'failed'.
|
||||
const { gandalf, workerByName, waitForExecution, commandResult } = require('./helpers');
|
||||
|
||||
let workerId;
|
||||
beforeAll(async () => {
|
||||
workerId = (await workerByName('node-01')).id;
|
||||
});
|
||||
|
||||
test('a command runs and its stdout comes back the way Gandalf reads it', async () => {
|
||||
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'echo REACHABLE' });
|
||||
expect(submit.status).toBe(200);
|
||||
expect(submit.json.execution_id).toMatch(/^[0-9a-f-]{36}$/);
|
||||
|
||||
const ex = await waitForExecution(submit.json.execution_id);
|
||||
expect(ex.status).toBe('completed');
|
||||
expect(ex.started_by).toBe('gandalf:link_stats');
|
||||
expect(commandResult(ex).stdout.trim()).toBe('REACHABLE');
|
||||
});
|
||||
|
||||
test('a failing command ends as failed, with the exit code and stderr kept', async () => {
|
||||
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'echo oops >&2; exit 4' });
|
||||
const ex = await waitForExecution(submit.json.execution_id);
|
||||
expect(ex.status).toBe('failed');
|
||||
const r = commandResult(ex);
|
||||
expect(r.success).toBe(false);
|
||||
expect(r.exit_code).toBe(4);
|
||||
expect(r.stderr).toContain('oops');
|
||||
});
|
||||
|
||||
test.each([
|
||||
['a wrong key', 'not-the-key'],
|
||||
['no key', null],
|
||||
])('%s is refused on both endpoints', async (_label, key) => {
|
||||
const submit = await gandalf('POST', '/api/internal/command', { worker_id: workerId, command: 'true' }, key);
|
||||
expect(submit.status).toBe(401);
|
||||
const poll = await gandalf('GET', '/api/internal/executions/00000000-0000-0000-0000-000000000000', undefined, key);
|
||||
expect(poll.status).toBe(401);
|
||||
});
|
||||
|
||||
test('missing fields and unknown workers are rejected without creating an execution', async () => {
|
||||
expect((await gandalf('POST', '/api/internal/command', { worker_id: workerId })).status).toBe(400);
|
||||
expect((await gandalf('POST', '/api/internal/command', { command: 'true' })).status).toBe(400);
|
||||
const unknown = await gandalf('POST', '/api/internal/command', { worker_id: 'no-such-worker', command: 'true' });
|
||||
expect(unknown.status).toBe(400);
|
||||
expect(unknown.json.error).toBe('Worker not connected');
|
||||
});
|
||||
|
||||
test('an unknown execution id is a 404', async () => {
|
||||
const r = await gandalf('GET', '/api/internal/executions/00000000-0000-0000-0000-000000000000');
|
||||
expect(r.status).toBe(404);
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
'use strict';
|
||||
|
||||
const { spawn } = require('child_process');
|
||||
const path = require('path');
|
||||
const WebSocket = require('ws');
|
||||
|
||||
// Matches scripts/ci/ui-stack.sh.
|
||||
const BASE = process.env.PULSE_URL || 'http://127.0.0.1:8400';
|
||||
const WS_BASE = BASE.replace(/^http/, 'ws');
|
||||
const WORKER_KEY = process.env.PULSE_TEST_WORKER_KEY || 'ui-test-worker-key';
|
||||
const GANDALF_KEY = process.env.PULSE_TEST_GANDALF_KEY || 'ui-test-gandalf-key';
|
||||
|
||||
const SSO = {
|
||||
'Remote-User': 'int.tester',
|
||||
'Remote-Name': 'Integration Tester',
|
||||
'Remote-Email': 'int@example.invalid',
|
||||
'Remote-Groups': 'admin',
|
||||
};
|
||||
|
||||
async function api(method, url, { headers = {}, body } = {}) {
|
||||
const res = await fetch(BASE + url, {
|
||||
method,
|
||||
headers: { ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers },
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
const text = await res.text();
|
||||
let json = null;
|
||||
try { json = JSON.parse(text); } catch { /* not JSON */ }
|
||||
return { status: res.status, json, text };
|
||||
}
|
||||
const sso = (method, url, body) => api(method, url, { headers: SSO, body });
|
||||
const gandalf = (method, url, body, key = GANDALF_KEY) =>
|
||||
api(method, url, { headers: key === null ? {} : { 'X-Gandalf-API-Key': key }, body });
|
||||
|
||||
async function waitFor(fn, { timeout = 20_000, interval = 250, what = 'condition' } = {}) {
|
||||
const end = Date.now() + timeout;
|
||||
let last;
|
||||
while (Date.now() < end) {
|
||||
last = await fn();
|
||||
if (last) return last;
|
||||
await new Promise(r => setTimeout(r, interval));
|
||||
}
|
||||
throw new Error(`timed out waiting for ${what} (last value: ${JSON.stringify(last)})`);
|
||||
}
|
||||
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
async function workerByName(name) {
|
||||
const { json } = await sso('GET', '/api/workers');
|
||||
return (json || []).find(w => w.name === name);
|
||||
}
|
||||
|
||||
// Polls the Gandalf endpoint the way Gandalf does, until the execution leaves 'running'.
|
||||
async function waitForExecution(id, opts = {}) {
|
||||
return waitFor(async () => {
|
||||
const r = await gandalf('GET', `/api/internal/executions/${id}`);
|
||||
return r.json && r.json.status !== 'running' ? r.json : null;
|
||||
}, { what: `execution ${id} to finish`, ...opts });
|
||||
}
|
||||
|
||||
const commandResult = ex => (ex.logs || []).find(l => l.action === 'command_result');
|
||||
|
||||
// An extra worker process owned by one test, so it can be killed or limited.
|
||||
async function startWorker(name, env = {}) {
|
||||
const child = spawn(process.execPath, [path.join(__dirname, '..', '..', 'worker', 'worker.js')], {
|
||||
cwd: __dirname, // no .env here
|
||||
env: {
|
||||
...process.env,
|
||||
WORKER_NAME: name, PULSE_SERVER: BASE, PULSE_WS: WS_BASE,
|
||||
WORKER_API_KEY: WORKER_KEY, HEARTBEAT_INTERVAL: '5', ...env,
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
let log = '';
|
||||
child.stdout.on('data', d => { log += d; });
|
||||
child.stderr.on('data', d => { log += d; });
|
||||
const worker = await waitFor(async () => {
|
||||
const w = await workerByName(name);
|
||||
return w && w.status === 'online' ? w : null;
|
||||
}, { what: `worker ${name} to come online` }).catch(e => { child.kill('SIGKILL'); throw new Error(`${e.message}\n${log}`); });
|
||||
return {
|
||||
id: worker.id,
|
||||
child,
|
||||
log: () => log,
|
||||
async stop() {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill('SIGKILL');
|
||||
await new Promise(r => child.once('exit', r));
|
||||
}
|
||||
// Remove it so other suites (and the UI tests' worker counts) don't see it.
|
||||
await waitFor(async () => (await workerByName(name))?.status === 'offline', { timeout: 5_000, what: `${name} to show offline` });
|
||||
await sso('DELETE', `/api/workers/${worker.id}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Opens a WebSocket and resolves once open, or rejects with the HTTP status if refused.
|
||||
function openWs(headers = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(WS_BASE, { headers });
|
||||
const messages = [];
|
||||
ws.on('message', d => { try { messages.push(JSON.parse(d)); } catch { /* ignore */ } });
|
||||
ws.once('open', () => resolve(Object.assign(ws, { messages })));
|
||||
ws.once('unexpected-response', (req, res) => reject(Object.assign(new Error(`HTTP ${res.statusCode}`), { status: res.statusCode })));
|
||||
ws.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BASE, SSO, GANDALF_KEY, WORKER_KEY, api, sso, gandalf, waitFor, sleep,
|
||||
workerByName, waitForExecution, commandResult, startWorker, openWs,
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
'use strict';
|
||||
|
||||
// Integration tests: black-box tests against a running Pulse stack (real server,
|
||||
// MariaDB and workers), started by scripts/ci/ui-stack.sh. See README "Integration tests".
|
||||
module.exports = {
|
||||
rootDir: __dirname,
|
||||
testMatch: ['**/*.int.js'],
|
||||
testEnvironment: 'node',
|
||||
testTimeout: 60_000,
|
||||
maxWorkers: 1, // one shared stack: suites must not race each other
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
'use strict';
|
||||
|
||||
// Executions always reach a final state (#7), and a final state is final.
|
||||
const { sso, gandalf, startWorker, waitForExecution, commandResult, sleep, waitFor, workerByName } = require('./helpers');
|
||||
|
||||
const unique = () => `int-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
||||
|
||||
test('a worker that dies mid-command fails the execution at once, not hours later', async () => {
|
||||
const w = await startWorker(unique());
|
||||
try {
|
||||
const submit = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'sleep 30' });
|
||||
expect(submit.status).toBe(200);
|
||||
await sleep(500);
|
||||
w.child.kill('SIGKILL');
|
||||
|
||||
const ex = await waitForExecution(submit.json.execution_id, { timeout: 15_000 });
|
||||
expect(ex.status).toBe('failed');
|
||||
expect(commandResult(ex).error).toMatch(/disconnected/i);
|
||||
} finally { await w.stop(); }
|
||||
});
|
||||
|
||||
test('a worker that disconnects shows offline at once', async () => {
|
||||
const name = unique();
|
||||
const w = await startWorker(name);
|
||||
try {
|
||||
w.child.kill('SIGKILL');
|
||||
// Not after the stale-heartbeat sweep: the socket close marks it offline.
|
||||
await waitFor(async () => (await workerByName(name))?.status === 'offline', { timeout: 3_000, what: 'offline status' });
|
||||
} finally { await w.stop(); }
|
||||
});
|
||||
|
||||
test('a worker at capacity answers with a failure instead of staying silent', async () => {
|
||||
const w = await startWorker(unique(), { MAX_CONCURRENT_TASKS: '1' });
|
||||
try {
|
||||
const first = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'sleep 3; echo first' });
|
||||
await sleep(300);
|
||||
const second = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'echo second' });
|
||||
|
||||
const ex2 = await waitForExecution(second.json.execution_id, { timeout: 10_000 });
|
||||
expect(ex2.status).toBe('failed');
|
||||
expect(commandResult(ex2).error).toMatch(/capacity/i);
|
||||
|
||||
const ex1 = await waitForExecution(first.json.execution_id);
|
||||
expect(ex1.status).toBe('completed');
|
||||
} finally { await w.stop(); }
|
||||
});
|
||||
|
||||
test('an aborted execution stays failed when the worker reports back later', async () => {
|
||||
const w = await startWorker(unique());
|
||||
try {
|
||||
const submit = await gandalf('POST', '/api/internal/command', { worker_id: w.id, command: 'sleep 2; echo late' });
|
||||
const id = submit.json.execution_id;
|
||||
await sleep(300);
|
||||
expect((await sso('POST', `/api/executions/${id}/abort`)).status).toBe(200);
|
||||
|
||||
await sleep(3500); // the command finishes and the worker sends its result
|
||||
const ex = await waitForExecution(id);
|
||||
expect(ex.status).toBe('failed');
|
||||
expect((ex.logs || []).some(l => l.action === 'execution_aborted')).toBe(true);
|
||||
expect((ex.logs || []).some(l => l.action === 'command_result' && l.success)).toBe(false);
|
||||
} finally { await w.stop(); }
|
||||
});
|
||||
Reference in new issue
Block a user