SPB Git

Repository Public

index.ts 2.5 KB 54 lines typescript

1// Travailleurs en processus (instance unique). Tout l'état est dans PostgreSQL : un redémarrage ne perd rien, et les baux2// pris par `FOR UPDATE SKIP LOCKED` rendraient une seconde instance inoffensive. SPMAIL_WORKERS=off les désactive.3import { config } from "../config.js"4import { dispatchOutbound, trackDeliveries } from "./outbound.js"5import { watchInbound } from "./inbound.js"6import { deliverWebhooks } from "./webhooks.js"7import { expire, prune, retention } from "./maintenance.js"8import { nextWorkers } from "../next/index.js"910type Worker = { name: string; intervalMs: number; run: () => Promise<void> }11type Log = { info: (o: object, m?: string) => void; error: (o: object, m?: string) => void }1213let stopping = false14const timers = new Set<NodeJS.Timeout>()15const running = new Set<Promise<void>>()1617export function startWorkers(log: Log) {18  if (!config.workers) { log.info({}, "workers disabled (SPMAIL_WORKERS=off)"); return }19  const workers: Worker[] = [20    { name: "scheduled-send dispatcher", intervalMs: config.workerTickMs, run: dispatchOutbound },21    { name: "delivery tracker", intervalMs: config.workerTickMs, run: trackDeliveries },22    { name: "inbound watcher", intervalMs: config.watchIntervalMs, run: watchInbound },23    { name: "webhook dispatcher", intervalMs: config.workerTickMs, run: deliverWebhooks },24    { name: "expiry", intervalMs: config.expiryIntervalMs, run: expire },25    { name: "retention", intervalMs: 3600_000, run: () => retention(false).then(() => undefined) },26    { name: "pruning", intervalMs: 6 * 3600_000, run: prune },27    ...nextWorkers(),28  ]29  stopping = false30  for (const w of workers) {31    const tick = () => {32      if (stopping) return33      const p = w.run().catch((e) => log.error({ worker: w.name, err: String((e as Error).message ?? e).slice(0, 300) }, "worker error")).finally(() => {34        running.delete(p)35        if (stopping) return36        const t = setTimeout(() => { timers.delete(t); tick() }, w.intervalMs)37        timers.add(t)38      })39      running.add(p)40    }41    const first = setTimeout(() => { timers.delete(first); tick() }, Math.min(w.intervalMs, 500))42    timers.add(first)43  }44  log.info({ workers: workers.map((w) => w.name) }, "workers started")45}4647/** Arrêt propre : plus de nouveau tour, on attend les tours en cours (15 s au plus). */48export async function stopWorkers() {49  stopping = true50  for (const t of timers) clearTimeout(t)51  timers.clear()52  await Promise.race([Promise.allSettled([...running]), new Promise((r) => setTimeout(r, 15_000))])53}54
Files main
Menu

Theme