SPB Git

Repository Public

scheduler.ts 6.1 KB 92 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : services/scheduler/src/scheduler.ts9 * Module           : services10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Scheduler: PostgreSQL is the queue (FOR UPDATE SKIP LOCKED) and the source of truth. Decision recorded in43// docs/DECISIONS.md: no Redis/BullMQ — one fewer stateful service, and a job can never exist outside the database.44import { existsSync, rmSync } from 'node:fs';45import { join } from 'node:path';46import type { Config } from '../../control-api/src/config.ts';47import type { Db } from '../../control-api/src/db.ts';48import { sweep } from '../../control-api/src/core/jobs.ts';49import { supervise } from '../../control-api/src/core/agents.ts';50import { pollGitSources } from '../../control-api/src/core/sources.ts';5152const TOPIC_ALERT: Record<string, [string, string, string]> = {53  'job.awaiting_confirmation': ['info', 'awaiting_confirmation', 'Une publication attend votre confirmation.'],54  'job.unknown_outcome': ['critical', 'unknown_outcome', 'Résultat de publication inconnu : réconciliation manuelle requise.'],55  'job.dead_letter': ['warning', 'dead_letter', 'Tâche abandonnée après plusieurs essais de préparation.'],56};57/** Transactional outbox: events were written in the same transaction as the fact; delivery is at-least-once and idempotent (alert dedupe key). */58export async function drainOutbox(db: Db): Promise<number> {59  return db.tx(async (tx) => {60    const rows = (await tx.query('SELECT * FROM outbox_events WHERE dispatched_at IS NULL ORDER BY id LIMIT 50 FOR UPDATE SKIP LOCKED')).rows;61    for (const e of rows) {62      const a = TOPIC_ALERT[e.topic];63      if (a) { const key = `${a[1] === 'unknown_outcome' ? 'unknown' : a[1] === 'dead_letter' ? 'dead' : 'await-new'}:${e.payload.jobId}`; const brand = (await tx.query('SELECT brand_id FROM publication_jobs WHERE id=$1', [e.payload.jobId])).rows[0]?.brand_id ?? null;64        await tx.query("INSERT INTO alerts(severity, kind, message, dedupe_key, brand_id) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (dedupe_key) WHERE status='open' AND dedupe_key IS NOT NULL DO NOTHING", [a[0], a[1], a[2], key, brand]); }65      await tx.query('UPDATE outbox_events SET dispatched_at=now(), attempts=attempts+1 WHERE id=$1', [e.id]);66    }67    return rows.length;68  });69}70export async function housekeeping(db: Db, cfg: Config) {71  await db.query("DELETE FROM auth_tickets WHERE expires_at < now()-interval '1 day'");72  await db.query('DELETE FROM auth_sessions WHERE expires_at < now()');73  await db.query("UPDATE alerts SET status='resolved', updated_at=now() WHERE status='open' AND kind='awaiting_confirmation' AND NOT EXISTS (SELECT 1 FROM publication_jobs j WHERE 'await-new:'||j.id = alerts.dedupe_key AND j.state='AWAITING_CONFIRMATION')");74  await db.query("DELETE FROM outbox_events WHERE dispatched_at < now()-interval '30 days'");75  // Retention: a media file past its date and not referenced by any current content version is removed from disk.76  for (const m of (await db.query(`SELECT m.id, m.storage_ref FROM media_assets m WHERE m.status <> 'deleted' AND m.retention_until < now() AND NOT EXISTS (SELECT 1 FROM content_items c JOIN content_versions v ON v.id=c.current_version_id WHERE c.brand_id=m.brand_id AND m.sha256 = ANY(v.media_sha256))`)).rows) {77    const others = (await db.one("SELECT count(*)::int AS n FROM media_assets WHERE storage_ref=$1 AND id<>$2 AND status <> 'deleted'", [m.storage_ref, m.id]))!.n;78    if (!others) { const f = join(cfg.dataDir, 'media', m.storage_ref); if (existsSync(f)) rmSync(f); }79    await db.query("UPDATE media_assets SET status='deleted' WHERE id=$1", [m.id]);80  }81}82export function startScheduler(db: Db, cfg: Config, log: (o: object) => void = () => {}) {83  let stopped = false; const timers: NodeJS.Timeout[] = [];84  const every = (ms: number, name: string, fn: () => Promise<unknown>) => { let running = false; const run = async () => { if (running || stopped) return; running = true; try { const r = await fn(); if (r && typeof r === 'object' && Object.values(r).some((v) => typeof v === 'number' && v > 0)) log({ msg: name, ...r }); } catch (e) { log({ msg: `${name}_error`, error: String((e as Error).message) }); } finally { running = false; } }; timers.push(setInterval(run, ms)); run(); };85  every(Number(process.env.MLS_SWEEP_MS ?? 5000), 'sweep', () => db.tx((tx) => sweep(tx)));86  every(5000, 'outbox', async () => ({ dispatched: await drainOutbox(db) }));87  every(60_000, 'supervise', async () => { const r = await supervise(db); return { raised: r.raised.length }; });88  every(5 * 60_000, 'git', () => pollGitSources(db, cfg));89  every(6 * 3600_000, 'housekeeping', () => housekeeping(db, cfg));90  return () => { stopped = true; timers.forEach(clearInterval); };91}92
Files main
Menu

Theme