1
0
Fork 0
fahrPool/web/lib/notifications/dispatch.ts

92 lines
2.5 KiB
TypeScript

import type { SupabaseClient } from "@supabase/supabase-js";
import type { WhatsAppConfig } from "./config";
import { sendWhatsAppTemplate, type AuftragErstelltPayload } from "./whatsapp";
export type OutboxRow = {
id: string;
event_type: string;
payload: AuftragErstelltPayload;
versuche: number;
max_versuche: number;
};
export type VerarbeitungsErgebnis = {
verarbeitet: number;
gesendet: number;
fehlgeschlagen: number;
tot: number;
};
export type DispatchDeps = {
sender?: typeof sendWhatsAppTemplate;
jetzt?: () => Date;
};
const BATCH_LIMIT = 20;
const BACKOFF_MAX_MIN = 60;
// Uebernimmt einen Batch faelliger Outbox-Zeilen (atomar via
// claim_notification_batch) und sendet sie einzeln. Erfolg -> sent; Fehler ->
// failed mit exponentiellem Backoff, bzw. dead sobald max_versuche erreicht.
export async function verarbeiteOutbox(
admin: SupabaseClient,
cfg: WhatsAppConfig,
deps: DispatchDeps = {}
): Promise<VerarbeitungsErgebnis> {
const sender = deps.sender ?? sendWhatsAppTemplate;
const jetzt = deps.jetzt ?? (() => new Date());
const { data, error } = await admin.rpc("claim_notification_batch", { p_limit: BATCH_LIMIT });
if (error) {
throw new Error(`claim_notification_batch fehlgeschlagen: ${error.message}`);
}
const rows = (data ?? []) as OutboxRow[];
const ergebnis: VerarbeitungsErgebnis = {
verarbeitet: 0,
gesendet: 0,
fehlgeschlagen: 0,
tot: 0,
};
for (const row of rows) {
ergebnis.verarbeitet += 1;
const res = await sender(cfg, row.payload);
if (res.ok) {
await admin
.from("notification_outbox")
.update({
status: "sent",
wa_message_id: res.messageId,
letzter_fehler: null,
updated_at: jetzt().toISOString(),
})
.eq("id", row.id);
ergebnis.gesendet += 1;
continue;
}
const neueVersuche = row.versuche + 1;
const tot = neueVersuche >= row.max_versuche;
const backoffMin = Math.min(2 ** neueVersuche, BACKOFF_MAX_MIN);
const naechster = new Date(jetzt().getTime() + backoffMin * 60_000);
await admin
.from("notification_outbox")
.update({
status: tot ? "dead" : "failed",
versuche: neueVersuche,
naechster_versuch_ab: naechster.toISOString(),
letzter_fehler: res.fehler.slice(0, 500),
updated_at: jetzt().toISOString(),
})
.eq("id", row.id);
if (tot) ergebnis.tot += 1;
else ergebnis.fehlgeschlagen += 1;
}
return ergebnis;
}