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
@@ -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
|
||||
|
||||
Reference in new issue
Block a user