diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index b0a1bcd3e8..df5d7b72b9 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -614,16 +614,35 @@ export async function sendTestPush( return summary; } -let storePromise: Promise | null = null; - -/** The shared store; null when the Supabase path is unavailable. */ -export function getAlertsStore(): Promise { - if (!storePromise) { - storePromise = getSupabaseClient().then((db) => (db ? new AlertsStore(db) : null)); +/** + * Create the shared store resolver. Keep the in-flight attempt and successful + * store cached, but clear null/rejected attempts so a later call can recover. + */ +export function createAlertsStoreGetter( + getClient: typeof getSupabaseClient = getSupabaseClient, +): () => Promise { + let storePromise: Promise | null = null; + + return function getAlertsStore(): Promise { + if (!storePromise) { + const pending = getClient().then((db) => (db ? new AlertsStore(db) : null)); + storePromise = pending; + void pending.then( + (store) => { + if (store === null && storePromise === pending) storePromise = null; + }, + () => { + if (storePromise === pending) storePromise = null; + }, + ); + } + return storePromise; } - return storePromise; } +/** The shared store; null when the Supabase path is unavailable. */ +export const getAlertsStore = createAlertsStoreGetter(); + // --- The engine --------------------------------------------------------------- interface DeliverySummary { diff --git a/pm-stack/aggregator/src/supabase.ts b/pm-stack/aggregator/src/supabase.ts index d7171907cf..f42e0edb72 100644 --- a/pm-stack/aggregator/src/supabase.ts +++ b/pm-stack/aggregator/src/supabase.ts @@ -40,30 +40,39 @@ async function supabaseQuery(token: string, ref: string, sql: string): Promise | null = null; - /** - * The shared muse-dev2 client, resolved once. Null when no management - * token is reachable (callers fail soft — the alerts surface reports - * itself unavailable instead of taking the dashboard down). + * Create the shared muse-dev2 client resolver. In-flight calls share one + * attempt and successful clients stay cached; a null result is fail-soft + * but not permanent, so a later call can recover. */ -export function getSupabaseClient(): Promise { - if (!clientPromise) { - clientPromise = (async () => { - const token = await resolveBwsSecret("supabase.muse-dev2.access-token-muse-cli"); - if (!token) return null; - const ref = - process.env.SUPABASE_PROJECT_REF ?? - (await resolveBwsSecret("supabase.muse-dev2.project-ref")) ?? - "keihfchslgjetkmnmzra"; - return { - ref, - async query>(sql: string): Promise { - const out = await supabaseQuery(token, ref, sql); - return (Array.isArray(out) ? out : []) as T[]; - }, - }; - })().catch(() => null); +export function createSupabaseClientGetter( + resolveSecret: typeof resolveBwsSecret = resolveBwsSecret, +): () => Promise { + let clientPromise: Promise | null = null; + + return function getSupabaseClient(): Promise { + if (!clientPromise) { + const pending = (async () => { + const token = await resolveSecret("supabase.muse-dev2.access-token-muse-cli"); + if (!token) return null; + const ref = + process.env.SUPABASE_PROJECT_REF ?? (await resolveSecret("supabase.muse-dev2.project-ref")) ?? "keihfchslgjetkmnmzra"; + return { + ref, + async query>(sql: string): Promise { + const out = await supabaseQuery(token, ref, sql); + return (Array.isArray(out) ? out : []) as T[]; + }, + }; + })().catch(() => null); + clientPromise = pending; + void pending.then((client) => { + if (client === null && clientPromise === pending) clientPromise = null; + }); + } + return clientPromise; } - return clientPromise; } + +/** The shared muse-dev2 client, fail-soft while its management token is unavailable. */ +export const getSupabaseClient = createSupabaseClientGetter(); diff --git a/pm-stack/aggregator/test/alerts.test.ts b/pm-stack/aggregator/test/alerts.test.ts index 19bcb83253..53a3ccb8a3 100644 --- a/pm-stack/aggregator/test/alerts.test.ts +++ b/pm-stack/aggregator/test/alerts.test.ts @@ -9,6 +9,7 @@ import { buildIncidentPayload, buildTestPayload, classEnabled, + createAlertsStoreGetter, duplicateWouldRepeatDelivery, incidentObjectRef, incidentUrl, @@ -32,6 +33,47 @@ import type { Provenance } from "../src/model.ts"; import { sqlInt, sqlJson, sqlStr, type SupabaseClient } from "../src/supabase.ts"; import type { Config } from "../src/config.ts"; +describe("getAlertsStore retry-after-null memoization", () => { + test("retries a null client, shares the next in-flight attempt, and caches success", async () => { + let clientCalls = 0; + let resolveFirst!: (value: SupabaseClient | null) => void; + const firstResult = new Promise((resolve) => { + resolveFirst = resolve; + }); + let resolveRetry!: (value: SupabaseClient | null) => void; + const retryResult = new Promise((resolve) => { + resolveRetry = resolve; + }); + const fakeClient: SupabaseClient = { + ref: "test-project", + async query() { + return [] as T[]; + }, + }; + const getStore = createAlertsStoreGetter(async () => { + clientCalls += 1; + return clientCalls === 1 ? firstResult : retryResult; + }); + + const initial = getStore(); + const concurrentInitial = getStore(); + expect(clientCalls).toBe(1); + resolveFirst(null); + expect(await Promise.all([initial, concurrentInitial])).toEqual([null, null]); + + const first = getStore(); + const second = getStore(); + expect(clientCalls).toBe(2); + resolveRetry(fakeClient); + + const [store, concurrentStore] = await Promise.all([first, second]); + expect(store).not.toBeNull(); + expect(store).toBe(concurrentStore); + expect(await getStore()).toBe(store); + expect(clientCalls).toBe(2); + }); +}); + describe("sql literals", () => { test("single quotes double", () => { expect(sqlStr("o'brien")).toBe("'o''brien'"); diff --git a/pm-stack/aggregator/test/supabase-export.test.ts b/pm-stack/aggregator/test/supabase-export.test.ts index e9ce6ff64a..79ea0c327f 100644 --- a/pm-stack/aggregator/test/supabase-export.test.ts +++ b/pm-stack/aggregator/test/supabase-export.test.ts @@ -10,6 +10,7 @@ import { loadConfig } from "../src/config.ts"; import { applySupabaseExport, extractSaasServices, type SupabaseExportDoc } from "../src/saas-extract.ts"; import { SnapshotStore } from "../src/snapshots.ts"; import { liveSource } from "../src/sources/live.ts"; +import { createSupabaseClientGetter } from "../src/supabase.ts"; const VIEW = ` ## Summary (b) — subscriptions, infrastructure, account tooling @@ -28,6 +29,49 @@ const VIEW = ` const NOW = Date.parse("2026-10-29T15:00:00Z"); +describe("getSupabaseClient retry-after-null memoization", () => { + test("retries null, shares the next in-flight attempt, and caches success", async () => { + const previousProjectRef = process.env.SUPABASE_PROJECT_REF; + process.env.SUPABASE_PROJECT_REF = "test-project"; + let secretCalls = 0; + let resolveFirst!: (value: string | null) => void; + const firstResult = new Promise((resolve) => { + resolveFirst = resolve; + }); + let resolveRetry!: (value: string | null) => void; + const retryResult = new Promise((resolve) => { + resolveRetry = resolve; + }); + const getClient = createSupabaseClientGetter(async () => { + secretCalls += 1; + return secretCalls === 1 ? firstResult : retryResult; + }); + + try { + const initial = getClient(); + const concurrentInitial = getClient(); + expect(secretCalls).toBe(1); + resolveFirst(null); + expect(await Promise.all([initial, concurrentInitial])).toEqual([null, null]); + + const first = getClient(); + const second = getClient(); + expect(secretCalls).toBe(2); + resolveRetry("test-token"); + + const [client, concurrentClient] = await Promise.all([first, second]); + expect(client).not.toBeNull(); + expect(client).toBe(concurrentClient); + expect(client?.ref).toBe("test-project"); + expect(await getClient()).toBe(client); + expect(secretCalls).toBe(2); + } finally { + if (previousProjectRef === undefined) delete process.env.SUPABASE_PROJECT_REF; + else process.env.SUPABASE_PROJECT_REF = previousProjectRef; + } + }); +}); + function freshDoc(overrides: Partial = {}): SupabaseExportDoc { return { service: "supabase",