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:
1 parent
9647ac8c50
commit
1f6d41ab06
27 files changed
+1590
-25
No files matched your search
@@ -7,5 +7,7 @@
|
||||
!README.md
|
||||
|
||||
/runtime/
|
||||
/config/
|
||||
/jobs/
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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)`);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ digest() { "$1" image inspect --format '{{index .RepoDigests 0}}' "$2"; }
|
||||
|
||||
# The spawner runs as 10001 and shares group 10100 with the backend, which
|
||||
# runs as 10002 and writes the status file that sandboxes read.
|
||||
install -d -m 0755 runtime
|
||||
install -d -m 0755 runtime config jobs
|
||||
install -d -o 10001 -g 10100 -m 0750 runtime/spawner
|
||||
install -d -o 10002 -g 10002 -m 0755 runtime/status
|
||||
cat > runtime/deploy.env <<EOF
|
||||
|
||||
@@ -45,6 +45,10 @@ services:
|
||||
environment:
|
||||
SPAWNER_SOCKET: /run/spawner/spawner.sock
|
||||
STATUS_DIR: /run/status
|
||||
CONTENT_DIR: /content
|
||||
JOBS_FILE: /config/jobs.toml
|
||||
SITE_URL: ${SITE_URL:-https://security-command.org}
|
||||
LEGAL_PAGES: ${LEGAL_PAGES:-impressum:impressum.txt,datenschutz:datenschutz.txt}
|
||||
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://security-command.org}
|
||||
MAX_SESSIONS: ${MAX_SESSIONS:-12}
|
||||
MAX_QUEUE: ${MAX_QUEUE:-20}
|
||||
@@ -52,6 +56,8 @@ services:
|
||||
volumes:
|
||||
- ./runtime/spawner:/run/spawner
|
||||
- ./runtime/status:/run/status
|
||||
- ${CONTENT_DIR}:/content:ro
|
||||
- ./config:/config:ro
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
|
||||
+8
-1
@@ -1,6 +1,13 @@
|
||||
# Absolute host path of the homepage content. It is mounted read only.
|
||||
# Absolute host path of the homepage content. Sandboxes and the backend only
|
||||
# read it; jobs may write into it.
|
||||
CONTENT_DIR=
|
||||
|
||||
# Public address of the site, used by the sitemap.
|
||||
SITE_URL=https://security-command.org
|
||||
|
||||
# Legal pages as route:file pairs; the files live in the content directory.
|
||||
LEGAL_PAGES=impressum:impressum.txt,datenschutz:datenschutz.txt
|
||||
|
||||
# Container registry of the SecurityCommand organization.
|
||||
REGISTRY=git.security-command.org/securitycommand
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "@homepage/indexer",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": "./src/index.ts",
|
||||
"dependencies": {
|
||||
"marked": "^18.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './walk.ts';
|
||||
export * from './render.ts';
|
||||
export * from './site.ts';
|
||||
@@ -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('<script>');
|
||||
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 <b>');
|
||||
});
|
||||
|
||||
it('keeps mail links in markdown', () => {
|
||||
expect(renderMarkdown('[mail](mailto:a@b.c)')).toContain('href="mailto:a@b.c"');
|
||||
});
|
||||
});
|
||||
@@ -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('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
/** 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>
|
||||
`;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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]!]!;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './duration.ts';
|
||||
export * from './definition.ts';
|
||||
export * from './scheduler.ts';
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Generated
+40
@@ -181,6 +181,12 @@ importers:
|
||||
|
||||
apps/backend:
|
||||
dependencies:
|
||||
'@homepage/indexer':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/indexer
|
||||
'@homepage/jobs':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/jobs
|
||||
'@homepage/protocol':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/protocol
|
||||
@@ -223,6 +229,21 @@ importers:
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/protocol
|
||||
|
||||
packages/indexer:
|
||||
dependencies:
|
||||
marked:
|
||||
specifier: ^18.1.0
|
||||
version: 18.1.0
|
||||
|
||||
packages/jobs:
|
||||
dependencies:
|
||||
croner:
|
||||
specifier: ^10.0.1
|
||||
version: 10.0.1
|
||||
smol-toml:
|
||||
specifier: ^1.9.1
|
||||
version: 1.9.1
|
||||
|
||||
packages/protocol: {}
|
||||
|
||||
packages:
|
||||
@@ -667,6 +688,10 @@ packages:
|
||||
resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
croner@10.0.1:
|
||||
resolution: {integrity: sha512-ixNtAJndqh173VQ4KodSdJEI6nuioBWI0V1ITNKhZZsO0pEMoDxz539T4FTTbSZ/xIOSuDnzxLVRqBVSvPNE2g==}
|
||||
engines: {node: '>=18.0'}
|
||||
|
||||
detect-libc@2.1.2:
|
||||
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -777,6 +802,11 @@ packages:
|
||||
magic-string@1.4.3:
|
||||
resolution: {integrity: sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==}
|
||||
|
||||
marked@18.1.0:
|
||||
resolution: {integrity: sha512-PamYXWWWg2nboG3oX5Ffzpy3EFZROqZJK9hSlMmUnekp7TxPs5DcT95vwd46m73/exfKCRVMtgXoPMI4FEJL6w==}
|
||||
engines: {node: '>= 20'}
|
||||
hasBin: true
|
||||
|
||||
nanoid@3.3.20:
|
||||
resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
@@ -802,6 +832,10 @@ packages:
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
hasBin: true
|
||||
|
||||
smol-toml@1.9.1:
|
||||
resolution: {integrity: sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
source-map-js@1.2.2:
|
||||
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
@@ -1170,6 +1204,8 @@ snapshots:
|
||||
|
||||
chai@6.3.0: {}
|
||||
|
||||
croner@10.0.1: {}
|
||||
|
||||
detect-libc@2.1.2: {}
|
||||
|
||||
es-module-lexer@2.3.2: {}
|
||||
@@ -1269,6 +1305,8 @@ snapshots:
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
|
||||
marked@18.1.0: {}
|
||||
|
||||
nanoid@3.3.20: {}
|
||||
|
||||
obug@2.2.1: {}
|
||||
@@ -1304,6 +1342,8 @@ snapshots:
|
||||
'@rolldown/binding-win32-arm64-msvc': 1.2.13
|
||||
'@rolldown/binding-win32-x64-msvc': 1.2.13
|
||||
|
||||
smol-toml@1.9.1: {}
|
||||
|
||||
source-map-js@1.2.2: {}
|
||||
|
||||
std-env@4.3.0: {}
|
||||
|
||||
Reference in new issue
Block a user