Merge pull request 'Fix abort, missing goto, offline schedules and the cron 500' (#66) from fix-known-bugs into main
CI / UI screenshots (before/after) (push) Skipped
CI / Lint (eslint) (push) Successful in 1m41s
CI / Security (npm audit) (push) Successful in 1m0s
CI / Test (jest) (push) Failing after 1m5s
CI / Scan (secrets, workflows, shell) (push) Successful in 4m25s
CI / Integration (api) (push) Failing after 4m31s
CI / UI (playwright) (push) Successful in 5m23s
CI / Deploy (push) Skipped
CI / Deploy worker (push) Skipped
CI / Notify (push) Successful in 4s

This commit was merged in pull request #66.
This commit is contained in:
jared committed 2026-11-23 00:26:30 -05:00
commit 1a031515e7
5 files changed
+166 -32

No files matched your search

+74 -17
View File
@@ -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 });
}
});
}
@@ -1429,8 +1477,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 });
@@ -1686,6 +1734,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);
@@ -1753,8 +1805,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=?',
@@ -1800,8 +1852,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