Add jobs service with script execution, configuration support, and control interface.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-13 15:04:21 +02:00
1 parent 1f6d41ab06
commit 0ad5b5f44f
27 files changed
+1108 -45

No files matched your search

+11 -4
View File
@@ -27,12 +27,14 @@ export type JobDefinition = {
export type LoadedJobs = {
jobs: JobDefinition[];
/** False when the file is not valid TOML; then nothing should be appended to it. */
parsed: boolean;
/** 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}$/;
export const JOB_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';
@@ -78,7 +80,7 @@ function validate(raw: Record<string, unknown>): JobDefinition
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 (typeof id !== 'string' || !JOB_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');
@@ -152,8 +154,13 @@ export function loadJobs(text: string): LoadedJobs
const jobs: JobDefinition[] = [];
let raw: unknown[] = [];
let parsed = true;
try { raw = entries(text); }
catch (error) { warnings.push(`the job file cannot be read, only system jobs run: ${(error as Error).message}`); }
catch (error)
{
parsed = false;
warnings.push(`the job file cannot be read, only system jobs run: ${(error as Error).message}`);
}
for (const [index, entry] of raw.entries())
{
@@ -186,5 +193,5 @@ export function loadJobs(text: string): LoadedJobs
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 };
return { jobs, parsed, missing: missing.length > 0 ? `\n${missing.join('\n\n')}\n` : '', warnings };
}
+2
View File
@@ -1,3 +1,5 @@
export * from './duration.ts';
export * from './definition.ts';
export * from './scheduler.ts';
export * from './watch.ts';
export * from './triggers.ts';
+23
View File
@@ -0,0 +1,23 @@
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { watchTriggers, writeTrigger } from './triggers.ts';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
describe('triggers', () => {
it('delivers each write once and ignores invalid names', async () => {
const dir = mkdtempSync(join(tmpdir(), 'triggers-'));
const triggered: string[] = [];
const watcher = watchTriggers(dir, (id) => triggered.push(id), () => {});
await writeTrigger(dir, 'index');
await writeTrigger(dir, 'index');
await expect(writeTrigger(dir, '../escape')).rejects.toThrow('invalid job id');
await sleep(300);
watcher?.close();
expect(triggered).toEqual(['index']);
});
});
+46
View File
@@ -0,0 +1,46 @@
import { watch, type FSWatcher } from 'node:fs';
import { writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { JOB_ID } from './definition.ts';
import type { Log } from './watch.ts';
/**
* Builtin jobs run in the backend and script jobs in the jobs service. The
* jobs service triggers a builtin job by writing a file named after it into a
* directory the backend watches, so neither needs a socket to the other.
*/
const TRIGGER_QUIET_MS = 100;
export async function writeTrigger(directory: string, id: string): Promise<void>
{
if (!JOB_ID.test(id)) throw new Error(`invalid job id "${id}"`);
await writeFile(join(directory, id), `${Date.now()}\n`);
}
export function watchTriggers(directory: string, onTrigger: (id: string) => void, log: Log): FSWatcher | undefined
{
const pending = new Map<string, NodeJS.Timeout>();
try
{
const watcher = watch(directory, (_event, name) =>
{
if (!name || !JOB_ID.test(name)) return;
// One write raises several events, which count as one trigger.
clearTimeout(pending.get(name));
pending.set(name, setTimeout(() =>
{
pending.delete(name);
onTrigger(name);
}, TRIGGER_QUIET_MS));
});
watcher.on('error', (error) => log(`stopped watching ${directory} for triggers: ${error.message}`));
watcher.on('close', () => { for (const timer of pending.values()) clearTimeout(timer); });
return watcher;
}
catch (error)
{
log(`cannot watch ${directory} for triggers from the jobs service: ${(error as Error).message}`);
return undefined;
}
}
+63
View File
@@ -0,0 +1,63 @@
import { statSync, watch, type FSWatcher } from 'node:fs';
import { basename, dirname } from 'node:path';
export type Log = (message: string) => void;
/** Calls back once a directory tree has been quiet for the given time after a change. */
export function watchTree(directory: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined
{
let timer: NodeJS.Timeout | undefined;
try
{
const watcher = watch(directory, { recursive: true }, () =>
{
clearTimeout(timer);
timer = setTimeout(onChange, quietMs);
});
watcher.on('error', (error) => log(`stopped watching ${directory}: ${error.message}`));
watcher.on('close', () => clearTimeout(timer));
return watcher;
}
catch (error)
{
log(`cannot watch ${directory}: ${(error as Error).message}`);
return undefined;
}
}
/**
* Watches a single file through its directory, because editors and atomic
* writes replace files, which would end a watch on the old one. This also
* notices a file that does not exist yet.
*/
export function watchFile(file: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined
{
let timer: NodeJS.Timeout | undefined;
try
{
const watcher = watch(dirname(file), (_event, name) =>
{
if (name !== basename(file)) return;
clearTimeout(timer);
timer = setTimeout(onChange, quietMs);
});
watcher.on('error', (error) => log(`stopped watching ${file}: ${error.message}`));
watcher.on('close', () => clearTimeout(timer));
return watcher;
}
catch (error)
{
log(`cannot watch ${file}: ${(error as Error).message}`);
return undefined;
}
}
/** Watches a directory tree, or a file when the path is not a directory. */
export function watchPath(path: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined
{
let directory = false;
try { directory = statSync(path).isDirectory(); }
catch { /* A missing path is watched like a file, so its creation counts as a change. */ }
return directory ? watchTree(path, quietMs, onChange, log) : watchFile(path, quietMs, onChange, log);
}