@cross-deck/buckets 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/index.d.mts +179 -0
- package/dist/index.d.ts +147 -12
- package/dist/index.js +249 -33
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +236 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +7 -9
- package/dist/adapters/firestore.d.ts +0 -41
- package/dist/adapters/firestore.d.ts.map +0 -1
- package/dist/adapters/firestore.js +0 -145
- package/dist/adapters/firestore.js.map +0 -1
- package/dist/cost-context.d.ts +0 -25
- package/dist/cost-context.d.ts.map +0 -1
- package/dist/cost-context.js +0 -46
- package/dist/cost-context.js.map +0 -1
- package/dist/cost-meter.d.ts +0 -28
- package/dist/cost-meter.d.ts.map +0 -1
- package/dist/cost-meter.js +0 -137
- package/dist/cost-meter.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/sink.d.ts +0 -56
- package/dist/sink.d.ts.map +0 -1
- package/dist/sink.js +0 -42
- package/dist/sink.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,cAAc,EAAoB,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,UAAU,EAAa,MAAM,WAAW,CAAC;AAClD,OAAO,EAAE,qBAAqB,EAAyB,MAAM,yBAAyB,CAAC;AAsBvF;;;;GAIG;AACH,MAAM,UAAU,IAAI,CAAC,OAAoB;IACvC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,IAAI,UAAU,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC;IACpG,cAAc,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,CAAC,eAAe,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IAC7F,IAAI,OAAO,CAAC,SAAS;QAAE,qBAAqB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;AAClE,CAAC;AAED,4DAA4D;AAC5D,OAAO,EAAE,IAAI,IAAI,WAAW,EAAE,CAAC;AAE/B,qEAAqE;AACrE,OAAO,EACL,MAAM,EACN,cAAc,EACd,YAAY,EACZ,aAAa,EACb,cAAc,GAEf,MAAM,mBAAmB,CAAC;AAE3B,gFAAgF;AAChF,OAAO,EACL,WAAW,EACX,YAAY,EACZ,aAAa,EACb,KAAK,GAIN,MAAM,iBAAiB,CAAC;AAEzB,iEAAiE;AACjE,OAAO,EAAE,qBAAqB,EAAyB,MAAM,yBAAyB,CAAC;AAEvF,8EAA8E;AAC9E,OAAO,EAAE,UAAU,EAAuE,MAAM,WAAW,CAAC"}
|
|
1
|
+
{"version":3,"sources":["../src/cost-context.ts","../src/cost-meter.ts","../src/sink.ts","../src/adapters/firestore.ts","../src/index.ts"],"names":["AsyncLocalStorage","sink"],"mappings":";;;;;AAqBA,IAAM,cAAuB,EAAC;AAC9B,IAAM,KAAA,GAAQ,IAAIA,6BAAA,EAA2B;AAGtC,SAAS,cAAA,CAAkB,KAAc,EAAA,EAAgB;AAC9D,EAAA,OAAO,MAAM,GAAA,CAAI,EAAE,GAAG,GAAA,IAAO,EAAE,CAAA;AACjC;AAGO,SAAS,aAAa,GAAA,EAAoB;AAC/C,EAAA,KAAA,CAAM,SAAA,CAAU,EAAE,GAAG,GAAA,EAAK,CAAA;AAC5B;AAGO,SAAS,cAAc,KAAA,EAA+B;AAC3D,EAAA,MAAM,GAAA,GAAM,MAAM,QAAA,EAAS;AAC3B,EAAA,IAAI,GAAA,EAAK,MAAA,CAAO,MAAA,CAAO,GAAA,EAAK,KAAK,CAAA;AACnC;AAGO,SAAS,cAAA,GAA0B;AACxC,EAAA,OAAO,KAAA,CAA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AC1C,MAAA,UAAA,CAAW,KAAA,CAAM,OAAA,CAAQ,GAAG,CAAA,GAAI,GAAA,CAAI,MAAA,GAAS,IAAA,CAAK,MAAA,IAAU,CAAA,EAAG,QAAA,CAAS,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA;AAChF,MAAA,OAAO,GAAA;AAAA,IACT,CAAA;AAAA,EACF;AAGA,EAAA,MAAM,OAAA,GAAU,WAAW,SAAA,EAAW,MAAA;AACtC,EAAA,IAAI,OAAA,EAAS;AACX,IAAA,SAAA,CAAW,SAAA,CAAU,MAAA,GAAS,eAAA,GAAkC,IAAA,EAAa;AAC3E,MAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,KAAA,CAAM,MAAM,IAAI,CAAA;AAC1C,MAAA,UAAA,CAAW,KAAA,CAAM,OAAA,CAAQ,GAAG,CAAA,GAAI,GAAA,CAAI,MAAA,GAAS,IAAA,CAAK,MAAA,IAAU,CAAA,EAAG,QAAA,CAAS,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA;AAChF,MAAA,OAAO,GAAA;AAAA,IACT,CAAA;AAAA,EACF;AACF;;;AC1HO,SAAS,KAAK,OAAA,EAA4B;AAC/C,EAAA,MAAMC,KAAAA,GAAO,OAAA,CAAQ,IAAA,IAAQ,IAAI,UAAA,CAAW,EAAE,MAAA,EAAQ,OAAA,CAAQ,MAAA,EAAQ,QAAA,EAAU,OAAA,CAAQ,QAAA,EAAU,CAAA;AAClG,EAAA,cAAA,CAAe,EAAE,MAAAA,KAAAA,EAAM,eAAA,EAAiB,QAAQ,eAAA,EAAiB,OAAA,EAAS,OAAA,CAAQ,OAAA,EAAS,CAAA;AAC3F,EAAA,IAAI,OAAA,CAAQ,SAAA,EAAW,qBAAA,CAAsB,OAAA,CAAQ,SAAS,CAAA;AAChE","file":"index.js","sourcesContent":["/**\n * cost-context — the request-scoped tag every counted operation attributes\n * itself to. Set it ONCE at a boundary (or wrap a path with `bucket()`); it\n * rides Node's AsyncLocalStorage down through every async fan-out, so one\n * handler that triggers 15 reads attributes all 15 to the same bucket — with\n * zero per-call-site work.\n *\n * Generic by design: unlike a hardcoded product taxonomy, the only meaningful\n * field a consumer sets is the free-form `label` (the bucket name). `feature`\n * is an optional coarse grouping if you want one; nothing here is\n * Crossdeck-specific.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport interface CostTag {\n /** Optional coarse grouping (a caller-defined surface name). */\n feature?: string;\n /** The bucket name — what `bucket()` sets. Drives the report's `byLabel`. */\n label?: string;\n}\n\nconst DEFAULT_TAG: CostTag = {};\nconst store = new AsyncLocalStorage<CostTag>();\n\n/** Run `fn` with `tag` bound for its entire async subtree. */\nexport function runWithCostTag<T>(tag: CostTag, fn: () => T): T {\n return store.run({ ...tag }, fn);\n}\n\n/** Bind a tag for the remainder of the current async context (no closure to wrap). */\nexport function enterCostTag(tag: CostTag): void {\n store.enterWith({ ...tag });\n}\n\n/** Refine the live tag in place (e.g. stamp a feature after the boundary). */\nexport function refineCostTag(patch: Partial<CostTag>): void {\n const cur = store.getStore();\n if (cur) Object.assign(cur, patch);\n}\n\n/** The current tag, or a safe empty default outside any bound context. */\nexport function currentCostTag(): CostTag {\n return store.getStore() ?? DEFAULT_TAG;\n}\n\n/**\n * `bucket(name, fn)` — the headline verb, the `track()` of cost. Run `fn` with\n * every operation inside it attributed to the bucket `name`; the attribution\n * rides the async subtree automatically. The one verb most developers ever touch:\n *\n * await bucket(\"nightly-export\", async () => {\n * const rows = await db.collection(\"events\").where(...).get(); // → \"nightly-export\"\n * });\n */\nexport function bucket<T>(name: string, fn: () => T): T {\n return runWithCostTag({ ...currentCostTag(), label: name }, fn);\n}\n","/**\n * cost-meter — counts operations against the ambient tag and flushes them to the\n * configured Sink cheaply.\n *\n * LOW-OVERHEAD CONTRACT (the thing that warns you about reads must not run them\n * up): counts accumulate in an in-memory buffer and flush periodically — NEVER one\n * network call per counted operation. A flush coalesces the whole window into one\n * report per UTC day and hands it to the Sink. At steady state that is ~1 small\n * request a minute, regardless of how many ops you served.\n *\n * BEST-EFFORT CONTRACT: metering must never throw into your code. Every recorder\n * swallows its own errors; a failed flush drops that window's counts (surfaced via\n * `onError` if you pass one) rather than disturbing the app.\n */\nimport { currentCostTag } from \"./cost-context\";\nimport type { Sink, BucketsReport, OpCounts } from \"./sink\";\n\nexport type OpType = \"read\" | \"write\" | \"delete\";\n\n/** Optional read-site hint — the collection touched, derived at the trap from the\n * path. Lets an UNtagged read cascade to `col:<collection>` instead of vanishing. */\nexport interface CostHint {\n collection?: string;\n projectId?: string;\n}\n\n// NUL separator — a bucket/collection name can contain almost anything except\n// this, so the key never collides with a name that has a \"|\" or \":\" in it.\nconst SEP = \"\\u001f\"; // ASCII Unit Separator\n\n/** key = date <NUL> op <NUL> label → count */\nconst labelBuffer = new Map<string, number>();\n/** key = date <NUL> op <NUL> hour → count */\nconst hourBuffer = new Map<string, number>();\n\nlet sink: Sink | null = null;\nlet flushIntervalMs = 60_000;\nlet onError: ((e: unknown) => void) | null = null;\nlet timer: ReturnType<typeof setInterval> | null = null;\nlet flushing = false;\n/** Safety valve — flush early if a burst fills the buffer between intervals. */\nconst MAX_BUFFER_KEYS = 5_000;\n\nexport interface MeterConfig {\n sink: Sink;\n flushIntervalMs?: number;\n onError?: (e: unknown) => void;\n}\n\n/** Point the meter at a sink. Called by `init()`; pass your own sink to self-host. */\nexport function configureMeter(config: MeterConfig): void {\n sink = config.sink;\n if (config.flushIntervalMs && config.flushIntervalMs > 0) flushIntervalMs = config.flushIntervalMs;\n onError = config.onError ?? null;\n}\n\nconst utcDate = (): string => new Date().toISOString().slice(0, 10);\nconst utcHour = (): string => new Date().toISOString().slice(11, 13);\n\nfunction ensureFlushLoop(): void {\n if (timer) return;\n timer = setInterval(() => void flush(), flushIntervalMs);\n // Don't keep the event loop alive just for metering.\n (timer as { unref?: () => void }).unref?.();\n // Flush the last window on shutdown.\n process.once?.(\"SIGTERM\", () => void flush());\n process.once?.(\"beforeExit\", () => void flush());\n}\n\n/** Count `n` ops of `op` against the live tag. Never throws. */\nexport function recordFirestore(op: OpType, n: number, hint?: CostHint): void {\n try {\n if (!Number.isFinite(n) || n <= 0) return;\n const t = currentCostTag();\n const date = utcDate();\n // CASCADE — every op gets a label, by design (no blind spots): the bucket name\n // wins; else the collection it actually touched (`col:posts`); else\n // \"uncategorized\" as a loud last resort. A read is never invisible.\n const label = t.label || (hint?.collection ? `col:${hint.collection}` : \"uncategorized\");\n const lk = date + SEP + op + SEP + label;\n labelBuffer.set(lk, (labelBuffer.get(lk) ?? 0) + n);\n const hk = date + SEP + op + SEP + utcHour();\n hourBuffer.set(hk, (hourBuffer.get(hk) ?? 0) + n);\n ensureFlushLoop();\n if (labelBuffer.size + hourBuffer.size > MAX_BUFFER_KEYS) void flush();\n } catch {\n /* metering is best-effort — never disturb the caller */\n }\n}\n\n/** Firestore bills a minimum of one read even for an empty result, so 0 counts as 1. */\nexport function recordReads(n: number, hint?: CostHint): void {\n recordFirestore(\"read\", Math.max(n, 1), hint);\n}\nexport function recordWrites(n = 1): void {\n recordFirestore(\"write\", n);\n}\nexport function recordDeletes(n = 1): void {\n recordFirestore(\"delete\", n);\n}\n\nfunction add(target: Record<string, OpCounts>, key: string, op: OpType, n: number): void {\n const bag = (target[key] ??= {});\n bag[op] = (bag[op] ?? 0) + n;\n}\n\n/**\n * Coalesce the buffer into one report per UTC day and hand each to the Sink.\n * Snapshots + clears up front so concurrent records land in the next window.\n * Never throws; a sink failure drops that window (surfaced via `onError`).\n */\nexport async function flush(): Promise<void> {\n if (flushing) return;\n // Not configured (init not called) — drop, don't grow unbounded.\n if (!sink) {\n labelBuffer.clear();\n hourBuffer.clear();\n return;\n }\n if (labelBuffer.size === 0 && hourBuffer.size === 0) return;\n flushing = true;\n\n const labels = new Map(labelBuffer);\n const hours = new Map(hourBuffer);\n labelBuffer.clear();\n hourBuffer.clear();\n\n try {\n const byDate = new Map<string, BucketsReport>();\n const reportFor = (date: string): BucketsReport => {\n let r = byDate.get(date);\n if (!r) {\n r = { date, byLabel: {}, byHour: {} };\n byDate.set(date, r);\n }\n return r;\n };\n for (const [k, n] of labels) {\n const [date, op, label] = k.split(SEP) as [string, OpType, string];\n add(reportFor(date).byLabel, label, op, n);\n }\n for (const [k, n] of hours) {\n const [date, op, hour] = k.split(SEP) as [string, OpType, string];\n add(reportFor(date).byHour!, hour, op, n);\n }\n for (const report of byDate.values()) {\n await sink.flush(report);\n }\n } catch (e) {\n // Drop this window rather than risk a partial/double report on retry.\n onError?.(e);\n } finally {\n flushing = false;\n }\n}\n","/**\n * sink — where the meter sends a coalesced rollup, and the wire shape it sends.\n *\n * Abstracting the sink is what makes Buckets storage-agnostic: the meter never\n * knows where counts go. The DEFAULT sink (`ReportSink`) reports up to Crossdeck's\n * ingest endpoint so the numbers surface on your Crossdeck dashboard. A team that\n * wants to self-host can implement `Sink` against anything (Postgres, a file, your\n * own API) without touching the meter.\n */\n\nexport interface OpCounts {\n read?: number;\n write?: number;\n delete?: number;\n}\n\n/**\n * One coalesced report — the wire contract (see docs/ROLLUP_SCHEMA.md). The meter\n * produces one of these per UTC day in a flush window (usually exactly one).\n */\nexport interface BucketsReport {\n /** UTC day \"YYYY-MM-DD\". */\n date: string;\n /** bucket name → counts. The heart of the report. */\n byLabel: Record<string, OpCounts>;\n /** UTC hour \"HH\" → counts, for the hourly \"did my fix land this hour?\" view. */\n byHour?: Record<string, OpCounts>;\n}\n\n/**\n * A destination for coalesced rollups. `flush` MAY throw on failure — the meter\n * catches it, drops that one window, and never lets it reach your app.\n */\nexport interface Sink {\n flush(report: BucketsReport): Promise<void>;\n}\n\nexport interface ReportSinkConfig {\n /** The project's `cd_sk_` secret key. Server-to-server only. */\n apiKey: string;\n /** Defaults to https://api.cross-deck.com/v1/buckets/report */\n endpoint?: string;\n /** Request timeout (ms); a slow Crossdeck must never stall your flush. */\n timeoutMs?: number;\n}\n\nconst DEFAULT_ENDPOINT = \"https://api.cross-deck.com/v1/buckets/report\";\n\n/**\n * The default sink: POST one coalesced rollup to Crossdeck's ingest endpoint.\n * The ingest folds it into the day's maintained doc with `increment`, so many\n * reports a minute coalesce safely. This path does ZERO database reads — it sends\n * a summary, it does not read. Throws on a non-202 so the meter can log/drop the\n * window; the meter guarantees it never reaches your app.\n */\nexport class ReportSink implements Sink {\n private readonly endpoint: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n\n constructor(config: ReportSinkConfig) {\n this.endpoint = config.endpoint ?? DEFAULT_ENDPOINT;\n this.apiKey = config.apiKey;\n this.timeoutMs = config.timeoutMs ?? 5000;\n }\n\n async flush(report: BucketsReport): Promise<void> {\n const res = await fetch(this.endpoint, {\n method: \"POST\",\n signal: AbortSignal.timeout(this.timeoutMs),\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify(report),\n });\n if (res.status !== 202) {\n throw new Error(`Buckets report rejected: HTTP ${res.status}`);\n }\n }\n}\n","/**\n * adapters/firestore — the universal Firestore read meter (the trap).\n *\n * THE LESSON (learned on a real product): per-call-site `recordReads()`\n * instrumentation MISSES paths. You meter the read sites you're looking at and\n * leave the cron / trigger / ingest path uncounted — often the majority of reads,\n * invisible. Humans tag what they see and miss the path that matters.\n *\n * THE FIX: patch the admin SDK's read methods ONCE. From install onward, EVERY\n * read — anywhere, on any code path — is counted under the ambient tag, with zero\n * per-call-site work and no blind spots.\n *\n * SAFETY CONTRACT — this sits on your production read path, so it is defensive by\n * construction. Each wrapper:\n * 1. calls the REAL method first and captures the result,\n * 2. counts in a try/catch that can never throw into the caller,\n * 3. ALWAYS returns the real result, untouched.\n * It cannot break a read, change a result, or add latency beyond one in-memory\n * counter increment. A wrong count is a measurement error, never a correctness or\n * availability one. Idempotent — calling it twice patches once.\n *\n * COUNTING MODEL — a query returning N docs = N reads (an empty result still bills\n * 1, which the meter enforces). A document get = 1. getAll(...) = the ref count.\n * CollectionReference.get IS Query.get (shared prototype method), so patching Query\n * covers collections with no double-count.\n */\nimport { recordReads, type CostHint } from \"../cost-meter\";\n\nlet installed = false;\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\ntype AnyFn = (...args: any[]) => any;\n\n/**\n * The firebase-admin Firestore classes to patch. Pass the module namespace from\n * `firebase-admin/firestore` — only the prototypes present are patched.\n */\nexport interface FirestoreClasses {\n Query?: { prototype: { get?: AnyFn } };\n DocumentReference?: { prototype: { get?: AnyFn } };\n Transaction?: { prototype: { get?: AnyFn; getAll?: AnyFn } };\n Firestore?: { prototype: { getAll?: AnyFn } };\n}\n\n/** `projects/{id}/…` → the project id, else undefined. Pure string op. */\nfunction projectFromPath(path: string): string | undefined {\n const parts = path.split(\"/\");\n const i = parts.indexOf(\"projects\");\n return i >= 0 && parts[i + 1] ? parts[i + 1] : undefined;\n}\n\n/**\n * Derive { collection, projectId } from the read target's path so an UNtagged read\n * cascades to `col:<collection>` instead of \"uncategorized\". PURE CPU; never reads,\n * never throws. Falls back to firebase-admin's internal `_queryOptions` for filtered\n * queries (which don't expose `.path`).\n */\nfunction hintFrom(target: any): CostHint | undefined {\n try {\n const p = typeof target?.path === \"string\" ? target.path : \"\";\n if (p) {\n const parts = p.split(\"/\").filter(Boolean);\n const collection = parts.length % 2 === 0 ? parts[parts.length - 2] : parts[parts.length - 1];\n return { collection, projectId: projectFromPath(p) };\n }\n const qo = target?._queryOptions;\n if (qo) {\n const collection = typeof qo.collectionId === \"string\" ? qo.collectionId : undefined;\n const parent =\n typeof qo.parentPath?.relativeName === \"string\"\n ? qo.parentPath.relativeName\n : typeof qo.parentPath?.toString === \"function\"\n ? String(qo.parentPath.toString())\n : \"\";\n return { collection, projectId: parent ? projectFromPath(parent) : undefined };\n }\n } catch {\n /* the meter must never throw */\n }\n return undefined;\n}\n\nfunction meterSnap(snap: unknown, hint?: CostHint): void {\n try {\n const size = (snap as { size?: number } | null)?.size;\n recordReads(typeof size === \"number\" ? size : 1, hint);\n } catch {\n /* best-effort */\n }\n}\nfunction meterCount(n: number, hint?: CostHint): void {\n try {\n recordReads(n, hint);\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * Install the universal read meter on the firebase-admin Firestore classes. Call\n * ONCE at process start, before any reads. Pass the namespace from\n * `firebase-admin/firestore` so the exact prototypes the SDK uses are patched:\n *\n * import * as Firestore from \"firebase-admin/firestore\";\n * installFirestoreMeter(Firestore);\n */\nexport function installFirestoreMeter(classes: FirestoreClasses): void {\n if (installed) return;\n installed = true;\n const { Query, DocumentReference, Transaction, Firestore } = classes;\n\n // Query.get — covers Query AND CollectionReference (shared prototype method).\n const qGet = Query?.prototype?.get;\n if (qGet) {\n Query!.prototype.get = async function (this: unknown, ...args: any[]) {\n const snap = await qGet.apply(this, args);\n meterSnap(snap, hintFrom(this));\n return snap;\n };\n }\n\n // DocumentReference.get — a single doc = 1 read.\n const dGet = DocumentReference?.prototype?.get;\n if (dGet) {\n DocumentReference!.prototype.get = async function (this: unknown, ...args: any[]) {\n const snap = await dGet.apply(this, args);\n meterCount(1, hintFrom(this));\n return snap;\n };\n }\n\n // Transaction.get — query or doc; size when present, else 1.\n const tGet = Transaction?.prototype?.get;\n if (tGet) {\n Transaction!.prototype.get = async function (this: unknown, ...args: any[]) {\n const res = await tGet.apply(this, args);\n meterSnap(res, hintFrom(args[0]));\n return res;\n };\n }\n\n // Transaction.getAll(...refs) — one read per ref.\n const tGetAll = Transaction?.prototype?.getAll;\n if (tGetAll) {\n Transaction!.prototype.getAll = async function (this: unknown, ...args: any[]) {\n const res = await tGetAll.apply(this, args);\n meterCount(Array.isArray(res) ? res.length : args.length || 1, hintFrom(args[0]));\n return res;\n };\n }\n\n // Firestore.getAll(...refs) — batched doc reads.\n const fGetAll = Firestore?.prototype?.getAll;\n if (fGetAll) {\n Firestore!.prototype.getAll = async function (this: unknown, ...args: any[]) {\n const res = await fGetAll.apply(this, args);\n meterCount(Array.isArray(res) ? res.length : args.length || 1, hintFrom(args[0]));\n return res;\n };\n }\n}\n\n/** Test-only: reset the install guard so a suite can re-patch fresh prototypes. */\nexport function __resetFirestoreMeterForTests(): void {\n installed = false;\n}\n","/**\n * @cross-deck/buckets — know exactly what every database read costs you, and who\n * caused it. A tiny, never-throws collector for Firestore.\n *\n * The whole footprint a consumer sees:\n * 1. init({ apiKey, firestore }) — configure once, install the trap once\n * 2. bucket(name, fn) — name the read paths that matter\n * 3. (the dashboard shows the rest — and names the ones you haven't yet)\n */\nimport { configureMeter, type MeterConfig } from \"./cost-meter\";\nimport { ReportSink, type Sink } from \"./sink\";\nimport { installFirestoreMeter, type FirestoreClasses } from \"./adapters/firestore\";\n\nexport interface InitOptions {\n /** The project's `cd_sk_` SECRET key. Server-to-server only — never a browser key. */\n apiKey: string;\n /**\n * Pass the namespace from `firebase-admin/firestore` to auto-install the read\n * trap (recommended — this is what makes every read count with no per-call work).\n * Omit it if you'd rather call `installFirestoreMeter()` yourself, or you only\n * use the manual `recordReads()` recorders.\n */\n firestore?: FirestoreClasses;\n /** Override the report endpoint (defaults to Crossdeck's ingest). */\n endpoint?: string;\n /** How often to flush coalesced counts (ms). Default 60_000. */\n flushIntervalMs?: number;\n /** Bring your own sink (self-host the rollups). Defaults to reporting up to Crossdeck. */\n sink?: Sink;\n /** Notified when a flush fails, so a dropped window is never silent. Best-effort. */\n onError?: MeterConfig[\"onError\"];\n}\n\n/**\n * Configure Buckets once, at process start. Points the meter at a sink (Crossdeck's\n * ingest by default) and — if you pass `firestore` — installs the universal read\n * trap so every read counts automatically.\n */\nexport function init(options: InitOptions): void {\n const sink = options.sink ?? new ReportSink({ apiKey: options.apiKey, endpoint: options.endpoint });\n configureMeter({ sink, flushIntervalMs: options.flushIntervalMs, onError: options.onError });\n if (options.firestore) installFirestoreMeter(options.firestore);\n}\n\n/** Alias — reads well next to `bucket()` at a call site. */\nexport { init as initBuckets };\n\n// The headline verb + the lower-level tag controls it is sugar over.\nexport {\n bucket,\n runWithCostTag,\n enterCostTag,\n refineCostTag,\n currentCostTag,\n type CostTag,\n} from \"./cost-context\";\n\n// Manual recorders (for non-Firestore ops, or when you don't install the trap).\nexport {\n recordReads,\n recordWrites,\n recordDeletes,\n flush,\n type CostHint,\n type OpType,\n type MeterConfig,\n} from \"./cost-meter\";\n\n// The trap (the only datastore adapter today) + its class shape.\nexport { installFirestoreMeter, type FirestoreClasses } from \"./adapters/firestore\";\n\n// The sink seam — for self-hosting rollups instead of reporting to Crossdeck.\nexport { ReportSink, type Sink, type BucketsReport, type OpCounts, type ReportSinkConfig } from \"./sink\";\n"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
2
|
+
|
|
3
|
+
// src/cost-context.ts
|
|
4
|
+
var DEFAULT_TAG = {};
|
|
5
|
+
var store = new AsyncLocalStorage();
|
|
6
|
+
function runWithCostTag(tag, fn) {
|
|
7
|
+
return store.run({ ...tag }, fn);
|
|
8
|
+
}
|
|
9
|
+
function enterCostTag(tag) {
|
|
10
|
+
store.enterWith({ ...tag });
|
|
11
|
+
}
|
|
12
|
+
function refineCostTag(patch) {
|
|
13
|
+
const cur = store.getStore();
|
|
14
|
+
if (cur) Object.assign(cur, patch);
|
|
15
|
+
}
|
|
16
|
+
function currentCostTag() {
|
|
17
|
+
return store.getStore() ?? DEFAULT_TAG;
|
|
18
|
+
}
|
|
19
|
+
function bucket(name, fn) {
|
|
20
|
+
return runWithCostTag({ ...currentCostTag(), label: name }, fn);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/cost-meter.ts
|
|
24
|
+
var SEP = "";
|
|
25
|
+
var labelBuffer = /* @__PURE__ */ new Map();
|
|
26
|
+
var hourBuffer = /* @__PURE__ */ new Map();
|
|
27
|
+
var sink = null;
|
|
28
|
+
var flushIntervalMs = 6e4;
|
|
29
|
+
var onError = null;
|
|
30
|
+
var timer = null;
|
|
31
|
+
var flushing = false;
|
|
32
|
+
var MAX_BUFFER_KEYS = 5e3;
|
|
33
|
+
function configureMeter(config) {
|
|
34
|
+
sink = config.sink;
|
|
35
|
+
if (config.flushIntervalMs && config.flushIntervalMs > 0) flushIntervalMs = config.flushIntervalMs;
|
|
36
|
+
onError = config.onError ?? null;
|
|
37
|
+
}
|
|
38
|
+
var utcDate = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
39
|
+
var utcHour = () => (/* @__PURE__ */ new Date()).toISOString().slice(11, 13);
|
|
40
|
+
function ensureFlushLoop() {
|
|
41
|
+
if (timer) return;
|
|
42
|
+
timer = setInterval(() => void flush(), flushIntervalMs);
|
|
43
|
+
timer.unref?.();
|
|
44
|
+
process.once?.("SIGTERM", () => void flush());
|
|
45
|
+
process.once?.("beforeExit", () => void flush());
|
|
46
|
+
}
|
|
47
|
+
function recordFirestore(op, n, hint) {
|
|
48
|
+
try {
|
|
49
|
+
if (!Number.isFinite(n) || n <= 0) return;
|
|
50
|
+
const t = currentCostTag();
|
|
51
|
+
const date = utcDate();
|
|
52
|
+
const label = t.label || (hint?.collection ? `col:${hint.collection}` : "uncategorized");
|
|
53
|
+
const lk = date + SEP + op + SEP + label;
|
|
54
|
+
labelBuffer.set(lk, (labelBuffer.get(lk) ?? 0) + n);
|
|
55
|
+
const hk = date + SEP + op + SEP + utcHour();
|
|
56
|
+
hourBuffer.set(hk, (hourBuffer.get(hk) ?? 0) + n);
|
|
57
|
+
ensureFlushLoop();
|
|
58
|
+
if (labelBuffer.size + hourBuffer.size > MAX_BUFFER_KEYS) void flush();
|
|
59
|
+
} catch {
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function recordReads(n, hint) {
|
|
63
|
+
recordFirestore("read", Math.max(n, 1), hint);
|
|
64
|
+
}
|
|
65
|
+
function recordWrites(n = 1) {
|
|
66
|
+
recordFirestore("write", n);
|
|
67
|
+
}
|
|
68
|
+
function recordDeletes(n = 1) {
|
|
69
|
+
recordFirestore("delete", n);
|
|
70
|
+
}
|
|
71
|
+
function add(target, key, op, n) {
|
|
72
|
+
const bag = target[key] ??= {};
|
|
73
|
+
bag[op] = (bag[op] ?? 0) + n;
|
|
74
|
+
}
|
|
75
|
+
async function flush() {
|
|
76
|
+
if (flushing) return;
|
|
77
|
+
if (!sink) {
|
|
78
|
+
labelBuffer.clear();
|
|
79
|
+
hourBuffer.clear();
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (labelBuffer.size === 0 && hourBuffer.size === 0) return;
|
|
83
|
+
flushing = true;
|
|
84
|
+
const labels = new Map(labelBuffer);
|
|
85
|
+
const hours = new Map(hourBuffer);
|
|
86
|
+
labelBuffer.clear();
|
|
87
|
+
hourBuffer.clear();
|
|
88
|
+
try {
|
|
89
|
+
const byDate = /* @__PURE__ */ new Map();
|
|
90
|
+
const reportFor = (date) => {
|
|
91
|
+
let r = byDate.get(date);
|
|
92
|
+
if (!r) {
|
|
93
|
+
r = { date, byLabel: {}, byHour: {} };
|
|
94
|
+
byDate.set(date, r);
|
|
95
|
+
}
|
|
96
|
+
return r;
|
|
97
|
+
};
|
|
98
|
+
for (const [k, n] of labels) {
|
|
99
|
+
const [date, op, label] = k.split(SEP);
|
|
100
|
+
add(reportFor(date).byLabel, label, op, n);
|
|
101
|
+
}
|
|
102
|
+
for (const [k, n] of hours) {
|
|
103
|
+
const [date, op, hour] = k.split(SEP);
|
|
104
|
+
add(reportFor(date).byHour, hour, op, n);
|
|
105
|
+
}
|
|
106
|
+
for (const report of byDate.values()) {
|
|
107
|
+
await sink.flush(report);
|
|
108
|
+
}
|
|
109
|
+
} catch (e) {
|
|
110
|
+
onError?.(e);
|
|
111
|
+
} finally {
|
|
112
|
+
flushing = false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// src/sink.ts
|
|
117
|
+
var DEFAULT_ENDPOINT = "https://api.cross-deck.com/v1/buckets/report";
|
|
118
|
+
var ReportSink = class {
|
|
119
|
+
endpoint;
|
|
120
|
+
apiKey;
|
|
121
|
+
timeoutMs;
|
|
122
|
+
constructor(config) {
|
|
123
|
+
this.endpoint = config.endpoint ?? DEFAULT_ENDPOINT;
|
|
124
|
+
this.apiKey = config.apiKey;
|
|
125
|
+
this.timeoutMs = config.timeoutMs ?? 5e3;
|
|
126
|
+
}
|
|
127
|
+
async flush(report) {
|
|
128
|
+
const res = await fetch(this.endpoint, {
|
|
129
|
+
method: "POST",
|
|
130
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
131
|
+
headers: {
|
|
132
|
+
"content-type": "application/json",
|
|
133
|
+
authorization: `Bearer ${this.apiKey}`
|
|
134
|
+
},
|
|
135
|
+
body: JSON.stringify(report)
|
|
136
|
+
});
|
|
137
|
+
if (res.status !== 202) {
|
|
138
|
+
throw new Error(`Buckets report rejected: HTTP ${res.status}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// src/adapters/firestore.ts
|
|
144
|
+
var installed = false;
|
|
145
|
+
function projectFromPath(path) {
|
|
146
|
+
const parts = path.split("/");
|
|
147
|
+
const i = parts.indexOf("projects");
|
|
148
|
+
return i >= 0 && parts[i + 1] ? parts[i + 1] : void 0;
|
|
149
|
+
}
|
|
150
|
+
function hintFrom(target) {
|
|
151
|
+
try {
|
|
152
|
+
const p = typeof target?.path === "string" ? target.path : "";
|
|
153
|
+
if (p) {
|
|
154
|
+
const parts = p.split("/").filter(Boolean);
|
|
155
|
+
const collection = parts.length % 2 === 0 ? parts[parts.length - 2] : parts[parts.length - 1];
|
|
156
|
+
return { collection, projectId: projectFromPath(p) };
|
|
157
|
+
}
|
|
158
|
+
const qo = target?._queryOptions;
|
|
159
|
+
if (qo) {
|
|
160
|
+
const collection = typeof qo.collectionId === "string" ? qo.collectionId : void 0;
|
|
161
|
+
const parent = typeof qo.parentPath?.relativeName === "string" ? qo.parentPath.relativeName : typeof qo.parentPath?.toString === "function" ? String(qo.parentPath.toString()) : "";
|
|
162
|
+
return { collection, projectId: parent ? projectFromPath(parent) : void 0 };
|
|
163
|
+
}
|
|
164
|
+
} catch {
|
|
165
|
+
}
|
|
166
|
+
return void 0;
|
|
167
|
+
}
|
|
168
|
+
function meterSnap(snap, hint) {
|
|
169
|
+
try {
|
|
170
|
+
const size = snap?.size;
|
|
171
|
+
recordReads(typeof size === "number" ? size : 1, hint);
|
|
172
|
+
} catch {
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function meterCount(n, hint) {
|
|
176
|
+
try {
|
|
177
|
+
recordReads(n, hint);
|
|
178
|
+
} catch {
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function installFirestoreMeter(classes) {
|
|
182
|
+
if (installed) return;
|
|
183
|
+
installed = true;
|
|
184
|
+
const { Query, DocumentReference, Transaction, Firestore } = classes;
|
|
185
|
+
const qGet = Query?.prototype?.get;
|
|
186
|
+
if (qGet) {
|
|
187
|
+
Query.prototype.get = async function(...args) {
|
|
188
|
+
const snap = await qGet.apply(this, args);
|
|
189
|
+
meterSnap(snap, hintFrom(this));
|
|
190
|
+
return snap;
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
const dGet = DocumentReference?.prototype?.get;
|
|
194
|
+
if (dGet) {
|
|
195
|
+
DocumentReference.prototype.get = async function(...args) {
|
|
196
|
+
const snap = await dGet.apply(this, args);
|
|
197
|
+
meterCount(1, hintFrom(this));
|
|
198
|
+
return snap;
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
const tGet = Transaction?.prototype?.get;
|
|
202
|
+
if (tGet) {
|
|
203
|
+
Transaction.prototype.get = async function(...args) {
|
|
204
|
+
const res = await tGet.apply(this, args);
|
|
205
|
+
meterSnap(res, hintFrom(args[0]));
|
|
206
|
+
return res;
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
const tGetAll = Transaction?.prototype?.getAll;
|
|
210
|
+
if (tGetAll) {
|
|
211
|
+
Transaction.prototype.getAll = async function(...args) {
|
|
212
|
+
const res = await tGetAll.apply(this, args);
|
|
213
|
+
meterCount(Array.isArray(res) ? res.length : args.length || 1, hintFrom(args[0]));
|
|
214
|
+
return res;
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
const fGetAll = Firestore?.prototype?.getAll;
|
|
218
|
+
if (fGetAll) {
|
|
219
|
+
Firestore.prototype.getAll = async function(...args) {
|
|
220
|
+
const res = await fGetAll.apply(this, args);
|
|
221
|
+
meterCount(Array.isArray(res) ? res.length : args.length || 1, hintFrom(args[0]));
|
|
222
|
+
return res;
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// src/index.ts
|
|
228
|
+
function init(options) {
|
|
229
|
+
const sink2 = options.sink ?? new ReportSink({ apiKey: options.apiKey, endpoint: options.endpoint });
|
|
230
|
+
configureMeter({ sink: sink2, flushIntervalMs: options.flushIntervalMs, onError: options.onError });
|
|
231
|
+
if (options.firestore) installFirestoreMeter(options.firestore);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export { ReportSink, bucket, currentCostTag, enterCostTag, flush, init, init as initBuckets, installFirestoreMeter, recordDeletes, recordReads, recordWrites, refineCostTag, runWithCostTag };
|
|
235
|
+
//# sourceMappingURL=index.mjs.map
|
|
236
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cost-context.ts","../src/cost-meter.ts","../src/sink.ts","../src/adapters/firestore.ts","../src/index.ts"],"names":["sink"],"mappings":";;;AAqBA,IAAM,cAAuB,EAAC;AAC9B,IAAM,KAAA,GAAQ,IAAI,iBAAA,EAA2B;AAGtC,SAAS,cAAA,CAAkB,KAAc,EAAA,EAAgB;AAC9D,EAAA,OAAO,MAAM,GAAA,CAAI,EAAE,GAAG,GAAA,IAAO,EAAE,CAAA;AACjC;AAGO,SAAS,aAAa,GAAA,EAAoB;AAC/C,EAAA,KAAA,CAAM,SAAA,CAAU,EAAE,GAAG,GAAA,EAAK,CAAA;AAC5B;AAGO,SAAS,cAAc,KAAA,EAA+B;AAC3D,EAAA,MAAM,GAAA,GAA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BAAA,CAAsB,OAAA,CAAQ,SAAS,CAAA;AAChE","file":"index.mjs","sourcesContent":["/**\n * cost-context — the request-scoped tag every counted operation attributes\n * itself to. Set it ONCE at a boundary (or wrap a path with `bucket()`); it\n * rides Node's AsyncLocalStorage down through every async fan-out, so one\n * handler that triggers 15 reads attributes all 15 to the same bucket — with\n * zero per-call-site work.\n *\n * Generic by design: unlike a hardcoded product taxonomy, the only meaningful\n * field a consumer sets is the free-form `label` (the bucket name). `feature`\n * is an optional coarse grouping if you want one; nothing here is\n * Crossdeck-specific.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport interface CostTag {\n /** Optional coarse grouping (a caller-defined surface name). */\n feature?: string;\n /** The bucket name — what `bucket()` sets. Drives the report's `byLabel`. */\n label?: string;\n}\n\nconst DEFAULT_TAG: CostTag = {};\nconst store = new AsyncLocalStorage<CostTag>();\n\n/** Run `fn` with `tag` bound for its entire async subtree. */\nexport function runWithCostTag<T>(tag: CostTag, fn: () => T): T {\n return store.run({ ...tag }, fn);\n}\n\n/** Bind a tag for the remainder of the current async context (no closure to wrap). */\nexport function enterCostTag(tag: CostTag): void {\n store.enterWith({ ...tag });\n}\n\n/** Refine the live tag in place (e.g. stamp a feature after the boundary). */\nexport function refineCostTag(patch: Partial<CostTag>): void {\n const cur = store.getStore();\n if (cur) Object.assign(cur, patch);\n}\n\n/** The current tag, or a safe empty default outside any bound context. */\nexport function currentCostTag(): CostTag {\n return store.getStore() ?? DEFAULT_TAG;\n}\n\n/**\n * `bucket(name, fn)` — the headline verb, the `track()` of cost. Run `fn` with\n * every operation inside it attributed to the bucket `name`; the attribution\n * rides the async subtree automatically. The one verb most developers ever touch:\n *\n * await bucket(\"nightly-export\", async () => {\n * const rows = await db.collection(\"events\").where(...).get(); // → \"nightly-export\"\n * });\n */\nexport function bucket<T>(name: string, fn: () => T): T {\n return runWithCostTag({ ...currentCostTag(), label: name }, fn);\n}\n","/**\n * cost-meter — counts operations against the ambient tag and flushes them to the\n * configured Sink cheaply.\n *\n * LOW-OVERHEAD CONTRACT (the thing that warns you about reads must not run them\n * up): counts accumulate in an in-memory buffer and flush periodically — NEVER one\n * network call per counted operation. A flush coalesces the whole window into one\n * report per UTC day and hands it to the Sink. At steady state that is ~1 small\n * request a minute, regardless of how many ops you served.\n *\n * BEST-EFFORT CONTRACT: metering must never throw into your code. Every recorder\n * swallows its own errors; a failed flush drops that window's counts (surfaced via\n * `onError` if you pass one) rather than disturbing the app.\n */\nimport { currentCostTag } from \"./cost-context\";\nimport type { Sink, BucketsReport, OpCounts } from \"./sink\";\n\nexport type OpType = \"read\" | \"write\" | \"delete\";\n\n/** Optional read-site hint — the collection touched, derived at the trap from the\n * path. Lets an UNtagged read cascade to `col:<collection>` instead of vanishing. */\nexport interface CostHint {\n collection?: string;\n projectId?: string;\n}\n\n// NUL separator — a bucket/collection name can contain almost anything except\n// this, so the key never collides with a name that has a \"|\" or \":\" in it.\nconst SEP = \"\\u001f\"; // ASCII Unit Separator\n\n/** key = date <NUL> op <NUL> label → count */\nconst labelBuffer = new Map<string, number>();\n/** key = date <NUL> op <NUL> hour → count */\nconst hourBuffer = new Map<string, number>();\n\nlet sink: Sink | null = null;\nlet flushIntervalMs = 60_000;\nlet onError: ((e: unknown) => void) | null = null;\nlet timer: ReturnType<typeof setInterval> | null = null;\nlet flushing = false;\n/** Safety valve — flush early if a burst fills the buffer between intervals. */\nconst MAX_BUFFER_KEYS = 5_000;\n\nexport interface MeterConfig {\n sink: Sink;\n flushIntervalMs?: number;\n onError?: (e: unknown) => void;\n}\n\n/** Point the meter at a sink. Called by `init()`; pass your own sink to self-host. */\nexport function configureMeter(config: MeterConfig): void {\n sink = config.sink;\n if (config.flushIntervalMs && config.flushIntervalMs > 0) flushIntervalMs = config.flushIntervalMs;\n onError = config.onError ?? null;\n}\n\nconst utcDate = (): string => new Date().toISOString().slice(0, 10);\nconst utcHour = (): string => new Date().toISOString().slice(11, 13);\n\nfunction ensureFlushLoop(): void {\n if (timer) return;\n timer = setInterval(() => void flush(), flushIntervalMs);\n // Don't keep the event loop alive just for metering.\n (timer as { unref?: () => void }).unref?.();\n // Flush the last window on shutdown.\n process.once?.(\"SIGTERM\", () => void flush());\n process.once?.(\"beforeExit\", () => void flush());\n}\n\n/** Count `n` ops of `op` against the live tag. Never throws. */\nexport function recordFirestore(op: OpType, n: number, hint?: CostHint): void {\n try {\n if (!Number.isFinite(n) || n <= 0) return;\n const t = currentCostTag();\n const date = utcDate();\n // CASCADE — every op gets a label, by design (no blind spots): the bucket name\n // wins; else the collection it actually touched (`col:posts`); else\n // \"uncategorized\" as a loud last resort. A read is never invisible.\n const label = t.label || (hint?.collection ? `col:${hint.collection}` : \"uncategorized\");\n const lk = date + SEP + op + SEP + label;\n labelBuffer.set(lk, (labelBuffer.get(lk) ?? 0) + n);\n const hk = date + SEP + op + SEP + utcHour();\n hourBuffer.set(hk, (hourBuffer.get(hk) ?? 0) + n);\n ensureFlushLoop();\n if (labelBuffer.size + hourBuffer.size > MAX_BUFFER_KEYS) void flush();\n } catch {\n /* metering is best-effort — never disturb the caller */\n }\n}\n\n/** Firestore bills a minimum of one read even for an empty result, so 0 counts as 1. */\nexport function recordReads(n: number, hint?: CostHint): void {\n recordFirestore(\"read\", Math.max(n, 1), hint);\n}\nexport function recordWrites(n = 1): void {\n recordFirestore(\"write\", n);\n}\nexport function recordDeletes(n = 1): void {\n recordFirestore(\"delete\", n);\n}\n\nfunction add(target: Record<string, OpCounts>, key: string, op: OpType, n: number): void {\n const bag = (target[key] ??= {});\n bag[op] = (bag[op] ?? 0) + n;\n}\n\n/**\n * Coalesce the buffer into one report per UTC day and hand each to the Sink.\n * Snapshots + clears up front so concurrent records land in the next window.\n * Never throws; a sink failure drops that window (surfaced via `onError`).\n */\nexport async function flush(): Promise<void> {\n if (flushing) return;\n // Not configured (init not called) — drop, don't grow unbounded.\n if (!sink) {\n labelBuffer.clear();\n hourBuffer.clear();\n return;\n }\n if (labelBuffer.size === 0 && hourBuffer.size === 0) return;\n flushing = true;\n\n const labels = new Map(labelBuffer);\n const hours = new Map(hourBuffer);\n labelBuffer.clear();\n hourBuffer.clear();\n\n try {\n const byDate = new Map<string, BucketsReport>();\n const reportFor = (date: string): BucketsReport => {\n let r = byDate.get(date);\n if (!r) {\n r = { date, byLabel: {}, byHour: {} };\n byDate.set(date, r);\n }\n return r;\n };\n for (const [k, n] of labels) {\n const [date, op, label] = k.split(SEP) as [string, OpType, string];\n add(reportFor(date).byLabel, label, op, n);\n }\n for (const [k, n] of hours) {\n const [date, op, hour] = k.split(SEP) as [string, OpType, string];\n add(reportFor(date).byHour!, hour, op, n);\n }\n for (const report of byDate.values()) {\n await sink.flush(report);\n }\n } catch (e) {\n // Drop this window rather than risk a partial/double report on retry.\n onError?.(e);\n } finally {\n flushing = false;\n }\n}\n","/**\n * sink — where the meter sends a coalesced rollup, and the wire shape it sends.\n *\n * Abstracting the sink is what makes Buckets storage-agnostic: the meter never\n * knows where counts go. The DEFAULT sink (`ReportSink`) reports up to Crossdeck's\n * ingest endpoint so the numbers surface on your Crossdeck dashboard. A team that\n * wants to self-host can implement `Sink` against anything (Postgres, a file, your\n * own API) without touching the meter.\n */\n\nexport interface OpCounts {\n read?: number;\n write?: number;\n delete?: number;\n}\n\n/**\n * One coalesced report — the wire contract (see docs/ROLLUP_SCHEMA.md). The meter\n * produces one of these per UTC day in a flush window (usually exactly one).\n */\nexport interface BucketsReport {\n /** UTC day \"YYYY-MM-DD\". */\n date: string;\n /** bucket name → counts. The heart of the report. */\n byLabel: Record<string, OpCounts>;\n /** UTC hour \"HH\" → counts, for the hourly \"did my fix land this hour?\" view. */\n byHour?: Record<string, OpCounts>;\n}\n\n/**\n * A destination for coalesced rollups. `flush` MAY throw on failure — the meter\n * catches it, drops that one window, and never lets it reach your app.\n */\nexport interface Sink {\n flush(report: BucketsReport): Promise<void>;\n}\n\nexport interface ReportSinkConfig {\n /** The project's `cd_sk_` secret key. Server-to-server only. */\n apiKey: string;\n /** Defaults to https://api.cross-deck.com/v1/buckets/report */\n endpoint?: string;\n /** Request timeout (ms); a slow Crossdeck must never stall your flush. */\n timeoutMs?: number;\n}\n\nconst DEFAULT_ENDPOINT = \"https://api.cross-deck.com/v1/buckets/report\";\n\n/**\n * The default sink: POST one coalesced rollup to Crossdeck's ingest endpoint.\n * The ingest folds it into the day's maintained doc with `increment`, so many\n * reports a minute coalesce safely. This path does ZERO database reads — it sends\n * a summary, it does not read. Throws on a non-202 so the meter can log/drop the\n * window; the meter guarantees it never reaches your app.\n */\nexport class ReportSink implements Sink {\n private readonly endpoint: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n\n constructor(config: ReportSinkConfig) {\n this.endpoint = config.endpoint ?? DEFAULT_ENDPOINT;\n this.apiKey = config.apiKey;\n this.timeoutMs = config.timeoutMs ?? 5000;\n }\n\n async flush(report: BucketsReport): Promise<void> {\n const res = await fetch(this.endpoint, {\n method: \"POST\",\n signal: AbortSignal.timeout(this.timeoutMs),\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify(report),\n });\n if (res.status !== 202) {\n throw new Error(`Buckets report rejected: HTTP ${res.status}`);\n }\n }\n}\n","/**\n * adapters/firestore — the universal Firestore read meter (the trap).\n *\n * THE LESSON (learned on a real product): per-call-site `recordReads()`\n * instrumentation MISSES paths. You meter the read sites you're looking at and\n * leave the cron / trigger / ingest path uncounted — often the majority of reads,\n * invisible. Humans tag what they see and miss the path that matters.\n *\n * THE FIX: patch the admin SDK's read methods ONCE. From install onward, EVERY\n * read — anywhere, on any code path — is counted under the ambient tag, with zero\n * per-call-site work and no blind spots.\n *\n * SAFETY CONTRACT — this sits on your production read path, so it is defensive by\n * construction. Each wrapper:\n * 1. calls the REAL method first and captures the result,\n * 2. counts in a try/catch that can never throw into the caller,\n * 3. ALWAYS returns the real result, untouched.\n * It cannot break a read, change a result, or add latency beyond one in-memory\n * counter increment. A wrong count is a measurement error, never a correctness or\n * availability one. Idempotent — calling it twice patches once.\n *\n * COUNTING MODEL — a query returning N docs = N reads (an empty result still bills\n * 1, which the meter enforces). A document get = 1. getAll(...) = the ref count.\n * CollectionReference.get IS Query.get (shared prototype method), so patching Query\n * covers collections with no double-count.\n */\nimport { recordReads, type CostHint } from \"../cost-meter\";\n\nlet installed = false;\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\ntype AnyFn = (...args: any[]) => any;\n\n/**\n * The firebase-admin Firestore classes to patch. Pass the module namespace from\n * `firebase-admin/firestore` — only the prototypes present are patched.\n */\nexport interface FirestoreClasses {\n Query?: { prototype: { get?: AnyFn } };\n DocumentReference?: { prototype: { get?: AnyFn } };\n Transaction?: { prototype: { get?: AnyFn; getAll?: AnyFn } };\n Firestore?: { prototype: { getAll?: AnyFn } };\n}\n\n/** `projects/{id}/…` → the project id, else undefined. Pure string op. */\nfunction projectFromPath(path: string): string | undefined {\n const parts = path.split(\"/\");\n const i = parts.indexOf(\"projects\");\n return i >= 0 && parts[i + 1] ? parts[i + 1] : undefined;\n}\n\n/**\n * Derive { collection, projectId } from the read target's path so an UNtagged read\n * cascades to `col:<collection>` instead of \"uncategorized\". PURE CPU; never reads,\n * never throws. Falls back to firebase-admin's internal `_queryOptions` for filtered\n * queries (which don't expose `.path`).\n */\nfunction hintFrom(target: any): CostHint | undefined {\n try {\n const p = typeof target?.path === \"string\" ? target.path : \"\";\n if (p) {\n const parts = p.split(\"/\").filter(Boolean);\n const collection = parts.length % 2 === 0 ? parts[parts.length - 2] : parts[parts.length - 1];\n return { collection, projectId: projectFromPath(p) };\n }\n const qo = target?._queryOptions;\n if (qo) {\n const collection = typeof qo.collectionId === \"string\" ? qo.collectionId : undefined;\n const parent =\n typeof qo.parentPath?.relativeName === \"string\"\n ? qo.parentPath.relativeName\n : typeof qo.parentPath?.toString === \"function\"\n ? String(qo.parentPath.toString())\n : \"\";\n return { collection, projectId: parent ? projectFromPath(parent) : undefined };\n }\n } catch {\n /* the meter must never throw */\n }\n return undefined;\n}\n\nfunction meterSnap(snap: unknown, hint?: CostHint): void {\n try {\n const size = (snap as { size?: number } | null)?.size;\n recordReads(typeof size === \"number\" ? size : 1, hint);\n } catch {\n /* best-effort */\n }\n}\nfunction meterCount(n: number, hint?: CostHint): void {\n try {\n recordReads(n, hint);\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * Install the universal read meter on the firebase-admin Firestore classes. Call\n * ONCE at process start, before any reads. Pass the namespace from\n * `firebase-admin/firestore` so the exact prototypes the SDK uses are patched:\n *\n * import * as Firestore from \"firebase-admin/firestore\";\n * installFirestoreMeter(Firestore);\n */\nexport function installFirestoreMeter(classes: FirestoreClasses): void {\n if (installed) return;\n installed = true;\n const { Query, DocumentReference, Transaction, Firestore } = classes;\n\n // Query.get — covers Query AND CollectionReference (shared prototype method).\n const qGet = Query?.prototype?.get;\n if (qGet) {\n Query!.prototype.get = async function (this: unknown, ...args: any[]) {\n const snap = await qGet.apply(this, args);\n meterSnap(snap, hintFrom(this));\n return snap;\n };\n }\n\n // DocumentReference.get — a single doc = 1 read.\n const dGet = DocumentReference?.prototype?.get;\n if (dGet) {\n DocumentReference!.prototype.get = async function (this: unknown, ...args: any[]) {\n const snap = await dGet.apply(this, args);\n meterCount(1, hintFrom(this));\n return snap;\n };\n }\n\n // Transaction.get — query or doc; size when present, else 1.\n const tGet = Transaction?.prototype?.get;\n if (tGet) {\n Transaction!.prototype.get = async function (this: unknown, ...args: any[]) {\n const res = await tGet.apply(this, args);\n meterSnap(res, hintFrom(args[0]));\n return res;\n };\n }\n\n // Transaction.getAll(...refs) — one read per ref.\n const tGetAll = Transaction?.prototype?.getAll;\n if (tGetAll) {\n Transaction!.prototype.getAll = async function (this: unknown, ...args: any[]) {\n const res = await tGetAll.apply(this, args);\n meterCount(Array.isArray(res) ? res.length : args.length || 1, hintFrom(args[0]));\n return res;\n };\n }\n\n // Firestore.getAll(...refs) — batched doc reads.\n const fGetAll = Firestore?.prototype?.getAll;\n if (fGetAll) {\n Firestore!.prototype.getAll = async function (this: unknown, ...args: any[]) {\n const res = await fGetAll.apply(this, args);\n meterCount(Array.isArray(res) ? res.length : args.length || 1, hintFrom(args[0]));\n return res;\n };\n }\n}\n\n/** Test-only: reset the install guard so a suite can re-patch fresh prototypes. */\nexport function __resetFirestoreMeterForTests(): void {\n installed = false;\n}\n","/**\n * @cross-deck/buckets — know exactly what every database read costs you, and who\n * caused it. A tiny, never-throws collector for Firestore.\n *\n * The whole footprint a consumer sees:\n * 1. init({ apiKey, firestore }) — configure once, install the trap once\n * 2. bucket(name, fn) — name the read paths that matter\n * 3. (the dashboard shows the rest — and names the ones you haven't yet)\n */\nimport { configureMeter, type MeterConfig } from \"./cost-meter\";\nimport { ReportSink, type Sink } from \"./sink\";\nimport { installFirestoreMeter, type FirestoreClasses } from \"./adapters/firestore\";\n\nexport interface InitOptions {\n /** The project's `cd_sk_` SECRET key. Server-to-server only — never a browser key. */\n apiKey: string;\n /**\n * Pass the namespace from `firebase-admin/firestore` to auto-install the read\n * trap (recommended — this is what makes every read count with no per-call work).\n * Omit it if you'd rather call `installFirestoreMeter()` yourself, or you only\n * use the manual `recordReads()` recorders.\n */\n firestore?: FirestoreClasses;\n /** Override the report endpoint (defaults to Crossdeck's ingest). */\n endpoint?: string;\n /** How often to flush coalesced counts (ms). Default 60_000. */\n flushIntervalMs?: number;\n /** Bring your own sink (self-host the rollups). Defaults to reporting up to Crossdeck. */\n sink?: Sink;\n /** Notified when a flush fails, so a dropped window is never silent. Best-effort. */\n onError?: MeterConfig[\"onError\"];\n}\n\n/**\n * Configure Buckets once, at process start. Points the meter at a sink (Crossdeck's\n * ingest by default) and — if you pass `firestore` — installs the universal read\n * trap so every read counts automatically.\n */\nexport function init(options: InitOptions): void {\n const sink = options.sink ?? new ReportSink({ apiKey: options.apiKey, endpoint: options.endpoint });\n configureMeter({ sink, flushIntervalMs: options.flushIntervalMs, onError: options.onError });\n if (options.firestore) installFirestoreMeter(options.firestore);\n}\n\n/** Alias — reads well next to `bucket()` at a call site. */\nexport { init as initBuckets };\n\n// The headline verb + the lower-level tag controls it is sugar over.\nexport {\n bucket,\n runWithCostTag,\n enterCostTag,\n refineCostTag,\n currentCostTag,\n type CostTag,\n} from \"./cost-context\";\n\n// Manual recorders (for non-Firestore ops, or when you don't install the trap).\nexport {\n recordReads,\n recordWrites,\n recordDeletes,\n flush,\n type CostHint,\n type OpType,\n type MeterConfig,\n} from \"./cost-meter\";\n\n// The trap (the only datastore adapter today) + its class shape.\nexport { installFirestoreMeter, type FirestoreClasses } from \"./adapters/firestore\";\n\n// The sink seam — for self-hosting rollups instead of reporting to Crossdeck.\nexport { ReportSink, type Sink, type BucketsReport, type OpCounts, type ReportSinkConfig } from \"./sink\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,20 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cross-deck/buckets",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Know exactly what every database read costs you — and who caused it. A tiny, never-throws read-cost collector for Firestore.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crossdeck",
|
|
7
|
-
"type": "module",
|
|
8
7
|
"main": "./dist/index.js",
|
|
8
|
+
"module": "./dist/index.mjs",
|
|
9
9
|
"types": "./dist/index.d.ts",
|
|
10
10
|
"exports": {
|
|
11
11
|
".": {
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
|
-
"import": "./dist/index.
|
|
14
|
-
|
|
15
|
-
"./adapters/firestore": {
|
|
16
|
-
"types": "./dist/adapters/firestore.d.ts",
|
|
17
|
-
"import": "./dist/adapters/firestore.js"
|
|
13
|
+
"import": "./dist/index.mjs",
|
|
14
|
+
"require": "./dist/index.js"
|
|
18
15
|
}
|
|
19
16
|
},
|
|
20
17
|
"files": [
|
|
@@ -24,10 +21,10 @@
|
|
|
24
21
|
],
|
|
25
22
|
"sideEffects": false,
|
|
26
23
|
"scripts": {
|
|
27
|
-
"build": "
|
|
24
|
+
"build": "tsup",
|
|
28
25
|
"test": "vitest run",
|
|
29
26
|
"test:watch": "vitest",
|
|
30
|
-
"typecheck": "tsc
|
|
27
|
+
"typecheck": "tsc --noEmit",
|
|
31
28
|
"prepare": "npm run build",
|
|
32
29
|
"prepublishOnly": "npm run build"
|
|
33
30
|
},
|
|
@@ -61,6 +58,7 @@
|
|
|
61
58
|
"devDependencies": {
|
|
62
59
|
"@types/node": "^20.11.0",
|
|
63
60
|
"firebase-admin": "^12.0.0",
|
|
61
|
+
"tsup": "^8.0.0",
|
|
64
62
|
"typescript": "^5.4.0",
|
|
65
63
|
"vitest": "^1.6.0"
|
|
66
64
|
},
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
type AnyFn = (...args: any[]) => any;
|
|
2
|
-
/**
|
|
3
|
-
* The firebase-admin Firestore classes to patch. Pass the module namespace from
|
|
4
|
-
* `firebase-admin/firestore` — only the prototypes present are patched.
|
|
5
|
-
*/
|
|
6
|
-
export interface FirestoreClasses {
|
|
7
|
-
Query?: {
|
|
8
|
-
prototype: {
|
|
9
|
-
get?: AnyFn;
|
|
10
|
-
};
|
|
11
|
-
};
|
|
12
|
-
DocumentReference?: {
|
|
13
|
-
prototype: {
|
|
14
|
-
get?: AnyFn;
|
|
15
|
-
};
|
|
16
|
-
};
|
|
17
|
-
Transaction?: {
|
|
18
|
-
prototype: {
|
|
19
|
-
get?: AnyFn;
|
|
20
|
-
getAll?: AnyFn;
|
|
21
|
-
};
|
|
22
|
-
};
|
|
23
|
-
Firestore?: {
|
|
24
|
-
prototype: {
|
|
25
|
-
getAll?: AnyFn;
|
|
26
|
-
};
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Install the universal read meter on the firebase-admin Firestore classes. Call
|
|
31
|
-
* ONCE at process start, before any reads. Pass the namespace from
|
|
32
|
-
* `firebase-admin/firestore` so the exact prototypes the SDK uses are patched:
|
|
33
|
-
*
|
|
34
|
-
* import * as Firestore from "firebase-admin/firestore";
|
|
35
|
-
* installFirestoreMeter(Firestore);
|
|
36
|
-
*/
|
|
37
|
-
export declare function installFirestoreMeter(classes: FirestoreClasses): void;
|
|
38
|
-
/** Test-only: reset the install guard so a suite can re-patch fresh prototypes. */
|
|
39
|
-
export declare function __resetFirestoreMeterForTests(): void;
|
|
40
|
-
export {};
|
|
41
|
-
//# sourceMappingURL=firestore.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"firestore.d.ts","sourceRoot":"","sources":["../../src/adapters/firestore.ts"],"names":[],"mappings":"AA+BA,KAAK,KAAK,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AAErC;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,EAAE;QAAE,SAAS,EAAE;YAAE,GAAG,CAAC,EAAE,KAAK,CAAA;SAAE,CAAA;KAAE,CAAC;IACvC,iBAAiB,CAAC,EAAE;QAAE,SAAS,EAAE;YAAE,GAAG,CAAC,EAAE,KAAK,CAAA;SAAE,CAAA;KAAE,CAAC;IACnD,WAAW,CAAC,EAAE;QAAE,SAAS,EAAE;YAAE,GAAG,CAAC,EAAE,KAAK,CAAC;YAAC,MAAM,CAAC,EAAE,KAAK,CAAA;SAAE,CAAA;KAAE,CAAC;IAC7D,SAAS,CAAC,EAAE;QAAE,SAAS,EAAE;YAAE,MAAM,CAAC,EAAE,KAAK,CAAA;SAAE,CAAA;KAAE,CAAC;CAC/C;AAwDD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAsDrE;AAED,mFAAmF;AACnF,wBAAgB,6BAA6B,IAAI,IAAI,CAEpD"}
|
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* adapters/firestore — the universal Firestore read meter (the trap).
|
|
3
|
-
*
|
|
4
|
-
* THE LESSON (learned on a real product): per-call-site `recordReads()`
|
|
5
|
-
* instrumentation MISSES paths. You meter the read sites you're looking at and
|
|
6
|
-
* leave the cron / trigger / ingest path uncounted — often the majority of reads,
|
|
7
|
-
* invisible. Humans tag what they see and miss the path that matters.
|
|
8
|
-
*
|
|
9
|
-
* THE FIX: patch the admin SDK's read methods ONCE. From install onward, EVERY
|
|
10
|
-
* read — anywhere, on any code path — is counted under the ambient tag, with zero
|
|
11
|
-
* per-call-site work and no blind spots.
|
|
12
|
-
*
|
|
13
|
-
* SAFETY CONTRACT — this sits on your production read path, so it is defensive by
|
|
14
|
-
* construction. Each wrapper:
|
|
15
|
-
* 1. calls the REAL method first and captures the result,
|
|
16
|
-
* 2. counts in a try/catch that can never throw into the caller,
|
|
17
|
-
* 3. ALWAYS returns the real result, untouched.
|
|
18
|
-
* It cannot break a read, change a result, or add latency beyond one in-memory
|
|
19
|
-
* counter increment. A wrong count is a measurement error, never a correctness or
|
|
20
|
-
* availability one. Idempotent — calling it twice patches once.
|
|
21
|
-
*
|
|
22
|
-
* COUNTING MODEL — a query returning N docs = N reads (an empty result still bills
|
|
23
|
-
* 1, which the meter enforces). A document get = 1. getAll(...) = the ref count.
|
|
24
|
-
* CollectionReference.get IS Query.get (shared prototype method), so patching Query
|
|
25
|
-
* covers collections with no double-count.
|
|
26
|
-
*/
|
|
27
|
-
import { recordReads } from "../cost-meter.js";
|
|
28
|
-
let installed = false;
|
|
29
|
-
/** `projects/{id}/…` → the project id, else undefined. Pure string op. */
|
|
30
|
-
function projectFromPath(path) {
|
|
31
|
-
const parts = path.split("/");
|
|
32
|
-
const i = parts.indexOf("projects");
|
|
33
|
-
return i >= 0 && parts[i + 1] ? parts[i + 1] : undefined;
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Derive { collection, projectId } from the read target's path so an UNtagged read
|
|
37
|
-
* cascades to `col:<collection>` instead of "uncategorized". PURE CPU; never reads,
|
|
38
|
-
* never throws. Falls back to firebase-admin's internal `_queryOptions` for filtered
|
|
39
|
-
* queries (which don't expose `.path`).
|
|
40
|
-
*/
|
|
41
|
-
function hintFrom(target) {
|
|
42
|
-
try {
|
|
43
|
-
const p = typeof target?.path === "string" ? target.path : "";
|
|
44
|
-
if (p) {
|
|
45
|
-
const parts = p.split("/").filter(Boolean);
|
|
46
|
-
const collection = parts.length % 2 === 0 ? parts[parts.length - 2] : parts[parts.length - 1];
|
|
47
|
-
return { collection, projectId: projectFromPath(p) };
|
|
48
|
-
}
|
|
49
|
-
const qo = target?._queryOptions;
|
|
50
|
-
if (qo) {
|
|
51
|
-
const collection = typeof qo.collectionId === "string" ? qo.collectionId : undefined;
|
|
52
|
-
const parent = typeof qo.parentPath?.relativeName === "string"
|
|
53
|
-
? qo.parentPath.relativeName
|
|
54
|
-
: typeof qo.parentPath?.toString === "function"
|
|
55
|
-
? String(qo.parentPath.toString())
|
|
56
|
-
: "";
|
|
57
|
-
return { collection, projectId: parent ? projectFromPath(parent) : undefined };
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
catch {
|
|
61
|
-
/* the meter must never throw */
|
|
62
|
-
}
|
|
63
|
-
return undefined;
|
|
64
|
-
}
|
|
65
|
-
function meterSnap(snap, hint) {
|
|
66
|
-
try {
|
|
67
|
-
const size = snap?.size;
|
|
68
|
-
recordReads(typeof size === "number" ? size : 1, hint);
|
|
69
|
-
}
|
|
70
|
-
catch {
|
|
71
|
-
/* best-effort */
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
function meterCount(n, hint) {
|
|
75
|
-
try {
|
|
76
|
-
recordReads(n, hint);
|
|
77
|
-
}
|
|
78
|
-
catch {
|
|
79
|
-
/* best-effort */
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* Install the universal read meter on the firebase-admin Firestore classes. Call
|
|
84
|
-
* ONCE at process start, before any reads. Pass the namespace from
|
|
85
|
-
* `firebase-admin/firestore` so the exact prototypes the SDK uses are patched:
|
|
86
|
-
*
|
|
87
|
-
* import * as Firestore from "firebase-admin/firestore";
|
|
88
|
-
* installFirestoreMeter(Firestore);
|
|
89
|
-
*/
|
|
90
|
-
export function installFirestoreMeter(classes) {
|
|
91
|
-
if (installed)
|
|
92
|
-
return;
|
|
93
|
-
installed = true;
|
|
94
|
-
const { Query, DocumentReference, Transaction, Firestore } = classes;
|
|
95
|
-
// Query.get — covers Query AND CollectionReference (shared prototype method).
|
|
96
|
-
const qGet = Query?.prototype?.get;
|
|
97
|
-
if (qGet) {
|
|
98
|
-
Query.prototype.get = async function (...args) {
|
|
99
|
-
const snap = await qGet.apply(this, args);
|
|
100
|
-
meterSnap(snap, hintFrom(this));
|
|
101
|
-
return snap;
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
// DocumentReference.get — a single doc = 1 read.
|
|
105
|
-
const dGet = DocumentReference?.prototype?.get;
|
|
106
|
-
if (dGet) {
|
|
107
|
-
DocumentReference.prototype.get = async function (...args) {
|
|
108
|
-
const snap = await dGet.apply(this, args);
|
|
109
|
-
meterCount(1, hintFrom(this));
|
|
110
|
-
return snap;
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
// Transaction.get — query or doc; size when present, else 1.
|
|
114
|
-
const tGet = Transaction?.prototype?.get;
|
|
115
|
-
if (tGet) {
|
|
116
|
-
Transaction.prototype.get = async function (...args) {
|
|
117
|
-
const res = await tGet.apply(this, args);
|
|
118
|
-
meterSnap(res, hintFrom(args[0]));
|
|
119
|
-
return res;
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
// Transaction.getAll(...refs) — one read per ref.
|
|
123
|
-
const tGetAll = Transaction?.prototype?.getAll;
|
|
124
|
-
if (tGetAll) {
|
|
125
|
-
Transaction.prototype.getAll = async function (...args) {
|
|
126
|
-
const res = await tGetAll.apply(this, args);
|
|
127
|
-
meterCount(Array.isArray(res) ? res.length : args.length || 1, hintFrom(args[0]));
|
|
128
|
-
return res;
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
// Firestore.getAll(...refs) — batched doc reads.
|
|
132
|
-
const fGetAll = Firestore?.prototype?.getAll;
|
|
133
|
-
if (fGetAll) {
|
|
134
|
-
Firestore.prototype.getAll = async function (...args) {
|
|
135
|
-
const res = await fGetAll.apply(this, args);
|
|
136
|
-
meterCount(Array.isArray(res) ? res.length : args.length || 1, hintFrom(args[0]));
|
|
137
|
-
return res;
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
/** Test-only: reset the install guard so a suite can re-patch fresh prototypes. */
|
|
142
|
-
export function __resetFirestoreMeterForTests() {
|
|
143
|
-
installed = false;
|
|
144
|
-
}
|
|
145
|
-
//# sourceMappingURL=firestore.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"firestore.js","sourceRoot":"","sources":["../../src/adapters/firestore.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAAE,WAAW,EAAiB,MAAM,kBAAkB,CAAC;AAE9D,IAAI,SAAS,GAAG,KAAK,CAAC;AAgBtB,0EAA0E;AAC1E,SAAS,eAAe,CAAC,IAAY;IACnC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC9B,MAAM,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACpC,OAAO,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3D,CAAC;AAED;;;;;GAKG;AACH,SAAS,QAAQ,CAAC,MAAW;IAC3B,IAAI,CAAC;QACH,MAAM,CAAC,GAAG,OAAO,MAAM,EAAE,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9D,IAAI,CAAC,EAAE,CAAC;YACN,MAAM,KAAK,GA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5C,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAClF,OAAO,GAAG,CAAC;QACb,CAAC,CAAC;IACJ,CAAC;AACH,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,6BAA6B;IAC3C,SAAS,GAAG,KAAK,CAAC;AACpB,CAAC"}
|
package/dist/cost-context.d.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
export interface CostTag {
|
|
2
|
-
/** Optional coarse grouping (a caller-defined surface name). */
|
|
3
|
-
feature?: string;
|
|
4
|
-
/** The bucket name — what `bucket()` sets. Drives the report's `byLabel`. */
|
|
5
|
-
label?: string;
|
|
6
|
-
}
|
|
7
|
-
/** Run `fn` with `tag` bound for its entire async subtree. */
|
|
8
|
-
export declare function runWithCostTag<T>(tag: CostTag, fn: () => T): T;
|
|
9
|
-
/** Bind a tag for the remainder of the current async context (no closure to wrap). */
|
|
10
|
-
export declare function enterCostTag(tag: CostTag): void;
|
|
11
|
-
/** Refine the live tag in place (e.g. stamp a feature after the boundary). */
|
|
12
|
-
export declare function refineCostTag(patch: Partial<CostTag>): void;
|
|
13
|
-
/** The current tag, or a safe empty default outside any bound context. */
|
|
14
|
-
export declare function currentCostTag(): CostTag;
|
|
15
|
-
/**
|
|
16
|
-
* `bucket(name, fn)` — the headline verb, the `track()` of cost. Run `fn` with
|
|
17
|
-
* every operation inside it attributed to the bucket `name`; the attribution
|
|
18
|
-
* rides the async subtree automatically. The one verb most developers ever touch:
|
|
19
|
-
*
|
|
20
|
-
* await bucket("nightly-export", async () => {
|
|
21
|
-
* const rows = await db.collection("events").where(...).get(); // → "nightly-export"
|
|
22
|
-
* });
|
|
23
|
-
*/
|
|
24
|
-
export declare function bucket<T>(name: string, fn: () => T): T;
|
|
25
|
-
//# sourceMappingURL=cost-context.d.ts.map
|