diff --git a/lib/utils.js b/lib/utils.js index f404540..c282ad2 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -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 }; diff --git a/server.js b/server.js index 348453a..34aa22a 100644 --- a/server.js +++ b/server.js @@ -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 diff --git a/tests/condition.test.js b/tests/condition.test.js index 851077e..42df0ba 100644 --- a/tests/condition.test.js +++ b/tests/condition.test.js @@ -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([]); + }); +}); diff --git a/tests/integration/scheduler.int.js b/tests/integration/scheduler.int.js index 114b930..f7515f8 100644 --- a/tests/integration/scheduler.int.js +++ b/tests/integration/scheduler.int.js @@ -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(); } }); diff --git a/tests/integration/workflows.int.js b/tests/integration/workflows.int.js index b6a9a04..7aa83ce 100644 --- a/tests/integration/workflows.int.js +++ b/tests/integration/workflows.int.js @@ -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); +});