Files
pulse/tests/integration/workflows.int.js
T
jaredandClaude Opus 5.5 abb4b9326f
CI / Lint (eslint) (pull_request) Successful in 27s
CI / Test (jest) (pull_request) Successful in 19s
CI / Security (npm audit) (pull_request) Successful in 12s
CI / Scan (secrets, workflows, shell) (pull_request) Successful in 1m58s
CI / Integration (api) (pull_request) Successful in 2m49s
CI / UI (playwright) (pull_request) Successful in 2m15s
CI / Deploy (pull_request) Skipped
CI / Deploy worker (pull_request) Skipped
CI / Notify (pull_request) Skipped
CI / UI screenshots (before/after) (pull_request) Successful in 2m6s
Run multi-target commands in parallel (#26)
- Workflow execute steps send to all targets at once and wait for every
  result (Promise.all), so one slow or hung worker no longer holds up the
  rest; any failed target fails the step. parallel: false keeps the old
  one-at-a-time order, stopping at the first failure, for rolling changes.
  (Log appends are atomic in SQL, so concurrent targets can't lose
  entries.)
- Quick Command's multi-worker mode sends to every selected worker at once.
- Integration tests: 3 workers x 2 s finish in about 2 s; parallel: false
  takes 6 s or more; one failing target fails the step after all report.
- README: the parallel field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:07:26 -05:00

259 lines
12 KiB
JavaScript

'use strict';
// The workflow engine (executeWorkflowSteps in server.js), driven through the API
// with real workers. Known bugs, when there are any, are written as test.failing: they
// document today's behaviour and start failing once the bug is fixed.
const { sso, waitFor, waitForExecution, sleep } = require('./helpers');
const unique = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
async function createWorkflow(steps, extra = {}) {
const r = await sso('POST', '/api/workflows', { name: `int ${unique()}`, definition: { steps, ...extra } });
expect(r.status).toBe(200);
return r.json.id;
}
async function start(workflowId, body = {}) {
const r = await sso('POST', '/api/executions', { workflow_id: workflowId, ...body });
expect(r.status).toBe(200);
return r.json.id;
}
const logs = (ex, action) => (ex.logs || []).filter(l => l.action === action);
const outputs = ex => logs(ex, 'command_result').map(l => (l.stdout || '').trim());
test('an execute step on all workers runs everywhere and completes', async () => {
const marker = `all-${unique()}`;
const id = await start(await createWorkflow([
{ id: 'hello', name: 'Hello', type: 'execute', command: `echo ${marker}`, targets: ['all'] },
]));
const ex = await waitForExecution(id);
expect(ex.status).toBe('completed');
expect(outputs(ex).filter(o => o === marker)).toHaveLength(3);
});
test('a failing step fails the execution and stops the workflow', async () => {
const id = await start(await createWorkflow([
{ id: 'bad', type: 'execute', command: 'exit 3', targets: ['node-01'] },
{ id: 'never', type: 'execute', command: 'echo should-not-run', targets: ['node-01'] },
]));
const ex = await waitForExecution(id);
expect(ex.status).toBe('failed');
expect(outputs(ex)).not.toContain('should-not-run');
});
test('parse reads KEY=VALUE output and route jumps on it', async () => {
const id = await start(await createWorkflow([
{ id: 'probe', type: 'execute', command: 'echo STATUS=degraded', targets: ['node-01'] },
{ id: 'parse', type: 'parse' },
{ id: 'decide', type: 'route', conditions: [
{ if: "state.status === 'degraded'", goto: 'fix', label: 'needs fixing' },
{ default: true, goto: 'end' },
] },
{ id: 'skipped', type: 'execute', command: 'echo not-me', targets: ['node-01'] },
{ id: 'fix', type: 'execute', command: 'echo fixed', targets: ['node-01'] },
]));
const ex = await waitForExecution(id);
expect(ex.status).toBe('completed');
expect(logs(ex, 'parse_complete')[0].parsed).toEqual({ status: 'degraded' });
expect(logs(ex, 'route_taken')[0]).toMatchObject({ goto: 'fix', label: 'needs fixing' });
expect(outputs(ex)).toContain('fixed');
expect(outputs(ex)).not.toContain('not-me');
});
test('a false condition skips the step', async () => {
const id = await start(await createWorkflow([
{ id: 'prod-only', type: 'execute', command: 'echo prod', targets: ['node-01'], condition: "params.env === 'prod'" },
{ id: 'always', type: 'execute', command: 'echo always', targets: ['node-01'] },
], { params: [{ name: 'env' }] }), { params: { env: 'staging' } });
const ex = await waitForExecution(id);
expect(ex.status).toBe('completed');
expect(logs(ex, 'step_skipped')).toHaveLength(1);
expect(outputs(ex)).toEqual(['always']);
});
test('a prompt waits for an answer, rejects invalid options, and routes on the answer', async () => {
const id = await start(await createWorkflow([
{ id: 'ask', type: 'prompt', message: 'Restart?', options: ['Yes', 'No'], key: 'answer', routes: { No: 'end' } },
{ id: 'restart', type: 'execute', command: 'echo restarted', targets: ['node-02'] },
]));
await waitFor(async () => logs((await sso('GET', `/api/executions/${id}`)).json || {}, 'prompt').length > 0,
{ what: 'the prompt to be asked' });
expect((await sso('POST', `/api/executions/${id}/respond`, { response: 'Maybe' })).status).toBe(400);
expect((await sso('POST', `/api/executions/${id}/respond`, { response: 'Yes' })).status).toBe(200);
const ex = await waitForExecution(id);
expect(ex.status).toBe('completed');
expect(logs(ex, 'prompt_response')[0]).toMatchObject({ response: 'Yes', responded_by: 'int.tester' });
expect(outputs(ex)).toEqual(['restarted']);
});
test('parameters are substituted, and unsafe values are refused', async () => {
const wf = await createWorkflow([
{ id: 'greet', type: 'execute', command: 'echo host={{host}}', targets: ['node-03'] },
], { params: [{ name: 'host', required: true }] });
expect((await sso('POST', '/api/executions', { workflow_id: wf })).status).toBe(400); // required
const ok = await waitForExecution(await start(wf, { params: { host: 'db-01.lan' } }));
expect(ok.status).toBe('completed');
expect(outputs(ok)).toEqual(['host=db-01.lan']);
const bad = await waitForExecution(await start(wf, { params: { host: 'x; reboot' } }));
expect(bad.status).toBe('failed');
expect(outputs(bad)).toEqual([]);
});
test('a dry run logs the commands without running them', async () => {
const id = await start(await createWorkflow([
{ id: 'danger', type: 'execute', command: 'echo would-run', targets: ['all'] },
]), { dry_run: true });
const ex = await waitForExecution(id);
expect(ex.status).toBe('completed');
expect(logs(ex, 'dry_run_skipped')).toHaveLength(1);
expect(logs(ex, 'command_result')).toHaveLength(0);
});
test('an endless goto loop is detected and fails the execution', async () => {
const id = await start(await createWorkflow([
{ id: 'loop', type: 'route', conditions: [{ default: true, goto: 'loop' }] },
]));
const ex = await waitForExecution(id, { timeout: 60_000 });
expect(ex.status).toBe('failed');
expect(logs(ex, 'workflow_error')[0].error).toMatch(/Infinite loop/);
});
test('an aborted execution stays failed', async () => {
const id = await start(await createWorkflow([
{ id: 'pause', type: 'wait', duration: 2 },
{ id: 'after', type: 'execute', command: 'echo after-abort', targets: ['node-01'] },
]));
await sleep(500);
expect((await sso('POST', `/api/executions/${id}/abort`)).status).toBe(200);
await sleep(4000);
const ex = (await sso('GET', `/api/executions/${id}`)).json;
expect(ex.status).toBe('failed');
});
test('abort stops the workflow before its next step (#8)', async () => {
const id = await start(await createWorkflow([
{ id: 'pause', type: 'wait', duration: 2 },
{ id: 'after', type: 'execute', command: 'echo after-abort', targets: ['node-01'] },
]));
await sleep(500);
await sso('POST', `/api/executions/${id}/abort`);
await sleep(5000);
const ex = (await sso('GET', `/api/executions/${id}`)).json;
expect(logs(ex, 'step_started').map(l => l.step)).toEqual([1]);
});
test('a goto to a missing step is refused on save (#20)', async () => {
const r = await sso('POST', '/api/workflows', { name: `int ${unique()}`, definition: { steps: [
{ id: 'jump', type: 'route', conditions: [{ default: true, goto: 'no-such-step' }] },
] } });
expect(r.status).toBe(400);
expect(r.json.problems[0]).toMatchObject({ step: 'jump', goto: 'no-such-step' });
});
test('a saved workflow whose goto is missing fails at runtime instead of completing (#20)', async () => {
// Workflows saved before the check existed can still contain one: write it directly.
const mysql = require('mysql2/promise');
const db = await mysql.createConnection({
host: process.env.DB_HOST || '127.0.0.1', port: Number(process.env.DB_PORT || 3306),
user: process.env.DB_USER || 'pulse', password: process.env.DB_PASSWORD || 'ci-only', database: process.env.DB_NAME || 'pulse',
});
const wf = require('crypto').randomUUID();
try {
await db.query('INSERT INTO workflows (id, name, description, definition, created_by) VALUES (?, ?, ?, ?, ?)', [
wf, `int legacy ${unique()}`, '', JSON.stringify({ steps: [
{ id: 'jump', type: 'route', conditions: [{ default: true, goto: 'no-such-step' }] },
{ id: 'after', type: 'execute', command: 'echo should-not-run', targets: ['node-01'] },
] }), 'int.tester',
]);
} finally { await db.end(); }
const ex = await waitForExecution(await start(wf));
expect(ex.status).toBe('failed');
expect(logs(ex, 'goto_error')[0]).toMatchObject({ target: 'no-such-step' });
expect(outputs(ex)).toEqual([]);
});
test('a workflow whose condition does not parse is refused on save', async () => {
const create = await sso('POST', '/api/workflows', { name: `int ${unique()}`, definition: { steps: [
{ id: 'a', type: 'execute', command: 'true', targets: ['node-01'], condition: 'state.constructor' },
] } });
expect(create.status).toBe(400);
expect(create.json.problems[0]).toMatchObject({ step: 'a', condition: 'state.constructor' });
const id = await createWorkflow([{ id: 'ok', type: 'execute', command: 'true', targets: ['node-01'] }]);
const update = await sso('PUT', `/api/workflows/${id}`, { name: 'x', definition: { steps: [
{ id: 'r', type: 'route', conditions: [{ if: 'process', goto: 'end' }] },
] } });
expect(update.status).toBe(400);
});
test('abort during a long command stops the workflow at once, without waiting for the command (#8)', async () => {
const id = await start(await createWorkflow([
{ id: 'slow', type: 'execute', command: 'sleep 20', targets: ['node-02'] },
{ id: 'after', type: 'execute', command: 'echo after-abort', targets: ['node-02'] },
]));
await sleep(1000);
const t0 = Date.now();
expect((await sso('POST', `/api/executions/${id}/abort`)).status).toBe(200);
await sleep(2500);
const ex = (await sso('GET', `/api/executions/${id}`)).json;
expect(ex.status).toBe('failed');
expect(logs(ex, 'step_started').map(l => l.step)).toEqual([1]);
expect(Date.now() - t0).toBeLessThan(10_000);
});
test('an unanswered prompt fails the execution instead of continuing (#21)', async () => {
// The test stack sets PULSE_PROMPT_TIMEOUT_MS=8000.
const id = await start(await createWorkflow([
{ id: 'ask', type: 'prompt', message: 'Anyone there?', options: ['Yes'] },
{ id: 'after', type: 'execute', command: 'echo continued', targets: ['node-01'] },
]));
const ex = await waitForExecution(id, { timeout: 20_000 });
expect(ex.status).toBe('failed');
expect(logs(ex, 'prompt_timeout')).toHaveLength(1);
expect(outputs(ex)).toEqual([]);
});
test('the execution list marks runs waiting on a prompt (#3)', async () => {
const id = await start(await createWorkflow([
{ id: 'ask', type: 'prompt', message: 'Proceed?', options: ['Yes'] },
]));
const row = async () => ((await sso('GET', '/api/executions?limit=100')).json.executions || []).find(e => e.id === id);
await waitFor(async () => (await row())?.waiting_for_input === true, { what: 'the list to show it waiting' });
await sso('POST', `/api/executions/${id}/respond`, { response: 'Yes' });
await waitForExecution(id);
expect((await row()).waiting_for_input).toBe(false);
});
test('a step runs on all its targets at once (#26)', async () => {
const t0 = Date.now();
const ex = await waitForExecution(await start(await createWorkflow([
{ id: 'slow', type: 'execute', command: 'sleep 2; echo done', targets: ['all'] },
])));
expect(ex.status).toBe('completed');
expect(outputs(ex).filter(o => o === 'done')).toHaveLength(3);
expect(Date.now() - t0).toBeLessThan(5500); // in sequence it would take 6 s or more
});
test('parallel: false runs the targets one after another (#26)', async () => {
const t0 = Date.now();
const ex = await waitForExecution(await start(await createWorkflow([
{ id: 'slow', type: 'execute', command: 'sleep 2; echo done', targets: ['all'], parallel: false },
])), { timeout: 30_000 });
expect(ex.status).toBe('completed');
expect(Date.now() - t0).toBeGreaterThanOrEqual(6000);
});
test('a failure on one target fails the step, after every target has reported (#26)', async () => {
const ex = await waitForExecution(await start(await createWorkflow([
{ id: 'one-bad', type: 'execute', command: 'test "$WORKER_NAME" != node-02 && echo ok', targets: ['all'] },
{ id: 'after', type: 'execute', command: 'echo should-not-run', targets: ['node-01'] },
])));
expect(ex.status).toBe('failed');
expect(outputs(ex).filter(o => o === 'ok')).toHaveLength(2);
expect(outputs(ex)).not.toContain('should-not-run');
});