- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin; the choice is kept in the database (job_overrides), wins over the .env and applies at once. Accounts gets an Admin -> Background jobs page and per-job env flags, as Events. - Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same plain text (src/lib/emails.ts). - Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName. - crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads, and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats). - Agent 1.3.0: runs env-read and env-set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
304 lines
14 KiB
TypeScript
304 lines
14 KiB
TypeScript
/**
|
|
* Background jobs on pg-boss (as Cross Events): one run per schedule however many processes run,
|
|
* and timers in this process if the queue can't start. JOBS_ENABLED=false turns them all off.
|
|
*
|
|
* 1.4.0 (as Events 3.4.0): Admin → Background jobs shows each job's schedule and last runs, runs
|
|
* one now, and switches one on or off or changes its schedule. That choice is kept in the
|
|
* database (`job_overrides`), wins over the .env (a job's own flag, e.g. BACKUP_ENABLED=false, and
|
|
* JOB_SCHEDULE_<NAME>) and takes effect straight away (in other processes within 30 seconds).
|
|
*/
|
|
import { CronExpressionParser } from 'cron-parser';
|
|
import PgBoss from 'pg-boss';
|
|
import type { Ctx } from './context.js';
|
|
import { runBackupJob } from './backups/backups.js';
|
|
import { heartbeat } from './hub/client.js';
|
|
import { runDue } from './links/deliveries.js';
|
|
import { forgetOldRequests } from './links/requests.js';
|
|
import { deleteExpired } from './oidc/adapter.js';
|
|
import { runDeletionJob } from './privacy/deletion.js';
|
|
import { runExportsJob } from './privacy/export.js';
|
|
|
|
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
|
|
|
|
export const JOBS: Job[] = [
|
|
{ name: 'deliveries', label: 'Linked products: send what they need to know (sign-outs, changes), retrying failures', cron: '* * * * *', env: null, run: (ctx) => runDue(ctx) },
|
|
{ name: 'exports', label: 'Privacy: make the copies of their data people asked for', cron: '*/5 * * * *', env: 'EXPORTS_JOB_ENABLED', run: (ctx) => runExportsJob(ctx) },
|
|
{ name: 'deletions', label: 'Privacy: delete the accounts whose deletion is due', cron: '*/15 * * * *', env: 'DELETIONS_JOB_ENABLED', run: (ctx) => runDeletionJob(ctx) },
|
|
// 1.3.0: a database backup every night (Settings → Backups), as Cross Events.
|
|
{ name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runBackupJob(ctx) },
|
|
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
|
|
{
|
|
name: 'cleanup', label: 'Delete expired sign-ins, codes and links', cron: '17 * * * *', env: null,
|
|
run: async (ctx) => {
|
|
const now = ctx.now();
|
|
const [oidc, pending, tokens, nonces, requests] = await Promise.all([
|
|
deleteExpired(ctx),
|
|
ctx.db.pendingSignIn.deleteMany({ where: { expiresAt: { lt: now } } }),
|
|
ctx.db.emailToken.deleteMany({ where: { expiresAt: { lt: new Date(now.getTime() - 7 * 24 * 3600e3) } } }),
|
|
ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - 3600e3) } } }),
|
|
forgetOldRequests(ctx),
|
|
]);
|
|
return { oidc: oidc.count, pending: pending.count, tokens: tokens.count, nonces: nonces.count, requests: requests.count };
|
|
},
|
|
},
|
|
];
|
|
|
|
const SCHEMA = 'pgboss_accounts';
|
|
const OVERRIDES_KEY = 'job_overrides';
|
|
const OVERRIDES_TTL_MS = 30_000;
|
|
|
|
export type Override = { enabled?: boolean; cron?: string };
|
|
type Run = { state: string; createdOn?: Date | null; startedOn: Date | null; completedOn: Date | null; output: unknown };
|
|
|
|
/** The running queue or timers, the admin's choices (cached), and a short history for timer mode. */
|
|
type State = {
|
|
mode: 'queue' | 'timers' | 'off';
|
|
boss: PgBoss | null;
|
|
timers: Map<string, NodeJS.Timeout>;
|
|
history: Map<string, Run[]>;
|
|
overrides: Record<string, Override>;
|
|
overridesAt: number;
|
|
env: NodeJS.ProcessEnv;
|
|
};
|
|
|
|
const state: State = { mode: 'off', boss: null, timers: new Map(), history: new Map(), overrides: {}, overridesAt: 0, env: process.env };
|
|
|
|
/** Tests: a different environment for the env flags and schedules. */
|
|
export function useEnvForTest(env: NodeJS.ProcessEnv): void {
|
|
state.env = env;
|
|
}
|
|
|
|
const flag = (name: string | null) => {
|
|
if (!name) return true;
|
|
const v = state.env[name];
|
|
return v === undefined || v === '' ? true : String(v).toLowerCase() !== 'false';
|
|
};
|
|
|
|
export function isCron(cron: unknown, tz = 'Africa/Johannesburg'): cron is string {
|
|
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
|
|
try {
|
|
CronExpressionParser.parse(cron, { tz });
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function loadOverrides(ctx: Ctx, force = false): Promise<Record<string, Override>> {
|
|
if (!force && state.overridesAt && Date.now() - state.overridesAt < OVERRIDES_TTL_MS) return state.overrides;
|
|
try {
|
|
// Straight from the table: Settings caches for 30 s too, and a save must show at once here.
|
|
const row = await ctx.db.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
|
|
const parsed = row?.value ? JSON.parse(row.value) : {};
|
|
state.overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
state.overridesAt = Date.now();
|
|
} catch (e) {
|
|
if (force) console.warn('[jobs] Could not read the job overrides:', (e as Error).message);
|
|
}
|
|
return state.overrides;
|
|
}
|
|
|
|
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
|
|
export const envEnabled = (job: Job) => flag(job.env);
|
|
|
|
/** JOBS_ENABLED=false turns all off; then the admin's choice; then the job's env flag. */
|
|
export function isEnabled(ctx: Ctx, job: Job): boolean {
|
|
if (!ctx.config.jobsEnabled) return false;
|
|
const o = state.overrides[job.name];
|
|
if (o && typeof o.enabled === 'boolean') return o.enabled;
|
|
return envEnabled(job);
|
|
}
|
|
|
|
/** The .env's schedule (JOB_SCHEDULE_<NAME>, checked) or the job's own. */
|
|
export function envCronFor(ctx: Ctx, job: Job): string {
|
|
const v = state.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
|
|
if (v && isCron(v, ctx.config.timezone)) return v;
|
|
if (v) console.warn(`[jobs] Ignoring invalid schedule for ${job.name}: "${v}"`);
|
|
return job.cron;
|
|
}
|
|
|
|
export function cronFor(ctx: Ctx, job: Job): string {
|
|
const o = state.overrides[job.name];
|
|
if (o && isCron(o.cron, ctx.config.timezone)) return o.cron;
|
|
return envCronFor(ctx, job);
|
|
}
|
|
|
|
export const nextRun = (cron: string, tz: string, from = new Date()) => CronExpressionParser.parse(cron, { tz, currentDate: from }).next().toDate();
|
|
|
|
function remember(name: string, run: Run) {
|
|
state.history.set(name, [run, ...(state.history.get(name) ?? [])].slice(0, 10));
|
|
}
|
|
|
|
async function runJob(ctx: Ctx, job: Job) {
|
|
return (await job.run(ctx)) ?? null;
|
|
}
|
|
|
|
function startTimer(ctx: Ctx, job: Job) {
|
|
const tz = ctx.config.timezone;
|
|
const scheduleNext = () => {
|
|
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
|
|
const delay = Math.max(1000, nextRun(cronFor(ctx, job), tz).getTime() - Date.now());
|
|
state.timers.set(job.name, setTimeout(async () => {
|
|
await loadOverrides(ctx);
|
|
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
|
|
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
|
|
try {
|
|
entry.output = await runJob(ctx, job);
|
|
entry.state = 'completed';
|
|
} catch (e) {
|
|
entry.state = 'failed';
|
|
entry.output = { message: (e as Error).message };
|
|
console.warn(`[jobs] ${job.name}:`, (e as Error).message);
|
|
} finally {
|
|
entry.completedOn = new Date();
|
|
remember(job.name, entry);
|
|
scheduleNext();
|
|
}
|
|
}, Math.min(delay, 2 ** 31 - 1)));
|
|
};
|
|
scheduleNext();
|
|
}
|
|
|
|
async function applyJob(ctx: Ctx, job: Job) {
|
|
if (state.mode === 'queue' && state.boss) {
|
|
if (isEnabled(ctx, job)) await state.boss.schedule(job.name, cronFor(ctx, job), undefined, { tz: ctx.config.timezone });
|
|
else await state.boss.unschedule(job.name).catch(() => {});
|
|
} else if (state.mode === 'timers') {
|
|
clearTimeout(state.timers.get(job.name));
|
|
state.timers.delete(job.name);
|
|
startTimer(ctx, job);
|
|
}
|
|
}
|
|
|
|
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
|
|
if (!ctx.config.jobsEnabled) {
|
|
state.mode = 'off';
|
|
return async () => {};
|
|
}
|
|
await loadOverrides(ctx, true);
|
|
const tz = ctx.config.timezone;
|
|
try {
|
|
const boss = new PgBoss({ connectionString, schema: SCHEMA, application_name: 'crosscode-accounts-jobs' });
|
|
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
|
|
await boss.start();
|
|
state.boss = boss;
|
|
state.mode = 'queue';
|
|
for (const job of JOBS) {
|
|
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
|
|
// Every job has a worker (an admin can switch one on later); only those on are scheduled.
|
|
await boss.work(job.name, async (batch) => {
|
|
await loadOverrides(ctx);
|
|
const manual = (Array.isArray(batch) ? batch : [batch]).some((j) => (j as { data?: { manual?: boolean } })?.data?.manual);
|
|
if (!manual && !isEnabled(ctx, job)) return { skipped: 'switched off' };
|
|
return runJob(ctx, job);
|
|
});
|
|
if (isEnabled(ctx, job)) await boss.schedule(job.name, cronFor(ctx, job), undefined, { tz });
|
|
else await boss.unschedule(job.name).catch(() => {});
|
|
}
|
|
const off = JOBS.filter((j) => !isEnabled(ctx, j)).map((j) => j.name);
|
|
console.log(`[jobs] Job queue started: ${JOBS.filter((j) => isEnabled(ctx, j)).map((j) => j.name).join(', ')}${off.length ? ` (off: ${off.join(', ')})` : ''}.`);
|
|
return async () => { await boss.stop({ graceful: true }); state.boss = null; state.mode = 'off'; };
|
|
} catch (e) {
|
|
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
|
|
state.boss = null;
|
|
state.mode = 'timers';
|
|
for (const job of JOBS) startTimer(ctx, job);
|
|
return async () => { state.timers.forEach(clearTimeout); state.timers.clear(); state.mode = 'off'; };
|
|
}
|
|
}
|
|
|
|
export class JobError extends Error {
|
|
constructor(public status: number, message: string) { super(message); }
|
|
}
|
|
|
|
/**
|
|
* Saves an admin's choice for one job and applies it. `enabled` / `cron`: a value wins over the
|
|
* .env, null goes back to it, undefined leaves it.
|
|
*/
|
|
export async function setOverride(ctx: Ctx, name: string, change: { enabled?: unknown; cron?: unknown }): Promise<{ enabled: boolean | null; cron: string | null }> {
|
|
const job = JOBS.find((j) => j.name === name);
|
|
if (!job) throw new JobError(404, 'There\'s no such job.');
|
|
const { enabled, cron } = change;
|
|
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw new JobError(400, '"enabled" must be true, false or null.');
|
|
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim(), ctx.config.timezone))) {
|
|
throw new JobError(400, 'That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
|
|
}
|
|
const all = { ...(await loadOverrides(ctx, true)) };
|
|
const entry: Override = { ...(all[name] ?? {}) };
|
|
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled as boolean; }
|
|
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = (cron as string).trim(); }
|
|
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
|
|
const value = JSON.stringify(all);
|
|
await ctx.db.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
|
|
ctx.settings.forget();
|
|
state.overrides = all;
|
|
state.overridesAt = Date.now();
|
|
await applyJob(ctx, job);
|
|
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
|
|
}
|
|
|
|
/** Runs a job now: queued in queue mode (it runs even when switched off), here otherwise. */
|
|
export async function runNow(ctx: Ctx, name: string): Promise<{ queued: boolean; output?: unknown }> {
|
|
const job = JOBS.find((j) => j.name === name);
|
|
if (!job) throw new JobError(404, 'There\'s no such job.');
|
|
if (state.mode === 'queue' && state.boss) {
|
|
await state.boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
|
|
return { queued: true };
|
|
}
|
|
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
|
|
try {
|
|
entry.output = await runJob(ctx, job);
|
|
entry.state = 'completed';
|
|
return { queued: false, output: entry.output };
|
|
} catch (e) {
|
|
entry.state = 'failed';
|
|
entry.output = { message: (e as Error).message };
|
|
throw new JobError(502, `The job failed: ${(e as Error).message}`);
|
|
} finally {
|
|
entry.completedOn = new Date();
|
|
remember(job.name, entry);
|
|
}
|
|
}
|
|
|
|
/** Each job with its switch, schedule, what the .env says, the admin's choice, and its last runs. */
|
|
export async function jobStatus(ctx: Ctx) {
|
|
await loadOverrides(ctx, true);
|
|
const tz = ctx.config.timezone;
|
|
const recent = new Map<string, Run[]>();
|
|
if (state.mode === 'queue') {
|
|
try {
|
|
// As in Cross Events: timestamptz as plain UTC, so Prisma's pg adapter doesn't drop the offset.
|
|
const rows = await ctx.db.$queryRawUnsafe<(Run & { name: string })[]>(`
|
|
SELECT name, state, created_on AT TIME ZONE 'UTC' AS "createdOn", started_on AT TIME ZONE 'UTC' AS "startedOn",
|
|
completed_on AT TIME ZONE 'UTC' AS "completedOn", output
|
|
FROM (
|
|
SELECT name, state::text, created_on, started_on, completed_on, output,
|
|
row_number() OVER (PARTITION BY name ORDER BY created_on DESC) AS rn
|
|
FROM ${SCHEMA}.job WHERE name = ANY($1::text[])
|
|
) ranked WHERE rn <= 10 ORDER BY "createdOn" DESC`, JOBS.map((j) => j.name));
|
|
for (const r of rows) recent.set(r.name, [...(recent.get(r.name) ?? []), r]);
|
|
} catch (e) {
|
|
console.warn('[jobs] Could not read the run history:', (e as Error).message);
|
|
}
|
|
} else {
|
|
for (const [name, list] of state.history) recent.set(name, list);
|
|
}
|
|
return {
|
|
mode: state.mode,
|
|
timezone: tz,
|
|
jobsEnabledEnv: ctx.config.jobsEnabled,
|
|
jobs: JOBS.map((job) => {
|
|
const cron = cronFor(ctx, job);
|
|
const enabled = isEnabled(ctx, job);
|
|
const o = state.overrides[job.name] ?? {};
|
|
return {
|
|
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
|
|
envEnabled: envEnabled(job), envCron: envCronFor(ctx, job), defaultCron: job.cron,
|
|
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron, tz) ? o.cron : null },
|
|
nextRun: enabled && state.mode !== 'off' ? nextRun(cron, tz) : null,
|
|
recent: recent.get(job.name) ?? [],
|
|
};
|
|
}),
|
|
};
|
|
}
|