/** * Background jobs — one registry, run by pg-boss (a job queue stored in Postgres). * * Why a queue instead of setInterval: * - Schedules live in the database, so a job runs once per schedule even when more than * one backend process is running (PM2 cluster, two servers on one database). * - Every run is recorded (state, start/end, result or error), shown on the admin * Background jobs page, which can also run a job straight away. * - A run that fails is retried, and a slow run never overlaps the next one. * * Each job can be switched off with its env flag (e.g. WAITLIST_JOB_ENABLED=false), and * its schedule changed with JOB_SCHEDULE_ (cron, e.g. JOB_SCHEDULE_WAITLIST="*\/5 * * * *"). * 3.4.0: an admin can do both on the Background jobs page; their choice is kept in the database * (AppSetting job_overrides), wins over the .env and takes effect straight away (other processes * within 30 seconds). * JOBS_ENABLED=false still turns all of them off (used by the end-to-end tests). * If the queue can't start (e.g. the database user can't create the pgboss schema), the * same jobs run on in-process timers instead, as before. */ const { CronExpressionParser } = require('cron-parser'); const TIMEZONE = process.env.APP_TIMEZONE || 'Africa/Johannesburg'; // pg-boss 11 can't upgrade pg-boss 10's schema (it migrates only from 11.0), so it has its own. // The old `pgboss` schema (10.x) is left as it was; it can be dropped (DROP SCHEMA pgboss CASCADE) // once 1.51.7 has run — it only held queued runs and their history. const SCHEMA = 'pgboss_v11'; const JOBS = [ { name: 'daily-summary', label: 'Daily event summary email', cron: '0 7 * * *', env: 'DAILY_SUMMARY_ENABLED', run: async () => { await require('../utils/notifications').sendDailyEventSummaries(new Date()); return { sent: true }; }, }, { name: 'waitlist', label: 'Waitlist: expire offers, offer freed places', cron: '*/10 * * * *', env: 'WAITLIST_JOB_ENABLED', run: () => require('../utils/waitlist').runWaitlistJob(), }, { name: 'payment-status', label: 'Payments: check providers for notifications that never arrived', cron: '*/15 * * * *', env: 'PAYMENT_STATUS_JOB_ENABLED', run: () => require('../payments/status').runPaymentStatusJob(), }, { name: 'feedback', label: 'Post-event feedback forms and reminders', cron: '*/15 * * * *', env: 'FEEDBACK_JOB_ENABLED', run: () => require('../utils/feedback').runFeedbackJob(), }, { name: 'sessions', label: 'Session reminders and certificates', cron: '*/5 * * * *', env: 'SESSION_JOBS_ENABLED', run: async () => { const reminders = await require('../utils/sessionReminders').runSessionReminderJob(); const certificates = await require('../utils/certificates').runCertificateJob(); return { reminders, certificates }; }, }, { name: 'volunteers', label: 'Volunteer reminders the day before a shift', cron: '*/15 * * * *', env: 'VOLUNTEER_JOBS_ENABLED', run: () => require('../utils/volunteers').runReminderJob(), }, { name: 'webhooks', label: 'Outbound webhooks: send what is due, retry failures, delete deliveries after 30 days', cron: '* * * * *', env: 'WEBHOOKS_JOBS_ENABLED', run: () => require('../utils/webhooks').runJob(), }, { name: 'series', label: 'Event series: tell followers when a new event goes live', cron: '*/15 * * * *', env: 'SERIES_JOBS_ENABLED', run: () => require('../utils/series').runAnnounceJob(), }, { name: 'consent', label: 'Parental consent reminders and medical-detail deletion', cron: '0 9 * * *', env: 'CONSENT_JOBS_ENABLED', run: async () => { const { sendConsentReminders, purgeConsentMedicalData } = require('../utils/consent'); return { reminded: await sendConsentReminders(new Date()), purged: await purgeConsentMedicalData(new Date()) }; }, }, { name: 'privacy', label: 'Privacy requests: remind admins of requests due soon', cron: '0 8 * * *', env: 'PRIVACY_JOBS_ENABLED', run: () => require('../utils/privacy').remindDueRequests(new Date()), }, { name: 'hub-heartbeat', label: 'Cross Events Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: () => require('../hub/client').heartbeat(), }, { name: 'feed', label: 'Event feed: publish changes (going live, closing, selling out) and tell linked products', cron: '*/5 * * * *', env: 'FEED_JOBS_ENABLED', run: () => require('../feed/notify').refreshAndNotify(new Date()), }, { name: 'feed-sync', label: 'Linked products: fetch events from the products shown here', cron: '*/15 * * * *', env: 'FEED_JOBS_ENABLED', run: () => require('../feed/sync').syncAll(new Date()), }, { name: 'retention', label: 'Retention: delete or anonymise personal information past its retention period', cron: '30 3 * * *', env: 'RETENTION_JOBS_ENABLED', run: () => require('../utils/retention').runRetention(new Date()), }, { name: 'analytics-rollup', label: 'Funnel analytics: roll up visits older than 90 days', cron: '15 4 * * *', env: 'ANALYTICS_ROLLUP_ENABLED', run: async () => ({ rolledUp: await require('../utils/analytics').rollupOldEvents() }), }, { name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED', run: async () => ({ file: (await require('../utils/backupUtils').runBackup()).filename }), }, { // 3.6.0: catch any change from Accounts that never arrived (accounts/peopleCheck.ts). name: 'accounts-people-check', label: 'Accounts: check everyone\'s details here match their church account', cron: '30 4 * * *', env: 'ACCOUNTS_PEOPLE_CHECK_ENABLED', run: () => require('../accounts/peopleCheck').runPeopleCheck(), }, { // 3.0.0 (docs/EVENTS-3.0-PLAN.md §5): 14 days after sign-in moved to Accounts, Events' old // passwords and 2FA secrets go; sign-in records (for signing out of Accounts) after 40 days. name: 'accounts-secrets', label: 'Accounts: clear old passwords 14 days after the move, and old sign-in records', cron: '45 3 * * *', env: null, run: async () => { const { clearOldSecrets } = require('../accounts/move'); const prisma = require('../config/db'); const old = await prisma.accountsSignIn.deleteMany({ where: { createdAt: { lt: new Date(Date.now() - 40 * 24 * 3600e3) } } }); return { ...(await clearOldSecrets(new Date())), signInsRemoved: old.count }; }, }, { name: 'temp-cleanup', label: 'Delete temp files older than 7 days', cron: '0 3 * * *', env: null, run: async () => require('../utils/cleanupTemp').cleanupTempFiles(), }, ]; const flag = (name, def = true) => { const v = process.env[name]; return v === undefined || v === '' ? def : String(v).toLowerCase() !== 'false'; }; // ─── The admin's choices (3.4.0) ────────────────────────────────────────────── const OVERRIDES_KEY = 'job_overrides'; const OVERRIDES_TTL_MS = 30 * 1000; /** { [job name]: { enabled?: boolean, cron?: string } } from the database, cached here. */ let overrides = {}; let overridesAt = 0; /** Reads the admin's choices again when the copy here is older than 30 s (or with `force`). */ async function loadOverrides(force = false) { if (!force && overridesAt && Date.now() - overridesAt < OVERRIDES_TTL_MS) return overrides; try { const prisma = require('../config/db'); const row = await prisma.appSetting.findUnique({ where: { key: OVERRIDES_KEY } }); const parsed = row?.value ? JSON.parse(row.value) : {}; overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; overridesAt = Date.now(); } catch (e) { // Keep the last copy (or none): the .env still applies. if (force) console.warn('[jobs] Could not read the job overrides:', e?.message || e); } return overrides; } /** Sets the cached choices (tests, and after saving). */ function setOverridesForTest(value) { overrides = value || {}; overridesAt = Date.now(); } /** A cron expression with five fields that cron-parser understands. */ function isCron(cron) { if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false; try { CronExpressionParser.parse(cron, { tz: TIMEZONE }); return true; } catch { return false; } } /** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */ function envEnabled(job) { return !job.env || flag(job.env); } /** Whether a job is switched on: JOBS_ENABLED=false turns all off; then the admin's choice; then its env flag. */ function isEnabled(job) { if (!flag('JOBS_ENABLED')) return false; const o = overrides[job.name]; if (o && typeof o.enabled === 'boolean') return o.enabled; return envEnabled(job); } /** A job's cron schedule: the admin's choice, else JOB_SCHEDULE_, else its default. */ function cronFor(job) { const o = overrides[job.name]; if (o && isCron(o.cron)) return o.cron; return envCronFor(job); } /** A job's cron schedule from the .env (JOB_SCHEDULE_, checked), else its default. */ function envCronFor(job) { const override = process.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`]; if (override) { try { CronExpressionParser.parse(override, { tz: TIMEZONE }); return override; } catch { console.warn(`[jobs] Ignoring invalid schedule for ${job.name}: "${override}"`); } } return job.cron; } /** When a cron schedule next fires after `from`. */ function nextRun(cron, from = new Date()) { return CronExpressionParser.parse(cron, { tz: TIMEZONE, currentDate: from }).next().toDate(); } function summarize(result) { try { const s = JSON.stringify(result ?? null); return s.length > 300 ? `${s.slice(0, 300)}…` : s; } catch { return ''; } } /** True when a job's result says nothing happened (all zeros/false/empty). */ function isNoop(value) { if (value === null || value === undefined || value === 0 || value === false || value === '') return true; if (Array.isArray(value)) return value.length === 0; if (typeof value === 'object') return Object.values(value).every(isNoop); return false; } /** * One-off background tasks (2.1.1): work a request starts but shouldn't wait for, like sending * a feedback form to everyone. Queued in pg-boss (retried if it fails, kept across a restart); * without the queue they run in this process straight after the response. A task must be safe * to run twice. */ const TASKS = { 'feedback-send': (data) => require('../utils/feedback').runFeedbackTask(data), // A linked product said its events changed (event.changed): fetch its feed now. 'feed-sync-link': (data) => require('../feed/sync').syncOne(String(data.installId || '')), }; async function runTask(name, data) { const started = Date.now(); const result = await TASKS[name](data || {}); if (!isNoop(result)) console.log(`[jobs] task ${name} done in ${Date.now() - started} ms: ${summarize(result)}`); return result ?? null; } /** Starts a task in the background. Resolves once it's queued (or started), not when it's done. */ async function enqueueTask(name, data) { if (!TASKS[name]) throw new Error(`Unknown task ${name}`); if (mode === 'queue' && boss) { try { await boss.send(name, data || {}, { retryLimit: 2, retryDelay: 30, expireInSeconds: 60 * 60 }); return { queued: true }; } catch (e) { console.warn(`[jobs] could not queue ${name}, running it here:`, e?.message || e); } } setImmediate(() => runTask(name, data).catch(e => console.warn(`[jobs] task ${name} failed:`, e?.message || e))); return { queued: false }; } async function runJob(job) { const started = Date.now(); const result = await job.run(); // Quiet when nothing happened, like the old timers. if (!isNoop(result)) console.log(`[jobs] ${job.name} done in ${Date.now() - started} ms: ${summarize(result)}`); return result ?? null; } // ─── Runner ─────────────────────────────────────────────────────────────────── let boss = null; let mode = 'off'; // 'queue' | 'timers' | 'off' const timers = new Map(); // Timer mode keeps its own short history so the admin page still has something to show. const timerHistory = new Map(); /** One job on an in-process timer while it's on. The schedule and the switch are read each time. */ function startTimer(job) { const scheduleNext = () => { if (!isEnabled(job)) { timers.delete(job.name); return; } const delay = Math.max(1000, nextRun(cronFor(job)).getTime() - Date.now()); timers.set(job.name, setTimeout(async () => { await loadOverrides(); if (!isEnabled(job)) { timers.delete(job.name); return; } const entry = { state: 'active', startedOn: new Date(), completedOn: null, output: null }; try { entry.output = await runJob(job); entry.state = 'completed'; } catch (e) { entry.state = 'failed'; entry.output = { message: e?.message || String(e) }; console.warn(`[jobs] ${job.name} failed:`, e?.message || e); } finally { entry.completedOn = new Date(); timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10)); scheduleNext(); } }, Math.min(delay, 2 ** 31 - 1))); }; scheduleNext(); } function startTimers(jobs) { mode = 'timers'; for (const job of jobs) startTimer(job); console.log(`[jobs] Running ${jobs.filter(isEnabled).length} job(s) on in-process timers.`); } /** Puts one job's schedule in line with its switch and schedule now (queue or timers). */ async function applyJob(job) { if (mode === 'queue' && boss) { if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE }); else await boss.unschedule(job.name).catch(() => {}); } else if (mode === 'timers') { clearTimeout(timers.get(job.name)); timers.delete(job.name); startTimer(job); } } const badRequest = (message) => Object.assign(new Error(message), { statusCode: 400 }); /** * Saves an admin's choice for one job and applies it straight away. `enabled` / `cron`: a value * wins over the .env; null goes back to the .env; undefined leaves it as it is. * @returns the job's choices now ({ enabled, cron }, null where the .env applies) */ async function setOverride(name, { enabled, cron } = {}) { const job = JOBS.find(j => j.name === name); if (!job) throw Object.assign(new Error('Unknown job'), { statusCode: 404 }); if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw badRequest('"enabled" must be true, false or null.'); if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim()))) { throw badRequest('That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".'); } const prisma = require('../config/db'); const all = { ...(await loadOverrides(true)) }; const entry = { ...(all[name] || {}) }; if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled; } if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = cron.trim(); } if (Object.keys(entry).length) all[name] = entry; else delete all[name]; const value = JSON.stringify(all); await prisma.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } }); setOverridesForTest(all); await applyJob(job); return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null }; } /** * Starts the background jobs. Call once after the server is listening. * @returns {Promise<'queue'|'timers'|'off'>} */ async function startJobs() { if (!flag('JOBS_ENABLED')) { console.log('[jobs] All background jobs disabled by env JOBS_ENABLED=false'); mode = 'off'; return mode; } await loadOverrides(true); const enabled = JOBS.filter(isEnabled); try { const PgBoss = require('pg-boss'); boss = new PgBoss({ connectionString: process.env.DATABASE_URL, schema: SCHEMA, application_name: 'hope-events-jobs' }); boss.on('error', (e) => console.warn('[jobs] Queue error:', e?.message || e)); await boss.start(); const existing = new Set((await boss.getQueues()).map(q => q.name)); for (const job of JOBS) { if (!existing.has(job.name)) { // stately: at most one waiting and one running, so a slow run never piles up. await boss.createQueue(job.name, { policy: 'stately', retryLimit: 2, retryDelay: 60, expireInSeconds: 60 * 60 }); } // 3.4.0: every job has a worker (an admin can switch one on later); only those on are scheduled. await boss.work(job.name, async (batch) => { const list = Array.isArray(batch) ? batch : [batch]; await loadOverrides(); // Switched off (perhaps in another process) after this run was scheduled: skip it. "Run now" still runs. if (!isEnabled(job) && !list.some(j => j?.data?.manual)) return { skipped: 'switched off' }; try { return await runJob(job); } catch (e) { console.warn(`[jobs] ${job.name} failed:`, e?.message || e); throw e; // recorded as failed, and retried } }); if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE }); else await boss.unschedule(job.name).catch(() => {}); } // One-off tasks: any number can wait and run (unlike the stately scheduled jobs). for (const name of Object.keys(TASKS)) { if (!existing.has(name)) await boss.createQueue(name, { policy: 'standard', retryLimit: 2, retryDelay: 30, expireInSeconds: 60 * 60 }); await boss.work(name, async (batch) => { const list = Array.isArray(batch) ? batch : [batch]; const out = []; for (const job of list) { try { out.push(await runTask(name, job?.data)); } catch (e) { console.warn(`[jobs] task ${name} failed:`, e?.message || e); throw e; // recorded as failed, and retried } } return out.length === 1 ? out[0] : out; }); } mode = 'queue'; const off = JOBS.filter(j => !isEnabled(j)).map(j => j.name); console.log(`[jobs] Job queue started: ${enabled.map(j => j.name).join(', ')}${off.length ? ` (off: ${off.join(', ')})` : ''}.`); } catch (e) { console.warn('[jobs] Job queue unavailable, falling back to timers:', e?.message || e); if (boss) { try { await boss.stop({ graceful: false }); } catch { /* ignore */ } } boss = null; startTimers(JOBS); } return mode; } async function stopJobs() { for (const t of timers.values()) clearTimeout(t); timers.clear(); if (boss) { await boss.stop({ graceful: true, timeout: 10000 }).catch(() => {}); boss = null; } mode = 'off'; } /** Runs a job now (admin "Run now"). Queue mode: queued for a worker; timer mode: inline. */ async function runNow(name) { const job = JOBS.find(j => j.name === name); if (!job) { const err = new Error('Unknown job'); err.statusCode = 404; throw err; } if (mode === 'queue' && boss) { // Marked manual so it runs even when the job is switched off. const id = await boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` }); return { queued: true, id }; } const output = await runJob(job); const entry = { state: 'completed', startedOn: new Date(), completedOn: new Date(), output }; timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10)); return { queued: false, output }; } /** Each job with its schedule, next run and recent runs, for the admin page. */ async function jobStatus(prisma) { await loadOverrides(true); const recent = new Map(); if (mode === 'queue') { // pg-boss columns are timestamptz, and Prisma's pg adapter drops their offset in raw queries // (10:55+02 came back as 10:55Z). As plain UTC timestamps they come back right. const rows = await prisma.$queryRawUnsafe(` 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, created_on, started_on, completed_on, output, row_number() OVER (PARTITION BY name ORDER BY created_on DESC) AS rn -- pg-boss 11 keeps finished runs in job until they expire (there's no archive table). FROM (SELECT name, state::text, created_on, started_on, completed_on, output FROM ${SCHEMA}.job) all_jobs 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]); } else { for (const [name, list] of timerHistory) recent.set(name, list); } return { mode, timezone: TIMEZONE, jobsEnabledEnv: flag('JOBS_ENABLED'), jobs: JOBS.map(job => { const cron = cronFor(job); const enabled = isEnabled(job); const o = overrides[job.name] || {}; return { name: job.name, label: job.label, cron, enabled, envFlag: job.env, // 3.4.0: what the .env says, and the admin's choice over it (null: the .env applies). envEnabled: envEnabled(job), envCron: envCronFor(job), defaultCron: job.cron, override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron) ? o.cron : null }, nextRun: enabled && mode !== 'off' ? nextRun(cron) : null, recent: recent.get(job.name) || [], }; }), }; } module.exports = { JOBS, TASKS, TIMEZONE, isEnabled, envEnabled, cronFor, isCron, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask, setOverride, loadOverrides, setOverridesForTest, };