From 8e27a610d270b997227b4cda9de3f7aac15c44fb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 10:46:05 -0500 Subject: [PATCH 1/3] feat(usage-hub): Supabase usage collector as gatherer file-export (#1050) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Supabase half of the #1151 file-export family, in the #1048 Cloudflare adapter shape: a laptop tick probes the Management API for muse-dev and the aggregator prefers a fresh document over quota-view prose. Scope probe with the existing supabase.* management token (recorded endpoint-by-endpoint in every document's .scope array): projects, project, database/query, analytics usage.api-counts and usage.api-requests-count, billing/addons, storage/buckets and health all answer 200/201; the org-scoped reads answer 403 (token is project-scoped) and the GB usage endpoints (usage, database/size, usage.egress, usage.unified-egress) do not exist — so egress bytes are a documented gap, with request counts as context, not an invented zero. Measured on the first live probe: muse-dev database 1.154 GB against the Free 500 MB limit — 230.8%, so db-size carries approaching-paid-trigger. Storage is 0 GB (no buckets); billed $0 comes from a measured addons read, not the hardcoded constant. Aggregator: applySupabaseExport prefers used/limit/measured-at/source from a document younger than 30 minutes and takes the measured billed state; a missing, failed, unparseable or stale document reproduces today's card exactly. Tests cover both paths plus the fail-closed failure documents. Closes #1050 --- pm-stack/aggregator/src/config.ts | 7 + pm-stack/aggregator/src/saas-extract.ts | 96 +++++ pm-stack/aggregator/src/sources/live.ts | 8 +- .../aggregator/test/supabase-export.test.ts | 105 +++++ pm-stack/supabase-export/README.md | 93 +++++ pm-stack/supabase-export/install-laptop.sh | 22 + .../supabase-export/supabase-quota-export.mjs | 388 ++++++++++++++++++ .../supabase-quota-export.service | 8 + .../supabase-quota-export.test.mjs | 128 ++++++ .../supabase-quota-export.timer | 11 + 10 files changed, 864 insertions(+), 2 deletions(-) create mode 100644 pm-stack/aggregator/test/supabase-export.test.ts create mode 100644 pm-stack/supabase-export/README.md create mode 100755 pm-stack/supabase-export/install-laptop.sh create mode 100755 pm-stack/supabase-export/supabase-quota-export.mjs create mode 100644 pm-stack/supabase-export/supabase-quota-export.service create mode 100644 pm-stack/supabase-export/supabase-quota-export.test.mjs create mode 100644 pm-stack/supabase-export/supabase-quota-export.timer diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index d2e5c28058..d6310e3909 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -24,6 +24,9 @@ export interface Config { /** The stewardship quota view; the hub's live fallback source when the * fleet feed carries no saas/payg sections yet (hub §2.3). */ quotaViewFile: string; + /** The Supabase usage exporter's document (#1050): the gathered live read + * preferred over the quota view's Supabase prose when fresh. */ + supabaseExportFile: string; /** The provider quota registry; the hub's second dated-read source * (billing incidents) for the same fallback path. */ quotaRegistryFile: string; @@ -78,6 +81,10 @@ export function loadConfig(env: Record = process.env "workspace/goals/stewardship-commission-recurring-review-and-dispatch/hidden_files/visibility/quota-view.md", ), ), + supabaseExportFile: s( + env.PM_AGG_SUPABASE_EXPORT, + join(homedir(), "atlas/supabase-export/latest.json"), + ), quotaRegistryFile: s( env.PM_AGG_QUOTA_REGISTRY, join(homedir(), "workspace/goals/keep-the-four-repos-healthy/hidden_files/provider-quota-registry.md"), diff --git a/pm-stack/aggregator/src/saas-extract.ts b/pm-stack/aggregator/src/saas-extract.ts index 22b0829906..8250a158fc 100644 --- a/pm-stack/aggregator/src/saas-extract.ts +++ b/pm-stack/aggregator/src/saas-extract.ts @@ -654,6 +654,102 @@ export function extractSaasServices(doc: string): SaasService[] { return services; } +// --- Supabase live export overlay (#1050) ----------------------------------- + +/** One metric row of a supabase-quota-export document. */ +export interface SupabaseExportMetric { + id: string; + label?: string; + /** null = the probe could not measure it this tick (a documented gap). */ + used: number | null; + limit?: number | null; + unit?: string; + source?: string; + detail?: string; + /** "approaching-paid-trigger" when used >= 80% of the Free limit. */ + flag?: string; +} + +/** The file-export document written by pm-stack/supabase-export. */ +export interface SupabaseExportDoc { + service?: string; + source?: string; + /** ok | partial (some scope gaps recorded) — measurements are present. */ + status?: string; + measuredAt?: string | null; + project?: string; + ref?: string; + metrics?: SupabaseExportMetric[]; + billing?: { plan?: string; billedUsd?: number; measured?: boolean; source?: string }; + scope?: { endpoint?: string; path?: string; status?: number; note?: string }[]; +} + +/** Freshness bound mirroring the #1151 tick: > 30 min means the producer is + * unreachable/stale and the card falls back to its recorded prose. */ +export const SUPABASE_EXPORT_STALE_MS = 30 * 60 * 1000; + +/** + * Prefer a fresh supabase-export document on the Supabase card (#1050). + * Matching metric ids take `used`, `limit`, `unit` and a measured-at/source + * note from the export; a metric the probe could not measure keeps today's + * null-but-recorded behaviour with the export's gap detail. `billedUsd` + * becomes the export's measured addon read instead of the hardcoded 0. + * Missing, failed, unparseable or stale documents change nothing. + */ +export function applySupabaseExport( + services: SaasService[], + doc: SupabaseExportDoc | null, + nowMs: number = Date.now(), +): SaasService[] { + if (!doc || (doc.status !== "ok" && doc.status !== "partial")) return services; + if (!doc.measuredAt || !Array.isArray(doc.metrics)) return services; + const measuredMs = Date.parse(doc.measuredAt); + if (!Number.isFinite(measuredMs)) return services; + if (nowMs - measuredMs > SUPABASE_EXPORT_STALE_MS || measuredMs > nowMs + 5 * 60 * 1000) return services; + const supabase = services.find((s) => s.id === "supabase"); + if (!supabase) return services; + const byId = new Map( + doc.metrics.filter((m) => m && typeof m.id === "string").map((m) => [m.id, m]), + ); + if (!byId.size) return services; + supabase.metrics = supabase.metrics.map((m) => { + const live = byId.get(m.id); + if (!live) return m; + const unit = live.unit === "gb" || live.unit === "pct" || live.unit === "count" ? live.unit : m.unit; + const used = typeof live.used === "number" && Number.isFinite(live.used) ? live.used : null; + const limit = typeof live.limit === "number" && Number.isFinite(live.limit) ? live.limit : m.limit; + const parts: string[] = []; + if (used == null) { + parts.push(`Not measured this tick${live.detail ? ` — ${live.detail}` : ""}`); + } else { + parts.push(`Live via ${live.source ?? doc.source ?? "file-export/supabase"}, measured ${doc.measuredAt}.`); + if (live.detail) parts.push(live.detail); + if (live.flag === "approaching-paid-trigger") { + parts.push("Approaching-paid trigger: at or above 80% of the Free-plan limit (Drew's $30/mo ceiling is the decision context)."); + } + } + return { + ...m, + used, + limit, + unit, + percent: used != null && limit != null && limit > 0 ? Math.round((used / limit) * 1000) / 10 : undefined, + note: parts.join(" ").slice(0, 600), + }; + }); + if (doc.billing && typeof doc.billing.billedUsd === "number" && Number.isFinite(doc.billing.billedUsd)) { + supabase.billedUsd = doc.billing.billedUsd; + } + supabase.plan = doc.billing?.plan ? `Free plan (${doc.project ?? "supabase"}); measured ${doc.measuredAt}` : supabase.plan; + supabase.measuredAt = doc.measuredAt.slice(0, 10); + supabase.sourceClass = "api"; + const gapCount = (doc.scope ?? []).filter((s) => typeof s.status === "number" && s.status >= 400).length; + supabase.sourceNote = `Supabase usage collector (#1050): ${doc.source ?? "file-export/supabase"}, measured ${doc.measuredAt}; ${ + gapCount ? `${gapCount} documented scope gap(s) — see the export's scope array` : "every probed endpoint answered" + }; limits from the Free-plan record.`; + return services; +} + // --- PAYG lines (§1.2) ------------------------------------------------------- /** diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index ae9bbd44db..c6d3f915dd 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -20,7 +20,8 @@ import { import { isSessionRecord, mergeRecords, recordFromSessionEntry } from "../registry.ts"; import { buildAttentionFlags } from "../derive.ts"; import { summarizeDns } from "../dns.ts"; -import { extractCharges, extractPaygLines, extractSaasServices, extractSubscriptions } from "../saas-extract.ts"; +import { applySupabaseExport, extractCharges, extractPaygLines, extractSaasServices, extractSubscriptions } from "../saas-extract.ts"; +import type { SupabaseExportDoc } from "../saas-extract.ts"; import { isProjectPoolItem, poolItemToGhItem } from "../projects.ts"; import { INITIAL_STANDING_AUTO, sanitizeTierItemExtensions, withUserFallbacks } from "../tier-items.ts"; import { overlayQuotaCurrent, parseQuotaCurrent } from "../quota-current.ts"; @@ -839,8 +840,11 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise ""), ]); + const supabaseExport = await readFile(cfg.supabaseExportFile, "utf8") + .then((text) => JSON.parse(text) as SupabaseExportDoc) + .catch(() => null); const partial = { - services: extractSaasServices(doc), + services: applySupabaseExport(extractSaasServices(doc), supabaseExport), payg: extractPaygLines(doc, registryText), charges: extractCharges(doc, registryText), subscriptions: extractSubscriptions(doc), diff --git a/pm-stack/aggregator/test/supabase-export.test.ts b/pm-stack/aggregator/test/supabase-export.test.ts new file mode 100644 index 0000000000..70f6815086 --- /dev/null +++ b/pm-stack/aggregator/test/supabase-export.test.ts @@ -0,0 +1,105 @@ +// Supabase live-export overlay (#1050 / queue task 2985): a fresh +// supabase-export document puts measured used/limit + the measured +// billed state on the Supabase card; a missing, failed or stale +// document reproduces the recorded prose exactly. +import { describe, expect, test } from "bun:test"; +import { applySupabaseExport, extractSaasServices, type SupabaseExportDoc } from "../src/saas-extract.ts"; + +const VIEW = ` +## Summary (b) — subscriptions, infrastructure, account tooling + +| Service | Plan / price | Allowance sketch | Usage / status | Next date recorded | +|---|---|---|---|---| +| Supabase | Free plan (muse-dev) | DB + egress + storage | manual dashboard read needed | unknown | + +## Service details (b) + +### Supabase +- **Plan / price:** Free plan (muse-dev); numerical quotas unknown in local records. +- **Usage / dates:** Not measured — manual dashboard read needed. +- **Last checked:** 2026-10-28. +`; + +const NOW = Date.parse("2026-10-29T15:00:00Z"); + +function freshDoc(overrides: Partial = {}): SupabaseExportDoc { + return { + service: "supabase", + source: "file-export/supabase", + status: "partial", + measuredAt: "2026-10-29T14:55:00Z", + project: "muse-dev", + ref: "nltgxorqwxhgfzseiirt", + metrics: [ + { id: "db-size", label: "Database size", used: 1.154, limit: 0.5, unit: "gb", source: "management-api:/database/query pg_database_size", flag: "approaching-paid-trigger" }, + { id: "egress", label: "Egress (cycle)", used: null, limit: 5, unit: "gb", source: "none", detail: "No Management API endpoint reports egress bytes." }, + { id: "storage", label: "File storage", used: 0, limit: 1, unit: "gb", source: "management-api:/storage/buckets", detail: "0 buckets on the project" }, + ], + billing: { plan: "free", billedUsd: 0, measured: true, source: "management-api:/billing/addons" }, + scope: [ + { endpoint: "projects", status: 200 }, + { endpoint: "organizations/:slug", status: 403, note: "scope gap" }, + { endpoint: "usage.egress", status: 404 }, + ], + ...overrides, + }; +} + +const supabaseCard = (services: ReturnType) => services.find((s) => s.id === "supabase")!; +const metricOf = (services: ReturnType, id: string) => + supabaseCard(services).metrics.find((m) => m.id === id)!; + +describe("applySupabaseExport", () => { + test("a fresh export supplies measured used + Free limits for db-size and storage", () => { + const out = applySupabaseExport(extractSaasServices(VIEW), freshDoc(), NOW); + const db = metricOf(out, "db-size"); + expect(db.used).toBe(1.154); + expect(db.limit).toBe(0.5); + expect(db.unit).toBe("gb"); + expect(db.percent).toBe(230.8); + expect(db.note).toContain("measured 2026-10-29T14:55:00Z"); + expect(db.note).toContain("Approaching-paid trigger"); + const storage = metricOf(out, "storage"); + expect(storage.used).toBe(0); + expect(storage.limit).toBe(1); + expect(supabaseCard(out).sourceClass).toBe("api"); + expect(supabaseCard(out).measuredAt).toBe("2026-10-29"); + }); + + test("egress keeps a recorded limit but stays unmeasured, with the gap detail", () => { + const out = applySupabaseExport(extractSaasServices(VIEW), freshDoc(), NOW); + const egress = metricOf(out, "egress"); + expect(egress.used).toBeNull(); + expect(egress.limit).toBe(5); + expect(egress.percent).toBeUndefined(); + expect(egress.note).toContain("Not measured this tick"); + expect(egress.note).toContain("egress bytes"); + }); + + test("billed is the export's measured addon read, not the hardcoded 0", () => { + const out = applySupabaseExport(extractSaasServices(VIEW), freshDoc({ billing: { plan: "free", billedUsd: 25, measured: true } }), NOW); + expect(supabaseCard(out).billedUsd).toBe(25); + expect(supabaseCard(out).plan).toContain("measured 2026-10-29T14:55:00Z"); + }); + + test("a stale export falls back to exactly today's card", () => { + const base = extractSaasServices(VIEW); + const out = applySupabaseExport(base, freshDoc({ measuredAt: "2026-10-29T12:00:00Z" }), NOW); + expect(out).toEqual(base); + expect(supabaseCard(out).billedUsd).toBe(0); // today's constant + expect(metricOf(out, "db-size").used).toBeNull(); + }); + + test("missing, failed and unparseable documents change nothing", () => { + const base = extractSaasServices(VIEW); + expect(applySupabaseExport(base, null, NOW)).toEqual(base); + expect(applySupabaseExport(base, freshDoc({ status: "fetch-failed", metrics: undefined }), NOW)).toEqual(base); + expect(applySupabaseExport(base, freshDoc({ measuredAt: "not-a-date" }), NOW)).toEqual(base); + expect(applySupabaseExport(base, freshDoc({ metrics: [] }), NOW)).toEqual(base); + }); + + test("a document without a Supabase card in the view is a no-op", () => { + const out = applySupabaseExport(extractSaasServices("nothing here"), freshDoc(), NOW); + expect(out.find((s) => s.id === "supabase")!.metrics).toEqual([]); + }); +}); diff --git a/pm-stack/supabase-export/README.md b/pm-stack/supabase-export/README.md new file mode 100644 index 0000000000..0300820ebc --- /dev/null +++ b/pm-stack/supabase-export/README.md @@ -0,0 +1,93 @@ +# supabase-export — Supabase usage producer (#1050) + +The Supabase half of the usage hub's file-export family (#1151 gatherer, +#1048 Cloudflare adapter shape). Runs on the laptop tick, probes the Supabase +Management API for project `muse-dev`, and writes the document the aggregator +prefers over `quota-view.md` prose on the Supabase card. + +``` +~/atlas/supabase-export/latest.json atomic latest document +~/atlas/supabase-export/history.jsonl one line per tick, success or failure +``` + +## Document + +```json +{ + "service": "supabase", + "source": "file-export/supabase", + "status": "ok | partial", + "measuredAt": "2026-10-29T15:55:00Z", + "project": "muse-dev", + "ref": "nltgxorqwxhgfzseiirt", + "metrics": [ + { "id": "db-size", "used": 1.154, "limit": 0.5, "unit": "gb", + "source": "management-api:/database/query pg_database_size", + "flag": "approaching-paid-trigger" } + ], + "billing": { "plan": "free", "billedUsd": 0, "measured": true, + "source": "management-api:/billing/addons (no selected paid addons)" }, + "scope": [ { "endpoint": "organizations/:slug", "status": 403, "note": "scope gap: …" } ] +} +``` + +Failure documents carry `status` + `attemptedAt` + `detail` and **no** metrics +or billing — a failed tick can never look like a reading. Statuses: `no-token` +(exit 3), `scope-denied` (4), `fetch-failed` (5), `unparseable` (6). + +`status: "partial"` means at least one probed endpoint answered >= 400; the +`.scope` array records exactly which, so the card can state the gap instead of +guessing around it. + +## Metrics and limits + +| Metric | Source | Free limit | +|---|---|---| +| `db-size` | `POST /database/query` → `pg_database_size(current_database())` | 0.5 GB | +| `egress` | **no endpoint reports bytes** — gap recorded, request counts as context | 5 GB | +| `storage` | `GET /storage/buckets` (0 buckets on muse-dev → 0 GB) | 1 GB | + +Limits are the Supabase Free-plan allowances recorded on 2026-10-29 +(supabase.com/pricing); the API measures usage, it does not publish the numbers. +Any metric at >= 80% of its Free limit carries `flag: "approaching-paid-trigger"` +— the signal for Drew's standing $30/mo spend ceiling. + +## Scope probe (2026-10-29, the existing `supabase.*` management token) + +Recorded endpoint-by-endpoint in `.scope` on every run: + +| Endpoint | Status | +|---|---| +| `GET /projects`, `GET /projects/:ref` | 200 | +| `POST /projects/:ref/database/query` | 201 | +| `GET /projects/:ref/analytics/endpoints/usage.api-counts` | 200 | +| `GET /projects/:ref/analytics/endpoints/usage.api-requests-count` | 200 | +| `GET /projects/:ref/billing/addons` | 200 (`selected_addons: []`) | +| `GET /projects/:ref/storage/buckets` | 200 | +| `GET /projects/:ref/health?services=db` | 200 | +| `GET /organizations/:slug` | **403** — token is project-scoped; org plan/billing reads need an org token (Drew's account action) | +| `GET /organizations/:slug/{billing,usage}` | 403 / 404 | +| `GET /projects/:ref/usage`, `…/database/size` | 404 — no such endpoint | +| egress bytes | no endpoint exists; only request counts | + +Creating a token or granting org consent is out of scope for the producer; the +gap is recorded, not worked around. + +## Token + +Resolved by **name** from Bitwarden Secrets Manager at runtime +(`supabase.access-token-muse-cli`, override `SUPABASE_TOKEN_SECRET_NAME`; +`SUPABASE_MANAGEMENT_TOKEN` wins if set). The value is sent only to +`api.supabase.com` and is never written to the document, a log line, a fixture, +or argv. + +## Run + +```bash +bun supabase-quota-export.mjs --out-dir ~/atlas/supabase-export +bun test # offline: the API is an injected fake fetch +``` + +Aggregator side: `saas-extract.ts` `applySupabaseExport` prefers a document +younger than 30 minutes (the #1151 tick); older or missing falls back to the +quota-view prose exactly as before. diff --git a/pm-stack/supabase-export/install-laptop.sh b/pm-stack/supabase-export/install-laptop.sh new file mode 100755 index 0000000000..c96ad078b0 --- /dev/null +++ b/pm-stack/supabase-export/install-laptop.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# install-laptop.sh — install the Supabase usage exporter on the laptop +# (developing-today/code#1050). Copies the producer beside its output +# directory and enables the 15-minute timer beside the #1151 gatherer tick. +# The management token is resolved BY NAME from Bitwarden at runtime +# (SUPABASE_TOKEN_SECRET_NAME, default supabase.access-token-muse-cli); +# this script never reads, prints, or stores its value. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +target="${SUPABASE_EXPORT_DIR:-$HOME/atlas/supabase-export}" +units="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user" + +mkdir -p "$target" "$units" +install -m 0644 "$here/supabase-quota-export.mjs" "$target/supabase-quota-export.mjs" +install -m 0644 "$here/supabase-quota-export.service" "$units/supabase-quota-export.service" +install -m 0644 "$here/supabase-quota-export.timer" "$units/supabase-quota-export.timer" + +systemctl --user daemon-reload +systemctl --user enable --now supabase-quota-export.timer +systemctl --user list-timers supabase-quota-export.timer --no-pager +echo "supabase-export: installed to $target; first tick on the next quarter hour" diff --git a/pm-stack/supabase-export/supabase-quota-export.mjs b/pm-stack/supabase-export/supabase-quota-export.mjs new file mode 100755 index 0000000000..cb58b35259 --- /dev/null +++ b/pm-stack/supabase-export/supabase-quota-export.mjs @@ -0,0 +1,388 @@ +#!/usr/bin/env node +/** + * supabase-quota-export — Supabase usage exporter (developing-today/code#1050, + * follow-up to triage task 2313). The Supabase half of the #1151 file-export + * family, in the #1048 Cloudflare adapter shape: a producer that runs on the + * laptop tick and writes the document the aggregator prefers over quota-view + * prose. + * + * Every run writes atomically to + * /latest.json (default ~/atlas/supabase-export/) + * and appends the same document to /history.jsonl. + * + * Success document (file-export format the #1151 gatherer ingests): + * { service: "supabase", source: "file-export/supabase", + * status: "ok" | "partial", + * measuredAt: , project: "muse-dev", ref: , + * metrics: [ { id: "db-size", used: 1.15, limit: 0.5, unit: "gb", + * source: "management-api:/database/query pg_database_size", + * flag?: "approaching-paid-trigger", detail? } ], + * billing: { plan: "free", billedUsd: 0, measured: true, source: ... }, + * scope: [ { endpoint, path, status, note? } ] } + * + * Failure documents carry status + attemptedAt + detail and NO metrics or + * billing values — a failed tick can never be mistaken for a reading: + * no-token the Bitwarden secret did not resolve. Exit 3. + * scope-denied GET /projects/:ref answered 401/403. Exit 4. + * fetch-failed network/other error. Exit 5. + * unparseable an endpoint answered a shape this parser does not know. + * Exit 6. + * + * The management token is resolved by NAME from Bitwarden Secrets Manager at + * runtime and sent only to api.supabase.com. Its value is never read into a + * document, log line, fixture, or argv. + * + * Scope probe (recorded endpoint-by-endpoint in the `.scope` array of every + * successful document; task #2985 re-ran it against the live token): + * GET /projects 200 (auth works) + * GET /projects/:ref 200 + * GET /projects/:ref/database/query 201 (db size SQL) + * GET /projects/:ref/analytics/endpoints/usage.api-counts 200 + * GET /projects/:ref/analytics/endpoints/usage.api-requests-count 200 + * GET /projects/:ref/billing/addons 200 (measured $0 addons) + * GET /projects/:ref/storage/buckets 200 + * GET /organizations/:slug 403 scope gap: org-scope + * GET /organizations/:slug/{billing,usage} 403/404 scope gap + * GET /projects/:ref/{usage,database/size} 404 no such endpoint + * egres bytes no endpoint exists (request counts only) — documented gap + */ +import { execFile } from "node:child_process"; +import { appendFile, mkdir, rename, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +export const SOURCE = "file-export/supabase"; +export const DEFAULT_PROJECT_REF = "nltgxorqwxhgfzseiirt"; // muse-dev (#1050) +export const DEFAULT_SECRET_NAME = "supabase.access-token-muse-cli"; +export const API_BASE = "https://api.supabase.com/v1"; + +/** Supabase Free-plan allowances (supabase.com/pricing, recorded 2026-10-29: + * 500 MB database, 1 GB file storage, 5 GB egress). There is no API read of + * the numbers themselves; the API measures usage against them. */ +export const FREE_LIMITS = { + "db-size": 0.5, + egress: 5, + storage: 1, +}; + +/** Metric ids at >= this share of their Free limit carry the paid trigger. */ +export const PAID_TRIGGER_RATIO = 0.8; + +const GB = (bytes) => Math.round((bytes / 1e9) * 1000) / 1000; + +export class ExportError extends Error { + constructor(status, exitCode, detail) { + super(detail); + this.status = status; + this.exitCode = exitCode; + } +} + +/** Non-secret shape check for the SQL row the db-size query returns. */ +export function parseDbSize(rows) { + const bytes = rows?.[0]?.bytes; + const n = typeof bytes === "string" ? Number(bytes) : bytes; + if (typeof n !== "number" || !Number.isFinite(n) || n < 0) { + throw new ExportError("unparseable", 6, "database/query: pg_database_size row missing/invalid"); + } + return n; +} + +/** Total requests from usage.api-requests-count ({ result: [{ count }] }). */ +export function parseRequestCount(payload) { + const count = payload?.result?.[0]?.count; + const n = typeof count === "string" ? Number(count) : count; + return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : null; +} + +/** Measured $0 (or more) from billing/addons: selected addons priced fixed + * monthly amounts; usage-priced addons are unknown while none are selected. */ +export function billedFromAddons(payload) { + const selected = payload?.selected_addons; + if (!Array.isArray(selected)) { + throw new ExportError("unparseable", 6, "billing/addons: selected_addons missing"); + } + let usd = 0; + for (const addon of selected) { + const amount = addon?.price?.amount; + if (typeof amount === "number" && Number.isFinite(amount)) usd += amount; + } + return Math.round(usd * 100) / 100; +} + +export function metric(id, label, used, limit, unit, source, detail) { + const m = { id, label, used, limit, unit, source }; + if (detail) m.detail = detail; + if (used != null && limit != null && limit > 0 && used / limit >= PAID_TRIGGER_RATIO) { + m.flag = "approaching-paid-trigger"; + } + return m; +} + +/** Build the three tracked metrics from whatever the API answered. Missing + * reads stay null (never zero) and carry the reason in `detail`. */ +export function buildMetrics({ dbBytes, bucketCount, requestTotal }) { + const dbUsed = dbBytes == null ? null : GB(dbBytes); + const storageUsed = bucketCount === 0 ? 0 : null; // no buckets = no stored bytes (a non-empty bucket inventory exposes no byte sizes) + return [ + metric( + "db-size", + "Database size", + dbUsed, + FREE_LIMITS["db-size"], + "gb", + "management-api:/database/query pg_database_size", + dbBytes == null ? "SQL read unavailable this tick" : `${dbBytes} bytes`, + ), + metric( + "egress", + "Egress (cycle)", + null, + FREE_LIMITS.egress, + "gb", + "none", + `No Management API endpoint reports egress bytes (usage.egress / usage.unified-egress 404); ${ + requestTotal == null ? "request count also unavailable" : `${requestTotal} API requests observed (usage.api-requests-count)` + }.`, + ), + metric( + "storage", + "File storage", + storageUsed, + FREE_LIMITS.storage, + "gb", + "management-api:/storage/buckets", + bucketCount == null + ? "storage/buckets unavailable this tick" + : bucketCount === 0 + ? "0 buckets on the project — no stored objects" + : `${bucketCount} buckets; per-bucket byte sizes are not exposed by this endpoint`, + ), + ]; +} + +/** Probe a path and return { status, json? , text? } without throwing on HTTP. */ +async function probe(fetchImpl, path) { + const res = await fetchImpl(`${API_BASE}${path}`); + let body = null; + try { + body = await res.text(); + } catch { + body = null; + } + let json = null; + try { + json = body ? JSON.parse(body) : null; + } catch { + json = null; + } + return { status: res.status, json, body }; +} + +async function api(fetchImpl, token, path, init) { + const res = await fetchImpl(`${API_BASE}${path}`, { + ...init, + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/json", + ...(init?.headers ?? {}), + }, + }); + const text = await res.text(); + return { status: res.status, text }; +} + +export async function run({ token, ref = DEFAULT_PROJECT_REF, fetchImpl = fetch } = {}) { + if (!token) throw new ExportError("no-token", 3, "Bitwarden secret did not resolve"); + const call = (path, init) => api(fetchImpl, token, path, init); + + const project = await call(`/projects/${ref}`); + if (project.status === 401 || project.status === 403) { + throw new ExportError("scope-denied", 4, `GET /projects/${ref}: HTTP ${project.status}`); + } + if (project.status !== 200) { + throw new ExportError("fetch-failed", 5, `GET /projects/${ref}: HTTP ${project.status}`); + } + let projectBody; + try { + projectBody = JSON.parse(project.text); + } catch { + throw new ExportError("unparseable", 6, "GET /projects/:ref returned non-JSON"); + } + + const scope = [ + { endpoint: "projects", path: "/projects", status: project.status }, + { endpoint: "project", path: `/projects/${ref}`, status: project.status }, + ]; + + // Database size — the one real measure of the Free 500 MB wedge. + let dbBytes = null; + const size = await call(`/projects/${ref}/database/query`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ query: "select pg_database_size(current_database()) as bytes" }), + }); + scope.push({ endpoint: "db-size SQL", path: `/projects/${ref}/database/query`, status: size.status }); + if (size.status === 200 || size.status === 201) { + try { + dbBytes = parseDbSize(JSON.parse(size.text)); + } catch (err) { + scope.push({ endpoint: "db-size SQL", path: `/projects/${ref}/database/query`, status: size.status, note: err.message }); + } + } + + // File storage — bucket inventory (a project with no buckets stores nothing). + let bucketCount = null; + const buckets = await call(`/projects/${ref}/storage/buckets`); + scope.push({ endpoint: "storage/buckets", path: `/projects/${ref}/storage/buckets`, status: buckets.status }); + if (buckets.status === 200) { + try { + const parsed = JSON.parse(buckets.text); + if (Array.isArray(parsed)) bucketCount = parsed.length; + } catch { + /* leave null — the metric says so */ + } + } + + // Egress: there is no bytes endpoint. Record the gap precisely and keep the + // request count as context, then the available usage endpoints for the record. + const requests = await probe(fetchImpl, `/projects/${ref}/analytics/endpoints/usage.api-requests-count`); + scope.push({ + endpoint: "usage.api-requests-count", + path: `/projects/${ref}/analytics/endpoints/usage.api-requests-count`, + status: requests.status, + note: "request counts only — no egress bytes", + }); + const requestTotal = requests.status === 200 ? parseRequestCount(requests.json) : null; + for (const path of [ + `/projects/${ref}/analytics/endpoints/usage.egress`, + `/projects/${ref}/analytics/endpoints/usage.unified-egress`, + `/projects/${ref}/usage`, + `/projects/${ref}/database/size`, + ]) { + const r = await probe(fetchImpl, path); + scope.push({ endpoint: path.split("/").pop(), path, status: r.status, note: r.status === 404 ? "no such endpoint" : undefined }); + } + + // Billing: addons are the only readable $ state; the org-scope plan read is + // Forbidden with this token, which is recorded, not guessed around. + let billing = null; + const addons = await call(`/projects/${ref}/billing/addons`); + scope.push({ endpoint: "billing/addons", path: `/projects/${ref}/billing/addons`, status: addons.status }); + if (addons.status === 200) { + try { + const usd = billedFromAddons(JSON.parse(addons.text)); + billing = { + plan: "free", + billedUsd: usd, + measured: true, + source: "management-api:/billing/addons (no selected paid addons)", + }; + } catch { + billing = null; + } + } + const slug = projectBody?.organization_slug; + if (slug) { + const org = await probe(fetchImpl, `/organizations/${slug}`); + scope.push({ + endpoint: "organizations/:slug", + path: `/organizations/${slug}`, + status: org.status, + note: org.status === 403 ? "scope gap: token is project-scoped; plan/billing org reads need an org token (Drew's account action)" : undefined, + }); + } + + const metrics = buildMetrics({ dbBytes, bucketCount, requestTotal }); + const measured = metrics.some((m) => m.used != null); + if (!measured) { + throw new ExportError("unparseable", 6, "no metric could be measured this tick (scope: see probe)"); + } + const gaps = scope.filter((s) => s.status >= 400); + return { + service: "supabase", + source: SOURCE, + status: gaps.length ? "partial" : "ok", + measuredAt: new Date().toISOString(), + project: projectBody?.name ?? "unknown", + ref, + metrics, + billing, + scope, + }; +} + +export function failureDocument({ attemptedAt, status, detail }) { + return { + service: "supabase", + source: SOURCE, + status, + measuredAt: null, + attemptedAt, + detail, + }; +} + +export async function writeOutputs(outDir, doc) { + await mkdir(outDir, { recursive: true }); + const tmp = join(outDir, `.latest.json.tmp-${process.pid}`); + await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); + await rename(tmp, join(outDir, "latest.json")); + await appendFile(join(outDir, "history.jsonl"), `${JSON.stringify(doc)}\n`, "utf8"); +} + +/** Resolve the management token by its Bitwarden NAME — value stays in memory. */ +export async function resolveToken({ secretName = process.env.SUPABASE_TOKEN_SECRET_NAME ?? DEFAULT_SECRET_NAME, bwsBin = process.env.BWS_BIN ?? "bws" } = {}) { + if (process.env.SUPABASE_MANAGEMENT_TOKEN) return process.env.SUPABASE_MANAGEMENT_TOKEN; + const accessToken = process.env.BWS_ACCESS_TOKEN; + const env = { ...process.env, ...(accessToken ? { BWS_ACCESS_TOKEN: accessToken } : {}) }; + const runBws = (args) => + new Promise((resolve, reject) => { + execFile(bwsBin, args, { env, maxBuffer: 16 << 20, timeout: 30_000 }, (err, stdout) => + err ? reject(new Error("bws call failed")) : resolve(stdout), + ); + }); + try { + const list = JSON.parse(await runBws(["secret", "list"])); + const entry = Array.isArray(list) ? list.find((s) => s.key === secretName) : null; + if (!entry?.id) return null; + const got = JSON.parse(await runBws(["secret", "get", entry.id])); + return typeof got?.value === "string" && got.value.trim() ? got.value.trim() : null; + } catch { + return null; // never log why: the failure detail may carry the secret's neighbourhood + } +} + +async function main() { + const args = process.argv.slice(2); + const opt = (name, fallback) => { + const i = args.indexOf(name); + return i >= 0 && args[i + 1] ? args[i + 1] : fallback; + }; + const outDir = opt("--out-dir", join(homedir(), "atlas", "supabase-export")); + const ref = opt("--project-ref", process.env.SUPABASE_PROJECT_REF ?? DEFAULT_PROJECT_REF); + try { + const token = await resolveToken(); + const doc = await run({ token, ref }); + await writeOutputs(outDir, doc); + const flags = doc.metrics.filter((m) => m.flag).map((m) => m.id); + console.log( + JSON.stringify({ status: doc.status, measuredAt: doc.measuredAt, metrics: doc.metrics.map((m) => m.id), triggers: flags, outDir }), + ); + } catch (e) { + const err = e instanceof ExportError ? e : new ExportError("fetch-failed", 5, `unexpected: ${e.message ?? String(e)}`); + const doc = failureDocument({ attemptedAt: new Date().toISOString(), status: err.status, detail: err.message }); + try { + await writeOutputs(outDir, doc); + } catch (writeErr) { + console.error(`supabase-quota-export: could not write outputs: ${writeErr.message}`); + } + console.error(`supabase-quota-export: ${err.status}: ${err.message}`); + process.exit(err.exitCode); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await main(); +} diff --git a/pm-stack/supabase-export/supabase-quota-export.service b/pm-stack/supabase-export/supabase-quota-export.service new file mode 100644 index 0000000000..b9ab0627db --- /dev/null +++ b/pm-stack/supabase-export/supabase-quota-export.service @@ -0,0 +1,8 @@ +[Unit] +Description=Supabase usage exporter — code#1050 +After=network-online.target + +[Service] +Type=oneshot +TimeoutStartSec=120 +ExecStart=%h/.bun/bin/bun %h/atlas/supabase-export/supabase-quota-export.mjs --out-dir %h/atlas/supabase-export diff --git a/pm-stack/supabase-export/supabase-quota-export.test.mjs b/pm-stack/supabase-export/supabase-quota-export.test.mjs new file mode 100644 index 0000000000..d9bacbf10e --- /dev/null +++ b/pm-stack/supabase-export/supabase-quota-export.test.mjs @@ -0,0 +1,128 @@ +// Offline tests for pm-stack/supabase-export (#1050 / queue task 2985). +// No network, no Bitwarden: the Supabase API is an injected fake fetch. +import { describe, expect, test } from "bun:test"; +import { + ExportError, + FREE_LIMITS, + PAID_TRIGGER_RATIO, + billedFromAddons, + buildMetrics, + failureDocument, + parseDbSize, + parseRequestCount, + run, +} from "./supabase-quota-export.mjs"; + +const REF = "nltgxorqwxhgfzseiirt"; + +function response(status, body) { + return { + status, + text: async () => (typeof body === "string" ? body : JSON.stringify(body)), + }; +} + +/** Fake Management API: muse-dev answers like the live probe of 2026-10-29. */ +function fakeFetch({ dbBytes = 1_153_939_123, bucketCount = 0, addonsStatus = 200 } = {}) { + const calls = []; + const impl = async (url, init) => { + calls.push({ url, method: init?.method ?? "GET" }); + const path = url.replace("https://api.supabase.com/v1", ""); + if (path === `/projects/${REF}`) { + return response(200, { + ref: REF, + name: "muse-dev", + organization_slug: "crwkmndylaagtbprrljn", + status: "ACTIVE_HEALTHY", + }); + } + if (path === `/projects/${REF}/database/query`) return response(dbBytes == null ? 500 : 201, [{ bytes: dbBytes }]); + if (path === `/projects/${REF}/storage/buckets`) return response(200, Array.from({ length: bucketCount }, (_, i) => ({ id: `b${i}` }))); + if (path === `/projects/${REF}/analytics/endpoints/usage.api-requests-count`) return response(200, { result: [{ count: 185893 }] }); + if (path === `/projects/${REF}/billing/addons`) return response(addonsStatus, { selected_addons: [], available_addons: [] }); + if (path === `/organizations/crwkmndylaagtbprrljn`) return response(403, { message: "Forbidden" }); + return response(404, { message: `Cannot GET ${path}` }); + }; + return { impl, calls }; +} + +describe("supabase-quota-export", () => { + test("measures db size against the Free limit and flags the paid trigger", async () => { + const { impl } = fakeFetch(); + const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); + expect(doc.service).toBe("supabase"); + expect(doc.source).toBe("file-export/supabase"); + const db = doc.metrics.find((m) => m.id === "db-size"); + expect(db.used).toBeCloseTo(1.154, 2); + expect(db.limit).toBe(FREE_LIMITS["db-size"]); + expect(db.used / db.limit).toBeGreaterThanOrEqual(PAID_TRIGGER_RATIO); + expect(db.flag).toBe("approaching-paid-trigger"); + expect(db.source).toContain("pg_database_size"); + }); + + test("records the egress scope gap without inventing a value", async () => { + const { impl } = fakeFetch(); + const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); + const egress = doc.metrics.find((m) => m.id === "egress"); + expect(egress.used).toBeNull(); + expect(egress.limit).toBe(FREE_LIMITS.egress); + expect(egress.detail).toContain("185893"); + expect(egress.flag).toBeUndefined(); + const egressProbe = doc.scope.find((s) => s.path.endsWith("usage.egress")); + expect(egressProbe.status).toBe(404); + const orgProbe = doc.scope.find((s) => s.endpoint === "organizations/:slug"); + expect(orgProbe.status).toBe(403); + expect(orgProbe.note).toContain("scope gap"); + }); + + test("storage is zero when the project has no buckets, and billing is a measured addon read", async () => { + const { impl } = fakeFetch({ bucketCount: 0 }); + const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); + const storage = doc.metrics.find((m) => m.id === "storage"); + expect(storage.used).toBe(0); + expect(storage.limit).toBe(FREE_LIMITS.storage); + expect(doc.billing).toMatchObject({ plan: "free", billedUsd: 0, measured: true }); + expect(doc.status).toBe("partial"); // 403/404 probes were recorded + }); + + test("an unreadable db size leaves used null rather than zero", async () => { + const { impl } = fakeFetch({ dbBytes: null }); + const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); + const db = doc.metrics.find((m) => m.id === "db-size"); + expect(db.used).toBeNull(); + expect(db.flag).toBeUndefined(); + }); + + test("a token the API refuses is a scope-denied failure with no values", async () => { + const impl = async () => response(401, { message: "Unauthorized" }); + const err = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }).catch((e) => e); + expect(err).toBeInstanceOf(ExportError); + expect(err.status).toBe("scope-denied"); + expect(err.exitCode).toBe(4); + }); + + test("a missing token is a no-token failure", async () => { + const err = await run({ token: null, ref: REF }).catch((e) => e); + expect(err.status).toBe("no-token"); + }); + + test("failure documents carry no metric or billing values", () => { + const doc = failureDocument({ attemptedAt: "2026-10-29T10:00:00Z", status: "fetch-failed", detail: "HTTP 502" }); + expect(doc.metrics).toBeUndefined(); + expect(doc.billing).toBeUndefined(); + expect(doc.measuredAt).toBeNull(); + }); + + test("parsers reject shape drift", () => { + expect(() => parseDbSize([{ bytes: "nope" }])).toThrow(ExportError); + expect(parseRequestCount({ result: [{ count: "12" }] })).toBe(12); + expect(parseRequestCount({ result: [] })).toBeNull(); + expect(() => billedFromAddons({})).toThrow(ExportError); + expect(billedFromAddons({ selected_addons: [{ price: { amount: 25 } }] })).toBe(25); + }); + + test("buildMetrics never emits a paid trigger for an unmeasured metric", () => { + const metrics = buildMetrics({ dbBytes: null, bucketCount: null, requestTotal: null }); + expect(metrics.every((m) => m.flag === undefined)).toBe(true); + }); +}); diff --git a/pm-stack/supabase-export/supabase-quota-export.timer b/pm-stack/supabase-export/supabase-quota-export.timer new file mode 100644 index 0000000000..9afe2a6034 --- /dev/null +++ b/pm-stack/supabase-export/supabase-quota-export.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Run the Supabase usage exporter every 15 minutes — code#1050 (gatherer tick, #1151) + +[Timer] +OnCalendar=*:0/15 +RandomizedDelaySec=20 +Persistent=true +Unit=supabase-quota-export.service + +[Install] +WantedBy=timers.target From cd690fc5402cd5439acf39dc703f1ba3fe6925a8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 11:17:54 -0500 Subject: [PATCH 2/3] fix(usage-hub): disposition Codex findings on the Supabase exporter (#1050) - probe() now sends the bearer token, so the analytics/organization scope probes report the credential's real permissions; the fake API in tests refuses unauthenticated calls like the real one. - live usage() applies the Supabase export overlay to fleet-feed saas services too, not only the quota-view fallback branch. - the systemd unit starts through bash (path rendered at install time; this NixOS laptop has no /bin/bash) so BASH_ENV loads the agent-shell-env hook that supplies BWS_ACCESS_TOKEN. - install-laptop.sh renders the unit's export dir and bun path from the selected install directory instead of copying it unchanged, and fails if a placeholder survives rendering. Tests: supabase-export 10 pass; aggregator supabase-export+usage 28 pass (laptop bun). --- pm-stack/aggregator/src/sources/live.ts | 12 ++++-- .../aggregator/test/supabase-export.test.ts | 43 +++++++++++++++++++ pm-stack/supabase-export/install-laptop.sh | 20 ++++++++- .../supabase-export/supabase-quota-export.mjs | 15 ++++--- .../supabase-quota-export.service | 12 +++++- .../supabase-quota-export.test.mjs | 12 +++++- 6 files changed, 102 insertions(+), 12 deletions(-) diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index c6d3f915dd..8f7090a7f0 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -806,10 +806,17 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise JSON.parse(text) as SupabaseExportDoc) + .catch(() => null); if (feed?.saas && feed.saas.length) { provenance.usage = `live (fleet feed · ${feedAgeText(feed.generatedAt)} · collected ${feed.generatedAt})`; const partial = { - services: feed.saas, + services: applySupabaseExport(feed.saas, supabaseExport), payg: feed.payg ?? [], charges: feed.charges ?? [], subscriptions: feed.subscriptions ?? [], @@ -840,9 +847,6 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise ""), ]); - const supabaseExport = await readFile(cfg.supabaseExportFile, "utf8") - .then((text) => JSON.parse(text) as SupabaseExportDoc) - .catch(() => null); const partial = { services: applySupabaseExport(extractSaasServices(doc), supabaseExport), payg: extractPaygLines(doc, registryText), diff --git a/pm-stack/aggregator/test/supabase-export.test.ts b/pm-stack/aggregator/test/supabase-export.test.ts index 70f6815086..7c78995c2a 100644 --- a/pm-stack/aggregator/test/supabase-export.test.ts +++ b/pm-stack/aggregator/test/supabase-export.test.ts @@ -3,7 +3,12 @@ // billed state on the Supabase card; a missing, failed or stale // document reproduces the recorded prose exactly. import { describe, expect, test } from "bun:test"; +import { mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { loadConfig } from "../src/config.ts"; import { applySupabaseExport, extractSaasServices, type SupabaseExportDoc } from "../src/saas-extract.ts"; +import { liveSource } from "../src/sources/live.ts"; const VIEW = ` ## Summary (b) — subscriptions, infrastructure, account tooling @@ -103,3 +108,41 @@ describe("applySupabaseExport", () => { expect(out.find((s) => s.id === "supabase")!.metrics).toEqual([]); }); }); + +describe("live source usage(): the overlay reaches fleet-feed services too", () => { + test("feed.saas cards get the fresh export overlay, not just the quota-view fallback", async () => { + const dir = await mkdtemp(join(tmpdir(), "pm-supa-feed-")); + const nowIso = new Date().toISOString(); + const feedFile = join(dir, "fleet-feed.json"); + const exportFile = join(dir, "latest.json"); + await writeFile(exportFile, JSON.stringify(freshDoc({ measuredAt: nowIso }))); + await writeFile( + feedFile, + JSON.stringify({ + version: 1, + generatedAt: nowIso, + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + saas: extractSaasServices(VIEW), + }), + ); + const cfg = loadConfig({ + PM_AGG_SOURCE: "live", + PM_AGG_FEED_FILE: feedFile, + PM_AGG_SUPABASE_EXPORT: exportFile, + PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), + PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), + PM_AGG_SNAPSHOTS_DIR: join(dir, "snapshots"), + PM_AGG_OPENCHAMBER_STATE: join(dir, "no-state.json"), + PM_PROJECTOR_URL: "off", + KANEO_ADMIN_EMAIL: "", + KANEO_ADMIN_PASSWORD: "", + GRIST_API_KEY: "", + }); + const usage = await liveSource(cfg).usage(); + const db = metricOf(usage.services, "db-size"); + expect(db.used).toBe(1.154); + expect(db.limit).toBe(0.5); + expect(supabaseCard(usage.services).billedUsd).toBe(0); + }); +}); diff --git a/pm-stack/supabase-export/install-laptop.sh b/pm-stack/supabase-export/install-laptop.sh index c96ad078b0..9c8757fa3b 100755 --- a/pm-stack/supabase-export/install-laptop.sh +++ b/pm-stack/supabase-export/install-laptop.sh @@ -13,7 +13,25 @@ units="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user" mkdir -p "$target" "$units" install -m 0644 "$here/supabase-quota-export.mjs" "$target/supabase-quota-export.mjs" -install -m 0644 "$here/supabase-quota-export.service" "$units/supabase-quota-export.service" +# Render the unit's paths from the selected install directory — copying it +# unchanged would leave the timer pointing at the default directory. +bash_bin="$(command -v bash || true)" +if [[ -z $bash_bin ]]; then + echo "install-laptop: bash not found on PATH" >&2 + exit 1 +fi +bun_bin="$(command -v bun || true)" +if [[ -z $bun_bin && -x $HOME/.bun/bin/bun ]]; then bun_bin="$HOME/.bun/bin/bun"; fi +if [[ -z $bun_bin ]]; then + echo "install-laptop: bun not found on PATH or at ~/.bun/bin/bun" >&2 + exit 1 +fi +sed -e "s|@EXPORT_DIR@|$target|g" -e "s|@BUN@|$bun_bin|g" -e "s|@BASH@|$bash_bin|g" "$here/supabase-quota-export.service" > "$units/supabase-quota-export.service" +chmod 0644 "$units/supabase-quota-export.service" +if grep -q '@EXPORT_DIR@\|@BUN@\|@BASH@' "$units/supabase-quota-export.service"; then + echo "install-laptop: service unit still contains an unrendered placeholder after rendering" >&2 + exit 1 +fi install -m 0644 "$here/supabase-quota-export.timer" "$units/supabase-quota-export.timer" systemctl --user daemon-reload diff --git a/pm-stack/supabase-export/supabase-quota-export.mjs b/pm-stack/supabase-export/supabase-quota-export.mjs index cb58b35259..6c2ac24256 100755 --- a/pm-stack/supabase-export/supabase-quota-export.mjs +++ b/pm-stack/supabase-export/supabase-quota-export.mjs @@ -163,8 +163,13 @@ export function buildMetrics({ dbBytes, bucketCount, requestTotal }) { } /** Probe a path and return { status, json? , text? } without throwing on HTTP. */ -async function probe(fetchImpl, path) { - const res = await fetchImpl(`${API_BASE}${path}`); +async function probe(fetchImpl, token, path) { + const res = await fetchImpl(`${API_BASE}${path}`, { + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/json", + }, + }); let body = null; try { body = await res.text(); @@ -247,7 +252,7 @@ export async function run({ token, ref = DEFAULT_PROJECT_REF, fetchImpl = fetch // Egress: there is no bytes endpoint. Record the gap precisely and keep the // request count as context, then the available usage endpoints for the record. - const requests = await probe(fetchImpl, `/projects/${ref}/analytics/endpoints/usage.api-requests-count`); + const requests = await probe(fetchImpl, token, `/projects/${ref}/analytics/endpoints/usage.api-requests-count`); scope.push({ endpoint: "usage.api-requests-count", path: `/projects/${ref}/analytics/endpoints/usage.api-requests-count`, @@ -261,7 +266,7 @@ export async function run({ token, ref = DEFAULT_PROJECT_REF, fetchImpl = fetch `/projects/${ref}/usage`, `/projects/${ref}/database/size`, ]) { - const r = await probe(fetchImpl, path); + const r = await probe(fetchImpl, token, path); scope.push({ endpoint: path.split("/").pop(), path, status: r.status, note: r.status === 404 ? "no such endpoint" : undefined }); } @@ -285,7 +290,7 @@ export async function run({ token, ref = DEFAULT_PROJECT_REF, fetchImpl = fetch } const slug = projectBody?.organization_slug; if (slug) { - const org = await probe(fetchImpl, `/organizations/${slug}`); + const org = await probe(fetchImpl, token, `/organizations/${slug}`); scope.push({ endpoint: "organizations/:slug", path: `/organizations/${slug}`, diff --git a/pm-stack/supabase-export/supabase-quota-export.service b/pm-stack/supabase-export/supabase-quota-export.service index b9ab0627db..8685a90527 100644 --- a/pm-stack/supabase-export/supabase-quota-export.service +++ b/pm-stack/supabase-export/supabase-quota-export.service @@ -5,4 +5,14 @@ After=network-online.target [Service] Type=oneshot TimeoutStartSec=120 -ExecStart=%h/.bun/bin/bun %h/atlas/supabase-export/supabase-quota-export.mjs --out-dir %h/atlas/supabase-export +# Start through bash so the laptop auth hook loads: systemd user units get +# BASH_ENV from the manager environment (home/common/default.nix +# sessionVariables -> agent-shell-env env.sh), and a non-interactive bash +# sources $BASH_ENV before running the command — that hook is what puts +# BWS_ACCESS_TOKEN in the environment for the producer's Bitwarden token +# resolution. Starting bun directly skipped the hook and every tick failed +# no-token. The placeholders in ExecStart are rendered by +# install-laptop.sh from the selected installation directory and the +# laptop's bash/bun found on PATH at install time (this NixOS laptop has +# no /bin/bash, so a hardcoded shell path would not even start). +ExecStart=@BASH@ -c "exec @BUN@ @EXPORT_DIR@/supabase-quota-export.mjs --out-dir @EXPORT_DIR@" diff --git a/pm-stack/supabase-export/supabase-quota-export.test.mjs b/pm-stack/supabase-export/supabase-quota-export.test.mjs index d9bacbf10e..e946148bb1 100644 --- a/pm-stack/supabase-export/supabase-quota-export.test.mjs +++ b/pm-stack/supabase-export/supabase-quota-export.test.mjs @@ -26,7 +26,10 @@ function response(status, body) { function fakeFetch({ dbBytes = 1_153_939_123, bucketCount = 0, addonsStatus = 200 } = {}) { const calls = []; const impl = async (url, init) => { - calls.push({ url, method: init?.method ?? "GET" }); + calls.push({ url, method: init?.method ?? "GET", authorization: init?.headers?.Authorization }); + // The real Management API refuses unauthenticated calls; the fake does + // too, so a probe that forgets the bearer token cannot pass silently. + if (init?.headers?.Authorization !== "Bearer sbp_fake") return response(401, { message: "Unauthorized" }); const path = url.replace("https://api.supabase.com/v1", ""); if (path === `/projects/${REF}`) { return response(200, { @@ -60,6 +63,13 @@ describe("supabase-quota-export", () => { expect(db.source).toContain("pg_database_size"); }); + test("every Management API call, probes included, carries the bearer token", async () => { + const { impl, calls } = fakeFetch(); + await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); + expect(calls.length).toBeGreaterThan(5); + expect(calls.every((c) => c.authorization === "Bearer sbp_fake")).toBe(true); + }); + test("records the egress scope gap without inventing a value", async () => { const { impl } = fakeFetch(); const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); From 36280d58800dbf953279a819dfe4d744baf32434 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 18:56:01 -0500 Subject: [PATCH 3/3] fix(usage-hub): billed amount unknown when supabase billing probe unavailable (#1050) --- pm-stack/aggregator/src/saas-extract.ts | 13 +++++++++++-- pm-stack/aggregator/test/supabase-export.test.ts | 9 +++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/pm-stack/aggregator/src/saas-extract.ts b/pm-stack/aggregator/src/saas-extract.ts index 8250a158fc..34dd1733c2 100644 --- a/pm-stack/aggregator/src/saas-extract.ts +++ b/pm-stack/aggregator/src/saas-extract.ts @@ -693,7 +693,9 @@ export const SUPABASE_EXPORT_STALE_MS = 30 * 60 * 1000; * Matching metric ids take `used`, `limit`, `unit` and a measured-at/source * note from the export; a metric the probe could not measure keeps today's * null-but-recorded behaviour with the export's gap detail. `billedUsd` - * becomes the export's measured addon read instead of the hardcoded 0. + * becomes the export's measured addon read instead of the hardcoded 0 — + * or unknown (null) when the accepted export carries no valid billing + * measurement, so a failed billing probe never renders as $0.00 billed. * Missing, failed, unparseable or stale documents change nothing. */ export function applySupabaseExport( @@ -737,8 +739,15 @@ export function applySupabaseExport( note: parts.join(" ").slice(0, 600), }; }); - if (doc.billing && typeof doc.billing.billedUsd === "number" && Number.isFinite(doc.billing.billedUsd)) { + if (doc.billing && doc.billing.measured !== false && typeof doc.billing.billedUsd === "number" && Number.isFinite(doc.billing.billedUsd)) { supabase.billedUsd = doc.billing.billedUsd; + } else { + // Codex P2 (PR #2369 re-review, 2026-10-29): an accepted export with no + // valid billing measurement must not keep the hardcoded 0 from + // extractSaasServices — the card is stamped fresh/api below, so $0.00 + // would read as a measured billed amount. Unknown (null) renders as + // no billed line at all. + supabase.billedUsd = null; } supabase.plan = doc.billing?.plan ? `Free plan (${doc.project ?? "supabase"}); measured ${doc.measuredAt}` : supabase.plan; supabase.measuredAt = doc.measuredAt.slice(0, 10); diff --git a/pm-stack/aggregator/test/supabase-export.test.ts b/pm-stack/aggregator/test/supabase-export.test.ts index 7c78995c2a..d299751754 100644 --- a/pm-stack/aggregator/test/supabase-export.test.ts +++ b/pm-stack/aggregator/test/supabase-export.test.ts @@ -87,6 +87,15 @@ describe("applySupabaseExport", () => { expect(supabaseCard(out).plan).toContain("measured 2026-10-29T14:55:00Z"); }); + test("an accepted export without a valid billing measurement clears billed to unknown", () => { + const noBilling = applySupabaseExport(extractSaasServices(VIEW), freshDoc({ billing: null as unknown as SupabaseExportDoc["billing"] }), NOW); + expect(supabaseCard(noBilling).billedUsd).toBeNull(); + expect(supabaseCard(noBilling).sourceClass).toBe("api"); // the rest of the overlay still applied + expect(metricOf(noBilling, "db-size").used).toBe(1.154); + const unmeasured = applySupabaseExport(extractSaasServices(VIEW), freshDoc({ billing: { plan: "free" } }), NOW); + expect(supabaseCard(unmeasured).billedUsd).toBeNull(); + }); + test("a stale export falls back to exactly today's card", () => { const base = extractSaasServices(VIEW); const out = applySupabaseExport(base, freshDoc({ measuredAt: "2026-10-29T12:00:00Z" }), NOW);