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
69 changes: 36 additions & 33 deletions pm-stack/aggregator/scripts/collect-fleet-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ import {
isAaSection,
type AaRawPayload,
} from "../src/aa.ts";
import { AA_BATCH_INDEX_SQL, AA_PAYLOAD_SQL_REVISION, AA_PRICES_SQL, aaPayloadSql } from "../src/aa-batch-sql.ts";
import { AA_BATCH_INDEX_SQL, AA_PAYLOAD_SQL_REVISION, AA_PRICES_SQL, aaPayloadSql, aaNumericInputsSql, assertAaNumericInputs, aaSectionQueries, aaRankingValuesSql, rankAaValues } from "../src/aa-turso-sql.ts";
import {
aaBatchFingerprint,
aaCacheFileName,
Expand Down Expand Up @@ -168,7 +168,7 @@ import { staleIssueSearchQuery, type RepoCensus } from "../src/coverage.ts";
import { loadLaunchRecords, recordFromSessionEntry } from "../src/registry.ts";
import { defaultHiddenDir, defaultQuotaViewPath, defaultUsageOutboxPath } from "../src/default-paths.ts";
import { mapServerSessions, poolBurn } from "../src/sources/opencode.ts";
import { resolveSupabaseProjectRef } from "../src/supabase.ts";
import { getTursoStoreClient } from "../src/turso-stores.ts";
import { AaLastGoodStore } from "../src/aa-last-good.ts";
import { createSupabaseDocumentRemote } from "../src/remote-stores.ts";
import { parseStoreBackend } from "../src/store-backend.ts";
Expand Down Expand Up @@ -470,7 +470,7 @@ const aaLastGoodPath = join(dirname(outPath), "aa-last-good.json");
* then neither read nor written. */
const aaLastGoodStore = new AaLastGoodStore(
aaLastGoodPath,
parseStoreBackend() === "supabase" ? createSupabaseDocumentRemote() : undefined,
parseStoreBackend() === "turso" ? createSupabaseDocumentRemote(getTursoStoreClient) : parseStoreBackend() === "supabase" ? createSupabaseDocumentRemote() : undefined,
);
// #1116: last-good attention entries, carried across runs whose server
// read fails (restart churn) so one bad read cannot zero the feed.
Expand Down Expand Up @@ -554,15 +554,10 @@ async function opencodeConfigFingerprint(): Promise<string> {
}
}

