Add backend jobs system with built-in tasks and TOML-based configuration parsing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-13 14:20:31 +02:00
1 parent 9647ac8c50
commit 1f6d41ab06
27 files changed
+1590 -25

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
{
"name": "@homepage/jobs",
"private": true,
"type": "module",
"exports": "./src/index.ts",
"dependencies": {
"croner": "^10.0.1",
"smol-toml": "^1.9.1"
}
}
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from 'vitest';
import { loadJobs } from './definition.ts';
import { parseDuration } from './duration.ts';
const SYSTEM = ['index', 'status', 'reap-orphans'];
describe('parseDuration', () => {
it('understands the usual units', () => {
expect(parseDuration('500ms')).toBe(500);
expect(parseDuration('5s')).toBe(5000);
expect(parseDuration('15m')).toBe(900_000);
expect(parseDuration('1h')).toBe(3_600_000);
expect(parseDuration('2d')).toBe(172_800_000);
expect(() => parseDuration('soon')).toThrow();
});
});
describe('loadJobs', () => {
it('adds every system job to an empty file and reports them as missing', () => {
const loaded = loadJobs('');
expect(loaded.jobs.map((job) => job.id)).toEqual(SYSTEM);
expect(loaded.warnings).toEqual([]);
expect(loadJobs(loaded.missing).missing).toBe('');
});
it('reads script jobs with their defaults', () => {
const { jobs } = loadJobs(`
[[job]]
id = "services"
path = "jobs/services.sh"
args = ["--verbose"]
every = "15m"
on = ["start", "watch"]
watch = ["/host/srv"]
then = ["index"]
env = { MODE = "full" }
`);
expect(jobs[0]).toEqual({
id: 'services',
path: 'jobs/services.sh',
args: ['--verbose'],
every: 900_000,
on: ['start', 'watch'],
watch: ['/host/srv'],
then: ['index'],
timeout: 300_000,
env: { MODE: 'full' },
enabled: true,
parallel: false,
});
});
it('keeps disabled system jobs disabled and warns about them', () => {
const loaded = loadJobs(`
[[job]]
id = "status"
builtin = "status"
enabled = false
`);
expect(loaded.jobs.find((job) => job.id === 'status')?.enabled).toBe(false);
expect(loaded.warnings).toContain('job "status" is disabled');
expect(loaded.missing).not.toContain('id = "status"');
});
it.each([
['both kinds', 'id = "a"\nbuiltin = "x"\npath = "y"', 'exactly one of builtin or path'],
['a bad id', 'id = "Bad Id"\npath = "y"', 'id must be'],
['an unknown key', 'id = "a"\npath = "y"\nretries = 3', 'unknown keys retries'],
['content-change on a script', 'id = "a"\npath = "y"\non = ["content-change"]', 'reserved for builtin jobs'],
['watch without paths', 'id = "a"\npath = "y"\non = ["watch"]', 'belong together'],
['a broken cron', 'id = "a"\npath = "y"\ncron = "every day"', 'invalid cron'],
['a tiny interval', 'id = "a"\npath = "y"\nevery = "100ms"', 'at least 1s'],
])('skips a job with %s', (_name, body, message) => {
const loaded = loadJobs(`[[job]]\n${body}`);
expect(loaded.jobs.map((job) => job.id)).toEqual(SYSTEM);
expect(loaded.warnings.join('\n')).toContain(message);
});
it('warns about duplicates and unknown then targets', () => {
const loaded = loadJobs(`
[[job]]
id = "a"
path = "a.sh"
then = ["nowhere"]
[[job]]
id = "a"
path = "b.sh"
`);
expect(loaded.warnings).toEqual(['job "a" is skipped: duplicate id "a"', 'job "a" triggers unknown job "nowhere"']);
});
it('falls back to the system jobs when the file is not valid TOML', () => {
const loaded = loadJobs('[[job]\nid = ');
expect(loaded.jobs.map((job) => job.id)).toEqual(SYSTEM);
expect(loaded.warnings[0]).toContain('cannot be read');
});
});
+190
View File
@@ -0,0 +1,190 @@
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 };
}
+9
View File
@@ -0,0 +1,9 @@
const UNITS: Record<string, number> = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
/** Parses durations like "500ms", "5s", "15m", "1h" or "2d" into milliseconds. */
export function parseDuration(text: string): number
{
const match = /^(\d+)(ms|s|m|h|d)$/.exec(text.trim());
if (!match) throw new Error(`invalid duration "${text}", expected something like 30s, 15m or 1h`);
return Number(match[1]) * UNITS[match[2]!]!;
}
+3
View File
@@ -0,0 +1,3 @@
export * from './duration.ts';
export * from './definition.ts';
export * from './scheduler.ts';
+116
View File
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest';
import type { JobDefinition } from './definition.ts';
import { Scheduler, type Executor } from './scheduler.ts';
function job(id: string, overrides: Partial<JobDefinition> = {}): JobDefinition
{
return { id, builtin: id, args: [], on: [], watch: [], then: [], timeout: 60_000, env: {}, enabled: true, parallel: false, ...overrides };
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
/** Records starts, ends and cancellations; each run takes the given time unless aborted. */
function recorder(durationMs = 50)
{
const events: string[] = [];
const executor: Executor = (definition, signal) => new Promise((resolve, reject) =>
{
events.push(`start ${definition.id}`);
const timer = setTimeout(() =>
{
events.push(`end ${definition.id}`);
resolve();
}, durationMs);
signal.addEventListener('abort', () =>
{
clearTimeout(timer);
events.push(`abort ${definition.id}`);
reject(signal.reason);
});
});
return { events, executor };
}
describe('Scheduler', () => {
it('runs start jobs and events, and skips disabled jobs', async () => {
const { events, executor } = recorder(1);
const scheduler = new Scheduler([
job('a', { on: ['start'] }),
job('b', { on: ['content-change'] }),
job('c', { on: ['start'], enabled: false }),
], executor, { log: () => {} });
scheduler.start();
scheduler.emit('content-change');
await sleep(20);
expect(events).toEqual(['start a', 'start b', 'end a', 'end b']);
expect(scheduler.trigger('c')).toBe(false);
scheduler.stop();
});
it('cancels a running run and starts over, collapsing triggers that arrive meanwhile', async () => {
const { events, executor } = recorder(50);
const scheduler = new Scheduler([job('a')], executor, { log: () => {} });
scheduler.trigger('a');
scheduler.trigger('a');
scheduler.trigger('a');
await sleep(100);
expect(events).toEqual(['start a', 'abort a', 'start a', 'end a']);
});
it('lets parallel jobs overlap', async () => {
const { events, executor } = recorder(30);
const scheduler = new Scheduler([job('a', { parallel: true })], executor, { log: () => {} });
scheduler.trigger('a');
scheduler.trigger('a');
await sleep(60);
expect(events).toEqual(['start a', 'start a', 'end a', 'end a']);
});
it('triggers then targets after success, locally or elsewhere', async () => {
const { events, executor } = recorder(1);
const elsewhere: string[] = [];
const scheduler = new Scheduler([job('a', { then: ['b', 'index'] }), job('b')], executor, {
log: () => {},
triggerOther: (id) => elsewhere.push(id),
});
scheduler.trigger('a');
await sleep(20);
expect(events).toEqual(['start a', 'end a', 'start b', 'end b']);
expect(elsewhere).toEqual(['index']);
});
it('times out and reports failures, but stays quiet about cancellations', async () => {
const { executor } = recorder(1000);
const logs: string[] = [];
const scheduler = new Scheduler([job('slow', { timeout: 20 }), job('cancelled')], executor, { log: (line) => logs.push(line) });
scheduler.trigger('slow');
scheduler.trigger('cancelled');
expect(scheduler.running()).toEqual(['slow', 'cancelled']);
expect(scheduler.cancel('cancelled')).toBe(true);
await sleep(50);
expect(logs).toEqual(['job "slow" failed: timed out after 20 ms']);
expect(scheduler.running()).toEqual([]);
});
it('runs jobs on their interval', async () => {
const { events, executor } = recorder(1);
const scheduler = new Scheduler([job('tick', { every: 1000 })], executor, { log: () => {} });
scheduler.start();
await sleep(1100);
scheduler.stop();
expect(events).toEqual(['start tick', 'end tick']);
});
});
+144
View File
@@ -0,0 +1,144 @@
import { Cron } from 'croner';
import type { JobDefinition, JobEvent } from './definition.ts';
export type Executor = (job: JobDefinition, signal: AbortSignal) => Promise<void>;
export type SchedulerOptions = {
log: (message: string) => void;
/** Receives "then" targets this scheduler does not run itself, for example builtin jobs of another app. */
triggerOther?: (id: string) => void;
};
export class JobTimeoutError extends Error {}
export class JobCancelledError extends Error {}
type Run = { controller: AbortController; done: Promise<void> };
/**
* Runs jobs on their schedules and events. Without parallel, a new trigger
* cancels a running run and starts over once it has stopped; triggers that
* arrive meanwhile collapse into that one restart.
*/
export class Scheduler
{
private readonly jobs: Map<string, JobDefinition>;
private readonly executor: Executor;
private readonly options: SchedulerOptions;
private readonly runs = new Map<string, Set<Run>>();
private readonly restarting = new Set<string>();
private readonly stoppers: (() => void)[] = [];
private stopped = false;
constructor(jobs: JobDefinition[], executor: Executor, options: SchedulerOptions)
{
this.jobs = new Map(jobs.map((job) => [job.id, job]));
this.executor = executor;
this.options = options;
}
start(): void
{
for (const job of this.jobs.values())
{
if (!job.enabled) continue;
if (job.every !== undefined)
{
const timer = setInterval(() => this.trigger(job.id), job.every);
this.stoppers.push(() => clearInterval(timer));
}
if (job.cron !== undefined)
{
const cron = new Cron(job.cron, () => { this.trigger(job.id); });
this.stoppers.push(() => cron.stop());
}
if (job.on.includes('start')) this.trigger(job.id);
}
}
/** Triggers every enabled job that listens to the event. */
emit(event: JobEvent): void {
for (const job of this.jobs.values()) if (job.on.includes(event)) this.trigger(job.id);
}
/** Starts a job. Returns false for unknown or disabled jobs. */
trigger(id: string): boolean
{
const job = this.jobs.get(id);
if (!job || !job.enabled || this.stopped) return false;
const runs = this.runs.get(id);
if (job.parallel || !runs || runs.size === 0)
{
this.launch(job);
return true;
}
if (this.restarting.has(id)) return true;
this.restarting.add(id);
for (const run of runs) run.controller.abort(new JobCancelledError('restarted by a new trigger'));
void Promise.allSettled([...runs].map((run) => run.done)).then(() =>
{
this.restarting.delete(id);
if (!this.stopped) this.launch(job);
});
return true;
}
/** Cancels all runs of a job. Returns whether anything was running. */
cancel(id: string): boolean
{
const runs = this.runs.get(id);
if (!runs || runs.size === 0) return false;
for (const run of runs) run.controller.abort(new JobCancelledError('cancelled'));
return true;
}
running(): string[] {
return [...this.runs].filter(([, runs]) => runs.size > 0).map(([id]) => id);
}
stop(): void
{
this.stopped = true;
for (const stop of this.stoppers) stop();
for (const id of this.runs.keys()) this.cancel(id);
}
private launch(job: JobDefinition): void
{
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(new JobTimeoutError(`timed out after ${job.timeout} ms`)), job.timeout);
const runs = this.runs.get(job.id) ?? new Set<Run>();
this.runs.set(job.id, runs);
const run: Run = { controller, done: Promise.resolve() };
run.done = this.executor(job, controller.signal)
.then(() =>
{
for (const next of job.then)
{
if (this.jobs.has(next)) this.trigger(next);
else if (this.options.triggerOther) this.options.triggerOther(next);
}
})
.catch((error: unknown) =>
{
const reason = controller.signal.aborted ? controller.signal.reason : error;
if (reason instanceof JobCancelledError) return;
this.options.log(`job "${job.id}" failed: ${reason instanceof Error ? reason.message : String(reason)}`);
})
.finally(() =>
{
clearTimeout(timer);
runs.delete(run);
});
runs.add(run);
}
}