SPB Git

Repository Public

dispatcher.ts 7.0 KB 125 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : backend/src/queue/dispatcher.ts9 * Module           : queue10 * Repository       : https://git.spboucher.ai/maclustr-sms11 * Project Website  : https://sms.spboucher.ai12 * Created          : 2026-11-3013 * Last Modified    : 2026-11-3014 *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 */4142import { bus, changed } from "../bus.ts"43import { config } from "../config.ts"44import { getSetting, sql } from "../db.ts"45import { transition } from "../messages/service.ts"46import { open } from "../security/crypto.ts"47import { iso } from "../util.ts"48import { connectedDevices, isConnected, sendToDevice } from "../websocket/hub.ts"4950const commandFrame = (m: any, subscriptionId: number) => ({51  command_id: m.command_id, message_id: m.id, to: m.to_number, text: open(m.text_enc, "sms-text:" + m.id) ?? "",52  subscription_id: subscriptionId, expires_at: iso(m.expires_at), delivery_report: m.delivery_report,53})5455/**56 * À la (re)connexion : les commandes déjà transmises mais sans issue sont reproposées à l'identique (même command_id).57 * C'est le journal local de l'appareil qui décide : il ne renvoie jamais un SMS déjà traité.58 */59async function redispatch(deviceId: string) {60  const rows = await sql`61    select m.*, s.subscription_id from message_queue q join messages m on m.id = q.message_id join sim_profiles s on s.id = m.sim_id62    where q.device_id = ${deviceId} and q.state = 'in_flight' order by q.dispatched_at`63  for (const m of rows) {64    if (!sendToDevice(deviceId, "sms.send.request", commandFrame(m, m.subscription_id))) break65    await sql`update message_queue set dispatch_count = dispatch_count + 1 where message_id = ${m.id}`66    await sql`insert into message_events(message_id, type, from_status, to_status, source, detail) values (${m.id}, 'command.reoffered', ${m.status}, ${m.status}, 'system', '{}')`67  }68}6970const busy = new Set<string>()71async function dispatchDevice(deviceId: string) {72  if (busy.has(deviceId) || !isConnected(deviceId)) return73  busy.add(deviceId)74  try {75    if (await getSetting("kill_switch", false)) return76    const [d] = await sql`select enabled, maintenance, revoked_at, status from devices where id = ${deviceId}`77    if (!d || !d.enabled || d.maintenance || d.revoked_at) return78    if (d.status?.gateway_state && d.status.gateway_state !== "running") return79    if (d.status?.permissions?.send_sms === false) return        // autorisation SMS absente sur le téléphone : la file attend80    for (;;) {81      const picked = await sql.begin(async tx => {82        const [f] = await tx`select count(*)::int as n from message_queue where device_id = ${deviceId} and state = 'in_flight'`83        if (f.n >= config.inFlightWindow) return null84        const [q] = await tx`85          select q.message_id from message_queue q join messages m on m.id = q.message_id join sim_profiles s on s.id = q.sim_id86          where q.device_id = ${deviceId} and q.state = 'pending' and m.status = 'QUEUED' and m.expires_at > now() and s.enabled and s.active87          order by q.priority desc, q.enqueued_at limit 1 for update of q skip locked`88        if (!q) return null89        await tx`update message_queue set state = 'in_flight', dispatched_at = now(), dispatch_count = 1 where message_id = ${q.message_id}`90        await transition(tx, q.message_id, "DISPATCHED", { source: "system", type: "command.dispatched", detail: { device_id: deviceId } })91        const [m] = await tx`select m.*, s.subscription_id from messages m join sim_profiles s on s.id = m.sim_id where m.id = ${q.message_id}`92        return m93      })94      if (!picked) break95      // L'état DISPATCHED est validé avant l'écriture sur la connexion : si l'envoi échoue ici, la commande sera reproposée à la reconnexion.96      const sent = sendToDevice(deviceId, "sms.send.request", commandFrame(picked, picked.subscription_id))97      changed("messages"); changed("queue")98      if (!sent) break99    }100  } finally { busy.delete(deviceId) }101}102103export function startDispatcher(log: { error: Function }) {104  const run = (id: string) => void dispatchDevice(id).catch(e => log.error({ err: String(e?.message ?? e), device_id: id }, "erreur de dispatch"))105  bus.on("queue", (deviceId: string | null) => { for (const id of deviceId ? [deviceId] : connectedDevices()) run(id) })106  bus.on("device.connected", (deviceId: string) => void redispatch(deviceId).then(() => dispatchDevice(deviceId)).catch(e => log.error({ err: String(e?.message ?? e) }, "erreur de reprise")))107  const t = setInterval(() => { for (const id of connectedDevices()) run(id) }, 5000)108  t.unref()109  return () => clearInterval(t)110}111112export async function queueSnapshot(appId?: string | null) {113  const rows = await sql`114    select m.id, m.status, m.to_number, m.device_id, m.sim_id, m.application_id, m.segments, m.created_at, m.expires_at, q.state, q.enqueued_at, q.dispatched_at, q.dispatch_count115    from message_queue q join messages m on m.id = q.message_id ${appId ? sql`where m.application_id = ${appId}` : sql``}116    order by q.priority desc, q.enqueued_at limit 500`117  const held = await sql`select count(*)::int as n from messages where status = 'HELD' ${appId ? sql`and application_id = ${appId}` : sql``}`118  return {119    pending: rows.filter(r => r.state === "pending").length, in_flight: rows.filter(r => r.state === "in_flight").length, held: held[0].n,120    oldest_pending_at: iso(rows.find(r => r.state === "pending")?.enqueued_at),121    items: rows.map(r => ({ message_id: r.id, status: String(r.status).toLowerCase(), queue_state: r.state, to: r.to_number, device_id: r.device_id, sim_id: r.sim_id, application_id: r.application_id,122      segments: r.segments, created_at: iso(r.created_at), expires_at: iso(r.expires_at), dispatched_at: iso(r.dispatched_at), dispatch_count: r.dispatch_count })),123  }124}125
Files main
Menu

Theme