From 1f6d41ab06cb1b1488b15bcb83daa0877329bf50 Mon Sep 17 00:00:00 2001 From: Overlord Date: Tue, 13 Oct 2026 14:20:31 +0200 Subject: [PATCH] Add backend jobs system with built-in tasks and TOML-based configuration parsing. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 + apps/backend/package.json | 2 + apps/backend/src/builtins.test.ts | 117 +++++++++++++++++ apps/backend/src/builtins.ts | 58 ++++++++ apps/backend/src/config.ts | 22 ++++ apps/backend/src/hub.ts | 5 + apps/backend/src/jobs.ts | 101 ++++++++++++++ apps/backend/src/main.ts | 44 +++---- apps/backend/src/server.test.ts | 31 ++++- apps/backend/src/server.ts | 27 ++++ deploy.sh | 2 +- deploy/compose.yml | 6 + deploy/env.example | 9 +- packages/indexer/package.json | 9 ++ packages/indexer/src/index.ts | 3 + packages/indexer/src/indexer.test.ts | 164 +++++++++++++++++++++++ packages/indexer/src/render.ts | 149 +++++++++++++++++++++ packages/indexer/src/site.ts | 137 +++++++++++++++++++ packages/indexer/src/walk.ts | 111 ++++++++++++++++ packages/jobs/package.json | 10 ++ packages/jobs/src/definition.test.ts | 104 +++++++++++++++ packages/jobs/src/definition.ts | 190 +++++++++++++++++++++++++++ packages/jobs/src/duration.ts | 9 ++ packages/jobs/src/index.ts | 3 + packages/jobs/src/scheduler.test.ts | 116 ++++++++++++++++ packages/jobs/src/scheduler.ts | 144 ++++++++++++++++++++ pnpm-lock.yaml | 40 ++++++ 27 files changed, 1590 insertions(+), 25 deletions(-) create mode 100644 apps/backend/src/builtins.test.ts create mode 100644 apps/backend/src/builtins.ts create mode 100644 apps/backend/src/jobs.ts create mode 100644 packages/indexer/package.json create mode 100644 packages/indexer/src/index.ts create mode 100644 packages/indexer/src/indexer.test.ts create mode 100644 packages/indexer/src/render.ts create mode 100644 packages/indexer/src/site.ts create mode 100644 packages/indexer/src/walk.ts create mode 100644 packages/jobs/package.json create mode 100644 packages/jobs/src/definition.test.ts create mode 100644 packages/jobs/src/definition.ts create mode 100644 packages/jobs/src/duration.ts create mode 100644 packages/jobs/src/index.ts create mode 100644 packages/jobs/src/scheduler.test.ts create mode 100644 packages/jobs/src/scheduler.ts diff --git a/.gitignore b/.gitignore index 1a0e624..2ad7669 100644 --- a/.gitignore +++ b/.gitignore @@ -7,5 +7,7 @@ !README.md /runtime/ +/config/ +/jobs/ node_modules/ dist/ diff --git a/apps/backend/package.json b/apps/backend/package.json index ebf2fb6..1e29634 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -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" }, diff --git a/apps/backend/src/builtins.test.ts b/apps/backend/src/builtins.test.ts new file mode 100644 index 0000000..a2ebf74 --- /dev/null +++ b/apps/backend/src/builtins.test.ts @@ -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); + }); +}); diff --git a/apps/backend/src/builtins.ts b/apps/backend/src/builtins.ts new file mode 100644 index 0000000..01ca9b1 --- /dev/null +++ b/apps/backend/src/builtins.ts @@ -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 & { 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 +{ + 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)`); + }, + }; +} diff --git a/apps/backend/src/config.ts b/apps/backend/src/config.ts index dadd6c2..cb37d96 100644 --- a/apps/backend/src/config.ts +++ b/apps/backend/src/config.ts @@ -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; /** 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 +{ + const pages = new Map(); + 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), diff --git a/apps/backend/src/hub.ts b/apps/backend/src/hub.ts index c3e7b4b..8f60315 100644 --- a/apps/backend/src/hub.ts +++ b/apps/backend/src/hub.ts @@ -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 { + return new Set([...this.sessions].map((session) => session.id)); + } + stats(): HubStats { const states = [...this.sessions].map((session) => session.state); diff --git a/apps/backend/src/jobs.ts b/apps/backend/src/jobs.ts new file mode 100644 index 0000000..5579cf0 --- /dev/null +++ b/apps/backend/src/jobs.ts @@ -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; + +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; + private readonly log: (message: string) => void; + private scheduler?: Scheduler; + private watcher?: FSWatcher; + private reloadTimer?: NodeJS.Timeout; + + constructor(file: string, builtins: Record, log: (message: string) => void) + { + this.file = file; + this.builtins = builtins; + this.log = log; + } + + async start(): Promise + { + 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 + { + 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; + } +} diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.ts index e740df2..c4f577b 100644 --- a/apps/backend/src/main.ts +++ b/apps/backend/src/main.ts @@ -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 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); diff --git a/apps/backend/src/server.test.ts b/apps/backend/src/server.test.ts index 6afbf00..72ed689 100644 --- a/apps/backend/src/server.test.ts +++ b/apps/backend/src/server.test.ts @@ -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(''), 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([ + ['/ls', { body: Buffer.from('

listing

'), type: 'text/html; charset=utf-8', headers: {} }], + ['/spaced name.txt', { body: Buffer.from('

page

'), type: 'text/html; charset=utf-8', headers: {} }], + ['/raw/page.html', { body: Buffer.from('\n\n[bad](javascript:alert(1)) [good](https://example.org)', + 'page.html': '', + 'logo.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('links/'); + expect(text(site, '/links')).toContain('github.txt'); + expect(text(site, '/links/github.txt')).toContain(''); + 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('

About

'); + expect(page).not.toContain('