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

+2
View File
@@ -6,6 +6,8 @@
"build": "esbuild src/main.ts --bundle --platform=node --target=node24 --format=esm --external:bufferutil --external:utf-8-validate --banner:js=\"import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);\" --outfile=dist/backend.js"
},
"dependencies": {
"@homepage/indexer": "workspace:*",
"@homepage/jobs": "workspace:*",
"@homepage/protocol": "workspace:*",
"ws": "^8.22.0"
},
+117
View File
@@ -0,0 +1,117 @@
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { Site } from '@homepage/indexer';
import { describe, expect, it } from 'vitest';
import { createBuiltins } from './builtins.ts';
import type { BackendConfig } from './config.ts';
import type { SessionHub } from './hub.ts';
import { BackendJobs } from './jobs.ts';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function setup()
{
const root = mkdtempSync(join(tmpdir(), 'builtins-'));
const content = join(root, 'content');
const status = join(root, 'status');
mkdirSync(content);
mkdirSync(status);
writeFileSync(join(content, 'about.txt'), 'about');
const killed: string[] = [];
const logs: string[] = [];
let site: Site | undefined;
const config = {
contentDir: content,
statusDir: status,
siteUrl: 'https://security-command.org',
legalPages: new Map([['impressum', 'impressum.txt']]),
build: 'abc1234',
} as BackendConfig;
const hub = {
sessionIds: () => new Set(['live']),
stats: () => ({ maxSessions: 12, starting: 0, active: 1, grace: 0, queued: 0 }),
} as unknown as SessionHub;
const builtins = createBuiltins({
config,
hub,
spawner: {
list: async () => [{ containerId: 'c1', sessionId: 'live' }, { containerId: 'c2', sessionId: 'stale' }],
kill: async (id) => { killed.push(id); },
},
started: Date.now(),
setSite: (next) => { site = next; },
log: (line) => logs.push(line),
});
return { root, status, builtins, killed, logs, site: () => site };
}
describe('builtin jobs', () => {
it('index builds the static site', async () => {
const { builtins, site } = setup();
await builtins.index!(new AbortController().signal);
expect(site()?.pages.has('/about.txt')).toBe(true);
expect(site()?.pages.has('/sitemap.xml')).toBe(true);
});
it('status writes the status file', async () => {
const { builtins, status } = setup();
await builtins.status!(new AbortController().signal);
expect(readFileSync(join(status, 'status'), 'utf8')).toContain('sessions 1/12');
});
it('reap-orphans keeps containers of live sessions', async () => {
const { builtins, killed } = setup();
await builtins['reap-orphans']!(new AbortController().signal);
expect(killed).toEqual(['c2']);
});
});
describe('BackendJobs', () => {
it('runs the system jobs without a file and applies edits to it', async () => {
const { root, builtins, logs } = setup();
const runs: string[] = [];
const counted = Object.fromEntries(Object.entries(builtins).map(([name, run]) => [name, async (signal: AbortSignal) =>
{
runs.push(name);
await run(signal);
}]));
const file = join(root, 'jobs.toml');
const jobs = new BackendJobs(file, counted, (line) => logs.push(line));
await jobs.start();
await sleep(50);
expect(runs.sort()).toEqual(['index', 'reap-orphans', 'status']);
writeFileSync(file, '[[job]]\nid = "index"\nbuiltin = "index"\nenabled = false\n');
await sleep(800);
runs.length = 0;
jobs.emit('content-change');
await sleep(50);
expect(runs).toEqual([]);
expect(logs).toContain('job "index" is disabled');
jobs.stop();
});
it('ignores script jobs, which belong to the jobs service', async () => {
const { root, builtins, logs } = setup();
const file = join(root, 'jobs.toml');
writeFileSync(file, '[[job]]\nid = "services"\npath = "jobs/services.sh"\non = ["start"]\n');
const jobs = new BackendJobs(file, builtins, (line) => logs.push(line));
await jobs.start();
await sleep(50);
jobs.stop();
expect(logs.some((line) => line.includes('services'))).toBe(false);
});
});
+58
View File
@@ -0,0 +1,58 @@
import { buildIndex, buildSite, reservedNames, type Site } from '@homepage/indexer';
import type { BackendConfig } from './config.ts';
import type { SessionHub } from './hub.ts';
import type { Builtin } from './jobs.ts';
import type { Spawner } from './session.ts';
import { renderStatus, writeStatus } from './status.ts';
export type BuiltinDependencies = {
config: BackendConfig;
hub: SessionHub;
spawner: Pick<Spawner, 'kill'> & { list(): Promise<{ containerId: string; sessionId: string }[]> };
started: number;
setSite: (site: Site) => void;
log: (message: string) => void;
};
/** Limits that keep the in-memory copy of the content small. */
const CONTENT_LIMITS = { maxFileBytes: 1024 * 1024, maxTotalBytes: 64 * 1024 * 1024, maxEntries: 10_000 };
/** The jobs that live inside the backend; config/jobs.toml decides when they run. */
export function createBuiltins(dependencies: BuiltinDependencies): Record<string, Builtin>
{
const { config, hub, spawner, log } = dependencies;
let lastWarnings = '';
return {
index: async (signal) =>
{
const index = await buildIndex(config.contentDir, { ...CONTENT_LIMITS, reserved: reservedNames(config.legalPages), signal });
signal.throwIfAborted();
dependencies.setSite(buildSite(index, { siteUrl: config.siteUrl, legal: config.legalPages }));
// The same warnings come back on every rebuild, so they are only logged when they change.
const warnings = index.warnings.join('\n');
if (warnings !== lastWarnings) for (const warning of index.warnings) log(`content: ${warning}`);
lastWarnings = warnings;
log(`indexed ${index.entries.size} entries (${index.hash})`);
},
status: async () =>
{
if (!config.statusDir) return;
writeStatus(config.statusDir, renderStatus(hub.stats(), (Date.now() - dependencies.started) / 1000, config.build));
},
/** Removes sandboxes no session knows about. Safe at any time, since live sessions are kept. */
'reap-orphans': async () =>
{
const live = hub.sessionIds();
const orphans = (await spawner.list()).filter((container) => !live.has(container.sessionId));
await Promise.all(orphans.map((container) => spawner.kill(container.containerId)));
if (orphans.length > 0) log(`removed ${orphans.length} orphaned sandbox(es)`);
},
};
}
+22
View File
@@ -5,6 +5,12 @@ export type BackendConfig = {
metricsPort: number;
spawnerSocket: string;
frontendDir: string;
contentDir: string;
jobsFile: string;
/** Absolute URL of the site, for the sitemap. */
siteUrl: string;
/** Route name to content file, from LEGAL_PAGES like "impressum:impressum.txt". */
legalPages: Map<string, string>;
/** Directory for the status file shown in sandboxes; empty disables it. */
statusDir: string;
build: string;
@@ -31,6 +37,18 @@ function list(value: string | undefined): string[] {
return (value ?? '').split(',').map((entry) => entry.trim()).filter(Boolean);
}
function legalPages(value: string): Map<string, string>
{
const pages = new Map<string, string>();
for (const pair of list(value))
{
const [route = '', file = ''] = pair.split(':');
if (!/^[a-z0-9-]+$/.test(route) || !file) throw new Error(`LEGAL_PAGES entry "${pair}" must look like route:file`);
pages.set(route, file);
}
return pages;
}
export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
{
const config: BackendConfig = {
@@ -39,6 +57,10 @@ export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
metricsPort: integer(env, 'METRICS_PORT', 9090, 0),
spawnerSocket: env.SPAWNER_SOCKET ?? '/run/spawner/spawner.sock',
frontendDir: env.FRONTEND_DIR ?? '/app/public',
contentDir: env.CONTENT_DIR ?? '/content',
jobsFile: env.JOBS_FILE ?? '/config/jobs.toml',
siteUrl: env.SITE_URL ?? 'https://security-command.org',
legalPages: legalPages(env.LEGAL_PAGES ?? 'impressum:impressum.txt,datenschutz:datenschutz.txt'),
statusDir: env.STATUS_DIR ?? '',
build: env.BUILD_SHA ?? 'dev',
allowedOrigins: list(env.ALLOWED_ORIGINS),
+5
View File
@@ -94,6 +94,11 @@ export class SessionHub
return this.options.powDifficulty;
}
/** Ids of every session that still owns a container, used to tell orphans apart. */
sessionIds(): Set<string> {
return new Set([...this.sessions].map((session) => session.id));
}
stats(): HubStats
{
const states = [...this.sessions].map((session) => session.state);
+101
View File
@@ -0,0 +1,101 @@
import { watch, type FSWatcher } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { basename, dirname } from 'node:path';
import { loadJobs, Scheduler, type JobDefinition, type JobEvent } from '@homepage/jobs';
export type Builtin = (signal: AbortSignal) => Promise<void>;
const RELOAD_DEBOUNCE_MS = 500;
/**
* Runs the builtin jobs of config/jobs.toml inside the backend. Script jobs
* in the same file belong to the jobs service and are ignored here. The file
* is watched, so edits apply without a restart.
*/
export class BackendJobs
{
private readonly file: string;
private readonly builtins: Record<string, Builtin>;
private readonly log: (message: string) => void;
private scheduler?: Scheduler;
private watcher?: FSWatcher;
private reloadTimer?: NodeJS.Timeout;
constructor(file: string, builtins: Record<string, Builtin>, log: (message: string) => void)
{
this.file = file;
this.builtins = builtins;
this.log = log;
}
async start(): Promise<void>
{
await this.load();
// The directory is watched instead of the file, because editors and the
// jobs service replace the file, which would end a watch on the old one.
try
{
this.watcher = watch(dirname(this.file), (_event, name) =>
{
if (name !== basename(this.file)) return;
clearTimeout(this.reloadTimer);
this.reloadTimer = setTimeout(() => void this.load(), RELOAD_DEBOUNCE_MS);
});
}
catch { this.log(`cannot watch ${this.file}, changes apply after a restart`); }
}
emit(event: JobEvent): void {
this.scheduler?.emit(event);
}
trigger(id: string): void {
this.scheduler?.trigger(id);
}
stop(): void
{
this.watcher?.close();
this.scheduler?.stop();
}
private async load(): Promise<void>
{
let text = '';
try { text = await readFile(this.file, 'utf8'); }
catch { this.log(`${this.file} does not exist yet, running the default system jobs`); }
const { jobs, warnings } = loadJobs(text);
for (const warning of warnings) this.log(warning);
const own = jobs.filter((job): job is JobDefinition & { builtin: string } => job.builtin !== undefined);
for (const job of own) if (!this.builtins[job.builtin]) this.log(`job "${job.id}" names the unknown builtin "${job.builtin}"`);
this.scheduler?.stop();
this.scheduler = new Scheduler(own.filter((job) => this.builtins[job.builtin]), (job, signal) => this.builtins[job.builtin!]!(signal), {
log: this.log,
triggerOther: (id) => this.log(`job "${id}" runs in the jobs service and cannot be triggered from the backend`),
});
this.scheduler.start();
}
}
/** 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: (message: string) => void): FSWatcher | undefined
{
let timer: NodeJS.Timeout | undefined;
try
{
return watch(directory, { recursive: true }, () =>
{
clearTimeout(timer);
timer = setTimeout(onChange, quietMs);
});
}
catch (error)
{
log(`cannot watch ${directory}: ${(error as Error).message}`);
return undefined;
}
}
+22 -22
View File
@@ -1,37 +1,40 @@
import type { Site } from '@homepage/indexer';
import { SpawnerClient } from '@homepage/protocol';
import { loadAssets } from './assets.ts';
import { createBuiltins } from './builtins.ts';
import { loadConfig } from './config.ts';
import { SessionHub } from './hub.ts';
import { BackendJobs, watchTree } from './jobs.ts';
import { createBackend, createMetricsServer } from './server.ts';
import { renderStatus, writeStatus } from './status.ts';
const log = (message: string) => console.log(`[backend] ${message}`);
const HEALTH_CACHE_MS = 10_000;
const STATUS_INTERVAL_MS = 5000;
const HEALTH_CACHE_MS = 10_000;
const CONTENT_QUIET_MS = 2000;
const config = loadConfig(process.env);
const spawner = new SpawnerClient(config.spawnerSocket);
// Sessions live in memory, so sandboxes of a previous backend process are unreachable.
const orphans = await spawner.list();
await Promise.all(orphans.map((container) => spawner.kill(container.containerId)));
if (orphans.length > 0) log(`removed ${orphans.length} orphaned sandbox(es)`);
const assets = loadAssets(config.frontendDir);
if (assets.size === 0) log(`no frontend found in ${config.frontendDir}`);
const started = Date.now();
function updateStatus(): void
{
if (!config.statusDir) return;
try { writeStatus(config.statusDir, renderStatus(hub.stats(), (Date.now() - started) / 1000, config.build)); }
catch (error) { log(`could not write the status file: ${String(error)}`); }
}
let site: Site | undefined;
let jobs: BackendJobs | undefined;
// Solving the proof of work happens after connecting, so slow phones get time for it.
const hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 90_000, log, onChange: updateStatus });
const hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 90_000, log, onChange: () => jobs?.trigger('status') });
jobs = new BackendJobs(config.jobsFile, createBuiltins({
config,
hub,
spawner,
started: Date.now(),
setSite: (next) => { site = next; },
log,
}), log);
await jobs.start();
watchTree(config.contentDir, CONTENT_QUIET_MS, () => jobs?.emit('content-change'), log);
// The public health check asks the spawner at most every few seconds, so it cannot be used to flood it.
let health = { ok: true, checkedAt: 0 };
@@ -44,18 +47,15 @@ async function healthy(): Promise<boolean>
return ok;
}
const server = createBackend(config, hub, { assets, healthy });
const server = createBackend(config, hub, { assets, healthy, site: () => site });
server.listen(config.port, config.host, () => log(`listening on ${config.host}:${config.port}`));
if (config.metricsPort > 0) createMetricsServer(hub).listen(config.metricsPort, config.host);
// Besides changes, the uptime line needs a regular refresh.
updateStatus();
setInterval(updateStatus, STATUS_INTERVAL_MS);
for (const signal of ['SIGTERM', 'SIGINT'] as const)
{
process.once(signal, () => {
jobs?.stop();
hub.endAll('closed');
server.close();
setTimeout(() => process.exit(0), 500);
+30 -1
View File
@@ -1,6 +1,7 @@
import type { AddressInfo } from 'node:net';
import type { Server } from 'node:http';
import { duplexPair, type Duplex } from 'node:stream';
import type { Site, SitePage } from '@homepage/indexer';
import { solveProof } from '@homepage/protocol/proof';
import type { ServerMessage } from '@homepage/protocol/terminal';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -14,6 +15,15 @@ const INDEX = { body: Buffer.from('<!doctype html>'), type: 'text/html; charset
const SCRIPT = { body: Buffer.from('console.log(1)'), type: 'text/javascript; charset=utf-8', immutable: true };
const ASSETS = new Map([['/', INDEX], ['/index.html', INDEX], ['/assets/index-abc.js', SCRIPT]]);
const SITE: Site = {
hash: 'abc123',
pages: new Map<string, SitePage>([
['/ls', { body: Buffer.from('<p>listing</p>'), type: 'text/html; charset=utf-8', headers: {} }],
['/spaced name.txt', { body: Buffer.from('<p>page</p>'), type: 'text/html; charset=utf-8', headers: {} }],
['/raw/page.html', { body: Buffer.from('<script>'), type: 'text/plain; charset=utf-8', headers: { 'Content-Security-Policy': 'sandbox' } }],
]),
};
/** Hands out one in-memory stream pair per spawn; the far end plays the container. */
class FakeSpawner implements Spawner
{
@@ -78,6 +88,10 @@ describe('backend', () => {
metricsPort: 0,
spawnerSocket: '',
frontendDir: '',
contentDir: '',
jobsFile: '',
siteUrl: 'https://security-command.org',
legalPages: new Map(),
statusDir: '',
build: 'test',
allowedOrigins: ['https://security-command.org'],
@@ -94,7 +108,7 @@ describe('backend', () => {
spawner = new FakeSpawner();
hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 10_000, log: () => {} });
server = createBackend(config, hub, { assets: ASSETS });
server = createBackend(config, hub, { assets: ASSETS, site: () => SITE });
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/ws`;
}
@@ -391,6 +405,21 @@ describe('backend', () => {
expect((await http('/', 'POST')).status).toBe(405);
});
it('serves static site pages with a content hash ETag', async () => {
const response = await http('/ls/');
expect(await response.text()).toBe('<p>listing</p>');
expect(response.headers.get('etag')).toBe('"abc123"');
const cached = await fetch(url.replace('ws://', 'http://').replace('/ws', '/ls'), { headers: { 'If-None-Match': '"abc123"' } });
expect(cached.status).toBe(304);
});
it('decodes paths and keeps the sandbox policy of raw files', async () => {
expect(await (await http('/spaced%20name.txt')).text()).toBe('<p>page</p>');
expect((await http('/raw/page.html')).headers.get('content-security-policy')).toBe('sandbox');
expect((await http('/%E0%A4%A')).status).toBe(404);
});
it('returns 404 for unknown paths', async () => {
expect((await http('/../../etc/passwd')).status).toBe(404);
expect((await http('/nothing')).status).toBe(404);
+27
View File
@@ -1,5 +1,6 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import type { Duplex } from 'node:stream';
import type { Site } from '@homepage/indexer';
import { TERMINAL_PATH } from '@homepage/protocol/terminal';
import { WebSocketServer, type WebSocket } from 'ws';
import type { Asset } from './assets.ts';
@@ -11,6 +12,8 @@ export type BackendOptions = {
assets?: Map<string, Asset>;
/** Resolves to false while the spawner is unreachable. */
healthy?: () => Promise<boolean>;
/** The static site of the content, rebuilt by the index job. */
site?: () => Site | undefined;
};
const MAX_FRAME_BYTES = 64 * 1024;
@@ -39,6 +42,13 @@ function send(response: ServerResponse, status: number, type: string, body: stri
response.end(head ? undefined : body);
}
/** Decoded path without a trailing slash, or undefined for malformed percent encoding. */
function sitePath(path: string): string | undefined
{
try { return decodeURIComponent(path).replace(/(.)\/+$/, '$1'); }
catch { return undefined; }
}
function reject(socket: Duplex, status: number, reason: string): void
{
socket.end(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
@@ -56,6 +66,7 @@ export function createBackend(config: BackendConfig, hub: SessionHub, options: B
{
const assets = options.assets ?? new Map<string, Asset>();
const healthy = options.healthy ?? (async () => true);
const site = options.site ?? (() => undefined);
const server = createServer(async (request, response) =>
{
@@ -76,6 +87,22 @@ export function createBackend(config: BackendConfig, hub: SessionHub, options: B
return send(response, 200, asset.type, asset.body, { 'Cache-Control': cache }, head);
}
const current = site();
const page = current && current.pages.get(sitePath(path) ?? '');
if (current && page)
{
// Every page changes together with the content, so the content hash is a valid ETag for all of them.
const etag = `"${current.hash}"`;
const headers = { 'Cache-Control': 'no-cache', ETag: etag, ...page.headers };
if (request.headers['if-none-match'] === etag)
{
response.writeHead(304, { ...SECURITY_HEADERS, ...headers }).end();
return;
}
return send(response, 200, page.type, page.body, headers, head);
}
send(response, 404, 'text/plain', 'not found', {}, head);
});