async function supabaseQuery(token: string, ref: string, sql: string): Promise<unknown> {
const res = await fetch(`https://api.supabase.com/v1/projects/${ref}/database/query`, {
method: "POST",
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: JSON.stringify({ query: sql }),
signal: AbortSignal.timeout(60_000),
});
if (!res.ok) throw new Error(`Supabase query failed (HTTP ${res.status})`);
return res.json();
async function storeQuery(sql: string): Promise<unknown> {
const client = await getTursoStoreClient();
if (!client) throw new Error("Turso store credential unavailable");
return client.query(sql);
}

function aaRawFromRows(rows: unknown): AaRawPayload | null {
Expand All @@ -571,10 +566,26 @@ function aaRawFromRows(rows: unknown): AaRawPayload | null {
}

/** Fetch one batch payload (a uuid; null is the latest fallback). */
async function fetchAaPayload(token: string, ref: string, batch: string | null): Promise<AaRawPayload> {
const raw = aaRawFromRows(await supabaseQuery(token, ref, aaPayloadSql(batch)));
if (!raw) throw new Error("Supabase returned no AA payload");
return raw;
async function fetchAaPayload(batch: string | null): Promise<AaRawPayload> {
// Pin one batch before independent section reads so an import during the
// request cannot mix different workbook versions into one cache entry.
if (batch === null) {
const latest = await storeQuery("select import_batch from ainventory_sources where kind='drive-workbook' order by imported_at desc limit 1") as {import_batch: string}[];
if (!latest[0]?.import_batch) throw new Error("Turso returned no AA workbook batch");
batch = latest[0].import_batch;
}
assertAaNumericInputs(await storeQuery(aaNumericInputsSql(batch)) as {cell: unknown}[]);
const payload: Record<string,unknown> = {};
for (const [key, sql] of Object.entries(aaSectionQueries(batch))) {
if (key === "rankings") {
payload[key] = rankAaValues(await storeQuery(aaRankingValuesSql(batch)) as Record<string,unknown>[]);
} else {
const rows = await storeQuery(sql) as {section: unknown}[];
if (rows.length !== 1) throw new Error(`Turso returned no AA ${key} section`);
payload[key] = key === "batch" ? rows[0].section : JSON.parse(rows[0].section as string);
}
}
return payload as unknown as AaRawPayload;
}

/**
Expand Down Expand Up @@ -628,20 +639,16 @@ async function collectAaSection(generatedAt: string): Promise<AaFeedSection> {
return section;
};

const token = await resolveBwsSecret("supabase.muse-dev2.access-token-muse-cli");
if (!token) return degrade("no Supabase management token available (bws)");
const ref = await resolveSupabaseProjectRef(resolveBwsSecret);
if (!ref) return degrade("no Supabase project ref available (bws)");

// The workbook index is the complete sources register; ingest_batches is
// optional metadata and a missing join row does not hide a batch.
let index: AaBatchIndexRow[];
try {
const rows = (await supabaseQuery(token, ref, AA_BATCH_INDEX_SQL)) as { batches?: unknown }[];
const rows = (await storeQuery(AA_BATCH_INDEX_SQL)) as { batches?: unknown }[];
index = parseBatchIndex(Array.isArray(rows) ? rows[0]?.batches : null);
} catch (err) {
const msg = err instanceof Error ? err.message : "error";
return degrade(msg.startsWith("Supabase query failed") ? msg : `Supabase unreachable (${msg})`);
return degrade(msg.startsWith("Turso") ? msg : `Turso unreachable (${msg})`);
}
if (index.length === 0) return degrade("no workbook batches in ainventory.sources");

Expand All @@ -652,11 +659,11 @@ async function collectAaSection(generatedAt: string): Promise<AaFeedSection> {
// page presents these prices as current.
let currentPricesFingerprint: string;
try {
const rows = (await supabaseQuery(token, ref, AA_PRICES_SQL)) as { prices?: unknown }[];
const rows = (await storeQuery(AA_PRICES_SQL)) as { prices?: unknown }[];
currentPricesFingerprint = aaPricesFingerprint(Array.isArray(rows) ? rows[0]?.prices : null);
} catch (err) {
const msg = err instanceof Error ? err.message : "error";
return degrade(msg.startsWith("Supabase query failed") ? msg : `Supabase unreachable (${msg})`);
return degrade(msg.startsWith("Turso") ? msg : `Turso unreachable (${msg})`);
}

// Read every batch cache once; a changed config, a changed
Expand Down Expand Up @@ -704,11 +711,11 @@ async function collectAaSection(generatedAt: string): Promise<AaFeedSection> {
cacheMeta.set(latestBatch, { fingerprint: lastGood.fingerprint, cached });
} else if (latestBatch) {
try {
latestSection = await assemble(await fetchAaPayload(token, ref, latestBatch));
if (!latestSection) return degrade("Supabase payload failed its structural check");
latestSection = await assemble(await fetchAaPayload(latestBatch));
if (!latestSection) return degrade("Turso payload failed its structural check");
} catch (err) {
const msg = err instanceof Error ? err.message : "error";
return degrade(msg.startsWith("Supabase query failed") ? msg : `Supabase unreachable (${msg})`);
return degrade(msg.startsWith("Turso") ? msg : `Turso unreachable (${msg})`);
}
}
if (!latestSection) return degrade("no AA payload for the latest workbook batch");
Expand All @@ -732,7 +739,7 @@ async function collectAaSection(generatedAt: string): Promise<AaFeedSection> {
if (cacheMeta.get(row.importBatch)?.cached) continue;
attempts++;
try {
await assemble(await fetchAaPayload(token, ref, row.importBatch));
await assemble(await fetchAaPayload(row.importBatch));
} catch (err) {
console.error(`collector: AA historical batch build failed (${err instanceof Error ? err.message : "error"})`);
}
Expand Down Expand Up @@ -1033,11 +1040,7 @@ async function main(): Promise<void> {
const resolution = await resolveOrchestrationDocument({
source: orchestrationSourceFromEnv(process.env),
readDb: async () => {
const token = await resolveBwsSecret("supabase.muse-dev2.access-token-muse-cli");
if (!token) throw new Error("no Supabase management token available (bws)");
const ref = await resolveSupabaseProjectRef(resolveBwsSecret);
if (!ref) throw new Error("no Supabase project ref available (bws)");
const row = orchestrationDocumentFromRows(await supabaseQuery(token, ref, LATEST_ORCH_RUN_SQL));
const row = orchestrationDocumentFromRows(await storeQuery(LATEST_ORCH_RUN_SQL));
if (!row) throw new Error("orch_runs returned no usable latest row");
return row.document;
},
Expand Down
42 changes: 42 additions & 0 deletions pm-stack/aggregator/scripts/export-turso-stores.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env bun
// Usage: export-turso-stores.ts --output-dir DIRECTORY
// Strict arguments before I/O. Exports only the fixed canonical PM stores.
// Each table is keyset-paginated independently: this is NOT an atomic
// cross-table point-in-time snapshot; concurrent writes can appear at different
// cutoffs. Quiesce writers when a transaction-consistent restore set is needed.
// Output includes private subscription data; keep it inside the private backup.
const args = process.argv.slice(2);
if (args.length !== 2 || args[0] !== "--output-dir" || !args[1] || args[1].startsWith("-")) {
console.error("Usage: export-turso-stores.ts --output-dir DIRECTORY");
process.exit(2);
}
const { mkdir, writeFile, rename } = await import("node:fs/promises");
const { join } = await import("node:path");
const { getTursoStoreClient } = await import("../src/turso-stores.ts");
const db = await getTursoStoreClient();
if (!db) throw new Error("Turso store credential unavailable");
const tables = {
agg_actions: "id", agg_activity_ingestion: "source", agg_activity_gaps: "id",
agg_usage_snapshots: "snapshot_key", agg_store_documents: "store",
alerts_incidents: "id", alerts_incident_events: "id", alerts_push_subscriptions: "id",
alerts_notification_sends: "id", orch_runs: "run_id",
};
await mkdir(args[1], { recursive: true, mode: 0o700 });
for (const [table, key] of Object.entries(tables)) {
const rows: Record<string, unknown>[] = [];
let cursor: unknown = null;
for (;;) {
const value = typeof cursor === "number" ? String(cursor) : `'${String(cursor).replaceAll("'", "''")}'`;
const batch = await db.query<Record<string, unknown>>(`select * from ${table} ${cursor === null ? "" : `where ${key} > ${value}`} order by ${key} limit 500`);
rows.push(...batch);
if (batch.length < 500) break;
const next = batch.at(-1)![key];
if (next === null || next === undefined || next === cursor) throw new Error("nonadvancing export cursor");
cursor = next;
}
const dest = join(args[1], `${table}.json`);
const temp = `${dest}.tmp-${process.pid}`;
await writeFile(temp, JSON.stringify(rows), {mode:0o600, flag:"wx"});
await rename(temp, dest);
console.log(`${table}=${rows.length}`);
}
Loading