Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 26 additions & 7 deletions pm-stack/aggregator/src/alerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -614,16 +614,35 @@ export async function sendTestPush(
return summary;
}

let storePromise: Promise<AlertsStore | null> | null = null;

/** The shared store; null when the Supabase path is unavailable. */
export function getAlertsStore(): Promise<AlertsStore | null> {
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<AlertsStore | null> {
let storePromise: Promise<AlertsStore | null> | null = null;

return function getAlertsStore(): Promise<AlertsStore | null> {
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 {
Expand Down
55 changes: 32 additions & 23 deletions pm-stack/aggregator/src/supabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,30 +40,39 @@ async function supabaseQuery(token: string, ref: string, sql: string): Promise<u
return res.json();
}

let clientPromise: Promise<SupabaseClient | null> | 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<SupabaseClient | null> {
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<T = Record<string, unknown>>(sql: string): Promise<T[]> {
const out = await supabaseQuery(token, ref, sql);
return (Array.isArray(out) ? out : []) as T[];
},
};
})().catch(() => null);
export function createSupabaseClientGetter(
resolveSecret: typeof resolveBwsSecret = resolveBwsSecret,
): () => Promise<SupabaseClient | null> {
let clientPromise: Promise<SupabaseClient | null> | null = null;

return function getSupabaseClient(): Promise<SupabaseClient | null> {
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<T = Record<string, unknown>>(sql: string): Promise<T[]> {
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();
42 changes: 42 additions & 0 deletions pm-stack/aggregator/test/alerts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
buildIncidentPayload,
buildTestPayload,
classEnabled,
createAlertsStoreGetter,
duplicateWouldRepeatDelivery,
incidentObjectRef,
incidentUrl,
Expand All @@ -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<SupabaseClient | null>((resolve) => {
resolveFirst = resolve;
});
let resolveRetry!: (value: SupabaseClient | null) => void;
const retryResult = new Promise<SupabaseClient | null>((resolve) => {
resolveRetry = resolve;
});
const fakeClient: SupabaseClient = {
ref: "test-project",
async query<T>() {
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'");
Expand Down
44 changes: 44 additions & 0 deletions pm-stack/aggregator/test/supabase-export.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<string | null>((resolve) => {
resolveFirst = resolve;
});
let resolveRetry!: (value: string | null) => void;
const retryResult = new Promise<string | null>((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> = {}): SupabaseExportDoc {
return {
service: "supabase",
Expand Down