Add jobs service with script execution, configuration support, and control interface.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1f6d41ab06
commit
0ad5b5f44f
27 files changed
+1108
-45
No files matched your search
@@ -60,6 +60,16 @@ describe('builtin jobs', () => {
|
||||
expect(site()?.pages.has('/sitemap.xml')).toBe(true);
|
||||
});
|
||||
|
||||
it('index keeps the site when the content did not change', async () => {
|
||||
const { builtins, site, logs } = setup();
|
||||
await builtins.index!(new AbortController().signal);
|
||||
const first = site();
|
||||
await builtins.index!(new AbortController().signal);
|
||||
|
||||
expect(site()).toBe(first);
|
||||
expect(logs.filter((line) => line.startsWith('indexed'))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('status writes the status file', async () => {
|
||||
const { builtins, status } = setup();
|
||||
await builtins.status!(new AbortController().signal);
|
||||
|
||||
@@ -21,6 +21,7 @@ const CONTENT_LIMITS = { maxFileBytes: 1024 * 1024, maxTotalBytes: 64 * 1024 * 1
|
||||
export function createBuiltins(dependencies: BuiltinDependencies): Record<string, Builtin>
|
||||
{
|
||||
const { config, hub, spawner, log } = dependencies;
|
||||
let lastHash = '';
|
||||
let lastWarnings = '';
|
||||
|
||||
return {
|
||||
@@ -29,6 +30,10 @@ export function createBuiltins(dependencies: BuiltinDependencies): Record<string
|
||||
const index = await buildIndex(config.contentDir, { ...CONTENT_LIMITS, reserved: reservedNames(config.legalPages), signal });
|
||||
signal.throwIfAborted();
|
||||
|
||||
// Content changes often arrive twice, through "then" and the content watcher.
|
||||
if (index.hash === lastHash) return;
|
||||
lastHash = index.hash;
|
||||
|
||||
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.
|
||||
|
||||
@@ -7,6 +7,8 @@ export type BackendConfig = {
|
||||
frontendDir: string;
|
||||
contentDir: string;
|
||||
jobsFile: string;
|
||||
/** Directory the jobs service writes triggers for builtin jobs into; empty disables them. */
|
||||
triggerDir: string;
|
||||
/** Absolute URL of the site, for the sitemap. */
|
||||
siteUrl: string;
|
||||
/** Route name to content file, from LEGAL_PAGES like "impressum:impressum.txt". */
|
||||
@@ -59,6 +61,7 @@ export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
|
||||
frontendDir: env.FRONTEND_DIR ?? '/app/public',
|
||||
contentDir: env.CONTENT_DIR ?? '/content',
|
||||
jobsFile: env.JOBS_FILE ?? '/config/jobs.toml',
|
||||
triggerDir: env.TRIGGER_DIR ?? '',
|
||||
siteUrl: env.SITE_URL ?? 'https://security-command.org',
|
||||
legalPages: legalPages(env.LEGAL_PAGES ?? 'impressum:impressum.txt,datenschutz:datenschutz.txt'),
|
||||
statusDir: env.STATUS_DIR ?? '',
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { watch, type FSWatcher } from 'node:fs';
|
||||
import 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';
|
||||
import { loadJobs, Scheduler, watchFile, type JobDefinition, type JobEvent } from '@homepage/jobs';
|
||||
|
||||
export type Builtin = (signal: AbortSignal) => Promise<void>;
|
||||
|
||||
@@ -19,7 +18,6 @@ export class BackendJobs
|
||||
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)
|
||||
{
|
||||
@@ -31,27 +29,16 @@ export class BackendJobs
|
||||
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`); }
|
||||
this.watcher = watchFile(this.file, RELOAD_DEBOUNCE_MS, () => void this.load(), this.log);
|
||||
}
|
||||
|
||||
emit(event: JobEvent): void {
|
||||
this.scheduler?.emit(event);
|
||||
}
|
||||
|
||||
trigger(id: string): void {
|
||||
this.scheduler?.trigger(id);
|
||||
/** Starts a job. Returns false for unknown or disabled jobs. */
|
||||
trigger(id: string): boolean {
|
||||
return this.scheduler?.trigger(id) ?? false;
|
||||
}
|
||||
|
||||
stop(): void
|
||||
@@ -80,22 +67,3 @@ export class BackendJobs
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { Site } from '@homepage/indexer';
|
||||
import { watchTree, watchTriggers } from '@homepage/jobs';
|
||||
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 { BackendJobs } from './jobs.ts';
|
||||
import { createBackend, createMetricsServer } from './server.ts';
|
||||
|
||||
const log = (message: string) => console.log(`[backend] ${message}`);
|
||||
@@ -36,6 +37,15 @@ await jobs.start();
|
||||
|
||||
watchTree(config.contentDir, CONTENT_QUIET_MS, () => jobs?.emit('content-change'), log);
|
||||
|
||||
if (config.triggerDir)
|
||||
{
|
||||
watchTriggers(config.triggerDir, (id) =>
|
||||
{
|
||||
if (jobs?.trigger(id)) log(`job "${id}" triggered by the jobs service`);
|
||||
else log(`the jobs service triggered "${id}", which is no enabled builtin job`);
|
||||
}, 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 };
|
||||
async function healthy(): Promise<boolean>
|
||||
|
||||
@@ -90,6 +90,7 @@ describe('backend', () => {
|
||||
frontendDir: '',
|
||||
contentDir: '',
|
||||
jobsFile: '',
|
||||
triggerDir: '',
|
||||
siteUrl: 'https://security-command.org',
|
||||
legalPages: new Map(),
|
||||
statusDir: '',
|
||||
|
||||
Reference in new issue
Block a user