diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index 26af109d79..00c741b81c 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -296,9 +296,55 @@ export function validateNewSubscription( // --- The store (Supabase `alerts` schema) ------------------------------------ +interface PendingIncidentCursor { + timestamp: string; + id: string; +} + +type PendingIncidentOrder = "first_seen_at" | "delivered_at"; + export class AlertsStore { + // Each queue advances independently, even when a send fails and leaves + // the incident eligible. The keyset cursor lives for this store's lifetime. + private readonly deliveryCursor: { last: PendingIncidentCursor | null } = { last: null }; + private readonly escalationCursor: { last: PendingIncidentCursor | null } = { last: null }; + constructor(private readonly db: SupabaseClient) {} + private async pendingBatch( + eligibility: string, + orderColumn: PendingIncidentOrder, + cursor: { last: PendingIncidentCursor | null }, + limit: number, + ): Promise { + const previous = cursor.last; + const page = (wrap: boolean, pageLimit: number) => { + const cursorFilter = previous + ? `and (${orderColumn}, id) ${wrap ? "<=" : ">"} (${sqlStr(previous.timestamp)}, ${sqlStr(previous.id)})` + : ""; + return this.db.query( + `select * from alerts.incidents + where ${eligibility} ${cursorFilter} + order by ${orderColumn}, id limit ${sqlInt(pageLimit)}`, + ); + }; + + const rows = await page(false, limit); + let advanceTo = rows.at(-1); + if (previous && rows.length < limit) { + const wrapped = await page(true, limit - rows.length); + rows.push(...wrapped); + if (wrapped.length) advanceTo = wrapped.at(-1); + } + + if (advanceTo) { + const timestamp = advanceTo[orderColumn]; + if (timestamp === null) throw new Error(`pending incident has no ${orderColumn}`); + cursor.last = { timestamp, id: advanceTo.id }; + } + return rows; + } + private async addEvent(incidentId: string, kind: IncidentEvent["kind"], detail?: Record) { await this.db.query( `insert into alerts.incident_events (incident_id, kind, detail) values (${sqlStr(incidentId)}, ${sqlStr(kind)}, ${sqlJson(detail ?? null)})`, @@ -434,20 +480,22 @@ export class AlertsStore { } async pendingDeliveries(limit = 20): Promise { - return this.db.query( - `select * from alerts.incidents - where status = 'open' and severity = 'critical' and delivered_at is null - order by first_seen_at limit ${sqlInt(limit)}`, + return this.pendingBatch( + "status = 'open' and severity = 'critical' and delivered_at is null", + "first_seen_at", + this.deliveryCursor, + limit, ); } async pendingEscalations(ackWindowMin: number, limit = 20): Promise { - return this.db.query( - `select * from alerts.incidents - where status = 'open' and severity = 'critical' - and delivered_at is not null and escalated_at is null - and delivered_at < now() - make_interval(mins => ${sqlInt(ackWindowMin)}) - order by delivered_at limit ${sqlInt(limit)}`, + return this.pendingBatch( + `status = 'open' and severity = 'critical' + and delivered_at is not null and escalated_at is null + and delivered_at < now() - make_interval(mins => ${sqlInt(ackWindowMin)})`, + "delivered_at", + this.escalationCursor, + limit, ); } diff --git a/pm-stack/aggregator/test/alerts.test.ts b/pm-stack/aggregator/test/alerts.test.ts index d3ae9b95d7..b84c4f15e8 100644 --- a/pm-stack/aggregator/test/alerts.test.ts +++ b/pm-stack/aggregator/test/alerts.test.ts @@ -21,14 +21,15 @@ import { toPublicSubscription, validateNewIncident, validateNewSubscription, - type AlertsStore, + AlertsStore, + type AlertsStore as AlertsStoreType, type Incident, type PushSubscriptionRow, } from "../src/alerts.ts"; import { isForeignSwScript, type PushOutcome, type PushTarget } from "../src/push.ts"; import { renderAlerts } from "../src/render.ts"; import type { Provenance } from "../src/model.ts"; -import { sqlInt, sqlJson, sqlStr } from "../src/supabase.ts"; +import { sqlInt, sqlJson, sqlStr, type SupabaseClient } from "../src/supabase.ts"; import type { Config } from "../src/config.ts"; describe("sql literals", () => { @@ -265,7 +266,60 @@ function alertTickStore( noteSubscriptionAlive: async () => {}, noteSubscriptionGone: async () => "marked" as const, }; - return { store: store as unknown as AlertsStore, calls }; + return { store: store as unknown as AlertsStoreType, calls }; +} + +function pendingIncidentStore(rows: Incident[]): AlertsStore { + const db: SupabaseClient = { + ref: "test", + async query(sql: string): Promise { + const orderColumn = /order by (first_seen_at|delivered_at)/i.exec(sql)?.[1] as + | "first_seen_at" + | "delivered_at" + | undefined; + if (!orderColumn) throw new Error(`unexpected query: ${sql}`); + const isDeliveryQuery = /delivered_at is null/i.test(sql); + const limit = Number(/limit (\d+)/i.exec(sql)?.[1]); + const cursorMatch = /and \((first_seen_at|delivered_at), id\) (>|<=) \('([^']+)', '([^']+)'\)/i.exec(sql); + const candidates = rows + .filter((row) => (isDeliveryQuery ? row.delivered_at === null : row.delivered_at !== null)) + .filter((row) => { + if (!cursorMatch) return true; + const [, column, operator, timestamp, id] = cursorMatch; + const value = column === "first_seen_at" ? row.first_seen_at : row.delivered_at!; + const comparison = value.localeCompare(timestamp) || row.id.localeCompare(id); + return operator === ">" ? comparison > 0 : comparison <= 0; + }) + .sort((a, b) => { + const aValue = orderColumn === "first_seen_at" ? a.first_seen_at : a.delivered_at!; + const bValue = orderColumn === "first_seen_at" ? b.first_seen_at : b.delivered_at!; + return aValue.localeCompare(bValue) || a.id.localeCompare(b.id); + }) + .slice(0, limit); + return candidates as T[]; + }, + }; + const store = new AlertsStore(db); + Object.assign(store, { + listSubscriptions: async () => [ + { + id: "sub-1", + endpoint: "https://push.example/sub-1", + p256dh: "p256dh", + auth: "auth", + classes: { incident: true }, + quiet: { start: "23:00", end: "07:00", tz: "UTC" }, + user_agent: null, + created_at: "2026-11-01T00:00:00Z", + last_seen_at: "2026-11-01T00:00:00Z", + gone_count: 0, + }, + ], + logSend: async () => {}, + noteSubscriptionAlive: async () => {}, + noteSubscriptionGone: async () => "marked" as const, + }); + return store; } const failedSend = async (_target: PushTarget, _payload: unknown): Promise => ({ @@ -278,6 +332,49 @@ const successfulSend = async (_target: PushTarget, _payload: unknown): Promise

{ + const incidents = (delivered: boolean) => + Array.from({ length: 21 }, (_, index) => { + const timestamp = new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(); + return { + ...incident, + id: `00000000-0000-0000-0000-${String(index + 1).padStart(12, "0")}`, + first_seen_at: timestamp, + delivered_at: delivered ? timestamp : null, + }; + }); + + test("a newer incident gets a delivery attempt after the oldest batch keeps failing", async () => { + const rows = incidents(false); + const store = pendingIncidentStore(rows); + const attempted: string[] = []; + + const failingPush = async (_target: PushTarget, payload: unknown): Promise => { + attempted.push((payload as { objectRef: string }).objectRef); + return failedSend(_target, payload); + }; + await runAlertTick(tickConfig, store, failingPush); + await runAlertTick(tickConfig, store, failingPush); + + expect(attempted).toContain(`incident:${rows[20].id}`); + }); + + test("a newer incident gets an escalation attempt after the oldest batch keeps failing", async () => { + const rows = incidents(true); + const store = pendingIncidentStore(rows); + const attempted: string[] = []; + + const failingPush = async (_target: PushTarget, payload: unknown): Promise => { + attempted.push((payload as { objectRef: string }).objectRef); + return failedSend(_target, payload); + }; + await runAlertTick(tickConfig, store, failingPush); + await runAlertTick(tickConfig, store, failingPush); + + expect(attempted).toContain(`incident:${rows[20].id}`); + }); +}); + describe("alert tick delivery state", () => { test("all-error delivery stays pending and a later successful tick marks it delivered once", async () => { const { store, calls } = alertTickStore();