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

+9
View File
@@ -0,0 +1,9 @@
{
"name": "@homepage/indexer",
"private": true,
"type": "module",
"exports": "./src/index.ts",
"dependencies": {
"marked": "^18.1.0"
}
}
+3
View File
@@ -0,0 +1,3 @@
export * from './walk.ts';
export * from './render.ts';
export * from './site.ts';
+164
View File
@@ -0,0 +1,164 @@
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { beforeEach, describe, expect, it } from 'vitest';
import { renderMarkdown, renderText } from './render.ts';
import { buildSite, reservedNames, type Site } from './site.ts';
import { buildIndex, type WalkOptions } from './walk.ts';
const LEGAL = new Map([['impressum', 'impressum.txt']]);
function options(overrides: Partial<WalkOptions> = {}): WalkOptions {
return { maxFileBytes: 1024, maxTotalBytes: 4096, maxEntries: 100, reserved: reservedNames(LEGAL), ...overrides };
}
function write(root: string, files: Record<string, string>): void
{
for (const [path, content] of Object.entries(files))
{
mkdirSync(join(root, path, '..'), { recursive: true });
writeFileSync(join(root, path), content);
}
}
const text = (site: Site, path: string) => site.pages.get(path)?.body.toString();
describe('buildIndex', () => {
let root: string;
let outside: string;
beforeEach(() =>
{
root = mkdtempSync(join(tmpdir(), 'content-'));
outside = mkdtempSync(join(tmpdir(), 'outside-'));
write(outside, { 'secret.txt': 'host secret' });
write(root, {
'about.txt': 'about me',
'subdomains/git.example.org/README': 'gitea',
'.env': 'TOKEN=1',
'.git/config': 'repo',
'subdomains/.hidden': 'hidden',
});
});
it('lists files and directories in order', async () => {
const index = await buildIndex(root, options());
expect([...index.entries.keys()]).toEqual(['', 'about.txt', 'subdomains', 'subdomains/git.example.org', 'subdomains/git.example.org/README']);
expect(index.entries.get('about.txt')?.content?.toString()).toBe('about me');
});
it('never follows symlinks, inside or outside the root', async () => {
symlinkSync(join(outside, 'secret.txt'), join(root, 'leak.txt'));
symlinkSync(outside, join(root, 'leakdir'));
symlinkSync(join(root, 'about.txt'), join(root, 'alias.txt'));
const index = await buildIndex(root, options());
expect([...index.entries.keys()].filter((path) => /leak|alias/.test(path))).toEqual([]);
});
it('skips dotfiles and dot directories everywhere', async () => {
const index = await buildIndex(root, options());
expect([...index.entries.keys()].some((path) => path.split('/').some((part) => part.startsWith('.')))).toBe(false);
});
it('skips top level names reserved for the site', async () => {
write(root, { 'raw/x': 'x', 'impressum': 'collides', 'sitemap.xml': 'x', 'deep/raw': 'fine' });
const index = await buildIndex(root, options());
expect(index.entries.has('raw')).toBe(false);
expect(index.entries.has('impressum')).toBe(false);
expect(index.entries.has('deep/raw')).toBe(true);
expect(index.warnings).toContain('"impressum" is skipped because the name is reserved for the site itself');
});
it('lists but does not load files above the limits', async () => {
write(root, { 'big.bin': 'x'.repeat(2000) });
const index = await buildIndex(root, options());
expect(index.entries.get('big.bin')?.content).toBeUndefined();
expect(index.warnings.join('\n')).toContain('big.bin is listed but not served');
});
it('changes its hash when content changes', async () => {
const before = (await buildIndex(root, options())).hash;
write(root, { 'about.txt': 'about someone else' });
expect((await buildIndex(root, options())).hash).not.toBe(before);
});
it('survives a missing content directory', async () => {
const index = await buildIndex(join(root, 'missing'), options());
expect([...index.entries.keys()]).toEqual(['']);
expect(index.warnings[0]).toContain('cannot be read');
});
});
describe('buildSite', () => {
let site: Site;
beforeEach(async () =>
{
const root = mkdtempSync(join(tmpdir(), 'site-'));
write(root, {
'about.md': '# About\n\n<script>alert(1)</script>\n\n[bad](javascript:alert(1)) [good](https://example.org)',
'page.html': '<script>alert(1)</script>',
'logo.svg': '<svg onload="alert(1)"></svg>',
'links/github.txt': 'https://github.com/example',
'spaced name.txt': 'x',
'impressum.txt': 'Max Mustermann',
});
site = buildSite(await buildIndex(root, options()), { siteUrl: 'https://security-command.org/', legal: LEGAL });
});
it('serves listings, file pages and the root listing at /ls', () => {
expect(text(site, '/ls')).toContain('<a href="/links">links/</a>');
expect(text(site, '/links')).toContain('<a href="/links/github.txt">github.txt</a>');
expect(text(site, '/links/github.txt')).toContain('<a href="https://github.com/example">');
expect(text(site, '/ls')).toContain('href="/spaced%20name.txt"');
expect(site.pages.has('/spaced name.txt')).toBe(true);
});
it('escapes raw HTML and neutralizes script links in markdown', () => {
const page = text(site, '/about.md')!;
expect(page).toContain('<h1>About</h1>');
expect(page).not.toContain('<script>');
expect(page).toContain('&lt;script&gt;');
expect(page).toContain('<a href="#">bad</a>');
expect(page).toContain('<a href="https://example.org">good</a>');
});
it('serves raw HTML and SVG as sandboxed plain text', () => {
for (const path of ['/raw/page.html', '/raw/logo.svg'])
{
const page = site.pages.get(path)!;
expect(page.type).toBe('text/plain; charset=utf-8');
expect(page.headers['Content-Security-Policy']).toContain('sandbox');
}
});
it('renders legal pages from their content files', () => {
expect(text(site, '/impressum')).toContain('Max Mustermann');
});
it('lists every page in the sitemap and points robots.txt at it', () => {
const sitemap = text(site, '/sitemap.xml')!;
expect(sitemap).toContain('<loc>https://security-command.org/</loc>');
expect(sitemap).toContain('<loc>https://security-command.org/ls</loc>');
expect(sitemap).toContain('<loc>https://security-command.org/spaced%20name.txt</loc>');
expect(sitemap).toContain('<loc>https://security-command.org/impressum</loc>');
expect(text(site, '/robots.txt')).toContain('Sitemap: https://security-command.org/sitemap.xml');
});
});
describe('render helpers', () => {
it('links only web addresses in plain text', () => {
expect(renderText('see https://a.example/x. and <b>')).toBe('see <a href="https://a.example/x">https://a.example/x</a>. and &lt;b&gt;');
});
it('keeps mail links in markdown', () => {
expect(renderMarkdown('[mail](mailto:a@b.c)')).toContain('href="mailto:a@b.c"');
});
});
+149
View File
@@ -0,0 +1,149 @@
import { Marked, type Tokens } from 'marked';
import type { Entry } from './walk.ts';
export type Link = { label: string; href: string };
const SAFE_SCHEME = /^(https?|mailto):/i;
const ANY_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
export function escapeHtml(text: string): string
{
return text
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
/** Encodes every segment of a content path for use in a URL. */
export function urlPath(path: string): string {
return path.split('/').map(encodeURIComponent).join('/');
}
function safeHref(href: string): string {
return ANY_SCHEME.test(href) && !SAFE_SCHEME.test(href) ? '#' : href;
}
/**
* Markdown with raw HTML shown as text and only web and mail links, because
* jobs may write content from outside sources into the directory.
*/
const markdown = new Marked({
gfm: true,
renderer: { html: ({ text }: Tokens.HTML | Tokens.Tag) => escapeHtml(text) },
walkTokens: (token) =>
{
if (token.type === 'link' || token.type === 'image') token.href = safeHref(token.href);
},
});
export function renderMarkdown(text: string): string {
return markdown.parse(text, { async: false });
}
/** Escapes text and turns plain web addresses into links, like the terminal does. */
export function renderText(text: string): string {
return escapeHtml(text).replace(/https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)\]]/g, (url) => `<a href="${url}">${url}</a>`);
}
function formatSize(bytes: number): string
{
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} K`;
return `${(bytes / 1024 / 1024).toFixed(1)} M`;
}
export function renderListing(entry: Entry, children: Entry[]): string
{
const rows = children.map((child) =>
{
const name = escapeHtml(child.name) + (child.kind === 'dir' ? '/' : '');
const size = child.kind === 'dir' ? '' : formatSize(child.size);
return `<tr><td><a href="/${urlPath(child.path)}">${name}</a></td><td class="size">${size}</td><td>${child.modified.toISOString().slice(0, 10)}</td></tr>`;
});
if (rows.length === 0) return '<p class="muted">This directory is empty.</p>';
return `<table><tbody>\n${rows.join('\n')}\n</tbody></table>`;
}
const IMAGE = /\.(png|jpe?g|gif|webp|avif)$/i;
export function renderFile(entry: Entry): string
{
const raw = `/raw/${urlPath(entry.path)}`;
if (!entry.content) return `<p class="muted">This file is too large to show. <a href="${raw}">Download it</a>.</p>`;
if (IMAGE.test(entry.name)) return `<p><img src="${raw}" alt="${escapeHtml(entry.name)}"></p>`;
if (!isText(entry.content)) return `<p class="muted">Binary file. <a href="${raw}">Download it</a>.</p>`;
const text = entry.content.toString('utf8');
if (/\.md$/i.test(entry.name)) return `<article class="markdown">${renderMarkdown(text)}</article>`;
return `<pre>${renderText(text)}</pre>`;
}
/** Treats content without NUL bytes that decodes as UTF-8 as text. The sample may end inside a character. */
export function isText(content: Buffer): boolean
{
const sample = content.subarray(0, 8192);
if (sample.includes(0)) return false;
try { new TextDecoder('utf-8', { fatal: true }).decode(sample, { stream: true }); }
catch { return false; }
return true;
}
const STYLE = `
:root { color-scheme: dark; --bg: #0b0d10; --text: #d6dde6; --muted: #7d8794; --accent: #7ee787; --border: #1f262e; }
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.6 "JetBrains Mono", ui-monospace, monospace; }
header, main, footer { max-width: 60rem; margin: 0 auto; padding: 0.75rem 1rem; }
header { display: flex; flex-wrap: wrap; gap: 0.5rem 1rem; justify-content: space-between; border-bottom: 1px solid var(--border); font-size: 0.85rem; }
header .site { color: var(--accent); }
nav a { margin-left: 0.75rem; }
a { color: var(--accent); }
.crumbs { color: var(--muted); }
.muted, .size { color: var(--muted); }
pre { white-space: pre-wrap; word-break: break-word; }
table { border-collapse: collapse; width: 100%; }
td { padding: 0.15rem 1.5rem 0.15rem 0; white-space: nowrap; }
td:first-child { width: 100%; white-space: normal; }
img { max-width: 100%; }
.markdown code, .markdown pre { background: #12161b; }
`;
export type PageOptions = {
title: string;
description: string;
crumbs: Link[];
body: string;
nav: Link[];
};
export function renderPage(options: PageOptions): string
{
const crumbs = options.crumbs.map((crumb) => `<a href="${crumb.href}">${escapeHtml(crumb.label)}</a>`).join(' / ');
const nav = options.nav.map((link) => `<a href="${link.href}">${escapeHtml(link.label)}</a>`).join('');
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>${escapeHtml(options.title)}</title>
<meta name="description" content="${escapeHtml(options.description)}">
<meta property="og:title" content="${escapeHtml(options.title)}">
<meta property="og:description" content="${escapeHtml(options.description)}">
<style>${STYLE}</style>
</head>
<body>
<header><a class="site" href="/">security-command.org</a><nav>${nav}</nav></header>
<main>
<p class="crumbs">${crumbs}</p>
${options.body}
</main>
</body>
</html>
`;
}
+137
View File
@@ -0,0 +1,137 @@
import { escapeHtml, isText, renderFile, renderListing, renderPage, urlPath, type Link } from './render.ts';
import type { ContentIndex, Entry } from './walk.ts';
export type SitePage = {
body: Buffer;
type: string;
headers: Record<string, string>;
};
export type Site = {
pages: Map<string, SitePage>;
hash: string;
};
export type SiteOptions = {
/** Absolute URL of the site, used by the sitemap. */
siteUrl: string;
/** Route name to content file, for example impressum to impressum.txt. */
legal: Map<string, string>;
};
const RESERVED = ['ws', 'raw', 'ls', 'healthz', 'assets', 'index.html', 'sitemap.xml', 'robots.txt'];
/** Route names the content cannot use at its top level, including the legal pages. */
export function reservedNames(legal: Map<string, string>): Set<string> {
return new Set([...RESERVED, ...legal.keys()]);
}
const RAW_TYPES: [RegExp, string][] = [
[/\.png$/i, 'image/png'],
[/\.jpe?g$/i, 'image/jpeg'],
[/\.gif$/i, 'image/gif'],
[/\.webp$/i, 'image/webp'],
[/\.avif$/i, 'image/avif'],
];
/**
* Raw files never run in the site's origin: text is served as plain text,
* also for HTML and SVG, and a sandbox policy disables scripts entirely.
*/
const RAW_HEADERS = { 'Content-Security-Policy': "sandbox; default-src 'none'; img-src 'self'" };
function rawPage(entry: Entry & { content: Buffer }): SitePage
{
const image = RAW_TYPES.find(([pattern]) => pattern.test(entry.name))?.[1];
if (image) return { body: entry.content, type: image, headers: RAW_HEADERS };
if (isText(entry.content)) return { body: entry.content, type: 'text/plain; charset=utf-8', headers: RAW_HEADERS };
return {
body: entry.content,
type: 'application/octet-stream',
headers: { ...RAW_HEADERS, 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(entry.name)}` },
};
}
function describe(entry: Entry): string
{
if (entry.kind === 'dir') return `Contents of /${entry.path || ''} on security-command.org.`;
if (!entry.content || !isText(entry.content)) return `${entry.name} on security-command.org.`;
const text = entry.content.toString('utf8').replace(/[#*_`>\[\]()]/g, '').replace(/\s+/g, ' ').trim();
return text.length > 160 ? `${text.slice(0, 157)}...` : text;
}
function crumbs(entry: Entry): Link[]
{
const parts = entry.path ? entry.path.split('/') : [];
return [
{ label: '~', href: '/ls' },
...parts.map((label, index) => ({ label, href: `/${urlPath(parts.slice(0, index + 1).join('/'))}` })),
];
}
/** Builds every static route from the index. Paths are decoded, with a leading slash and no trailing one. */
export function buildSite(index: ContentIndex, options: SiteOptions): Site
{
const pages = new Map<string, SitePage>();
const nav: Link[] = [
{ label: 'terminal', href: '/' },
{ label: 'ls', href: '/ls' },
...[...options.legal.keys()].map((route) => ({ label: route, href: `/${route}` })),
];
const html = (title: string, description: string, entryCrumbs: Link[], body: string): SitePage => ({
body: Buffer.from(renderPage({ title, description, crumbs: entryCrumbs, body, nav })),
type: 'text/html; charset=utf-8',
headers: {},
});
for (const entry of index.entries.values())
{
const title = `${entry.path ? `/${entry.path}` : '~'} · security-command.org`;
const route = entry.path ? `/${entry.path}` : '/ls';
if (entry.kind === 'dir')
{
const children = (entry.children ?? []).map((path) => index.entries.get(path)!);
pages.set(route, html(title, describe(entry), crumbs(entry), renderListing(entry, children)));
continue;
}
pages.set(route, html(title, describe(entry), crumbs(entry), renderFile(entry)));
if (entry.content) pages.set(`/raw/${entry.path}`, rawPage(entry as Entry & { content: Buffer }));
}
for (const [routeName, file] of options.legal)
{
const entry = index.entries.get(file);
const body = entry?.kind === 'file'
? renderFile(entry)
: `<p class="muted">${escapeHtml(file)} is missing from the content directory.</p>`;
pages.set(`/${routeName}`, html(`${routeName} · security-command.org`, `${routeName} of security-command.org.`, [], body));
}
const base = options.siteUrl.replace(/\/$/, '');
const urls: [string, Date | undefined][] = [
['/', undefined],
...[...index.entries.values()].map((entry): [string, Date] => [entry.path ? `/${urlPath(entry.path)}` : '/ls', entry.modified]),
...[...options.legal].map(([route, file]): [string, Date | undefined] => [`/${route}`, index.entries.get(file)?.modified]),
];
const sitemap = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
...urls.map(([url, modified]) =>
`<url><loc>${escapeHtml(base + url)}</loc>${modified ? `<lastmod>${modified.toISOString().slice(0, 10)}</lastmod>` : ''}</url>`),
'</urlset>',
'',
].join('\n');
pages.set('/sitemap.xml', { body: Buffer.from(sitemap), type: 'application/xml; charset=utf-8', headers: {} });
const robots = ['User-agent: *', 'Disallow: /ws', 'Disallow: /raw/', `Sitemap: ${base}/sitemap.xml`, ''].join('\n');
pages.set('/robots.txt', { body: Buffer.from(robots), type: 'text/plain; charset=utf-8', headers: {} });
return { pages, hash: index.hash };
}
+111
View File
@@ -0,0 +1,111 @@
import { createHash } from 'node:crypto';
import { lstat, readdir, readFile } from 'node:fs/promises';
import { join } from 'node:path';
export type Entry = {
/** Path relative to the content root with forward slashes; the root itself is "". */
path: string;
name: string;
kind: 'file' | 'dir';
size: number;
modified: Date;
/** Missing for directories and for files above the size limit. */
content?: Buffer;
children?: string[];
};
export type ContentIndex = {
entries: Map<string, Entry>;
hash: string;
warnings: string[];
};
export type WalkOptions = {
maxFileBytes: number;
maxTotalBytes: number;
maxEntries: number;
/** Top level names that would collide with the app's own routes. */
reserved: Set<string>;
signal?: AbortSignal;
};
/**
* Indexes the content directory. Symlinks are never followed, because the
* walk runs on the host side and a link could point anywhere; dotfiles are
* skipped so that things like .git or .env never become public.
*/
export async function buildIndex(root: string, options: WalkOptions): Promise<ContentIndex>
{
const entries = new Map<string, Entry>();
const warnings: string[] = [];
const hash = createHash('sha256');
let total = 0;
async function visit(path: string, absolute: string): Promise<Entry | undefined>
{
options.signal?.throwIfAborted();
const stats = await lstat(absolute);
const name = path.split('/').at(-1) ?? '';
if (stats.isSymbolicLink()) return undefined;
if (entries.size >= options.maxEntries)
{
warnings.push(`stopped at ${options.maxEntries} entries, ${path} and later ones are missing`);
return undefined;
}
if (stats.isDirectory())
{
const entry: Entry = { path, name, kind: 'dir', size: 0, modified: stats.mtime, children: [] };
entries.set(path, entry);
hash.update(`d\0${path}\0`);
const names = (await readdir(absolute)).filter((child) => !child.startsWith('.')).sort((a, b) => a.localeCompare(b, 'en'));
for (const child of names)
{
if (path === '' && options.reserved.has(child))
{
warnings.push(`"${child}" is skipped because the name is reserved for the site itself`);
continue;
}
const visited = await visit(path ? `${path}/${child}` : child, join(absolute, child));
if (visited) entry.children!.push(visited.path);
}
return entry;
}
if (!stats.isFile()) return undefined;
const entry: Entry = { path, name, kind: 'file', size: stats.size, modified: stats.mtime };
if (stats.size > options.maxFileBytes)
{
warnings.push(`${path} is listed but not served, it is larger than ${options.maxFileBytes} bytes`);
}
else if (total + stats.size > options.maxTotalBytes)
{
warnings.push(`${path} is listed but not served, the content exceeds ${options.maxTotalBytes} bytes in total`);
}
else
{
entry.content = await readFile(absolute);
total += entry.content.length;
}
entries.set(path, entry);
hash.update(`f\0${path}\0`);
hash.update(entry.content ?? `${stats.size}:${stats.mtimeMs}`);
return entry;
}
try { await visit('', root); }
catch (error)
{
if (options.signal?.aborted) throw error;
warnings.push(`the content directory cannot be read: ${(error as Error).message}`);
}
if (!entries.has('')) entries.set('', { path: '', name: '', kind: 'dir', size: 0, modified: new Date(0), children: [] });
return { entries, hash: hash.digest('hex').slice(0, 16), warnings };
}
+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);
}
}