Fix abort, missing goto, offline schedules and the cron 500 (#8, #20, #9)
CI / UI screenshots (before/after) (push) Skipped
CI / Test (jest) (push) Successful in 32s
CI / Security (npm audit) (push) Successful in 15s
CI / Integration (api) (push) Successful in 4m4s
CI / Scan (secrets, workflows, shell) (push) Successful in 3m26s
CI / Lint (eslint) (pull_request) Successful in 1m12s
CI / Test (jest) (pull_request) Successful in 1m11s
CI / Scan (secrets, workflows, shell) (pull_request) Successful in 7m1s
CI / Integration (api) (pull_request) Successful in 7m41s
CI / UI screenshots (before/after) (pull_request) Successful in 28s
CI / UI (playwright) (pull_request) Successful in 4m41s
CI / Lint (eslint) (push) Successful in 24s
CI / Security (npm audit) (pull_request) Successful in 23s
CI / Deploy (pull_request) Skipped
CI / Deploy worker (pull_request) Skipped
CI / Notify (pull_request) Skipped
CI / UI (playwright) (push) Successful in 3m41s
CI / Deploy (push) Skipped
CI / Deploy worker (push) Skipped
CI / Notify (push) Skipped
CI / UI screenshots (before/after) (push) Skipped
CI / Test (jest) (push) Successful in 32s
CI / Security (npm audit) (push) Successful in 15s
CI / Integration (api) (push) Successful in 4m4s
CI / Scan (secrets, workflows, shell) (push) Successful in 3m26s
CI / Lint (eslint) (pull_request) Successful in 1m12s
CI / Test (jest) (pull_request) Successful in 1m11s
CI / Scan (secrets, workflows, shell) (pull_request) Successful in 7m1s
CI / Integration (api) (pull_request) Successful in 7m41s
CI / UI screenshots (before/after) (pull_request) Successful in 28s
CI / UI (playwright) (pull_request) Successful in 4m41s
CI / Lint (eslint) (push) Successful in 24s
CI / Security (npm audit) (pull_request) Successful in 23s
CI / Deploy (pull_request) Skipped
CI / Deploy worker (pull_request) Skipped
CI / Notify (pull_request) Skipped
CI / UI (playwright) (push) Successful in 3m41s
CI / Deploy (push) Skipped
CI / Deploy worker (push) Skipped
CI / Notify (push) Skipped
The four known-bug tests from #59 now pass as normal tests. - #8 abort: each workflow execution gets an AbortController. The abort route fires it; the engine checks it before every step and stops; wait steps, retry delays and waits for a worker's result end as soon as it fires. New test: aborting during a 20 s command stops the workflow within seconds and runs no further step. - #20 goto to a missing step: the execution now fails (it reported completed). Workflows are also checked on save: a goto, route or prompt route to a step id that doesn't exist is a 400 ('end' is always valid). A workflow saved before the check still fails at runtime (tested by writing one directly). - #9 schedules whose worker is offline: instead of skipping silently, the scheduler records a failed run ('Worker offline: the scheduled command was not sent'), visible in Executions. - An invalid cron expression (or any bad schedule) is a 400 with the parser's message instead of a 500. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8d96028070
commit
dc732a1ec5
5 files changed
+166
-32
No files matched your search
+28
-1
@@ -82,6 +82,33 @@ function conditionErrors(definition) {
|
||||
return problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every jump in a workflow definition to a step id that doesn't exist (#20), as
|
||||
* [{ step, goto, error }]. 'end' and '__end__' finish the workflow and are always valid.
|
||||
*/
|
||||
function gotoErrors(definition) {
|
||||
let def = definition;
|
||||
if (typeof def === 'string') {
|
||||
try { def = JSON.parse(def); } catch { return []; }
|
||||
}
|
||||
const steps = (def && Array.isArray(def.steps)) ? def.steps : [];
|
||||
const ids = new Set(steps.map(st => st && st.id).filter(Boolean));
|
||||
const ok = target => target === 'end' || target === '__end__' || ids.has(target);
|
||||
const problems = [];
|
||||
steps.forEach((step, i) => {
|
||||
if (!step) return;
|
||||
const label = step.id || step.name || `step ${i + 1}`;
|
||||
const targets = [];
|
||||
if (step.goto) targets.push(step.goto);
|
||||
for (const c of (Array.isArray(step.conditions) ? step.conditions : [])) if (c && c.goto) targets.push(c.goto);
|
||||
if (step.routes && typeof step.routes === 'object') targets.push(...Object.values(step.routes));
|
||||
for (const t of targets) {
|
||||
if (typeof t !== 'string' || !ok(t)) problems.push({ step: label, goto: t, error: `no step with id ${JSON.stringify(t)}` });
|
||||
}
|
||||
});
|
||||
return problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the next run date for a scheduled command.
|
||||
*/
|
||||
@@ -112,4 +139,4 @@ function calculateNextRun(scheduleType, scheduleValue) {
|
||||
throw new Error(`Unknown schedule type: ${scheduleType}`);
|
||||
}
|
||||
|
||||
module.exports = { validateWebhookUrl, applyParams, evalCondition, conditionErrors, calculateNextRun };
|
||||
module.exports = { validateWebhookUrl, applyParams, evalCondition, conditionErrors, gotoErrors, calculateNextRun };
|
||||
@@ -8,7 +8,7 @@ const path = require('path');
|
||||
const fs = require('fs');
|
||||
const helmet = require('helmet');
|
||||
require('dotenv').config();
|
||||
const { validateWebhookUrl, applyParams, evalCondition, conditionErrors, calculateNextRun } = require('./lib/utils');
|
||||
const { validateWebhookUrl, applyParams, evalCondition, conditionErrors, gotoErrors, calculateNextRun } = require('./lib/utils');
|
||||
const { PAGES } = require('./lib/nav');
|
||||
const { renderPage, renderError } = require('./lib/render');
|
||||
const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies, ALLOWED_GROUPS } = require('./lib/pageauth');
|
||||
@@ -369,6 +369,22 @@ async function processScheduledCommands() {
|
||||
});
|
||||
|
||||
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null });
|
||||
} else {
|
||||
// The worker isn't connected: record a failed run with the reason rather than
|
||||
// skipping silently, so a missed schedule shows up in Executions (#9).
|
||||
const executionId = crypto.randomUUID();
|
||||
const timestamp = new Date().toISOString();
|
||||
await pool.query(
|
||||
'INSERT INTO executions (id, workflow_id, status, started_by, started_at, completed_at, logs) VALUES (?, ?, ?, ?, NOW(), NOW(), ?)',
|
||||
[executionId, null, 'failed', `scheduler:${schedule.name}`, JSON.stringify([
|
||||
{ step: 'scheduled_command', action: 'command_sent', worker_id: workerId, command: schedule.command, timestamp },
|
||||
{ step: 'command_execution', action: 'command_result', worker_id: workerId, success: false,
|
||||
error: 'Worker offline: the scheduled command was not sent', stdout: '', stderr: '', timestamp }
|
||||
])]
|
||||
);
|
||||
console.warn(`[Scheduler] "${schedule.name}": worker ${workerId} is offline; recorded a failed run`);
|
||||
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null });
|
||||
broadcast({ type: 'execution_status', execution_id: executionId, status: 'failed' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -922,7 +938,7 @@ const _executionPrompts = new Map(); // executionId → resolve fn
|
||||
const _commandResolvers = new Map(); // commandId → resolve fn (event-driven result delivery)
|
||||
|
||||
async function executeWorkflowSteps(executionId, workflowId, definition, username, params = {}, dryRun = false) {
|
||||
_executionState.set(executionId, { params, state: {} });
|
||||
_executionState.set(executionId, { params, state: {}, abort: new AbortController() });
|
||||
|
||||
// Global execution timeout
|
||||
const maxMinutes = parseInt(process.env.EXECUTION_MAX_MINUTES) || 60;
|
||||
@@ -975,6 +991,11 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam
|
||||
await updateExecutionStatus(executionId, 'failed');
|
||||
return;
|
||||
}
|
||||
// Aborted (#8): the abort route already logged it and marked the execution failed.
|
||||
if (execState.abort && execState.abort.signal.aborted) {
|
||||
console.log(`[Workflow] ${executionId} aborted; not running step ${currentIndex + 1}`);
|
||||
return;
|
||||
}
|
||||
const stepLabel = step.name || step.id || `Step ${currentIndex + 1}`;
|
||||
console.log(`[Workflow] ${executionId} step ${currentIndex + 1}: ${stepLabel}`);
|
||||
|
||||
@@ -1030,7 +1051,7 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam
|
||||
step: currentIndex + 1, action: 'waiting', duration_ms: ms,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
await new Promise(r => setTimeout(r, ms));
|
||||
await abortableDelay(ms, execState.abort && execState.abort.signal);
|
||||
|
||||
} else if (step.type === 'parse') {
|
||||
// Parse KEY=VALUE lines from last command output into execution state.
|
||||
@@ -1088,12 +1109,14 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam
|
||||
if (stepIdMap.has(gotoId)) {
|
||||
currentIndex = stepIdMap.get(gotoId);
|
||||
} else {
|
||||
// A jump to a step that doesn't exist is a broken workflow, not a finished one (#20).
|
||||
await addExecutionLog(executionId, {
|
||||
action: 'goto_error', target: gotoId,
|
||||
message: `No step with id "${gotoId}" found`,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
break;
|
||||
await updateExecutionStatus(executionId, 'failed');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
currentIndex++;
|
||||
@@ -1265,7 +1288,8 @@ async function executeCommandStep(executionId, step, stepNumber, params = {}) {
|
||||
message: `Command failed, retrying (attempt ${attempt}/${maxRetries})...`,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
await new Promise(r => setTimeout(r, retryDelayMs));
|
||||
await abortableDelay(retryDelayMs, abortSignalOf(executionId));
|
||||
if (abortSignalOf(executionId) && abortSignalOf(executionId).aborted) break;
|
||||
// Re-send command for retry
|
||||
const retryCommandId = crypto.randomUUID();
|
||||
await addExecutionLog(executionId, {
|
||||
@@ -1314,18 +1338,42 @@ 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.
|
||||
// The abort signal of a running workflow execution (#8), or null.
|
||||
function abortSignalOf(executionId) {
|
||||
const st = _executionState.get(executionId);
|
||||
return st && st.abort ? st.abort.signal : null;
|
||||
}
|
||||
|
||||
// setTimeout that ends early when the execution is aborted.
|
||||
function abortableDelay(ms, signal) {
|
||||
return new Promise(resolve => {
|
||||
if (signal && signal.aborted) return resolve();
|
||||
const timer = setTimeout(done, ms);
|
||||
function done() {
|
||||
clearTimeout(timer);
|
||||
if (signal) signal.removeEventListener('abort', done);
|
||||
resolve();
|
||||
}
|
||||
if (signal) signal.addEventListener('abort', done, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForCommandResult(executionId, commandId, timeout) {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
_commandResolvers.delete(commandId);
|
||||
resolve({ success: false, error: 'Command timeout' });
|
||||
}, timeout);
|
||||
|
||||
_commandResolvers.set(commandId, (result) => {
|
||||
const signal = abortSignalOf(executionId);
|
||||
const finish = (result) => {
|
||||
clearTimeout(timer);
|
||||
_commandResolvers.delete(commandId);
|
||||
if (signal) signal.removeEventListener('abort', onAbort);
|
||||
resolve(result);
|
||||
});
|
||||
};
|
||||
const onAbort = () => finish({ success: false, error: 'Aborted' });
|
||||
const timer = setTimeout(() => finish({ success: false, error: 'Command timeout' }), timeout);
|
||||
_commandResolvers.set(commandId, finish);
|
||||
if (signal) {
|
||||
if (signal.aborted) onAbort();
|
||||
else signal.addEventListener('abort', onAbort, { once: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1428,8 +1476,8 @@ app.post('/api/workflows', authenticateSSO, requireJSON, async (req, res) => {
|
||||
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin only' });
|
||||
const { name, description, definition, webhook_url } = req.body;
|
||||
if (!name || !definition) return res.status(400).json({ error: 'name and definition are required' });
|
||||
const badConditions = conditionErrors(definition);
|
||||
if (badConditions.length) return res.status(400).json({ error: 'Invalid condition', problems: badConditions });
|
||||
const problems = [...conditionErrors(definition), ...gotoErrors(definition)];
|
||||
if (problems.length) return res.status(400).json({ error: 'Invalid workflow definition', problems });
|
||||
|
||||
const webhookCheck = validateWebhookUrl(webhook_url);
|
||||
if (!webhookCheck.ok) return res.status(400).json({ error: webhookCheck.reason });
|
||||
@@ -1685,6 +1733,10 @@ app.post('/api/executions/:id/abort', authenticateSSO, async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Stop the workflow engine: it checks this before each step, and waits end early (#8).
|
||||
const st = _executionState.get(executionId);
|
||||
if (st && st.abort) st.abort.abort();
|
||||
|
||||
// Unblock any pending prompt so the thread can exit
|
||||
const pending = _executionPrompts.get(executionId);
|
||||
if (pending) pending.resolve(null);
|
||||
@@ -1752,8 +1804,8 @@ app.put('/api/workflows/:id', authenticateSSO, requireJSON, async (req, res) =>
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Invalid JSON in definition' });
|
||||
}
|
||||
const badConditions = conditionErrors(defObj);
|
||||
if (badConditions.length) return res.status(400).json({ error: 'Invalid condition', problems: badConditions });
|
||||
const problems = [...conditionErrors(defObj), ...gotoErrors(defObj)];
|
||||
if (problems.length) return res.status(400).json({ error: 'Invalid workflow definition', problems });
|
||||
|
||||
const [result] = await pool.query(
|
||||
'UPDATE workflows SET name=?, description=?, definition=?, webhook_url=?, updated_at=NOW() WHERE id=?',
|
||||
@@ -1799,8 +1851,13 @@ app.post('/api/scheduled-commands', authenticateSSO, requireJSON, async (req, re
|
||||
}
|
||||
}
|
||||
|
||||
let nextRun;
|
||||
try {
|
||||
nextRun = calculateNextRun(schedule_type, schedule_value);
|
||||
} catch (e) {
|
||||
return res.status(400).json({ error: `Invalid schedule: ${e.message}` });
|
||||
}
|
||||
const id = crypto.randomUUID();
|
||||
const nextRun = calculateNextRun(schedule_type, schedule_value);
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO scheduled_commands
|
||||
|
||||
+16
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
const vm = require('vm');
|
||||
const { evaluateCondition, checkCondition } = require('../lib/condition');
|
||||
const { evalCondition, conditionErrors } = require('../lib/utils');
|
||||
const { evalCondition, conditionErrors, gotoErrors } = require('../lib/utils');
|
||||
|
||||
// Every condition used by the production workflows (2026-11-22).
|
||||
const PRODUCTION = [
|
||||
@@ -133,3 +133,18 @@ describe('conditionErrors', () => {
|
||||
expect(conditionErrors('{not json')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gotoErrors (#20)', () => {
|
||||
test('lists jumps to step ids that do not exist; end is always valid', () => {
|
||||
const problems = gotoErrors({ steps: [
|
||||
{ id: 'a', type: 'execute', goto: 'c' },
|
||||
{ id: 'b', type: 'route', conditions: [{ if: 'true', goto: 'nope' }, { default: true, goto: 'end' }] },
|
||||
{ id: 'c', type: 'prompt', routes: { Yes: 'a', No: '__end__', Maybe: 'missing' } },
|
||||
] });
|
||||
expect(problems.map(p => `${p.step}->${p.goto}`)).toEqual(['b->nope', 'c->missing']);
|
||||
});
|
||||
test('accepts a JSON string and ignores malformed JSON', () => {
|
||||
expect(gotoErrors(JSON.stringify({ steps: [{ id: 'x', goto: 'y' }] }))).toHaveLength(1);
|
||||
expect(gotoErrors('{oops')).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -72,15 +72,13 @@ test('only admins can create schedules, and bad input is refused', async () => {
|
||||
expect((await createSchedule({ command: 'true', worker_ids: [worker.id], schedule_value: '-5' })).status).toBe(400);
|
||||
});
|
||||
|
||||
// Known bug: calculateNextRun throws on a bad cron expression, and the route answers 500.
|
||||
test.failing('an invalid cron expression is a 400, not a server error', async () => {
|
||||
test('an invalid cron expression is a 400, not a server error', async () => {
|
||||
const worker = await workerByName('node-01');
|
||||
const r = await createSchedule({ command: 'true', worker_ids: [worker.id], schedule_type: 'cron', schedule_value: 'not a cron' });
|
||||
expect(r.status).toBe(400);
|
||||
});
|
||||
|
||||
// Known bug #9: a schedule whose worker is offline is skipped silently, leaving no trace.
|
||||
test.failing('a schedule whose worker is offline records a failed run (#9)', async () => {
|
||||
test('a schedule whose worker is offline records a failed run (#9)', async () => {
|
||||
const workerName = `int-sched-${unique()}`;
|
||||
const w = await startWorker(workerName);
|
||||
const name = `int ${unique()}`;
|
||||
@@ -93,5 +91,7 @@ test.failing('a schedule whose worker is offline records a failed run (#9)', asy
|
||||
const runs = await executionsOf(name);
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs[0].status).toBe('failed');
|
||||
const ex = await waitForExecution(runs[0].id);
|
||||
expect(commandResult(ex).error).toMatch(/offline/i);
|
||||
} finally { await w.stop(); }
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
'use strict';
|
||||
|
||||
// The workflow engine (executeWorkflowSteps in server.js), driven through the API
|
||||
// with real workers. Known bugs are written as test.failing: they document today's
|
||||
// behaviour and start failing (so the marker must be removed) once the bug is fixed.
|
||||
// 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)}`;
|
||||
@@ -134,8 +134,7 @@ test('an aborted execution stays failed', async () => {
|
||||
expect(ex.status).toBe('failed');
|
||||
});
|
||||
|
||||
// Known bug #8: abort marks the execution failed but the engine keeps going.
|
||||
test.failing('abort stops the workflow before its next step (#8)', async () => {
|
||||
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'] },
|
||||
@@ -147,13 +146,34 @@ test.failing('abort stops the workflow before its next step (#8)', async () => {
|
||||
expect(logs(ex, 'step_started').map(l => l.step)).toEqual([1]);
|
||||
});
|
||||
|
||||
// Known bug #20: a goto to a step that doesn't exist ends as 'completed'.
|
||||
test.failing('a goto to a missing step fails the execution (#20)', async () => {
|
||||
const id = await start(await createWorkflow([
|
||||
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' }] },
|
||||
]));
|
||||
const ex = await waitForExecution(id);
|
||||
] } });
|
||||
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 () => {
|
||||
@@ -169,3 +189,18 @@ test('a workflow whose condition does not parse is refused on save', async () =>
|
||||
] } });
|
||||
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);
|
||||
});
|
||||
Reference in new issue
Block a user