Repository Public
1// Répartiteur des envois (programmés, approuvés, en attente du serveur de courrier) et suivi de remise.2import { sql } from "../db.js"3import { submitOutbound, trackOutbound, type OutboundRow } from "../outbound.js"45async function claim(statuses: string[], limit: number): Promise<OutboundRow[]> {6 return (await sql`update outbound_messages set locked_until = now() + interval '2 minutes'7 where id in (select id from outbound_messages where status = any(${statuses}) and next_check_at is not null and next_check_at <= now()8 and (locked_until is null or locked_until < now()) order by next_check_at limit ${limit} for update skip locked)9 returning *`) as unknown as OutboundRow[]10}11const release = (id: string, delaySec: number) => sql`update outbound_messages set locked_until = null, next_check_at = now() + make_interval(secs => ${delaySec}) where id = ${id}`1213/** Soumet à Stalwart les messages programmés arrivés à échéance et ceux restés « queued ». */14export async function dispatchOutbound() {15 for (const o of await claim(["queued", "scheduled"], 10)) await submitOutbound(o).catch(() => release(o.id, 30))16}1718/** Interroge EmailSubmission/get pour les messages non définitifs ; après un redémarrage, reprend depuis la table. */19export async function trackDeliveries() {20 const rows = await claim(["sent", "deferred"], 20)21 await Promise.all(rows.map((o) => trackOutbound(o).catch(() => release(o.id, 20))))22}23