Files
security-command.org/packages/jobs/src/definition.ts
T

191 lines
7.0 KiB
TypeScript

import { Cron } from 'croner';
import { parse } from 'smol-toml';
import { parseDuration } from './duration.ts';
/** Events a job can react to. Only builtin jobs may react to content changes, which prevents loops. */
export type JobEvent = 'start' | 'content-change' | 'watch';
export type JobDefinition = {
id: string;
/** Name of a job implemented inside an app; mutually exclusive with path. */
builtin?: string;
/** Script run by the jobs service. */
path?: string;
args: string[];
every?: number;
cron?: string;
on: JobEvent[];
watch: string[];
/** Jobs to trigger after a successful run. */
then: string[];
timeout: number;
env: Record<string, string>;
enabled: boolean;
/** Whether runs may overlap. Otherwise a new trigger cancels the running run and starts over. */
parallel: boolean;
};
export type LoadedJobs = {
jobs: JobDefinition[];
/** System jobs the file does not mention yet, as TOML ready to be appended. */
missing: string;
warnings: string[];
};
const ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
const EVENTS = new Set<JobEvent>(['start', 'content-change', 'watch']);
const KEYS = new Set(['id', 'builtin', 'path', 'args', 'every', 'cron', 'on', 'watch', 'then', 'timeout', 'env', 'enabled', 'parallel']);
const DEFAULT_TIMEOUT = '5m';
/** Jobs every installation has. They are appended to the config file when missing, so they can be switched off there. */
export const SYSTEM_JOBS = `
# System job: rebuilds the static site, sitemap and robots.txt from the content.
[[job]]
id = "index"
builtin = "index"
on = ["start", "content-change"]
# System job: refreshes the status file that sandboxes show with "status".
[[job]]
id = "status"
builtin = "status"
every = "5s"
on = ["start"]
# System job: removes sandboxes left behind by a previous backend process.
[[job]]
id = "reap-orphans"
builtin = "reap-orphans"
on = ["start"]
`;
class InvalidJobError extends Error {}
function fail(message: string): never {
throw new InvalidJobError(message);
}
function strings(value: unknown, name: string): string[]
{
if (value === undefined) return [];
if (!Array.isArray(value) || !value.every((entry) => typeof entry === 'string')) fail(`${name} must be a list of strings`);
return value;
}
function validate(raw: Record<string, unknown>): JobDefinition
{
const unknown = Object.keys(raw).filter((key) => !KEYS.has(key));
if (unknown.length > 0) fail(`unknown keys ${unknown.join(', ')}`);
const { id, builtin, path, every, cron, timeout, env, enabled, parallel } = raw;
if (typeof id !== 'string' || !ID.test(id)) fail('id must be lowercase letters, digits and dashes');
if ((builtin === undefined) === (path === undefined)) fail('needs exactly one of builtin or path');
if (builtin !== undefined && typeof builtin !== 'string') fail('builtin must be a string');
if (path !== undefined && typeof path !== 'string') fail('path must be a string');
if (every !== undefined && typeof every !== 'string') fail('every must be a duration like "15m"');
if (cron !== undefined && typeof cron !== 'string') fail('cron must be a string');
if (timeout !== undefined && typeof timeout !== 'string') fail('timeout must be a duration like "5m"');
if (enabled !== undefined && typeof enabled !== 'boolean') fail('enabled must be true or false');
if (parallel !== undefined && typeof parallel !== 'boolean') fail('parallel must be true or false');
const on = strings(raw.on, 'on') as JobEvent[];
for (const event of on) if (!EVENTS.has(event)) fail(`unknown event "${event}"`);
if (on.includes('content-change') && path) fail('content-change is reserved for builtin jobs, so jobs cannot trigger themselves');
const watch = strings(raw.watch, 'watch');
if (watch.length > 0 !== on.includes('watch')) fail('watch paths and on = ["watch"] belong together');
if (env !== undefined && (typeof env !== 'object' || env === null || Array.isArray(env) || !Object.values(env).every((value) => typeof value === 'string')))
{
fail('env must be a table of strings');
}
if (cron !== undefined)
{
try { new Cron(cron, { paused: true }).stop(); }
catch { fail(`invalid cron expression "${cron}"`); }
}
const everyMs = every === undefined ? undefined : parseDuration(every);
if (everyMs !== undefined && everyMs < 1000) fail('every must be at least 1s');
return {
id,
...(builtin === undefined ? {} : { builtin }),
...(path === undefined ? {} : { path }),
args: strings(raw.args, 'args'),
...(everyMs === undefined ? {} : { every: everyMs }),
...(cron === undefined ? {} : { cron }),
on,
watch,
then: strings(raw.then, 'then'),
timeout: parseDuration(timeout ?? DEFAULT_TIMEOUT),
env: (env ?? {}) as Record<string, string>,
enabled: enabled ?? true,
parallel: parallel ?? false,
};
}
function entries(text: string): unknown[]
{
const document = parse(text);
const jobs = document.job ?? [];
if (!Array.isArray(jobs)) fail('jobs must be written as [[job]] sections');
return jobs;
}
/** Splits the system defaults into one TOML block per job, keyed by id. */
function systemBlocks(): Map<string, string>
{
const blocks = SYSTEM_JOBS.split(/\n(?=\n# )/).map((block) => block.trim()).filter(Boolean);
return new Map(blocks.map((block) => [/^id\s*=\s*"([^"]+)"/m.exec(block)![1]!, block]));
}
/**
* Reads the job file. Broken jobs are skipped with a warning instead of
* stopping everything, and system jobs missing from the file are added with
* their defaults.
*/
export function loadJobs(text: string): LoadedJobs
{
const warnings: string[] = [];
const jobs: JobDefinition[] = [];
let raw: unknown[] = [];
try { raw = entries(text); }
catch (error) { warnings.push(`the job file cannot be read, only system jobs run: ${(error as Error).message}`); }
for (const [index, entry] of raw.entries())
{
try
{
if (typeof entry !== 'object' || entry === null) fail('must be a table');
const job = validate(entry as Record<string, unknown>);
if (jobs.some((other) => other.id === job.id)) fail(`duplicate id "${job.id}"`);
if (!job.enabled) warnings.push(`job "${job.id}" is disabled`);
jobs.push(job);
}
catch (error)
{
const id = (entry as { id?: unknown })?.id;
warnings.push(`job ${typeof id === 'string' ? `"${id}"` : `#${index + 1}`} is skipped: ${(error as Error).message}`);
}
}
const missing: string[] = [];
for (const [id, block] of systemBlocks())
{
if (raw.some((entry) => (entry as { id?: unknown })?.id === id)) continue;
missing.push(block);
jobs.push(validate(entries(block)[0] as Record<string, unknown>));
}
for (const job of jobs)
{
for (const next of job.then) if (!jobs.some((other) => other.id === next)) warnings.push(`job "${job.id}" triggers unknown job "${next}"`);
}
return { jobs, missing: missing.length > 0 ? `\n${missing.join('\n\n')}\n` : '', warnings };
}