Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb5ef452d5 | ||
|
|
16a93f02be | ||
|
|
567941cec4 | ||
|
|
57e4d7527f | ||
|
|
82ad678532 | ||
|
|
921d5f6540 | ||
|
|
b5e8455092 | ||
|
|
44e9f041f0 | ||
|
|
966c2be5cc |
No files matched your search
+19
-26
@@ -23,15 +23,15 @@ concurrency:
|
|||||||
|
|
||||||
# Node comes from each job's container image, not actions/setup-node: the runner
|
# Node comes from each job's container image, not actions/setup-node: the runner
|
||||||
# shares one tool cache volume between concurrent jobs, and parallel setup-node
|
# shares one tool cache volume between concurrent jobs, and parallel setup-node
|
||||||
# runs overwrote each other's Node install mid-job. node:20 matches production
|
# runs overwrote each other's Node install mid-job. Node 22 matches production
|
||||||
# (CT 122) and the worker (CT 153).
|
# (CT 122) and the worker (CT 153), both on NodeSource's node_22.x since 2026-11-23.
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint:
|
lint:
|
||||||
name: Lint (eslint)
|
name: Lint (eslint)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 20 # a hung step fails instead of blocking main
|
timeout-minutes: 20 # a hung step fails instead of blocking main
|
||||||
container: node:20-bookworm@sha256:8f693eaa7e0a8e71560c9a82b55fd54c2ae920a2ba5d2cde28bac7d1c01c9ba5
|
container: node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
with:
|
with:
|
||||||
@@ -53,7 +53,7 @@ jobs:
|
|||||||
name: Test (jest)
|
name: Test (jest)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 20
|
timeout-minutes: 20
|
||||||
container: node:20-bookworm@sha256:8f693eaa7e0a8e71560c9a82b55fd54c2ae920a2ba5d2cde28bac7d1c01c9ba5
|
container: node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
with:
|
with:
|
||||||
@@ -63,27 +63,11 @@ jobs:
|
|||||||
- name: Run jest with coverage
|
- name: Run jest with coverage
|
||||||
run: npm test -- --ci
|
run: npm test -- --ci
|
||||||
|
|
||||||
# The unit tests on the next Node LTS, ahead of moving production to it (#45). Not a
|
|
||||||
# required check: a failure here is a heads-up, not a blocker.
|
|
||||||
test-node22:
|
|
||||||
name: Test (Node 22)
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
timeout-minutes: 20
|
|
||||||
container: node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
|
||||||
with:
|
|
||||||
persist-credentials: false # no job pushes; keep the token out of .git/config
|
|
||||||
- name: Install dependencies (lockfile only)
|
|
||||||
run: npm ci
|
|
||||||
- name: Run jest
|
|
||||||
run: npx jest --ci
|
|
||||||
|
|
||||||
audit:
|
audit:
|
||||||
name: Security (npm audit)
|
name: Security (npm audit)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
container: node:20-bookworm@sha256:8f693eaa7e0a8e71560c9a82b55fd54c2ae920a2ba5d2cde28bac7d1c01c9ba5
|
container: node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
with:
|
with:
|
||||||
@@ -120,7 +104,7 @@ jobs:
|
|||||||
name: Integration (api)
|
name: Integration (api)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 25
|
timeout-minutes: 25
|
||||||
container: node:20-bookworm@sha256:8f693eaa7e0a8e71560c9a82b55fd54c2ae920a2ba5d2cde28bac7d1c01c9ba5 # the server and workers on production's Node
|
container: node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb # the server and workers on production's Node
|
||||||
env:
|
env:
|
||||||
DB_HOST: 127.0.0.1
|
DB_HOST: 127.0.0.1
|
||||||
DB_PORT: '3306'
|
DB_PORT: '3306'
|
||||||
@@ -147,7 +131,7 @@ jobs:
|
|||||||
name: Scan (secrets, workflows, shell)
|
name: Scan (secrets, workflows, shell)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 20
|
timeout-minutes: 20
|
||||||
container: node:20-bookworm@sha256:8f693eaa7e0a8e71560c9a82b55fd54c2ae920a2ba5d2cde28bac7d1c01c9ba5
|
container: node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
with:
|
with:
|
||||||
@@ -335,17 +319,26 @@ jobs:
|
|||||||
REPO: ${{ github.repository }}
|
REPO: ${{ github.repository }}
|
||||||
run: |
|
run: |
|
||||||
TAG="deploy-$(date -u +%Y.%m.%d)-${RUN_NUMBER}"
|
TAG="deploy-$(date -u +%Y.%m.%d)-${RUN_NUMBER}"
|
||||||
curl -sf -X POST \
|
API="https://code.lotusguild.org/api/v1/repos/${REPO}/tags"
|
||||||
|
code=$(curl -s -o /tmp/tag.json -w '%{http_code}' -X POST \
|
||||||
-H "Authorization: token $GITHUB_TOKEN" \
|
-H "Authorization: token $GITHUB_TOKEN" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d "{\"tag_name\":\"${TAG}\",\"target\":\"${GIT_SHA}\",\"message\":\"Deployed to production\"}" \
|
-d "{\"tag_name\":\"${TAG}\",\"target\":\"${GIT_SHA}\",\"message\":\"Deployed to production\"}" \
|
||||||
"https://code.lotusguild.org/api/v1/repos/${REPO}/tags"
|
"$API")
|
||||||
|
if [ "$code" = 201 ]; then echo "Tagged ${GIT_SHA} as ${TAG}"; exit 0; fi
|
||||||
|
# A rerun keeps its run number, so the tag can already exist: fine if it is
|
||||||
|
# this commit's, an error if it names another.
|
||||||
|
existing=$(curl -sf -H "Authorization: token $GITHUB_TOKEN" "$API/${TAG}" \
|
||||||
|
| node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{try{console.log(JSON.parse(d).commit.sha)}catch(e){}})')
|
||||||
|
if [ "$existing" = "$GIT_SHA" ]; then echo "${TAG} already marks ${GIT_SHA} (a rerun)"; exit 0; fi
|
||||||
|
echo "Could not tag ${GIT_SHA} as ${TAG} (HTTP ${code}; existing: ${existing:-none})"
|
||||||
|
cat /tmp/tag.json; exit 1
|
||||||
|
|
||||||
deploy-worker:
|
deploy-worker:
|
||||||
name: Deploy worker
|
name: Deploy worker
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 15
|
timeout-minutes: 15
|
||||||
container: node:20-bookworm@sha256:8f693eaa7e0a8e71560c9a82b55fd54c2ae920a2ba5d2cde28bac7d1c01c9ba5
|
container: node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb
|
||||||
needs: [deploy] # the server first: it must understand anything new the worker sends
|
needs: [deploy] # the server first: it must understand anything new the worker sends
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
concurrency:
|
concurrency:
|
||||||
|
|||||||
@@ -167,7 +167,7 @@ The central orchestration hub that:
|
|||||||
- Stores all data in MariaDB database
|
- Stores all data in MariaDB database
|
||||||
|
|
||||||
**Technology Stack:**
|
**Technology Stack:**
|
||||||
- Node.js 20.x
|
- Node.js 22.x
|
||||||
- Express.js (web framework)
|
- Express.js (web framework)
|
||||||
- WebSocket (ws package) for real-time bidirectional communication
|
- WebSocket (ws package) for real-time bidirectional communication
|
||||||
- MySQL2 (MariaDB driver)
|
- MySQL2 (MariaDB driver)
|
||||||
@@ -185,7 +185,7 @@ Lightweight execution agents that:
|
|||||||
- Automatically reconnect on connection loss
|
- Automatically reconnect on connection loss
|
||||||
|
|
||||||
**Technology Stack:**
|
**Technology Stack:**
|
||||||
- Node.js 20.x
|
- Node.js 22.x
|
||||||
- WebSocket client
|
- WebSocket client
|
||||||
- Child process execution
|
- Child process execution
|
||||||
- System metrics collection
|
- System metrics collection
|
||||||
@@ -213,7 +213,7 @@ Lightweight execution agents that:
|
|||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
- **Node.js 20.x** or higher
|
- **Node.js 22.x** or higher
|
||||||
- **MariaDB 10.x** or higher
|
- **MariaDB 10.x** or higher
|
||||||
- **Authelia** configured for SSO (optional but recommended)
|
- **Authelia** configured for SSO (optional but recommended)
|
||||||
- **Network Connectivity** between server and workers
|
- **Network Connectivity** between server and workers
|
||||||
@@ -405,6 +405,11 @@ expression). Each run is an execution started by `scheduler:<name>`. A run whose
|
|||||||
offline is recorded as failed ("Worker offline"), and a schedule whose previous run is still
|
offline is recorded as failed ("Worker offline"), and a schedule whose previous run is still
|
||||||
going is skipped.
|
going is skipped.
|
||||||
|
|
||||||
|
While you set a schedule, the dialog previews its next three runs. `daily` times and cron
|
||||||
|
expressions are worked out in the server's time zone, which the preview names. **Edit**
|
||||||
|
changes a schedule in place and works out its next run again. **Run now** runs it at once
|
||||||
|
(recording who asked) without moving its next run. **Runs** opens its past executions.
|
||||||
|
|
||||||
## Features in Detail
|
## Features in Detail
|
||||||
|
|
||||||
### Terminal Aesthetic
|
### Terminal Aesthetic
|
||||||
@@ -585,7 +590,7 @@ Everything runs from `.gitea/workflows/ci.yml`:
|
|||||||
| `Test (jest)` | `npm test`: unit tests for `lib/` and the worker, and the deploy-script sandbox tests. Fails if coverage drops below the floors in `package.json` (`lib/` 90% lines, `worker/` 40%) | Every push and PR |
|
| `Test (jest)` | `npm test`: unit tests for `lib/` and the worker, and the deploy-script sandbox tests. Fails if coverage drops below the floors in `package.json` (`lib/` 90% lines, `worker/` 40%) | Every push and PR |
|
||||||
| `Security (npm audit)` | `npm audit --audit-level=high`, plus a CycloneDX SBOM of production dependencies (kept 90 days as the `sbom-cyclonedx` artifact of each `main` build) | Every push and PR, and weekly (Monday 06:00) |
|
| `Security (npm audit)` | `npm audit --audit-level=high`, plus a CycloneDX SBOM of production dependencies (kept 90 days as the `sbom-cyclonedx` artifact of each `main` build) | Every push and PR, and weekly (Monday 06:00) |
|
||||||
| `Scan (secrets, workflows, shell)` | gitleaks over the whole git history, actionlint and zizmor on the workflow files (shellcheck on their scripts; zizmor for injection, credential persistence and unpinned images), shellcheck on every `*.sh`, a check that `public/web_template` is byte-identical to upstream at the commit in its `VERSION`, and semgrep (JavaScript, Node.js, Express, secrets and security-audit rule packs, plus Pulse's own rules in `.semgrep/pulse.yml`: no `vm`/`eval`, no shell commands in the server, no unescaped values in `innerHTML`; their test cases in `.semgrep/pulse.js` run first). Suppress a reviewed false positive on its line with `nosemgrep: <rule id>` and a comment saying why | Every push and PR |
|
| `Scan (secrets, workflows, shell)` | gitleaks over the whole git history, actionlint and zizmor on the workflow files (shellcheck on their scripts; zizmor for injection, credential persistence and unpinned images), shellcheck on every `*.sh`, a check that `public/web_template` is byte-identical to upstream at the commit in its `VERSION`, and semgrep (JavaScript, Node.js, Express, secrets and security-audit rule packs, plus Pulse's own rules in `.semgrep/pulse.yml`: no `vm`/`eval`, no shell commands in the server, no unescaped values in `innerHTML`; their test cases in `.semgrep/pulse.js` run first). Suppress a reviewed false positive on its line with `nosemgrep: <rule id>` and a comment saying why | Every push and PR |
|
||||||
| `Integration (api)` | Starts the real server and three workers on Node 20 against MariaDB, then runs `tests/integration/` over HTTP and WebSocket: the Gandalf API contract, HTTP and WebSocket auth, and execution reliability (worker crash, capacity, abort) | Every push and PR |
|
| `Integration (api)` | Starts the real server and three workers on Node 22 against MariaDB, then runs `tests/integration/` over HTTP and WebSocket: the Gandalf API contract, HTTP and WebSocket auth, and execution reliability (worker crash, capacity, abort) | Every push and PR |
|
||||||
| `UI (playwright)` | Starts the real server and three workers against a MariaDB service container, then runs the Playwright tests in `tests/ui/` (desktop and phone) | Every push and PR |
|
| `UI (playwright)` | Starts the real server and three workers against a MariaDB service container, then runs the Playwright tests in `tests/ui/` (desktop and phone) | Every push and PR |
|
||||||
| `UI screenshots (before/after)` | On PRs that touch `public/`, `views/` or the render/nav code: runs the base branch and the PR side by side with the same seeded data and uploads a `ui-screenshots` artifact with one before/after image per page (desktop and phone). Pages that came out identical are listed in `unchanged.txt`. Not a required check; attach the relevant images to the PR for review | Pull requests |
|
| `UI screenshots (before/after)` | On PRs that touch `public/`, `views/` or the render/nav code: runs the base branch and the PR side by side with the same seeded data and uploads a `ui-screenshots` artifact with one before/after image per page (desktop and phone). Pages that came out identical are listed in `unchanged.txt`. Not a required check; attach the relevant images to the PR for review | Pull requests |
|
||||||
| `Deploy` | Calls the `pulse-deploy` webhook on CT 122, waits until `/healthz` reports the tested commit, then tags it `deploy-*` | Push to `main`, only after all six checks pass |
|
| `Deploy` | Calls the `pulse-deploy` webhook on CT 122, waits until `/healthz` reports the tested commit, then tags it `deploy-*` | Push to `main`, only after all six checks pass |
|
||||||
@@ -727,10 +732,15 @@ Both Pulse hooks (`pulse-deploy` on CT 122 and `pulse-worker-deploy` on CT 153)
|
|||||||
from the CI runner, 10.10.10.70, as well as requiring the signature. If the runner's address changes,
|
from the CI runner, 10.10.10.70, as well as requiring the signature. If the runner's address changes,
|
||||||
deploys fail in CI (the verify step times out) until the `ip-range` is updated on both hosts.
|
deploys fail in CI (the verify step times out) until the `ip-range` is updated on both hosts.
|
||||||
|
|
||||||
To add a worker host, install Node 20 and the worker as above, give it a `.env` with `WORKER_NAME`,
|
To add a worker host, install Node 22 and the worker as above, give it a `.env` with `WORKER_NAME`,
|
||||||
`PULSE_SERVER`, `PULSE_WS` and `WORKER_API_KEY`, and add its hook (one hook URL per host in the
|
`PULSE_SERVER`, `PULSE_WS` and `WORKER_API_KEY`, and add its hook (one hook URL per host in the
|
||||||
`Deploy worker` job).
|
`Deploy worker` job).
|
||||||
|
|
||||||
|
Production installs Node from NodeSource's `node_22.x` apt repository. On Debian 13, use
|
||||||
|
NodeSource's current signing key (`https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key`,
|
||||||
|
dearmored to `/usr/share/keyrings/nodesource.gpg`): copies from before January 2026 bind the
|
||||||
|
key with SHA-1, which Debian 13 rejects, so `apt-get update` reports the repository as unsigned.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**PULSE** - Orchestrating your infrastructure, one heartbeat at a time. ⚡
|
**PULSE** - Orchestrating your infrastructure, one heartbeat at a time. ⚡
|
||||||
|
|||||||
+47
-2
@@ -269,9 +269,9 @@ function definitionErrors(definition) {
|
|||||||
/**
|
/**
|
||||||
* Calculate the next run date for a scheduled command.
|
* Calculate the next run date for a scheduled command.
|
||||||
*/
|
*/
|
||||||
function calculateNextRun(scheduleType, scheduleValue) {
|
function calculateNextRun(scheduleType, scheduleValue, from) {
|
||||||
const cronParser = require('cron-parser');
|
const cronParser = require('cron-parser');
|
||||||
const now = new Date();
|
const now = from instanceof Date ? new Date(from.getTime()) : new Date();
|
||||||
|
|
||||||
if (scheduleType === 'interval') {
|
if (scheduleType === 'interval') {
|
||||||
const minutes = parseInt(scheduleValue);
|
const minutes = parseInt(scheduleValue);
|
||||||
@@ -296,7 +296,52 @@ function calculateNextRun(scheduleType, scheduleValue) {
|
|||||||
throw new Error(`Unknown schedule type: ${scheduleType}`);
|
throw new Error(`Unknown schedule type: ${scheduleType}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The next `count` run times of a schedule, for the preview in the editor (#19). */
|
||||||
|
function nextRuns(scheduleType, scheduleValue, count = 3, from = new Date()) {
|
||||||
|
const runs = [];
|
||||||
|
let at = from;
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
at = calculateNextRun(scheduleType, scheduleValue, at);
|
||||||
|
runs.push(at);
|
||||||
|
}
|
||||||
|
return runs;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SCHEDULE_TYPES = ['interval', 'hourly', 'daily', 'cron'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check a schedule from the create or edit form (#19). Returns { error } or
|
||||||
|
* { value: { name, command, worker_ids, schedule_type, schedule_value, next_run } }.
|
||||||
|
*/
|
||||||
|
function scheduleInput(body) {
|
||||||
|
const b = body || {};
|
||||||
|
const name = typeof b.name === 'string' ? b.name.trim() : '';
|
||||||
|
const command = typeof b.command === 'string' ? b.command.trim() : '';
|
||||||
|
const type = b.schedule_type;
|
||||||
|
const value = b.schedule_value === undefined || b.schedule_value === null ? '' : String(b.schedule_value).trim();
|
||||||
|
if (!name) return { error: 'A name is required' };
|
||||||
|
if (name.length > 255) return { error: 'The name is too long (255 characters at most)' };
|
||||||
|
if (!command) return { error: 'A command is required' };
|
||||||
|
if (!Array.isArray(b.worker_ids) || b.worker_ids.length === 0 || !b.worker_ids.every(w => typeof w === 'string' && w)) {
|
||||||
|
return { error: 'Pick at least one worker' };
|
||||||
|
}
|
||||||
|
if (!SCHEDULE_TYPES.includes(type)) return { error: `schedule_type must be one of: ${SCHEDULE_TYPES.join(', ')}` };
|
||||||
|
if (!value) return { error: 'A schedule value is required' };
|
||||||
|
if ((type === 'interval' || type === 'hourly') && !/^[1-9]\d*$/.test(value)) {
|
||||||
|
return { error: `The ${type === 'interval' ? 'interval' : 'number of hours'} must be a whole number above 0` };
|
||||||
|
}
|
||||||
|
if (type === 'daily' && !/^([01]\d|2[0-3]):[0-5]\d$/.test(value)) return { error: 'The time must be HH:MM (24-hour)' };
|
||||||
|
let next;
|
||||||
|
try {
|
||||||
|
next = calculateNextRun(type, value);
|
||||||
|
} catch (e) {
|
||||||
|
return { error: `Invalid schedule: ${e.message}` };
|
||||||
|
}
|
||||||
|
return { value: { name, command, worker_ids: b.worker_ids, schedule_type: type, schedule_value: value, next_run: next } };
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
validateWebhookUrl, applyParams, evalCondition, conditionErrors, gotoErrors, calculateNextRun,
|
validateWebhookUrl, applyParams, evalCondition, conditionErrors, gotoErrors, calculateNextRun,
|
||||||
definitionErrors, resolveParams, checkParamValue, PARAM_RULE, PARAM_TYPES, STEP_TYPES,
|
definitionErrors, resolveParams, checkParamValue, PARAM_RULE, PARAM_TYPES, STEP_TYPES,
|
||||||
|
nextRuns, scheduleInput, SCHEDULE_TYPES,
|
||||||
};
|
};
|
||||||
Generated
+1
-1
@@ -26,7 +26,7 @@
|
|||||||
"jest": "^30.5.2"
|
"jest": "^30.5.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20"
|
"node": ">=22"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/code-frame": {
|
"node_modules/@babel/code-frame": {
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20"
|
"node": ">=22"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node server.js",
|
"start": "node server.js",
|
||||||
|
|||||||
@@ -181,6 +181,9 @@
|
|||||||
function listHtml(view) {
|
function listHtml(view) {
|
||||||
const st = state[view];
|
const st = state[view];
|
||||||
if (st.error) {
|
if (st.error) {
|
||||||
|
// The registry rule traces ?search= (deep link) into the request and on to this
|
||||||
|
// error text, but it does not know esc(); pulse-innerhtml-unescaped checks that.
|
||||||
|
// nosemgrep: javascript.browser.security.raw-html-concat.raw-html-concat
|
||||||
return '<div class="lt-alert lt-alert--error"><span class="lt-alert-icon">⚠</span>' +
|
return '<div class="lt-alert lt-alert--error"><span class="lt-alert-icon">⚠</span>' +
|
||||||
'<div class="lt-alert-body"><div class="lt-alert-title">Failed to load executions</div>' +
|
'<div class="lt-alert-body"><div class="lt-alert-title">Failed to load executions</div>' +
|
||||||
'<div class="lt-alert-msg">' + esc(st.error) + '</div></div></div>';
|
'<div class="lt-alert-msg">' + esc(st.error) + '</div></div></div>';
|
||||||
@@ -868,6 +871,14 @@
|
|||||||
async init() {
|
async init() {
|
||||||
const stored = Pulse.util.storage.get(VIEW_KEY, 'manual');
|
const stored = Pulse.util.storage.get(VIEW_KEY, 'manual');
|
||||||
state.view = (stored === 'automated') ? 'automated' : 'manual';
|
state.view = (stored === 'automated') ? 'automated' : 'manual';
|
||||||
|
// Deep link: /executions?view=automated&search=scheduler:<name> (#19, a schedule's runs).
|
||||||
|
try {
|
||||||
|
const q = new URLSearchParams(window.location.search);
|
||||||
|
const v = q.get('view');
|
||||||
|
if (v === 'manual' || v === 'automated') state.view = v;
|
||||||
|
const term = q.get('search');
|
||||||
|
if (term && $('ex-search')) $('ex-search').value = term;
|
||||||
|
} catch (e) { /* ignore a malformed query */ }
|
||||||
if (lt.tabs) lt.tabs.switch(PANEL[state.view]);
|
if (lt.tabs) lt.tabs.switch(PANEL[state.view]);
|
||||||
|
|
||||||
Pulse.events.on('tick', tickElapsed);
|
Pulse.events.on('tick', tickElapsed);
|
||||||
|
|||||||
@@ -8,3 +8,37 @@
|
|||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
font-size: 0.85em;
|
font-size: 0.85em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Next-runs preview in the schedule dialog (#19). */
|
||||||
|
.sc-preview {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
margin: -0.25rem 0 0.75rem;
|
||||||
|
}
|
||||||
|
.sc-preview:empty { display: none; }
|
||||||
|
.sc-preview ul { margin: 0.2rem 0; padding-left: 1.1rem; }
|
||||||
|
.sc-preview-title { color: var(--text-muted); letter-spacing: 0.05em; text-transform: uppercase; font-size: 0.65rem; }
|
||||||
|
.sc-preview-tz { color: var(--text-muted); font-size: 0.7rem; }
|
||||||
|
.sc-preview--bad { color: var(--accent-red); }
|
||||||
|
|
||||||
|
/* The schedule dialog's worker picker reuses Quick Command's markup, but quick.css
|
||||||
|
is not loaded here, so the rows ran together on one line. */
|
||||||
|
.qc-worker-list {
|
||||||
|
background: var(--bg-primary);
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
padding: 0.75rem;
|
||||||
|
max-height: 220px;
|
||||||
|
overflow-y: auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.4rem;
|
||||||
|
}
|
||||||
|
.qc-worker-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.4rem 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
}
|
||||||
|
.qc-worker-row--online { background: rgba(0, 255, 136, 0.05); }
|
||||||
@@ -10,6 +10,8 @@
|
|||||||
|
|
||||||
let _schedules = [];
|
let _schedules = [];
|
||||||
let _workers = [];
|
let _workers = [];
|
||||||
|
let _editingId = null; // set while the dialog edits an existing schedule (#19)
|
||||||
|
let _previewTimer = null;
|
||||||
|
|
||||||
/* -------------------------------------------------------------------
|
/* -------------------------------------------------------------------
|
||||||
Helpers
|
Helpers
|
||||||
@@ -68,14 +70,18 @@
|
|||||||
const statusBadge = s.enabled
|
const statusBadge = s.enabled
|
||||||
? '<span class="lt-badge lt-badge-green">ENABLED</span>'
|
? '<span class="lt-badge lt-badge-green">ENABLED</span>'
|
||||||
: '<span class="lt-badge lt-badge-red">DISABLED</span>';
|
: '<span class="lt-badge lt-badge-red">DISABLED</span>';
|
||||||
|
const runsHref = '/executions?view=automated&search=' + encodeURIComponent('scheduler:' + (s.name || ''));
|
||||||
const adminActions = Pulse.isAdmin
|
const adminActions = Pulse.isAdmin
|
||||||
? '<div class="lt-btn-group">' +
|
? '<div class="lt-btn-group">' +
|
||||||
|
'<button type="button" class="lt-btn lt-btn-primary lt-btn-sm" data-action="sc:run" data-id="' + esc(s.id) + '" data-name="' + esc(s.name || '') + '">▶ Run now</button>' +
|
||||||
|
'<button type="button" class="lt-btn lt-btn-secondary lt-btn-sm" data-action="sc:edit" data-id="' + esc(s.id) + '">✎ Edit</button>' +
|
||||||
'<button type="button" class="lt-btn lt-btn-secondary lt-btn-sm" data-action="sc:toggle" data-id="' + esc(s.id) + '" data-enabled="' + (s.enabled ? '1' : '0') + '">' +
|
'<button type="button" class="lt-btn lt-btn-secondary lt-btn-sm" data-action="sc:toggle" data-id="' + esc(s.id) + '" data-enabled="' + (s.enabled ? '1' : '0') + '">' +
|
||||||
(s.enabled ? '⏸ Disable' : '▶ Enable') +
|
(s.enabled ? '⏸ Disable' : '▶ Enable') +
|
||||||
'</button>' +
|
'</button>' +
|
||||||
'<button type="button" class="lt-btn lt-btn-danger lt-btn-sm" data-action="sc:delete" data-id="' + esc(s.id) + '" data-name="' + esc(s.name || '') + '">🗑 Delete</button>' +
|
'<button type="button" class="lt-btn lt-btn-danger lt-btn-sm" data-action="sc:delete" data-id="' + esc(s.id) + '" data-name="' + esc(s.name || '') + '">🗑 Delete</button>' +
|
||||||
|
'<a class="lt-btn lt-btn-ghost lt-btn-sm" href="' + esc(runsHref) + '">Runs</a>' +
|
||||||
'</div>'
|
'</div>'
|
||||||
: '';
|
: '<a class="lt-btn lt-btn-ghost lt-btn-sm" href="' + esc(runsHref) + '">Runs</a>';
|
||||||
return (
|
return (
|
||||||
'<tr class="' + (s.enabled ? '' : 'sc-row-disabled') + '">' +
|
'<tr class="' + (s.enabled ? '' : 'sc-row-disabled') + '">' +
|
||||||
'<td data-label="Name">' + esc(s.name || '') + '</td>' +
|
'<td data-label="Name">' + esc(s.name || '') + '</td>' +
|
||||||
@@ -161,12 +167,64 @@
|
|||||||
'<input type="number" id="sc-value" class="lt-input" placeholder="e.g. 2" min="1" max="24">';
|
'<input type="number" id="sc-value" class="lt-input" placeholder="e.g. 2" min="1" max="24">';
|
||||||
} else if (type === 'daily') {
|
} else if (type === 'daily') {
|
||||||
container.innerHTML =
|
container.innerHTML =
|
||||||
'<label class="lt-label" for="sc-value">Time (HH:MM)</label>' +
|
'<label class="lt-label" for="sc-value">Time (HH:MM, server time)</label>' +
|
||||||
'<input type="time" id="sc-value" class="lt-input">';
|
'<input type="time" id="sc-value" class="lt-input">';
|
||||||
|
} else if (type === 'cron') {
|
||||||
|
container.innerHTML =
|
||||||
|
'<label class="lt-label" for="sc-value">Cron expression</label>' +
|
||||||
|
'<input type="text" id="sc-value" class="lt-input" placeholder="*/15 * * * *" autocomplete="off" spellcheck="false">' +
|
||||||
|
'<div class="lt-form-hint">minute hour day-of-month month day-of-week, e.g. <code>0 2 * * 1-5</code> is 02:00 on weekdays</div>';
|
||||||
|
}
|
||||||
|
const valueEl = document.getElementById('sc-value');
|
||||||
|
if (valueEl) valueEl.addEventListener('input', previewSoon);
|
||||||
|
previewSoon();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The next three runs, worked out by the server in its own time zone (#19). */
|
||||||
|
function previewSoon() {
|
||||||
|
clearTimeout(_previewTimer);
|
||||||
|
_previewTimer = setTimeout(updatePreview, 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function updatePreview() {
|
||||||
|
const el = document.getElementById('sc-preview');
|
||||||
|
const typeEl = document.getElementById('sc-type');
|
||||||
|
const valueEl = document.getElementById('sc-value');
|
||||||
|
if (!el || !typeEl) return;
|
||||||
|
const value = valueEl ? valueEl.value.trim() : '';
|
||||||
|
if (!value) { el.textContent = ''; return; }
|
||||||
|
try {
|
||||||
|
const data = await Pulse.api.get('/api/scheduled-commands/preview?type=' + encodeURIComponent(typeEl.value) +
|
||||||
|
'&value=' + encodeURIComponent(value));
|
||||||
|
const runs = (data && data.next) || [];
|
||||||
|
el.className = 'sc-preview';
|
||||||
|
el.innerHTML = '<div class="sc-preview-title">Next runs</div><ul>' +
|
||||||
|
runs.map(r => '<li>' + esc(fmt.dateTime(r)) + '</li>').join('') + '</ul>' +
|
||||||
|
'<div class="sc-preview-tz">Worked out in the server\'s time zone: ' + esc((data && data.timezone) || 'unknown') + '</div>';
|
||||||
|
} catch (e) {
|
||||||
|
el.className = 'sc-preview sc-preview--bad';
|
||||||
|
el.textContent = (e && e.message) || 'Invalid schedule';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function showFormError(message) {
|
||||||
|
const el = document.getElementById('sc-create-error');
|
||||||
|
if (!el) return;
|
||||||
|
el.textContent = message || '';
|
||||||
|
el.hidden = !message;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setDialogMode(editing) {
|
||||||
|
const title = document.getElementById('sc-create-title');
|
||||||
|
const submit = document.getElementById('sc-submit');
|
||||||
|
if (title) title.textContent = editing ? 'Edit Scheduled Command' : 'Create Scheduled Command';
|
||||||
|
if (submit) submit.textContent = editing ? 'Save Changes' : 'Create Schedule';
|
||||||
|
}
|
||||||
|
|
||||||
function resetCreateForm() {
|
function resetCreateForm() {
|
||||||
|
_editingId = null;
|
||||||
|
setDialogMode(false);
|
||||||
|
showFormError('');
|
||||||
const form = document.getElementById('sc-create-form');
|
const form = document.getElementById('sc-create-form');
|
||||||
if (form) form.reset();
|
if (form) form.reset();
|
||||||
const type = document.getElementById('sc-type');
|
const type = document.getElementById('sc-type');
|
||||||
@@ -175,6 +233,37 @@
|
|||||||
renderCreateWorkerList();
|
renderCreateWorkerList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Edit in place (#19): the same dialog, filled in, saving with PUT.
|
||||||
|
function openEdit(id) {
|
||||||
|
const s = _schedules.find(x => x.id === id);
|
||||||
|
if (!s) return;
|
||||||
|
resetCreateForm();
|
||||||
|
_editingId = id;
|
||||||
|
setDialogMode(true);
|
||||||
|
document.getElementById('sc-name').value = s.name || '';
|
||||||
|
document.getElementById('sc-command').value = s.command || '';
|
||||||
|
document.getElementById('sc-type').value = s.schedule_type;
|
||||||
|
updateValueInput();
|
||||||
|
const valueEl = document.getElementById('sc-value');
|
||||||
|
if (valueEl) valueEl.value = s.schedule_value || '';
|
||||||
|
const ids = new Set(parseWorkerIds(s.worker_ids));
|
||||||
|
document.querySelectorAll('input[name="sc-worker-cb"]').forEach(cb => { cb.checked = ids.has(cb.value); });
|
||||||
|
previewSoon();
|
||||||
|
if (window.lt && lt.modal) lt.modal.open('sc-create-modal');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runNow(id, name) {
|
||||||
|
try {
|
||||||
|
const r = await Pulse.api.post('/api/scheduled-commands/' + encodeURIComponent(id) + '/run', {});
|
||||||
|
const msg = 'Ran "' + name + '" on ' + r.sent + ' worker' + (r.sent === 1 ? '' : 's') +
|
||||||
|
(r.offline ? ' (' + r.offline + ' offline)' : '');
|
||||||
|
if (r.offline) Pulse.toast.warning(msg); else Pulse.toast.success(msg);
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
Pulse.toast.error('Could not run "' + name + '": ' + (e.message || 'unknown error'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function submitCreate() {
|
async function submitCreate() {
|
||||||
const name = document.getElementById('sc-name').value.trim();
|
const name = document.getElementById('sc-name').value.trim();
|
||||||
const command = document.getElementById('sc-command').value.trim();
|
const command = document.getElementById('sc-command').value.trim();
|
||||||
@@ -184,24 +273,22 @@
|
|||||||
const workerIds = Array.from(document.querySelectorAll('input[name="sc-worker-cb"]:checked')).map(cb => cb.value);
|
const workerIds = Array.from(document.querySelectorAll('input[name="sc-worker-cb"]:checked')).map(cb => cb.value);
|
||||||
|
|
||||||
if (!name || !command || !value || workerIds.length === 0) {
|
if (!name || !command || !value || workerIds.length === 0) {
|
||||||
Pulse.toast.error('Please fill in all fields and select at least one worker');
|
showFormError('Fill in every field and pick at least one worker');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const body = { name: name, command: command, worker_ids: workerIds, schedule_type: type, schedule_value: value };
|
||||||
|
const editing = _editingId;
|
||||||
try {
|
try {
|
||||||
await Pulse.api.post('/api/scheduled-commands', {
|
if (editing) await Pulse.api.put('/api/scheduled-commands/' + encodeURIComponent(editing), body);
|
||||||
name: name,
|
else await Pulse.api.post('/api/scheduled-commands', body);
|
||||||
command: command,
|
|
||||||
worker_ids: workerIds,
|
|
||||||
schedule_type: type,
|
|
||||||
schedule_value: value,
|
|
||||||
});
|
|
||||||
if (window.lt && lt.modal) lt.modal.close('sc-create-modal');
|
if (window.lt && lt.modal) lt.modal.close('sc-create-modal');
|
||||||
Pulse.toast.success('Schedule created successfully');
|
Pulse.toast.success(editing ? 'Schedule saved' : 'Schedule created');
|
||||||
resetCreateForm();
|
resetCreateForm();
|
||||||
await load();
|
await load();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
Pulse.toast.error('Failed to create schedule: ' + (e.message || 'unknown error'));
|
// The server says what is wrong (e.g. a bad cron expression): keep the dialog open.
|
||||||
|
showFormError((e && e.message) || 'Could not save the schedule');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,6 +362,8 @@
|
|||||||
'sc:create-submit': submitCreate,
|
'sc:create-submit': submitCreate,
|
||||||
'sc:type': updateValueInput,
|
'sc:type': updateValueInput,
|
||||||
'sc:toggle': (el) => toggleSchedule(el.getAttribute('data-id')),
|
'sc:toggle': (el) => toggleSchedule(el.getAttribute('data-id')),
|
||||||
|
'sc:edit': (el) => openEdit(el.getAttribute('data-id')),
|
||||||
|
'sc:run': (el) => runNow(el.getAttribute('data-id'), el.getAttribute('data-name')),
|
||||||
'sc:delete': (el) => deleteSchedule(el.getAttribute('data-id'), el.getAttribute('data-name')),
|
'sc:delete': (el) => deleteSchedule(el.getAttribute('data-id'), el.getAttribute('data-name')),
|
||||||
});
|
});
|
||||||
Pulse.events.on('tick', onTick);
|
Pulse.events.on('tick', onTick);
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ const fs = require('fs');
|
|||||||
const helmet = require('helmet');
|
const helmet = require('helmet');
|
||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
const { validateWebhookUrl, applyParams, evalCondition, conditionErrors, gotoErrors, calculateNextRun,
|
const { validateWebhookUrl, applyParams, evalCondition, conditionErrors, gotoErrors, calculateNextRun,
|
||||||
definitionErrors, resolveParams } = require('./lib/utils');
|
definitionErrors, resolveParams, nextRuns, scheduleInput } = require('./lib/utils');
|
||||||
const { PAGES } = require('./lib/nav');
|
const { PAGES } = require('./lib/nav');
|
||||||
const { renderPage, renderError } = require('./lib/render');
|
const { renderPage, renderError } = require('./lib/render');
|
||||||
const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies, ALLOWED_GROUPS } = require('./lib/pageauth');
|
const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies, ALLOWED_GROUPS } = require('./lib/pageauth');
|
||||||
@@ -307,6 +307,76 @@ if (!DEV_READONLY) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Scheduled Commands Processor
|
// Scheduled Commands Processor
|
||||||
|
/**
|
||||||
|
* Send a schedule's command to each of its workers, recording a failed run for any
|
||||||
|
* that is offline (#9). Used by the scheduler loop and by Run now (#19, triggeredBy).
|
||||||
|
*/
|
||||||
|
async function dispatchSchedule(schedule, triggeredBy) {
|
||||||
|
// Handle both string (raw SQL) and object (auto-parsed by MySQL2 JSON column)
|
||||||
|
let workerIds;
|
||||||
|
try {
|
||||||
|
workerIds = typeof schedule.worker_ids === 'string'
|
||||||
|
? JSON.parse(schedule.worker_ids)
|
||||||
|
: schedule.worker_ids;
|
||||||
|
} catch {
|
||||||
|
console.error(`[Scheduler] Invalid worker_ids JSON for "${schedule.name}": skipping`);
|
||||||
|
return { sent: 0, offline: 0 };
|
||||||
|
}
|
||||||
|
let sent = 0;
|
||||||
|
let offline = 0;
|
||||||
|
|
||||||
|
// Execute command on each worker
|
||||||
|
for (const workerId of workerIds) {
|
||||||
|
const workerWs = workers.get(workerId);
|
||||||
|
if (workerWs && workerWs.readyState === WebSocket.OPEN) {
|
||||||
|
const executionId = crypto.randomUUID();
|
||||||
|
|
||||||
|
// Create execution record
|
||||||
|
await pool.query(
|
||||||
|
'INSERT INTO executions (id, workflow_id, status, started_by, started_at, logs) VALUES (?, ?, ?, ?, NOW(), ?)',
|
||||||
|
[executionId, null, 'running', `scheduler:${schedule.name}`, JSON.stringify([{
|
||||||
|
step: 'scheduled_command',
|
||||||
|
action: 'command_sent',
|
||||||
|
worker_id: workerId,
|
||||||
|
command: schedule.command,
|
||||||
|
...(triggeredBy ? { triggered_by: triggeredBy } : {}),
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
}])]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Send command to worker
|
||||||
|
sendCommandToWorker(workerWs, {
|
||||||
|
type: 'execute_command',
|
||||||
|
execution_id: executionId,
|
||||||
|
command: schedule.command,
|
||||||
|
worker_id: workerId,
|
||||||
|
timeout: 5 * 60_000 // SCHEDULED_CMD_TIMEOUT
|
||||||
|
});
|
||||||
|
|
||||||
|
broadcast({ type: 'execution_started', execution_id: executionId, workflow_id: null });
|
||||||
|
sent++;
|
||||||
|
} else {
|
||||||
|
offline++;
|
||||||
|
// 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' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { sent, offline };
|
||||||
|
}
|
||||||
|
|
||||||
async function processScheduledCommands() {
|
async function processScheduledCommands() {
|
||||||
try {
|
try {
|
||||||
const [schedules] = await pool.query(
|
const [schedules] = await pool.query(
|
||||||
@@ -340,64 +410,7 @@ async function processScheduledCommands() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
console.log(`[Scheduler] Running scheduled command: ${schedule.name}`);
|
console.log(`[Scheduler] Running scheduled command: ${schedule.name}`);
|
||||||
|
await dispatchSchedule(schedule);
|
||||||
// Handle both string (raw SQL) and object (auto-parsed by MySQL2 JSON column)
|
|
||||||
let workerIds;
|
|
||||||
try {
|
|
||||||
workerIds = typeof schedule.worker_ids === 'string'
|
|
||||||
? JSON.parse(schedule.worker_ids)
|
|
||||||
: schedule.worker_ids;
|
|
||||||
} catch {
|
|
||||||
console.error(`[Scheduler] Invalid worker_ids JSON for "${schedule.name}": skipping`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Execute command on each worker
|
|
||||||
for (const workerId of workerIds) {
|
|
||||||
const workerWs = workers.get(workerId);
|
|
||||||
if (workerWs && workerWs.readyState === WebSocket.OPEN) {
|
|
||||||
const executionId = crypto.randomUUID();
|
|
||||||
|
|
||||||
// Create execution record
|
|
||||||
await pool.query(
|
|
||||||
'INSERT INTO executions (id, workflow_id, status, started_by, started_at, logs) VALUES (?, ?, ?, ?, NOW(), ?)',
|
|
||||||
[executionId, null, 'running', `scheduler:${schedule.name}`, JSON.stringify([{
|
|
||||||
step: 'scheduled_command',
|
|
||||||
action: 'command_sent',
|
|
||||||
worker_id: workerId,
|
|
||||||
command: schedule.command,
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
}])]
|
|
||||||
);
|
|
||||||
|
|
||||||
// Send command to worker
|
|
||||||
sendCommandToWorker(workerWs, {
|
|
||||||
type: 'execute_command',
|
|
||||||
execution_id: executionId,
|
|
||||||
command: schedule.command,
|
|
||||||
worker_id: workerId,
|
|
||||||
timeout: 5 * 60_000 // SCHEDULED_CMD_TIMEOUT
|
|
||||||
});
|
|
||||||
|
|
||||||
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' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// next_run and last_run already updated atomically above when we claimed the slot
|
// next_run and last_run already updated atomically above when we claimed the slot
|
||||||
}
|
}
|
||||||
@@ -1903,44 +1916,76 @@ app.get('/api/scheduled-commands', authenticateSSO, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
app.get('/api/scheduled-commands/preview', authenticateSSO, (req, res) => {
|
||||||
|
// The next few runs for the editor, and the time zone they are worked out in.
|
||||||
|
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||||
|
try {
|
||||||
|
const runs = nextRuns(String(req.query.type || ''), String(req.query.value || ''), 3);
|
||||||
|
res.json({ next: runs.map(d => d.toISOString()), timezone });
|
||||||
|
} catch (e) {
|
||||||
|
res.status(400).json({ error: `Invalid schedule: ${e.message}`, timezone });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
app.post('/api/scheduled-commands', authenticateSSO, requireJSON, async (req, res) => {
|
app.post('/api/scheduled-commands', authenticateSSO, requireJSON, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });
|
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });
|
||||||
const { name, command, worker_ids, schedule_type, schedule_value } = req.body;
|
const checked = scheduleInput(req.body);
|
||||||
|
if (checked.error) return res.status(400).json({ error: checked.error });
|
||||||
if (!name || !command || !worker_ids || !schedule_type || !schedule_value) {
|
const v = checked.value;
|
||||||
return res.status(400).json({ error: 'Missing required fields' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate schedule_value for numeric types
|
|
||||||
if (schedule_type === 'interval' || schedule_type === 'hourly') {
|
|
||||||
const n = parseInt(schedule_value, 10);
|
|
||||||
if (!Number.isInteger(n) || n <= 0) {
|
|
||||||
return res.status(400).json({ error: `schedule_value for type "${schedule_type}" must be a positive integer` });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 id = crypto.randomUUID();
|
||||||
|
|
||||||
await pool.query(
|
await pool.query(
|
||||||
`INSERT INTO scheduled_commands
|
`INSERT INTO scheduled_commands
|
||||||
(id, name, command, worker_ids, schedule_type, schedule_value, created_by, next_run)
|
(id, name, command, worker_ids, schedule_type, schedule_value, created_by, next_run)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
[id, name, command, JSON.stringify(worker_ids), schedule_type, schedule_value, req.user.username, nextRun]
|
[id, v.name, v.command, JSON.stringify(v.worker_ids), v.schedule_type, v.schedule_value, req.user.username, v.next_run]
|
||||||
);
|
);
|
||||||
|
|
||||||
res.json({ success: true, id });
|
res.json({ success: true, id });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: 'Internal server error' });
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Edit a schedule in place, keeping its history (#19). The next run is worked out afresh.
|
||||||
|
app.put('/api/scheduled-commands/:id', authenticateSSO, requireJSON, async (req, res) => {
|
||||||
|
try {
|
||||||
|
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });
|
||||||
|
const checked = scheduleInput(req.body);
|
||||||
|
if (checked.error) return res.status(400).json({ error: checked.error });
|
||||||
|
const v = checked.value;
|
||||||
|
const [result] = await pool.query(
|
||||||
|
`UPDATE scheduled_commands SET name = ?, command = ?, worker_ids = ?, schedule_type = ?, schedule_value = ?, next_run = ?
|
||||||
|
WHERE id = ?`,
|
||||||
|
[v.name, v.command, JSON.stringify(v.worker_ids), v.schedule_type, v.schedule_value, v.next_run, req.params.id]
|
||||||
|
);
|
||||||
|
if (result.affectedRows === 0) return res.status(404).json({ error: 'Schedule not found' });
|
||||||
|
res.json({ success: true, next_run: v.next_run });
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run a schedule now, without changing when it next runs on its own (#19).
|
||||||
|
app.post('/api/scheduled-commands/:id/run', authenticateSSO, async (req, res) => {
|
||||||
|
try {
|
||||||
|
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });
|
||||||
|
const [rows] = await pool.query('SELECT * FROM scheduled_commands WHERE id = ?', [req.params.id]);
|
||||||
|
if (rows.length === 0) return res.status(404).json({ error: 'Schedule not found' });
|
||||||
|
const schedule = rows[0];
|
||||||
|
const [running] = await pool.query(
|
||||||
|
"SELECT id FROM executions WHERE started_by = ? AND status = 'running' LIMIT 1",
|
||||||
|
[`scheduler:${schedule.name}`]
|
||||||
|
);
|
||||||
|
if (running.length) return res.status(409).json({ error: 'A run of this schedule is still in progress' });
|
||||||
|
const result = await dispatchSchedule(schedule, req.user.username);
|
||||||
|
await pool.query('UPDATE scheduled_commands SET last_run = NOW() WHERE id = ?', [schedule.id]);
|
||||||
|
console.log(`[Scheduler] "${schedule.name}" run now by ${req.user.username}: ${result.sent} sent, ${result.offline} offline`);
|
||||||
|
res.json({ success: true, ...result });
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
app.put('/api/scheduled-commands/:id/toggle', authenticateSSO, async (req, res) => {
|
app.put('/api/scheduled-commands/:id/toggle', authenticateSSO, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });
|
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin access required' });
|
||||||
|
|||||||
@@ -95,3 +95,58 @@ test('a schedule whose worker is offline records a failed run (#9)', async () =>
|
|||||||
expect(commandResult(ex).error).toMatch(/offline/i);
|
expect(commandResult(ex).error).toMatch(/offline/i);
|
||||||
} finally { await w.stop(); }
|
} finally { await w.stop(); }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a schedule can be edited in place, and its next run is worked out again (#19)', async () => {
|
||||||
|
const worker = await workerByName('node-01');
|
||||||
|
const created = await createSchedule({ command: 'echo before', worker_ids: [worker.id] });
|
||||||
|
const id = created.json.id;
|
||||||
|
const r = await sso('PUT', `/api/scheduled-commands/${id}`, {
|
||||||
|
name: `int edited ${unique()}`, command: 'echo after', worker_ids: [worker.id], schedule_type: 'cron', schedule_value: '0 3 * * *',
|
||||||
|
});
|
||||||
|
expect(r.status).toBe(200);
|
||||||
|
const [[row]] = await db.query('SELECT command, schedule_type, schedule_value, next_run FROM scheduled_commands WHERE id = ?', [id]);
|
||||||
|
expect(row).toMatchObject({ command: 'echo after', schedule_type: 'cron', schedule_value: '0 3 * * *' });
|
||||||
|
const next = new Date(row.next_run);
|
||||||
|
expect(next.getHours()).toBe(3);
|
||||||
|
expect(next.getMinutes()).toBe(0);
|
||||||
|
|
||||||
|
const bad = await sso('PUT', `/api/scheduled-commands/${id}`, {
|
||||||
|
name: 'x', command: 'true', worker_ids: [worker.id], schedule_type: 'daily', schedule_value: '25:00',
|
||||||
|
});
|
||||||
|
expect(bad.status).toBe(400);
|
||||||
|
expect(bad.json.error).toBe('The time must be HH:MM (24-hour)');
|
||||||
|
expect((await sso('PUT', '/api/scheduled-commands/no-such-id', {
|
||||||
|
name: 'x', command: 'true', worker_ids: [worker.id], schedule_type: 'interval', schedule_value: '5',
|
||||||
|
})).status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Run now runs the schedule at once, records who asked, and leaves its next run alone (#19)', async () => {
|
||||||
|
const worker = await workerByName('node-02');
|
||||||
|
const name = `int ${unique()}`;
|
||||||
|
const created = await createSchedule({ name, command: 'sleep 2; echo ran-now', worker_ids: [worker.id] });
|
||||||
|
const [[before]] = await db.query('SELECT next_run FROM scheduled_commands WHERE id = ?', [created.json.id]);
|
||||||
|
|
||||||
|
const r = await sso('POST', `/api/scheduled-commands/${created.json.id}/run`, {});
|
||||||
|
expect(r.status).toBe(200);
|
||||||
|
expect(r.json).toMatchObject({ sent: 1, offline: 0 });
|
||||||
|
// A second Run now while the first is still going is refused.
|
||||||
|
expect((await sso('POST', `/api/scheduled-commands/${created.json.id}/run`, {})).status).toBe(409);
|
||||||
|
|
||||||
|
const [run] = await executionsOf(name);
|
||||||
|
const ex = await waitForExecution(run.id);
|
||||||
|
expect(commandResult(ex).stdout.trim()).toBe('ran-now');
|
||||||
|
expect(ex.logs[0].triggered_by).toBeTruthy();
|
||||||
|
const [[after]] = await db.query('SELECT next_run, last_run FROM scheduled_commands WHERE id = ?', [created.json.id]);
|
||||||
|
expect(new Date(after.next_run).getTime()).toBe(new Date(before.next_run).getTime());
|
||||||
|
expect(after.last_run).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the preview gives the next three runs and the server time zone (#19)', async () => {
|
||||||
|
const r = await sso('GET', '/api/scheduled-commands/preview?type=cron&value=' + encodeURIComponent('30 4 * * *'));
|
||||||
|
expect(r.status).toBe(200);
|
||||||
|
expect(r.json.next).toHaveLength(3);
|
||||||
|
expect(r.json.timezone).toBeTruthy();
|
||||||
|
const days = r.json.next.map(t => new Date(t));
|
||||||
|
expect(days.every(d => d.getHours() === 4 && d.getMinutes() === 30)).toBe(true);
|
||||||
|
expect((await sso('GET', '/api/scheduled-commands/preview?type=cron&value=nope')).status).toBe(400);
|
||||||
|
});
|
||||||
@@ -95,3 +95,45 @@ test('empty states say what to do next (#33)', async ({ page }) => {
|
|||||||
await page.goto('/workflows');
|
await page.goto('/workflows');
|
||||||
await expect(page.getByRole('link', { name: 'Step types and examples' })).toHaveAttribute('href', /#workflows$/);
|
await expect(page.getByRole('link', { name: 'Step types and examples' })).toHaveAttribute('href', /#workflows$/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a schedule can be created with cron, edited, run now, and its runs found (#19)', async ({ page, problems }) => {
|
||||||
|
const name = `UI sched ${Date.now()}`;
|
||||||
|
await page.goto('/scheduler');
|
||||||
|
await page.locator('[data-action="sc:create-open"]').first().click(); // header button or empty state
|
||||||
|
const modal = page.locator('#sc-create-modal');
|
||||||
|
await modal.locator('#sc-name').fill(name);
|
||||||
|
await modal.locator('#sc-command').fill('echo first');
|
||||||
|
await modal.locator('input[name="sc-worker-cb"]').first().check();
|
||||||
|
await modal.locator('#sc-type').selectOption('cron');
|
||||||
|
await modal.locator('#sc-value').fill('0 9 * * 1-5');
|
||||||
|
// The preview lists the next three runs and the server's time zone.
|
||||||
|
await expect(modal.locator('#sc-preview li')).toHaveCount(3);
|
||||||
|
await expect(modal.locator('#sc-preview')).toContainText("server's time zone");
|
||||||
|
// A bad expression says so, without leaving the dialog.
|
||||||
|
await modal.locator('#sc-value').fill('0 99 * * *');
|
||||||
|
await expect(modal.locator('#sc-preview')).toContainText('Invalid schedule');
|
||||||
|
expect(problems.every(p => /400/.test(p))).toBe(true); // that preview's 400 is expected
|
||||||
|
problems.length = 0;
|
||||||
|
await modal.locator('#sc-value').fill('0 9 * * 1-5');
|
||||||
|
await modal.getByRole('button', { name: 'Create Schedule' }).click();
|
||||||
|
const row = page.locator('#sc-wrap tr', { hasText: name });
|
||||||
|
await expect(row).toContainText('Cron: 0 9 * * 1-5');
|
||||||
|
|
||||||
|
// Edit in place.
|
||||||
|
await row.getByRole('button', { name: /Edit/ }).click();
|
||||||
|
await expect(modal.locator('#sc-create-title')).toHaveText('Edit Scheduled Command');
|
||||||
|
await expect(modal.locator('#sc-value')).toHaveValue('0 9 * * 1-5');
|
||||||
|
await modal.locator('#sc-command').fill('echo edited-run');
|
||||||
|
await modal.getByRole('button', { name: 'Save Changes' }).click();
|
||||||
|
await expect(row).toContainText('echo edited-run');
|
||||||
|
|
||||||
|
// Run now, then follow Runs to the Automated tab, filtered to this schedule.
|
||||||
|
await row.getByRole('button', { name: /Run now/ }).click();
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
await row.getByRole('link', { name: 'Runs' }).click();
|
||||||
|
await expect(page).toHaveURL(/view=automated/);
|
||||||
|
await expect(page.locator('#ex-search')).toHaveValue(`scheduler:${name}`);
|
||||||
|
const runs = page.locator('#ex-list-automated .ex-row');
|
||||||
|
await expect(runs).toHaveCount(1);
|
||||||
|
await expect(runs.first()).toContainText('echo edited-run');
|
||||||
|
});
|
||||||
@@ -268,3 +268,33 @@ describe('definitionErrors (#11)', () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('scheduleInput and nextRuns (#19)', () => {
|
||||||
|
const { scheduleInput, nextRuns } = require('../lib/utils');
|
||||||
|
const base = { name: 'n', command: 'true', worker_ids: ['w1'] };
|
||||||
|
|
||||||
|
test('accepts each schedule type and works out the next run', () => {
|
||||||
|
for (const [t, v] of [['interval', '15'], ['hourly', '2'], ['daily', '02:30'], ['cron', '*/5 * * * *']]) {
|
||||||
|
const r = scheduleInput({ ...base, schedule_type: t, schedule_value: v });
|
||||||
|
expect(r.error).toBeUndefined();
|
||||||
|
expect(r.value.next_run.getTime()).toBeGreaterThan(Date.now());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says what is wrong', () => {
|
||||||
|
const err = b => scheduleInput({ ...base, ...b }).error;
|
||||||
|
expect(err({ name: ' ' })).toBe('A name is required');
|
||||||
|
expect(err({ worker_ids: [] })).toBe('Pick at least one worker');
|
||||||
|
expect(err({ schedule_type: 'weekly', schedule_value: '1' })).toMatch(/^schedule_type must be one of/);
|
||||||
|
expect(err({ schedule_type: 'interval', schedule_value: '0' })).toBe('The interval must be a whole number above 0');
|
||||||
|
expect(err({ schedule_type: 'daily', schedule_value: '7pm' })).toBe('The time must be HH:MM (24-hour)');
|
||||||
|
expect(err({ schedule_type: 'cron', schedule_value: '99 * * * *' })).toMatch(/^Invalid schedule:/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('nextRuns steps forward from each run', () => {
|
||||||
|
const from = new Date(2026, 10, 23, 12, 0, 0);
|
||||||
|
expect(nextRuns('interval', '30', 3, from).map(d => d.getTime() - from.getTime())).toEqual([30, 60, 90].map(m => m * 60000));
|
||||||
|
const daily = nextRuns('daily', '02:00', 2, from);
|
||||||
|
expect(daily.map(d => [d.getDate(), d.getHours()])).toEqual([[24, 2], [25, 2]]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -46,15 +46,18 @@
|
|||||||
<option value="interval">Every X Minutes</option>
|
<option value="interval">Every X Minutes</option>
|
||||||
<option value="hourly">Every X Hours</option>
|
<option value="hourly">Every X Hours</option>
|
||||||
<option value="daily">Daily at Time</option>
|
<option value="daily">Daily at Time</option>
|
||||||
|
<option value="cron">Cron expression</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="lt-form-group" id="sc-value-container">
|
<div class="lt-form-group" id="sc-value-container">
|
||||||
<label class="lt-label" for="sc-value">Interval (minutes)</label>
|
<label class="lt-label" for="sc-value">Interval (minutes)</label>
|
||||||
<input type="number" id="sc-value" class="lt-input" placeholder="e.g. 30" min="1">
|
<input type="number" id="sc-value" class="lt-input" placeholder="e.g. 30" min="1">
|
||||||
</div>
|
</div>
|
||||||
|
<div class="sc-preview" id="sc-preview" aria-live="polite"></div>
|
||||||
|
<div class="lt-field-error" id="sc-create-error" hidden></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="lt-modal-footer">
|
<div class="lt-modal-footer">
|
||||||
<button type="submit" class="lt-btn lt-btn-primary">Create Schedule</button>
|
<button type="submit" class="lt-btn lt-btn-primary" id="sc-submit">Create Schedule</button>
|
||||||
<button type="button" class="lt-btn lt-btn-ghost" data-modal-close>Cancel</button>
|
<button type="button" class="lt-btn lt-btn-ghost" data-modal-close>Cancel</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
Reference in new issue
Block a user