@gusto/baerly-storage 0.5.0 → 0.7.0
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 +47 -124
- package/dist/API.md +161 -511
- package/dist/CHANGELOG.md +1148 -307
- package/dist/RECIPES.md +398 -80
- package/dist/THIRD-PARTY-LICENSES.txt +5 -26
- package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
- package/dist/app-config.d.ts +31 -1
- package/dist/app-config.js +1 -2
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +33 -28
- package/dist/auth.js +549 -985
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +130 -138
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +97 -22
- package/dist/capacity-warning-header-BlVopyiI.js +16 -0
- package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
- package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
- package/dist/client-react.d.ts +67 -20
- package/dist/client-react.js +240 -54
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +5 -4
- package/dist/client.js +51 -16
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
- package/dist/cloudflare-CKHYXccw.js.map +1 -0
- package/dist/cloudflare.d.ts +106 -71
- package/dist/cloudflare.js +334 -271
- package/dist/cloudflare.js.map +1 -1
- package/dist/code-resolution-CL_7L0wS.js +22 -0
- package/dist/code-resolution-CL_7L0wS.js.map +1 -0
- package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
- package/dist/config-DEzInG6M.js +4035 -0
- package/dist/config-DEzInG6M.js.map +1 -0
- package/dist/constants-D3GSH3tc.js +469 -0
- package/dist/constants-D3GSH3tc.js.map +1 -0
- package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
- package/dist/context-rlpSnHFA.js.map +1 -0
- package/dist/cost-B52llVDx.js +330 -0
- package/dist/cost-B52llVDx.js.map +1 -0
- package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
- package/dist/current-json-CC6lE4Aj.js.map +1 -0
- package/dist/db-plFUNTSF.d.ts +130 -0
- package/dist/db-read-seams-BSs0m1z1.js +3261 -0
- package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
- package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
- package/dist/deploy-Obj4nE-Z.js.map +1 -0
- package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
- package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
- package/dist/dev-landing-CD-si4dW.js +50 -0
- package/dist/dev-landing-CD-si4dW.js.map +1 -0
- package/dist/dev-vite.d.ts +38 -39
- package/dist/dev-vite.js +67 -36
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +3 -2
- package/dist/dev.js +2 -1
- package/dist/doctor-BA0i-YAN.js +270 -0
- package/dist/doctor-BA0i-YAN.js.map +1 -0
- package/dist/dump-D1vX8ozg.js +133 -0
- package/dist/dump-D1vX8ozg.js.map +1 -0
- package/dist/errors-7Rk1HGCE.js +160 -0
- package/dist/errors-7Rk1HGCE.js.map +1 -0
- package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
- package/dist/export-BVL2EvYE.js.map +1 -0
- package/dist/fsck-BWkPgov4.js +145 -0
- package/dist/fsck-BWkPgov4.js.map +1 -0
- package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
- package/dist/gcs.d.ts +30 -0
- package/dist/gcs.js +1 -0
- package/dist/goog4-signer-CeLIABoE.js +331 -0
- package/dist/goog4-signer-CeLIABoE.js.map +1 -0
- package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
- package/dist/http-Z5rZyYMX.js.map +1 -0
- package/dist/http-transport-DNUM8kU-.js +1299 -0
- package/dist/http-transport-DNUM8kU-.js.map +1 -0
- package/dist/http.d.ts +366 -294
- package/dist/http.js +2 -2
- package/dist/index-JJrIu1pO.d.ts +135 -0
- package/dist/index-LEgHN0qJ.d.ts +50 -0
- package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
- package/dist/index.d.ts +27 -6
- package/dist/index.js +3 -5
- package/dist/inspect-BTsVYZKd.js +196 -0
- package/dist/inspect-BTsVYZKd.js.map +1 -0
- package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
- package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
- package/dist/ledger-Dj_bGgo0.js +192 -0
- package/dist/ledger-Dj_bGgo0.js.map +1 -0
- package/dist/legacy-names-DgZBtgOh.js +47 -0
- package/dist/legacy-names-DgZBtgOh.js.map +1 -0
- package/dist/log-C9W15Dfo.d.ts +94 -0
- package/dist/log-tail-DWJbneBF.js +142 -0
- package/dist/log-tail-DWJbneBF.js.map +1 -0
- package/dist/log-walk-C-vA-WGJ.js +111 -0
- package/dist/log-walk-C-vA-WGJ.js.map +1 -0
- package/dist/maintenance-Dd-Yakqj.js +1709 -0
- package/dist/maintenance-Dd-Yakqj.js.map +1 -0
- package/dist/maintenance-DevB6z4e.js +2237 -0
- package/dist/maintenance-DevB6z4e.js.map +1 -0
- package/dist/maintenance.d.ts +100 -3
- package/dist/maintenance.js +1 -3
- package/dist/node.d.ts +130 -142
- package/dist/node.js +4 -3
- package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
- package/dist/observability-C-ISCCLE.js.map +1 -0
- package/dist/observability.d.ts +27 -3
- package/dist/observability.js +3 -3
- package/dist/path-segment-DBXG26PW.js +363 -0
- package/dist/path-segment-DBXG26PW.js.map +1 -0
- package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
- package/dist/plan-BvQbaNMe.js.map +1 -0
- package/dist/request-CRWiTrza.js +272 -0
- package/dist/request-CRWiTrza.js.map +1 -0
- package/dist/restore-U6Im8V1V.js +1467 -0
- package/dist/restore-U6Im8V1V.js.map +1 -0
- package/dist/retry-OBtLB2GC.js +126 -0
- package/dist/retry-OBtLB2GC.js.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
- package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
- package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
- package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
- package/dist/s3.d.ts +20 -7
- package/dist/s3.js +4 -5
- package/dist/s3.js.map +1 -1
- package/dist/sha256-4FfGQNPw.js +22 -0
- package/dist/sha256-4FfGQNPw.js.map +1 -0
- package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
- package/dist/shared-secret-Vkur-8r0.js.map +1 -0
- package/dist/sigv4-sign-5IUflUD_.js +507 -0
- package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
- package/dist/snapshot-CknzkDM0.js +148 -0
- package/dist/snapshot-CknzkDM0.js.map +1 -0
- package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
- package/dist/src-Actga-bO.js.map +1 -0
- package/dist/src-D0MQfvOp.js +812 -0
- package/dist/src-D0MQfvOp.js.map +1 -0
- package/dist/src-Dr9uo3dc.js +501 -0
- package/dist/src-Dr9uo3dc.js.map +1 -0
- package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
- package/dist/subcommand-BLoF66dG.js.map +1 -0
- package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
- package/dist/time-DRxTP9iv.js.map +1 -0
- package/dist/types-suVbsEWS.d.ts +116 -0
- package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
- package/dist/usage-CPzVhrQr.js.map +1 -0
- package/dist/uuid-BuT_c404.js +333 -0
- package/dist/uuid-BuT_c404.js.map +1 -0
- package/dist/verifier-Bmlmndzo.d.ts +95 -0
- package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
- package/dist/wire-DndvKU-K.js.map +1 -0
- package/package.json +96 -69
- package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
- package/dist/bytes-BXdamO3L.js +0 -11
- package/dist/bytes-BXdamO3L.js.map +0 -1
- package/dist/cloudflare-DzKBrUlg.js.map +0 -1
- package/dist/config-1tv0-Yzm.js +0 -2693
- package/dist/config-1tv0-Yzm.js.map +0 -1
- package/dist/constants-CfeMWQWk.js +0 -222
- package/dist/constants-CfeMWQWk.js.map +0 -1
- package/dist/context-DRZ3tZ5l.js.map +0 -1
- package/dist/cost-DSMIVqzL.js +0 -203
- package/dist/cost-DSMIVqzL.js.map +0 -1
- package/dist/current-json-C6nhPOm1.js.map +0 -1
- package/dist/db-DsPkOVEH.d.ts +0 -254
- package/dist/deploy-DonTr-CV.js.map +0 -1
- package/dist/doctor-DSIyCDg_.js +0 -346
- package/dist/doctor-DSIyCDg_.js.map +0 -1
- package/dist/dump-Bh5k26VQ.js +0 -94
- package/dist/dump-Bh5k26VQ.js.map +0 -1
- package/dist/errors-Dfa3p78c.js +0 -78
- package/dist/errors-Dfa3p78c.js.map +0 -1
- package/dist/export-DtF5tDIM.js +0 -401
- package/dist/export-DtF5tDIM.js.map +0 -1
- package/dist/fsck-D_djMO5D.js +0 -279
- package/dist/fsck-D_djMO5D.js.map +0 -1
- package/dist/http-DGd5tbNs.js.map +0 -1
- package/dist/index-0rZcMBwy.d.ts +0 -115
- package/dist/index-BNRh23K9.d.ts +0 -162
- package/dist/index-BYk9oCNf.d.ts +0 -1112
- package/dist/indexes-Dn9hbGQG.d.ts +0 -22
- package/dist/inspect-6WZ-pC7-.js +0 -133
- package/dist/inspect-6WZ-pC7-.js.map +0 -1
- package/dist/log-tail-D98U1JBo.js +0 -522
- package/dist/log-tail-D98U1JBo.js.map +0 -1
- package/dist/maintenance-B4Dki6Ig.js +0 -2157
- package/dist/maintenance-B4Dki6Ig.js.map +0 -1
- package/dist/maintenance-B_e0T99L.d.ts +0 -537
- package/dist/maintenance-C7coQp4c.js +0 -1418
- package/dist/maintenance-C7coQp4c.js.map +0 -1
- package/dist/normalize-rjnZLwS4.js +0 -133
- package/dist/normalize-rjnZLwS4.js.map +0 -1
- package/dist/observability-BmflLCdF.js.map +0 -1
- package/dist/plan-a7PJHBCy.js.map +0 -1
- package/dist/query-rAtXNQQB.js +0 -1773
- package/dist/query-rAtXNQQB.js.map +0 -1
- package/dist/rebuild-index-BVzQSZlm.js +0 -81
- package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
- package/dist/request-u0M51mhJ.js +0 -72
- package/dist/request-u0M51mhJ.js.map +0 -1
- package/dist/restore-R-4rbciV.js +0 -778
- package/dist/restore-R-4rbciV.js.map +0 -1
- package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
- package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
- package/dist/shared-secret-DgEicd3x.js.map +0 -1
- package/dist/src-BL_JoPTn.js.map +0 -1
- package/dist/src-CYHFDrKz.js +0 -536
- package/dist/src-CYHFDrKz.js.map +0 -1
- package/dist/src-DYZ4H1aF.js +0 -392
- package/dist/src-DYZ4H1aF.js.map +0 -1
- package/dist/subcommand-DoDA-K7d.js.map +0 -1
- package/dist/time-DUqvFMHq.js.map +0 -1
- package/dist/usage-DBV1eQHC.js.map +0 -1
- package/dist/validate-DtljsCh1.js.map +0 -1
- package/dist/wire-izfGZDvr.js.map +0 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { a as setRequestLedgerResolver, i as setRequestHoldResolver } from "./ledger-Dj_bGgo0.js";
|
|
1
2
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
-
|
|
3
|
+
// packages/protocol/src/metrics.ts
|
|
3
4
|
/**
|
|
4
5
|
* No-op recorder. Safe default when no operator sink is wired —
|
|
5
6
|
* emission sites that read `getCurrentContext()?.recorder` fall
|
|
@@ -10,8 +11,7 @@ const noopMetricsRecorder = {
|
|
|
10
11
|
gauge: () => {},
|
|
11
12
|
histogram: () => {}
|
|
12
13
|
};
|
|
13
|
-
|
|
14
|
-
//#region packages/server/src/observability/recorder.ts
|
|
14
|
+
// packages/server/src/observability/recorder.ts
|
|
15
15
|
/**
|
|
16
16
|
* Implementation. Allocations:
|
|
17
17
|
*
|
|
@@ -87,14 +87,10 @@ var RequestScopedMetricsRecorder = class {
|
|
|
87
87
|
for (const row of this.#gauges) out[row.name] = row.value;
|
|
88
88
|
const buckets = /* @__PURE__ */ new Map();
|
|
89
89
|
for (const row of this.#histograms) {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
sum: 0
|
|
95
|
-
};
|
|
96
|
-
buckets.set(row.name, agg);
|
|
97
|
-
}
|
|
90
|
+
const agg = buckets.getOrInsertComputed(row.name, () => ({
|
|
91
|
+
count: 0,
|
|
92
|
+
sum: 0
|
|
93
|
+
}));
|
|
98
94
|
agg.count += 1;
|
|
99
95
|
agg.sum += row.value;
|
|
100
96
|
}
|
|
@@ -105,8 +101,7 @@ var RequestScopedMetricsRecorder = class {
|
|
|
105
101
|
return out;
|
|
106
102
|
}
|
|
107
103
|
};
|
|
108
|
-
|
|
109
|
-
//#region packages/server/src/observability/context.ts
|
|
104
|
+
// packages/server/src/observability/context.ts
|
|
110
105
|
/**
|
|
111
106
|
* Per-request observability context.
|
|
112
107
|
*
|
|
@@ -158,7 +153,9 @@ const createObservabilityContext = (init = {}) => ({
|
|
|
158
153
|
started_at: performance.now(),
|
|
159
154
|
fields: /* @__PURE__ */ new Map(),
|
|
160
155
|
recorder: init.recorder ?? new RequestScopedMetricsRecorder(),
|
|
161
|
-
...init.maintenance !== void 0 && { maintenance: init.maintenance }
|
|
156
|
+
...init.maintenance !== void 0 && { maintenance: init.maintenance },
|
|
157
|
+
...init.ledger !== void 0 && { ledger: init.ledger },
|
|
158
|
+
...init.readEnvelope !== void 0 && { readEnvelope: init.readEnvelope }
|
|
162
159
|
});
|
|
163
160
|
/**
|
|
164
161
|
* Module-level slot. One instance per process — the Workers
|
|
@@ -166,6 +163,8 @@ const createObservabilityContext = (init = {}) => ({
|
|
|
166
163
|
* per-request scope, so cross-request bleed is impossible there.
|
|
167
164
|
*/
|
|
168
165
|
const als = new AsyncLocalStorage();
|
|
166
|
+
setRequestLedgerResolver(() => als.getStore()?.ledger);
|
|
167
|
+
setRequestHoldResolver(() => als.getStore()?.hold);
|
|
169
168
|
/**
|
|
170
169
|
* Run `fn` with `ctx` active as the current observability context.
|
|
171
170
|
* Inside `fn` (and any `await`-chained continuation rooted in `fn`),
|
|
@@ -182,7 +181,8 @@ const als = new AsyncLocalStorage();
|
|
|
182
181
|
const runWithContext = (ctx, fn) => als.run(ctx, fn);
|
|
183
182
|
/** Returns the currently-active context, or `undefined` outside one. */
|
|
184
183
|
const getCurrentContext = () => als.getStore();
|
|
185
|
-
|
|
186
|
-
|
|
184
|
+
/** The active context's recorder, or the no-op recorder outside one. */
|
|
185
|
+
const ctxMetrics = () => getCurrentContext()?.recorder ?? noopMetricsRecorder;
|
|
186
|
+
export { noopMetricsRecorder as a, runWithContext as i, ctxMetrics as n, getCurrentContext as r, createObservabilityContext as t };
|
|
187
187
|
|
|
188
|
-
//# sourceMappingURL=context-
|
|
188
|
+
//# sourceMappingURL=context-rlpSnHFA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-rlpSnHFA.js","names":[],"sources":["../packages/protocol/src/metrics.ts","../packages/server/src/observability/recorder.ts","../packages/server/src/observability/context.ts"],"sourcesContent":["/**\n * `MetricsRecorder` — internal emission contract for the load-bearing\n * kernel metrics. Writer / compactor / GC emit through\n * an instance of this interface; in production the instance is the\n * per-request `RequestScopedMetricsRecorder` on the active\n * `ObservabilityContext`, and emissions flow onto the canonical line\n * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and\n * wrap their workload in `runWithContext` to attach it.\n *\n * Operators do not wire a custom sink against this interface — the\n * operator's view of kernel emissions is the canonical line on\n * stdout (one JSON object per HTTP request).\n *\n * **Naming convention** matches the load-bearing metrics:\n * - `db.write.class_a_ops_per_logical_write` — histogram (recommend p99 alert ~5; not gated).\n * The committing log create, 1 per commit. Idle-reader cost is unchanged.\n * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)\n * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)\n * - `db.write.ambiguous_commit_total` — counter, labelled by `collection`\n * and `cleanup` (`deleted` / `failed`). A committing create won at a\n * sequence already certified deleted, so the commit failed with\n * `AmbiguousCommit` rather than acknowledging a mutation whose\n * visibility cannot be determined.\n * `cleanup` reports whether the phantom log object was reclaimed. Any\n * sustained rate means writers are pausing across a fold plus a\n * retirement pass; a `failed` rate leaves behind sub-floor objects that\n * leak permanently — they sit below `log_delete_floor`, where\n * computed-range retirement starts, so nothing revisits them\n * - `db.write.delete_floor_check_skipped_total` — counter, labelled by\n * `collection`. The post-create re-read of `current.json` inside\n * `Writer#assertCommitAboveDeleteFloor` failed with a non-abort error, so\n * the delete-floor check was skipped for that commit rather than\n * evaluated. A sustained rate means the check is not covering the writes\n * it exists to protect, even though no individual commit is rejected.\n * - `db.write.post_commit_refused_total` — counter, labelled by\n * `collection` and `phase` (`delete-floor-check`, the only post-commit\n * step). The request ledger refused a storage call of a step that runs\n * after a known commit; the step was skipped and the commit stands. The\n * floor check runs inside the commit's ledger hold, so a count means a call outside every hold, or a\n * platform cap below the ledger's limit, cut into it.\n * - `db.write.unresolved_create_total` — counter, labelled by\n * `collection`. A rejected committing create could not be resolved by\n * readback, so the commit failed with `AmbiguousCommit`.\n * - `db.write.maintenance_dispatch_failed_total` — counter, labelled by\n * `collection`. The maintenance dispatcher threw or rejected after a\n * durable commit, so that write's maintenance tick did not run.\n * - `db.write.insert_replayed_total` — counter, labelled by `collection`.\n * An SDK-minted insert (`mintedId`) found its identical row already\n * stored and returned it as the original success, committing nothing.\n * A rate tracks clients retransmitting inserts after lost responses.\n * - `db.read.decoded_entries_total` / `db.read.live_documents_total` /\n * `db.read.returned_rows_total` — counters, labelled by `collection`,\n * emitted together by every collection read (a read terminal, or a\n * write verb's pre-commit read). Units:\n * - decoded entries: snapshot rows plus log entries the fold decoded,\n * before predicate and limit. Entries, not documents: an `_id`\n * updated twice since the last fold counts three times, and a\n * deleted row still counts its `I` and its `D`.\n * - live documents: distinct documents live once the fold completes,\n * before predicate, order and limit.\n * - returned rows: rows left after predicate, order and limit — the\n * rows a read returns, the rows `count()` counts, or the rows a write\n * verb's read matched.\n * A never-provisioned collection reports zeros. A point read still\n * folds the whole collection, so a large decoded count beside one\n * returned row is that read's actual work. No threshold or cap attaches.\n * - `db.manifest.lag_window_depth` — gauge (alert at >100)\n * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)\n * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)\n * - `db.compact.entries_folded` — histogram (entries folded per run)\n * - `db.compaction.deferred_total` — counter, labelled by `collection`,\n * `dimension` (`bytes` / `rows`) and `gate` (`pre-fold` / `rebuild`).\n * The write-tick fold hit the snapshot ceiling (`C` / `E`) and did not\n * run: `log_seq_start` and log retention are frozen until it folds again.\n * Emitted once per deferral by the write-tick runner, never by compact().\n * - `db.compaction.deferred_bytes_total` / `db.compaction.deferred_rows_total`\n * — the same event under a per-dimension name, labelled by `collection`\n * and `gate`, because the canonical line keys counters by name and drops\n * labels\n * - `db.gc.swept_total` — counter (labelled by reason)\n * - `db.gc.dropped_total` — counter (labelled by cause: `stale-generation`\n * / `still-live`). Candidates resolved out of the ledger WITHOUT a\n * DELETE because the sweep gate re-checked them and found them no\n * longer eligible. A drop frees no bytes, so this is deliberately\n * not folded into `db.gc.swept_total` — a pass that reclaimed\n * nothing must not read as productive. One `stale-generation` spike\n * per restore or upgrade is expected; a sustained `still-live` rate\n * means the mark phase is misjudging liveness\n *\n * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase\n * snake_case segments. Labels are flat\n * `Readonly<Record<string, string>>` — no numbers, no nested objects.\n *\n * Metric emissions never throw on the hot path; the default\n * `noopMetricsRecorder` cannot throw.\n */\nexport interface MetricsRecorder {\n /** Monotonically-incrementing event count. */\n counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Point-in-time value. */\n gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Distribution sample. */\n histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n}\n\n/**\n * No-op recorder. Safe default when no operator sink is wired —\n * emission sites that read `getCurrentContext()?.recorder` fall\n * back to this outside an active `runWithContext` scope.\n */\nexport const noopMetricsRecorder: MetricsRecorder = {\n counter: (): void => {},\n gauge: (): void => {},\n histogram: (): void => {},\n};\n","/**\n * Per-request `MetricsRecorder` whose primary product is the\n * canonical-line attribute set.\n *\n * `RequestScopedMetricsRecorder` is a deliberately tiny extension to\n * the {@link MetricsRecorder} interface that adds two readers\n * (`snapshot()` for tests / debug, `summarize()` for the canonical\n * log line). Every method just appends a row to a flat array — no\n * sorting, no JSON, no aggregation on the hot path. The work happens\n * once at end-of-request inside `summarize()`.\n *\n * The shape mirrors {@link InMemoryMetricsRecorder} from\n * `../_internal/in-memory-metrics.ts` but adds the per-request product. We do\n * NOT extend that class — composition over inheritance, and the\n * observability layer wants `summarize()` to be the only side-channel.\n */\n\nimport type { MetricsRecorder } from \"@baerly/protocol\";\n\n/** One observation row, kept in insertion order. */\nexport interface ObservationRow {\n readonly name: string;\n readonly value: number;\n readonly labels: Readonly<Record<string, string>>;\n}\n\n/** Result of {@link RequestScopedMetricsRecorder.snapshot}. */\nexport interface MetricsSnapshot {\n readonly counters: readonly ObservationRow[];\n readonly gauges: readonly ObservationRow[];\n readonly histograms: readonly ObservationRow[];\n}\n\n/** Flat per-metric aggregation as consumed by the canonical line. */\nexport type MetricsSummary = Record<string, number>;\n\n/**\n * Implementation. Allocations:\n *\n * - Three arrays at construction time, grown on each emission.\n * - On `summarize()` we materialize one extra `Map` per metric-\n * family (counter / gauge / histogram) plus a copy of each\n * histogram's values for sorting.\n *\n * CPU-ms budget on Workers is tight; we deliberately defer all of\n * that to flush time.\n */\nexport class RequestScopedMetricsRecorder implements MetricsRecorder {\n readonly #counters: ObservationRow[] = [];\n readonly #gauges: ObservationRow[] = [];\n readonly #histograms: ObservationRow[] = [];\n\n counter(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#counters.push({ name, value, labels });\n }\n gauge(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#gauges.push({ name, value, labels });\n }\n histogram(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#histograms.push({ name, value, labels });\n }\n\n /**\n * Read-only view of every observation seen so far. Intended for\n * tests + structured debugging; the canonical-line flusher uses\n * {@link summarize} instead.\n *\n * @internal Not part of the published observability surface; tests\n * import via relative path. Production reads via {@link summarize}.\n */\n snapshot(): MetricsSnapshot {\n return {\n counters: this.#counters.slice(),\n gauges: this.#gauges.slice(),\n histograms: this.#histograms.slice(),\n };\n }\n\n /**\n * Flat aggregation, keyed by metric name with suffixes baked in:\n *\n * - Counter `db.foo.bar` → `db.foo.bar_total` (sum of all observations)\n * - Gauge `db.foo.bar` → `db.foo.bar` (last value seen)\n * - Histogram `db.foo.bar` → `db.foo.bar_count` (number of observations)\n * + `db.foo.bar_sum` (sum of values)\n *\n * Histogram aggregation is a single pass in insertion order — no\n * sort. Returns numbers only — labels are NOT collapsed into keys;\n * if a metric is emitted with different label sets, its\n * observations are aggregated together by `name` alone. The\n * canonical line is per-request anyway; per-label fan-out belongs\n * to the operator's long-term recorder.\n */\n summarize(): MetricsSummary {\n const out: MetricsSummary = {};\n\n // Counters: sum.\n for (const row of this.#counters) {\n // Counter convention: prefer the emitter's name verbatim. If the\n // emitter already namespaced its counter with `_total` (Prometheus\n // convention — see packages/server/src/observability/storage.ts),\n // do not double-append. Otherwise append for canonical-line\n // consumers that key off the `_total` suffix.\n const key = row.name.endsWith(\"_total\") ? row.name : `${row.name}_total`;\n out[key] = (out[key] ?? 0) + row.value;\n }\n\n // Gauges: last write wins per name (observations are in\n // insertion order; iterate forward and overwrite).\n for (const row of this.#gauges) {\n out[row.name] = row.value;\n }\n\n // Histograms: bucket-by-name, then emit `_count` + `_sum`.\n const buckets = new Map<string, { count: number; sum: number }>();\n for (const row of this.#histograms) {\n const agg = buckets.getOrInsertComputed(row.name, () => ({ count: 0, sum: 0 }));\n agg.count += 1;\n agg.sum += row.value;\n }\n for (const [name, { count, sum }] of buckets) {\n out[`${name}_count`] = count;\n out[`${name}_sum`] = sum;\n }\n\n return out;\n }\n}\n","/**\n * Per-request observability context.\n *\n * One `ObservabilityContext` is created at the entry of each unit-of-\n * work (HTTP request, maintenance tick, GC sweep, rebuild run) and\n * carried through the call tree via {@link runWithContext} /\n * {@link getCurrentContext}, which delegates to a single module-level\n * `AsyncLocalStorage` instance.\n *\n * The context is intentionally tiny: an externally-set\n * {@link request_id}, a high-resolution `started_at`, and a mutable\n * {@link fields} bag used to accumulate canonical-line attributes\n * during the unit's lifecycle.\n *\n * The context shape is `readonly` everywhere it can be — only the\n * contents of `fields` are intended to mutate during a request. The\n * {@link fields} map itself is not `readonly` because callers (the\n * canonical-line emitter, middleware, the collection API once Dispatch\n * 3+ wires it up) need to set entries.\n *\n * The context carries no sampling state — every unit-of-work emits\n * one canonical line unconditionally; there is nothing to gate.\n *\n * ## Time source\n *\n * `started_at` uses `performance.now()` so durations can be\n * computed without worrying about wall-clock skew (NTP step,\n * leap-second smearing). `performance.now()` is part of both Node\n * 18+ and the Workers Runtime; we don't fall back to `Date.now()`.\n *\n * @example\n * ```ts\n * const ctx = createObservabilityContext({});\n * await runWithContext(ctx, async () => {\n * const inner = getCurrentContext();\n * inner?.fields.set(\"collection\", \"tickets\");\n * await doWork();\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n type MetricsRecorder,\n noopMetricsRecorder,\n type RequestHold,\n type RequestLedger,\n setRequestHoldResolver,\n setRequestLedgerResolver,\n} from \"@baerly/protocol\";\n// Type-only import — `maintenance.ts` imports this module's runtime\n// values (`getCurrentContext`), so a value import here would form a\n// runtime cycle. A type-only edge erases at build time, so tsc /\n// rolldown see no cycle.\nimport type { MaintenanceDispatch } from \"../maintenance.ts\";\nimport type { ReadEnvelope } from \"../read-admission.ts\";\nimport { RequestScopedMetricsRecorder } from \"./recorder.ts\";\n\n/** Read-mostly per-request observability state. */\nexport interface ObservabilityContext {\n /** Externally-correlatable request identifier (UUID-ish). */\n readonly request_id: string;\n /** Monotonic `performance.now()` reading captured at construction. */\n readonly started_at: number;\n /**\n * Mutable bag for canonical-line attributes. Callers `obs.fields.set(\"k\", v)`;\n * the canonical-line flusher spreads this onto the emitted properties at\n * end-of-request.\n */\n readonly fields: Map<string, unknown>;\n /**\n * Per-request metrics bag. Lives on the context so adapters can\n * reach it from inside the `Db`'s `MetricsRecorder` callback via\n * `getCurrentContext()?.recorder` — no parallel `AsyncLocalStorage`\n * lookup. The canonical-line flusher reads its `summarize()` at\n * end-of-request and spreads the result onto the emitted line.\n */\n readonly recorder: RequestScopedMetricsRecorder;\n /**\n * The invocation's storage request budget. Set by the adapter that owns\n * the invocation (an HTTP request, a Workers cron tick) with its host's\n * limits. Every storage attempt run inside this context, `waitUntil`\n * work included, is charged to it by `retryStorageCall`, and one that\n * does not fit is refused before it is sent. Absent ⇒ nothing is charged.\n */\n readonly ledger?: RequestLedger;\n /**\n * A hold on `ledger` that storage calls in this context draw on first.\n * Set only by the writer, on a child context scoped to one commit slot's\n * calls (`Writer#withCommitHold`); work dispatched from outside that\n * scope never sees it.\n */\n readonly hold?: RequestHold;\n}\n\n/**\n * {@link ObservabilityContext} plus the adapter-set host wiring the kernel\n * reads: the write-tick maintenance dispatch and the read envelope. The\n * kernel's {@link createObservabilityContext} / {@link getCurrentContext}\n * use this type; the published `/observability` entry re-exports them\n * typed with the narrower public context.\n *\n * @internal\n */\nexport interface InternalObservabilityContext extends ObservabilityContext {\n /**\n * Per-request write-tick maintenance dispatch config. Set by the\n * adapter (NOT `Db.create`) so the inherently-per-request\n * `dispatch = ctx.waitUntil` and the env-var-derived caps ride the\n * same scope the kernel write-tick reads from. The `Writer`\n * consults `getCurrentContext()?.maintenance` at the post-commit\n * dispatch point. Absent ⇒ inline dispatch + CF-free-safe caps.\n */\n readonly maintenance?: MaintenanceDispatch;\n /**\n * The host's read envelope, set by the adapter with its host's bounds.\n * A read whose staged work falls outside it is refused whole with\n * `CapacityExceeded` (see `read-admission.ts`). Absent ⇒ reads are\n * bounded by the ledger alone.\n */\n readonly readEnvelope?: ReadEnvelope;\n}\n\n/**\n * Optional construction inputs. All fields are optional so callers in\n * unit-of-work entry middleware (HTTP router, maintenance scheduler)\n * can pass only what they have. Defaults:\n *\n * - `request_id`: a fresh `crypto.randomUUID()`. Pass an externally-\n * supplied id (`X-Request-Id` header, scheduler-supplied tag) to\n * propagate correlation downstream.\n * - `recorder`: a fresh {@link RequestScopedMetricsRecorder}. Tests can\n * pass an externally-constructed recorder to assert on its\n * `snapshot()` after the unit-of-work completes; production callers\n * should accept the default.\n */\nexport interface ObservabilityContextInit {\n readonly request_id?: string;\n readonly recorder?: RequestScopedMetricsRecorder;\n /** Storage request budget. See {@link ObservabilityContext.ledger}. */\n readonly ledger?: RequestLedger;\n}\n\n/**\n * {@link ObservabilityContextInit} plus the adapter-set host wiring of\n * {@link InternalObservabilityContext}.\n *\n * @internal\n */\nexport interface InternalObservabilityContextInit extends ObservabilityContextInit {\n /** Write-tick maintenance dispatch config. See {@link InternalObservabilityContext.maintenance}. */\n readonly maintenance?: MaintenanceDispatch;\n /** Read envelope. See {@link InternalObservabilityContext.readEnvelope}. */\n readonly readEnvelope?: ReadEnvelope;\n}\n\n/**\n * Factory for {@link ObservabilityContext}. We use a factory rather\n * than a class so consumers can structural-type the result and so\n * the `AsyncLocalStorage` slot type stays a plain interface — no\n * surprises around `instanceof` across realms (Workers vs Node).\n */\nexport const createObservabilityContext = (\n init: InternalObservabilityContextInit = {},\n): InternalObservabilityContext => ({\n request_id: init.request_id ?? crypto.randomUUID(),\n started_at: performance.now(),\n fields: new Map(),\n recorder: init.recorder ?? new RequestScopedMetricsRecorder(),\n ...(init.maintenance !== undefined && { maintenance: init.maintenance }),\n ...(init.ledger !== undefined && { ledger: init.ledger }),\n ...(init.readEnvelope !== undefined && { readEnvelope: init.readEnvelope }),\n});\n\n/**\n * Module-level slot. One instance per process — the Workers\n * Runtime's `nodejs_compat` flag wires `node:async_hooks` to a\n * per-request scope, so cross-request bleed is impossible there.\n */\nconst als = new AsyncLocalStorage<InternalObservabilityContext>();\n\n// Adapters import only `@baerly/protocol`, so `retryStorageCall` finds the\n// active invocation's ledger through this resolver.\nsetRequestLedgerResolver(() => als.getStore()?.ledger);\nsetRequestHoldResolver(() => als.getStore()?.hold);\n\n/**\n * Run `fn` with `ctx` active as the current observability context.\n * Inside `fn` (and any `await`-chained continuation rooted in `fn`),\n * {@link getCurrentContext} returns `ctx`. Outside, it returns the\n * previously-active context (or `undefined`).\n *\n * `runWithContext` is async-safe via `AsyncLocalStorage`; it propagates\n * through `await`, `Promise.all`, `setTimeout`, and `queueMicrotask`.\n *\n * Returns `fn`'s return value verbatim — including its promise\n * identity, so callers can `await` or chain off it without extra\n * indirection.\n */\nexport const runWithContext = <T>(\n ctx: ObservabilityContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> => als.run(ctx, fn);\n\n/** Returns the currently-active context, or `undefined` outside one. */\nexport const getCurrentContext = (): InternalObservabilityContext | undefined => als.getStore();\n\n/** The active context's recorder, or the no-op recorder outside one. */\nexport const ctxMetrics = (): MetricsRecorder =>\n getCurrentContext()?.recorder ?? noopMetricsRecorder;\n"],"mappings":";;;;;;;;AA8GA,MAAa,sBAAuC;CAClD,eAAqB,CAAC;CACtB,aAAmB,CAAC;CACpB,iBAAuB,CAAC;AAC1B;;;;;;;;;;;;;ACnEA,IAAa,+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BACX,OAAyC,CAAC,OACR;CAClC,YAAY,KAAK,cAAc,OAAO,WAAW;CACjD,YAAY,YAAY,IAAI;CAC5B,wBAAQ,IAAI,IAAI;CAChB,UAAU,KAAK,YAAY,IAAI,6BAA6B;CAC5D,GAAI,KAAK,gBAAgB,KAAA,KAAa,EAAE,aAAa,KAAK,YAAY;CACtE,GAAI,KAAK,WAAW,KAAA,KAAa,EAAE,QAAQ,KAAK,OAAO;CACvD,GAAI,KAAK,iBAAiB,KAAA,KAAa,EAAE,cAAc,KAAK,aAAa;AAC3E;;;;;;AAOA,MAAM,MAAM,IAAI,kBAAgD;AAIhE,+BAA+B,IAAI,SAAS,CAAC,EAAE,MAAM;AACrD,6BAA6B,IAAI,SAAS,CAAC,EAAE,IAAI;;;;;;;;;;;;;;AAejD,MAAa,kBACX,KACA,OACmB,IAAI,IAAI,KAAK,EAAE;;AAGpC,MAAa,0BAAoE,IAAI,SAAS;;AAG9F,MAAa,mBACX,kBAAkB,CAAC,EAAE,YAAY"}
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { a as isJsonMode, r as emitSuccess, s as BaerlyError } from "./baerly.js";
|
|
2
|
+
import { n as parseBucketUri } from "./config-DEzInG6M.js";
|
|
3
|
+
import { estimateWritesPerMin } from "./usage-CPzVhrQr.js";
|
|
4
|
+
import { a as TENANT_ARG, c as defineBaerlySubcommand, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, t as APP_ARG } from "./subcommand-BLoF66dG.js";
|
|
5
|
+
// src/cost/provider.ts
|
|
6
|
+
const detectProvider = (args) => {
|
|
7
|
+
if (args.override !== void 0) return args.override;
|
|
8
|
+
if (args.bucketUri.startsWith("file://")) return "dev";
|
|
9
|
+
if (args.bucketUri.startsWith("memory://")) return "dev";
|
|
10
|
+
if (args.bucketUri.startsWith("gcs://")) return "gcs";
|
|
11
|
+
if (!args.bucketUri.startsWith("s3://")) return "self-hosted";
|
|
12
|
+
const endpoint = args.s3Endpoint ?? "";
|
|
13
|
+
if (endpoint === "") return "aws-s3";
|
|
14
|
+
if (/\.r2\.cloudflarestorage\.com(:\d+)?\/?$/i.test(endpoint)) return "r2";
|
|
15
|
+
if (/\.amazonaws\.com(:\d+)?\/?$/i.test(endpoint)) return "aws-s3";
|
|
16
|
+
return "self-hosted";
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* R2 price table.
|
|
20
|
+
* Source: <https://developers.cloudflare.com/r2/pricing/> (review date 2026-05-17).
|
|
21
|
+
* Change-control: pair every edit with a `docs/about/pricing-log.md` entry.
|
|
22
|
+
*/
|
|
23
|
+
const R2_PRICING = {
|
|
24
|
+
provider: "r2",
|
|
25
|
+
freeClassAPerMonth: 1e6,
|
|
26
|
+
usdPerMillionClassA: 4.5,
|
|
27
|
+
freeStorageGb: 10,
|
|
28
|
+
usdPerGbMonth: .015
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* AWS S3 (Standard) price table.
|
|
32
|
+
* Source: <https://aws.amazon.com/s3/pricing/> (review date 2026-05-17).
|
|
33
|
+
* The 12-month new-account free tier is intentionally excluded
|
|
34
|
+
* (most operators are past it; reporting $0 to them would lie).
|
|
35
|
+
*/
|
|
36
|
+
const AWS_S3_PRICING = {
|
|
37
|
+
provider: "aws-s3",
|
|
38
|
+
freeClassAPerMonth: 0,
|
|
39
|
+
usdPerMillionClassA: 5,
|
|
40
|
+
freeStorageGb: 0,
|
|
41
|
+
usdPerGbMonth: .023
|
|
42
|
+
};
|
|
43
|
+
/** Locations where the Always Free allowance applies. */
|
|
44
|
+
const GCS_ALWAYS_FREE_REGIONS = [
|
|
45
|
+
"us-west1",
|
|
46
|
+
"us-central1",
|
|
47
|
+
"us-east1"
|
|
48
|
+
];
|
|
49
|
+
/**
|
|
50
|
+
* Google Cloud Storage Standard, flat-namespace, regional price table.
|
|
51
|
+
* The allowance applies only in the eligible US regions documented by
|
|
52
|
+
* `docs/about/cost-model.md`; the CLI discloses that condition.
|
|
53
|
+
*/
|
|
54
|
+
const GCS_PRICING = {
|
|
55
|
+
provider: "gcs",
|
|
56
|
+
freeClassAPerMonth: 5e3,
|
|
57
|
+
usdPerMillionClassA: 5,
|
|
58
|
+
freeStorageGb: 5,
|
|
59
|
+
usdPerGbMonth: .02
|
|
60
|
+
};
|
|
61
|
+
const SELF_HOSTED_PRICING = {
|
|
62
|
+
provider: "self-hosted",
|
|
63
|
+
freeClassAPerMonth: 0,
|
|
64
|
+
usdPerMillionClassA: NaN,
|
|
65
|
+
freeStorageGb: 0,
|
|
66
|
+
usdPerGbMonth: NaN
|
|
67
|
+
};
|
|
68
|
+
const DEV_PRICING = {
|
|
69
|
+
provider: "dev",
|
|
70
|
+
freeClassAPerMonth: 0,
|
|
71
|
+
usdPerMillionClassA: NaN,
|
|
72
|
+
freeStorageGb: 0,
|
|
73
|
+
usdPerGbMonth: NaN
|
|
74
|
+
};
|
|
75
|
+
const CF_FREE_PROFILE = {
|
|
76
|
+
profile: "cf-free",
|
|
77
|
+
effectiveWriteAmp: 2
|
|
78
|
+
};
|
|
79
|
+
const NODE_PROFILE = {
|
|
80
|
+
profile: "node",
|
|
81
|
+
effectiveWriteAmp: 3
|
|
82
|
+
};
|
|
83
|
+
const costProfileFor = (profile) => profile === "cf-free" ? CF_FREE_PROFILE : NODE_PROFILE;
|
|
84
|
+
const defaultCostProfileFor = (provider) => provider === "r2" ? "cf-free" : "node";
|
|
85
|
+
/**
|
|
86
|
+
* GCS pricing for a bucket in `region`. Outside {@link GCS_ALWAYS_FREE_REGIONS}
|
|
87
|
+
* the free allowance is dropped; the per-op and per-GB rates stay the
|
|
88
|
+
* US-regional ones, which the CLI discloses as modeled.
|
|
89
|
+
*/
|
|
90
|
+
const gcsPricingForRegion = (region) => region === void 0 || GCS_ALWAYS_FREE_REGIONS.includes(region.toLowerCase()) ? GCS_PRICING : {
|
|
91
|
+
...GCS_PRICING,
|
|
92
|
+
freeClassAPerMonth: 0,
|
|
93
|
+
freeStorageGb: 0
|
|
94
|
+
};
|
|
95
|
+
const pricingFor = (provider) => {
|
|
96
|
+
switch (provider) {
|
|
97
|
+
case "r2": return R2_PRICING;
|
|
98
|
+
case "aws-s3": return AWS_S3_PRICING;
|
|
99
|
+
case "gcs": return GCS_PRICING;
|
|
100
|
+
case "self-hosted": return SELF_HOSTED_PRICING;
|
|
101
|
+
case "dev": return DEV_PRICING;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
// src/cost/project.ts
|
|
105
|
+
/**
|
|
106
|
+
* Hard Class A graduation envelope, sustained over seven days. Storage
|
|
107
|
+
* remains a cost signal rather than a hard trigger.
|
|
108
|
+
*/
|
|
109
|
+
const GRADUATION_CLASS_A_PER_MONTH = 5e7;
|
|
110
|
+
const bandForPositiveUsd = (usd) => {
|
|
111
|
+
if (usd < 25) return "<$25";
|
|
112
|
+
if (usd < 50) return "$25-$50";
|
|
113
|
+
if (usd < 100) return "$50-$100";
|
|
114
|
+
if (usd < 250) return "$100-$250";
|
|
115
|
+
if (usd < 500) return "$250-$500";
|
|
116
|
+
return "$500+";
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Project a sampled write rate into monthly operations and a stable
|
|
120
|
+
* provider-cost band. Exact continuous USD arithmetic remains internal.
|
|
121
|
+
* Returns `null` when `writesPerMin` is non-finite.
|
|
122
|
+
*/
|
|
123
|
+
const project = (writesPerMin, storedBytes, pricing, profile) => {
|
|
124
|
+
if (!Number.isFinite(writesPerMin)) return null;
|
|
125
|
+
const classAPerMonth = writesPerMin * (43200 * profile.effectiveWriteAmp);
|
|
126
|
+
const percentOfGraduation = classAPerMonth / GRADUATION_CLASS_A_PER_MONTH * 100;
|
|
127
|
+
const percentOfAdvisory = writesPerMin / 100 * 100;
|
|
128
|
+
const percentOfFreeTier = pricing.freeClassAPerMonth > 0 ? classAPerMonth / pricing.freeClassAPerMonth * 100 : null;
|
|
129
|
+
const storedGb = storedBytes / 1073741824;
|
|
130
|
+
const withinFreeTier = pricing.freeClassAPerMonth > 0 && classAPerMonth <= pricing.freeClassAPerMonth && storedGb <= pricing.freeStorageGb;
|
|
131
|
+
let projectedUsdBand;
|
|
132
|
+
if (Number.isNaN(pricing.usdPerMillionClassA)) projectedUsdBand = null;
|
|
133
|
+
else if (withinFreeTier) projectedUsdBand = "$0";
|
|
134
|
+
else {
|
|
135
|
+
const classAOverage = Math.max(0, classAPerMonth - pricing.freeClassAPerMonth);
|
|
136
|
+
const storageOverage = Math.max(0, storedGb - pricing.freeStorageGb);
|
|
137
|
+
const estimatedUsdPerMonth = classAOverage / 1e6 * pricing.usdPerMillionClassA + storageOverage * pricing.usdPerGbMonth;
|
|
138
|
+
projectedUsdBand = bandForPositiveUsd(estimatedUsdPerMonth);
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
writesPerMin,
|
|
142
|
+
classAPerMonth,
|
|
143
|
+
percentOfFreeTier,
|
|
144
|
+
percentOfGraduation,
|
|
145
|
+
percentOfAdvisory,
|
|
146
|
+
projectedUsdBand,
|
|
147
|
+
withinFreeTier,
|
|
148
|
+
provider: pricing.provider,
|
|
149
|
+
profile: profile.profile
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
// src/cost.ts
|
|
153
|
+
const COST_ARGS = {
|
|
154
|
+
bucket: BUCKET_ARG,
|
|
155
|
+
app: APP_ARG,
|
|
156
|
+
tenant: TENANT_ARG,
|
|
157
|
+
collection: COLLECTION_ARG,
|
|
158
|
+
provider: {
|
|
159
|
+
type: "string",
|
|
160
|
+
required: false,
|
|
161
|
+
description: "Override pricing provider (r2|aws-s3|gcs|self-hosted|dev). Auto-detected from bucket URI + BAERLY_S3_ENDPOINT.",
|
|
162
|
+
valueHint: "r2|aws-s3|gcs|self-hosted|dev"
|
|
163
|
+
},
|
|
164
|
+
profile: {
|
|
165
|
+
type: "string",
|
|
166
|
+
required: false,
|
|
167
|
+
description: "Override host maintenance profile (cf-free|node). Inferred as cf-free for R2 and node otherwise.",
|
|
168
|
+
valueHint: "cf-free|node"
|
|
169
|
+
},
|
|
170
|
+
region: {
|
|
171
|
+
type: "string",
|
|
172
|
+
required: false,
|
|
173
|
+
description: "GCS bucket location (e.g. us-central1). The Always Free allowance applies only in us-west1, us-central1 and us-east1; omit it to keep the disclosed assumption. GCS only.",
|
|
174
|
+
valueHint: "region"
|
|
175
|
+
},
|
|
176
|
+
json: JSON_ARG
|
|
177
|
+
};
|
|
178
|
+
const PROVIDER_TAGS = /* @__PURE__ */ new Set([
|
|
179
|
+
"r2",
|
|
180
|
+
"aws-s3",
|
|
181
|
+
"gcs",
|
|
182
|
+
"self-hosted",
|
|
183
|
+
"dev"
|
|
184
|
+
]);
|
|
185
|
+
const PROFILE_TAGS = /* @__PURE__ */ new Set(["cf-free", "node"]);
|
|
186
|
+
const GCS_PRICING_BASIS = {
|
|
187
|
+
storageClass: "Standard",
|
|
188
|
+
namespace: "flat",
|
|
189
|
+
locationPricing: "regional",
|
|
190
|
+
freeAllowance: {
|
|
191
|
+
classAOperationsPerMonth: 5e3,
|
|
192
|
+
storageGbMonth: 5,
|
|
193
|
+
eligibleRegions: GCS_ALWAYS_FREE_REGIONS
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
const GCS_UNMODELED = [
|
|
197
|
+
"hierarchical-namespace",
|
|
198
|
+
"dual-or-multi-region-pricing",
|
|
199
|
+
"egress",
|
|
200
|
+
"soft-delete-retention"
|
|
201
|
+
];
|
|
202
|
+
/** One-line disclosure of whether the GCS always-free allowance applies. */
|
|
203
|
+
const renderGcsAllowance = (region) => {
|
|
204
|
+
const indent = " ";
|
|
205
|
+
if (region === void 0) return `${indent}5,000 Class A ops and 5 GB-month free allowance assumes us-west1, us-central1, or us-east1`;
|
|
206
|
+
if (GCS_ALWAYS_FREE_REGIONS.includes(region)) return `${indent}5,000 Class A ops and 5 GB-month free allowance applies in ${region}`;
|
|
207
|
+
return `${indent}no free allowance in ${region} (it applies only in us-west1, us-central1, or us-east1); US-regional rates assumed`;
|
|
208
|
+
};
|
|
209
|
+
/** Compact `1.5M` / `22k` / `842` rendering for Class A op counts. */
|
|
210
|
+
const formatOps = (n) => {
|
|
211
|
+
if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
|
|
212
|
+
if (n >= 1e3) return `${(n / 1e3).toFixed(0)}k`;
|
|
213
|
+
return n.toFixed(0);
|
|
214
|
+
};
|
|
215
|
+
const providerDisplayName = (provider) => {
|
|
216
|
+
switch (provider) {
|
|
217
|
+
case "r2": return "R2";
|
|
218
|
+
case "aws-s3": return "S3";
|
|
219
|
+
case "gcs": return "GCS";
|
|
220
|
+
case "self-hosted": return "self-hosted";
|
|
221
|
+
case "dev": return "dev";
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
const renderUsdBand = (band) => {
|
|
225
|
+
if (band === "$0") return "$0";
|
|
226
|
+
if (band === "<$25") return "<$25/mo";
|
|
227
|
+
return `~${band}/mo`;
|
|
228
|
+
};
|
|
229
|
+
/** Advisory rendered after 100 writes/min and before the hard trigger. */
|
|
230
|
+
const renderAdvisoryLine = (trajectory, pricing) => {
|
|
231
|
+
if (trajectory.percentOfAdvisory < 100 || trajectory.percentOfGraduation >= 100) return "";
|
|
232
|
+
if (trajectory.projectedUsdBand === null) return " advisory: ~100 writes/min crossed. Object storage buys zero ops, no on-call,\n no migration; a managed DB trades those dollars for schema + SQL + ops.\n Hard graduation trigger: 50M Class A/mo. Self-hosted — bill model not modelled.\n";
|
|
233
|
+
const atAdvisory = project(100, 0, pricing, costProfileFor(trajectory.profile));
|
|
234
|
+
return ` advisory: ~100 writes/min crossed (${`${renderUsdBand(atAdvisory.projectedUsdBand)} on ${providerDisplayName(trajectory.provider)}`}, object-storage ops). Object storage buys\n zero ops, no on-call, and no migration for your bytes. A managed DB trades those\n dollars for a schema, SQL, and an ops surface. Review if that tradeoff\n makes sense for your workload. Hard graduation trigger: 50M Class A/mo.\n`;
|
|
235
|
+
};
|
|
236
|
+
const renderTrajectory = (trajectory, pricing) => {
|
|
237
|
+
const writesPerMin = trajectory.writesPerMin.toFixed(trajectory.writesPerMin < 10 ? 1 : 0);
|
|
238
|
+
const classA = formatOps(trajectory.classAPerMonth);
|
|
239
|
+
if (trajectory.projectedUsdBand === null) {
|
|
240
|
+
const advisory = renderAdvisoryLine(trajectory, pricing);
|
|
241
|
+
return [
|
|
242
|
+
` trajectory: ~${writesPerMin} writes/min → ~${classA} Class A/mo`,
|
|
243
|
+
` ${trajectory.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger. Self-hosted — bill model not modelled.`,
|
|
244
|
+
...advisory ? [advisory] : []
|
|
245
|
+
].join("\n");
|
|
246
|
+
}
|
|
247
|
+
const providerLabel = providerDisplayName(trajectory.provider);
|
|
248
|
+
const usd = trajectory.withinFreeTier ? `${renderUsdBand(trajectory.projectedUsdBand)} (${providerLabel} free tier)` : renderUsdBand(trajectory.projectedUsdBand);
|
|
249
|
+
const tail = trajectory.withinFreeTier ? `${trajectory.percentOfFreeTier.toFixed(0)}% of free-tier Class A budget. ${trajectory.percentOfFreeTier < 50 ? "Well inside the promise." : "Approaching free-tier ceiling."}` : `${trajectory.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger.`;
|
|
250
|
+
const advisory = renderAdvisoryLine(trajectory, pricing);
|
|
251
|
+
return [
|
|
252
|
+
` trajectory: ~${writesPerMin} writes/min → ~${classA} Class A/mo → ${usd}`,
|
|
253
|
+
` ${tail}`,
|
|
254
|
+
...advisory ? [advisory] : []
|
|
255
|
+
].join("\n");
|
|
256
|
+
};
|
|
257
|
+
const bundle = defineBaerlySubcommand({
|
|
258
|
+
name: "cost",
|
|
259
|
+
meta: { description: "Project a collection's monthly Class A write-operation trajectory." },
|
|
260
|
+
args: COST_ARGS,
|
|
261
|
+
handler: async (args, ctx) => {
|
|
262
|
+
if (typeof args.provider === "string" && args.provider.length > 0) {
|
|
263
|
+
if (!PROVIDER_TAGS.has(args.provider)) throw new BaerlyError("InvalidConfig", `baerly cost: --provider must be one of r2|aws-s3|gcs|self-hosted|dev (got ${JSON.stringify(args.provider)})`);
|
|
264
|
+
}
|
|
265
|
+
if (typeof args.profile === "string" && args.profile.length > 0) {
|
|
266
|
+
if (!PROFILE_TAGS.has(args.profile)) throw new BaerlyError("InvalidConfig", `baerly cost: --profile must be one of cf-free|node (got ${JSON.stringify(args.profile)})`);
|
|
267
|
+
}
|
|
268
|
+
const bucket = await parseBucketUri(args.bucket);
|
|
269
|
+
const { app, tenant } = await ctx.resolveAppTenant({
|
|
270
|
+
app: args.app,
|
|
271
|
+
tenant: args.tenant
|
|
272
|
+
});
|
|
273
|
+
assertCollectionArg(args.collection, "baerly cost");
|
|
274
|
+
const providerOverride = typeof args.provider === "string" && args.provider.length > 0 ? args.provider : void 0;
|
|
275
|
+
const region = typeof args.region === "string" && args.region.length > 0 ? args.region.toLowerCase() : void 0;
|
|
276
|
+
const provider = detectProvider({
|
|
277
|
+
bucketUri: args.bucket,
|
|
278
|
+
s3Endpoint: process.env["BAERLY_S3_ENDPOINT"],
|
|
279
|
+
override: providerOverride
|
|
280
|
+
});
|
|
281
|
+
if (region !== void 0 && provider !== "gcs") throw new BaerlyError("InvalidConfig", `baerly cost: --region applies only to GCS buckets (provider is ${provider})`);
|
|
282
|
+
if (provider === "dev") throw new BaerlyError("InvalidConfig", "baerly cost: dev backends (file://, memory://) have no $ model; pass --provider=r2|aws-s3|gcs|self-hosted to project against one.");
|
|
283
|
+
const profileOverride = typeof args.profile === "string" && args.profile.length > 0 ? args.profile : void 0;
|
|
284
|
+
const profileTag = profileOverride ?? defaultCostProfileFor(provider);
|
|
285
|
+
const verdict = await estimateWritesPerMin(bucket.storage, app, tenant, args.collection, { keyPrefix: bucket.keyPrefix });
|
|
286
|
+
const pricing = provider === "gcs" ? gcsPricingForRegion(region) : pricingFor(provider);
|
|
287
|
+
const trajectory = project(verdict.writesPerMin, 0, pricing, costProfileFor(profileTag));
|
|
288
|
+
if (trajectory === null) throw new BaerlyError("InvalidConfig", `baerly cost: not enough log entries under ${args.collection} to estimate writes/min (need >= 2)`);
|
|
289
|
+
const scope = {
|
|
290
|
+
kind: "collection",
|
|
291
|
+
collection: args.collection,
|
|
292
|
+
includesOtherAccountUsage: false,
|
|
293
|
+
includesStoredBytes: false
|
|
294
|
+
};
|
|
295
|
+
const commonAssumptions = {
|
|
296
|
+
pricingProvider: provider,
|
|
297
|
+
maintenanceProfile: profileTag,
|
|
298
|
+
maintenanceProfileSource: profileOverride === void 0 ? "inferred" : "explicit",
|
|
299
|
+
otherAccountClassAPerMonth: 0,
|
|
300
|
+
storedBytes: 0
|
|
301
|
+
};
|
|
302
|
+
const assumptions = provider === "gcs" ? {
|
|
303
|
+
...commonAssumptions,
|
|
304
|
+
pricingBasis: region === void 0 ? GCS_PRICING_BASIS : {
|
|
305
|
+
...GCS_PRICING_BASIS,
|
|
306
|
+
freeAllowance: {
|
|
307
|
+
...GCS_PRICING_BASIS.freeAllowance,
|
|
308
|
+
applies: GCS_ALWAYS_FREE_REGIONS.includes(region)
|
|
309
|
+
}
|
|
310
|
+
},
|
|
311
|
+
...region === void 0 ? {} : { bucketRegion: region },
|
|
312
|
+
unmodeled: GCS_UNMODELED
|
|
313
|
+
} : commonAssumptions;
|
|
314
|
+
if (isJsonMode()) emitSuccess({
|
|
315
|
+
command: "cost",
|
|
316
|
+
collection: args.collection,
|
|
317
|
+
scope,
|
|
318
|
+
assumptions,
|
|
319
|
+
trajectory
|
|
320
|
+
});
|
|
321
|
+
else process.stdout.write(`baerly cost ${args.collection}\n scope: selected collection only; storage and other account usage excluded\n assumptions: provider=${provider}; profile=${profileTag} (${assumptions.maintenanceProfileSource}); free-tier and dollar projection assumes 0 other account Class A ops and 0 stored bytes\n` + (provider === "gcs" ? ` GCS pricing basis: GCS Standard storage; flat namespace; regional pricing\n${renderGcsAllowance(region)}\n actual HNS, dual/multi-region pricing, egress, and soft-delete retention are not detected or modeled\n` : "") + `${renderTrajectory(trajectory, pricing)}\n`);
|
|
322
|
+
return 0;
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
/** citty `defineCommand` block for `baerly cost`. */
|
|
326
|
+
const cost = bundle.cmd;
|
|
327
|
+
bundle.run;
|
|
328
|
+
export { cost };
|
|
329
|
+
|
|
330
|
+
//# sourceMappingURL=cost-B52llVDx.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cost-B52llVDx.js","names":[],"sources":["../packages/cli/src/cost/provider.ts","../packages/cli/src/cost/project.ts","../packages/cli/src/cost.ts"],"sourcesContent":["/**\n * Provider sniffer: maps a bucket URI + optional S3 endpoint into a\n * pricing tag, and resolves that tag into a `ProviderPricing`\n * record. Pure — zero I/O.\n *\n * Detection rules (first match wins):\n * - `file://*` → \"dev\"\n * - `memory://*` → \"dev\"\n * - `gcs://*` → \"gcs\"\n * - `s3://*` + endpoint matching `*.r2.cloudflarestorage.com` → \"r2\"\n * - `s3://*` + endpoint matching `*.amazonaws.com` → \"aws-s3\"\n * - `s3://*` + no endpoint → \"aws-s3\"\n * - everything else (Minio, Backblaze, on-prem, unknown s3 endpoint) → \"self-hosted\"\n *\n * `override` skips detection entirely — used by the\n * `baerly inspect --provider=...` CLI flag when auto-detection picks\n * wrong (e.g., a self-hosted S3 gateway in front of R2).\n */\n\nimport type { CostProfile, CostProfileTag, ProviderPricing, ProviderTag } from \"./project.ts\";\n\nexport type { ProviderTag } from \"./project.ts\";\n\nexport interface DetectArgs {\n /** Raw bucket URI as passed on the CLI (s3://, file://, memory://). */\n readonly bucketUri: string;\n /** Effective S3 endpoint at parse time (typically `process.env[\"BAERLY_S3_ENDPOINT\"]`). */\n readonly s3Endpoint?: string;\n /** When set, skip detection and return this tag. */\n readonly override?: ProviderTag;\n}\n\nexport const detectProvider = (args: DetectArgs): ProviderTag => {\n if (args.override !== undefined) {\n return args.override;\n }\n if (args.bucketUri.startsWith(\"file://\")) {\n return \"dev\";\n }\n if (args.bucketUri.startsWith(\"memory://\")) {\n return \"dev\";\n }\n if (args.bucketUri.startsWith(\"gcs://\")) {\n return \"gcs\";\n }\n if (!args.bucketUri.startsWith(\"s3://\")) {\n return \"self-hosted\";\n }\n // s3:// branch — look at the endpoint.\n const endpoint = args.s3Endpoint ?? \"\";\n if (endpoint === \"\") {\n return \"aws-s3\";\n } // default AWS\n if (/\\.r2\\.cloudflarestorage\\.com(:\\d+)?\\/?$/i.test(endpoint)) {\n return \"r2\";\n }\n if (/\\.amazonaws\\.com(:\\d+)?\\/?$/i.test(endpoint)) {\n return \"aws-s3\";\n }\n return \"self-hosted\";\n};\n\n/**\n * R2 price table.\n * Source: <https://developers.cloudflare.com/r2/pricing/> (review date 2026-05-17).\n * Change-control: pair every edit with a `docs/about/pricing-log.md` entry.\n */\nconst R2_PRICING: ProviderPricing = {\n provider: \"r2\",\n freeClassAPerMonth: 1_000_000,\n usdPerMillionClassA: 4.5,\n freeStorageGb: 10,\n usdPerGbMonth: 0.015,\n};\n\n/**\n * AWS S3 (Standard) price table.\n * Source: <https://aws.amazon.com/s3/pricing/> (review date 2026-05-17).\n * The 12-month new-account free tier is intentionally excluded\n * (most operators are past it; reporting $0 to them would lie).\n */\nconst AWS_S3_PRICING: ProviderPricing = {\n provider: \"aws-s3\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: 5,\n freeStorageGb: 0,\n usdPerGbMonth: 0.023,\n};\n\n/** Locations where the Always Free allowance applies. */\nexport const GCS_ALWAYS_FREE_REGIONS: readonly string[] = [\"us-west1\", \"us-central1\", \"us-east1\"];\n\n/**\n * Google Cloud Storage Standard, flat-namespace, regional price table.\n * The allowance applies only in the eligible US regions documented by\n * `docs/about/cost-model.md`; the CLI discloses that condition.\n */\nconst GCS_PRICING: ProviderPricing = {\n provider: \"gcs\",\n freeClassAPerMonth: 5_000,\n usdPerMillionClassA: 5,\n freeStorageGb: 5,\n usdPerGbMonth: 0.02,\n};\n\nconst SELF_HOSTED_PRICING: ProviderPricing = {\n provider: \"self-hosted\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: Number.NaN,\n freeStorageGb: 0,\n usdPerGbMonth: Number.NaN,\n};\n\nconst DEV_PRICING: ProviderPricing = {\n provider: \"dev\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: Number.NaN,\n freeStorageGb: 0,\n usdPerGbMonth: Number.NaN,\n};\n\nconst CF_FREE_PROFILE: CostProfile = {\n profile: \"cf-free\",\n effectiveWriteAmp: 2,\n};\n\nconst NODE_PROFILE: CostProfile = {\n profile: \"node\",\n effectiveWriteAmp: 3,\n};\n\nexport const costProfileFor = (profile: CostProfileTag): CostProfile =>\n profile === \"cf-free\" ? CF_FREE_PROFILE : NODE_PROFILE;\n\nexport const defaultCostProfileFor = (provider: ProviderTag): CostProfileTag =>\n provider === \"r2\" ? \"cf-free\" : \"node\";\n\n/**\n * GCS pricing for a bucket in `region`. Outside {@link GCS_ALWAYS_FREE_REGIONS}\n * the free allowance is dropped; the per-op and per-GB rates stay the\n * US-regional ones, which the CLI discloses as modeled.\n */\nexport const gcsPricingForRegion = (region: string | undefined): ProviderPricing =>\n region === undefined || GCS_ALWAYS_FREE_REGIONS.includes(region.toLowerCase())\n ? GCS_PRICING\n : { ...GCS_PRICING, freeClassAPerMonth: 0, freeStorageGb: 0 };\n\nexport const pricingFor = (provider: ProviderTag): ProviderPricing => {\n switch (provider) {\n case \"r2\": {\n return R2_PRICING;\n }\n case \"aws-s3\": {\n return AWS_S3_PRICING;\n }\n case \"gcs\": {\n return GCS_PRICING;\n }\n case \"self-hosted\": {\n return SELF_HOSTED_PRICING;\n }\n case \"dev\": {\n return DEV_PRICING;\n }\n }\n};\n","/**\n * Pure projection math for the `baerly cost` trajectory output. Zero\n * I/O. Provider prices and measured host profiles are orthogonal inputs:\n * price tables own billing and profiles own write amplification.\n *\n * Three rules:\n * 1. `classAPerMonth = writesPerMin × 60 × 24 × 30 × effectiveWriteAmp`.\n * The profile's measured amplification includes in-band maintenance;\n * it is not the one-op commit floor.\n * 2. Exact continuous provider cost is calculated internally and then\n * mapped to a stable band. `$0` is reserved for a projection wholly\n * inside a modeled free tier; unmodeled providers return `null`.\n * 3. Non-finite writes/min returns `null`, preserving the estimator's\n * no-data behavior.\n */\n\nexport type ProviderTag = \"r2\" | \"aws-s3\" | \"gcs\" | \"self-hosted\" | \"dev\";\nexport type CostProfileTag = \"cf-free\" | \"node\";\nexport type ProjectedUsdBand =\n | \"$0\"\n | \"<$25\"\n | \"$25-$50\"\n | \"$50-$100\"\n | \"$100-$250\"\n | \"$250-$500\"\n | \"$500+\";\n\n/** Provider price table, independent of the host that performs writes. */\nexport interface ProviderPricing {\n readonly provider: ProviderTag;\n /** Free-tier Class A ops per month; 0 if no free tier. */\n readonly freeClassAPerMonth: number;\n /** $/1M Class A above free tier. NaN for self-hosted/dev. */\n readonly usdPerMillionClassA: number;\n /** Free-tier stored GB; 0 if no free tier. */\n readonly freeStorageGb: number;\n /** $/GB-month above free tier. NaN for self-hosted/dev. */\n readonly usdPerGbMonth: number;\n}\n\n/** Measured host execution profile, independent of provider pricing. */\nexport interface CostProfile {\n readonly profile: CostProfileTag;\n /**\n * Effective Class A ops per logical write, including in-band folds\n * and GC. Source:\n * docs/spec/attachments/amortized-write-cost-baseline.json.\n */\n readonly effectiveWriteAmp: number;\n}\n\n/**\n * Hard Class A graduation envelope, sustained over seven days. Storage\n * remains a cost signal rather than a hard trigger.\n */\nexport const GRADUATION_CLASS_A_PER_MONTH = 50_000_000;\n\n/**\n * Provider-agnostic eyes-open advisory crossing. It is keyed to the\n * sampled write rate, so provider/profile amplification changes the\n * displayed band without moving the 100-writes/min threshold.\n */\nexport const GRADUATION_ADVISORY_WRITES_PER_MIN = 100;\n\n/** What the cost command renders from. */\nexport interface Trajectory {\n readonly writesPerMin: number;\n readonly classAPerMonth: number;\n /**\n * Percent of the provider's Class A allowance. `null` for providers\n * with no modeled allowance or dollar model.\n */\n readonly percentOfFreeTier: number | null;\n /** Percent of the 50M/month hard graduation envelope. */\n readonly percentOfGraduation: number;\n /** Percent of the provider-agnostic 100 writes/min advisory. */\n readonly percentOfAdvisory: number;\n /**\n * Coarse monthly USD band. `$0` means wholly inside a modeled free\n * tier; `null` means the provider has no dollar model.\n */\n readonly projectedUsdBand: ProjectedUsdBand | null;\n readonly withinFreeTier: boolean;\n readonly provider: ProviderTag;\n readonly profile: CostProfileTag;\n}\n\nconst bandForPositiveUsd = (usd: number): ProjectedUsdBand => {\n if (usd < 25) {\n return \"<$25\";\n }\n if (usd < 50) {\n return \"$25-$50\";\n }\n if (usd < 100) {\n return \"$50-$100\";\n }\n if (usd < 250) {\n return \"$100-$250\";\n }\n if (usd < 500) {\n return \"$250-$500\";\n }\n return \"$500+\";\n};\n\n/**\n * Project a sampled write rate into monthly operations and a stable\n * provider-cost band. Exact continuous USD arithmetic remains internal.\n * Returns `null` when `writesPerMin` is non-finite.\n */\nexport const project = (\n writesPerMin: number,\n storedBytes: number,\n pricing: ProviderPricing,\n profile: CostProfile,\n): Trajectory | null => {\n if (!Number.isFinite(writesPerMin)) {\n return null;\n }\n\n // Group the exact month/profile multiplier before applying the sampled\n // floating-point rate so known free-tier boundaries do not drift one ULP.\n const classAPerMonth = writesPerMin * (60 * 24 * 30 * profile.effectiveWriteAmp);\n const percentOfGraduation = (classAPerMonth / GRADUATION_CLASS_A_PER_MONTH) * 100;\n const percentOfAdvisory = (writesPerMin / GRADUATION_ADVISORY_WRITES_PER_MIN) * 100;\n const percentOfFreeTier =\n pricing.freeClassAPerMonth > 0 ? (classAPerMonth / pricing.freeClassAPerMonth) * 100 : null;\n\n const storedGb = storedBytes / (1024 * 1024 * 1024);\n const withinFreeTier =\n pricing.freeClassAPerMonth > 0 &&\n classAPerMonth <= pricing.freeClassAPerMonth &&\n storedGb <= pricing.freeStorageGb;\n\n let projectedUsdBand: ProjectedUsdBand | null;\n if (Number.isNaN(pricing.usdPerMillionClassA)) {\n projectedUsdBand = null;\n } else if (withinFreeTier) {\n projectedUsdBand = \"$0\";\n } else {\n const classAOverage = Math.max(0, classAPerMonth - pricing.freeClassAPerMonth);\n const storageOverage = Math.max(0, storedGb - pricing.freeStorageGb);\n const estimatedUsdPerMonth =\n (classAOverage / 1_000_000) * pricing.usdPerMillionClassA +\n storageOverage * pricing.usdPerGbMonth;\n // `$0` is reserved for a projection wholly inside a modeled free tier.\n projectedUsdBand = bandForPositiveUsd(estimatedUsdPerMonth);\n }\n\n return {\n writesPerMin,\n classAPerMonth,\n percentOfFreeTier,\n percentOfGraduation,\n percentOfAdvisory,\n projectedUsdBand,\n withinFreeTier,\n provider: pricing.provider,\n profile: profile.profile,\n };\n};\n","/**\n * `baerly cost` — bounded cost trajectory for one collection.\n *\n * Samples the live log tail, projects monthly Class A write operations,\n * and reports a stable provider-cost band. Storage and other account\n * usage are explicit assumptions, not observed inputs.\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --provider Optional pricing provider override:\n * r2 | aws-s3 | gcs | self-hosted | dev.\n * --profile Optional host profile override: cf-free | node.\n * --json JSON envelope.\n *\n * Cost shape:\n * 1 GET for current.json + bounded galloping/binary tail probes\n * + up to 120 trailing log GETs. No log LIST; historical depth does\n * not change the sample window.\n *\n * Exit codes:\n * 0 — projection rendered.\n * 1 — InvalidConfig (bad bucket URI, missing args, unknown flag,\n * insufficient log entries to estimate, dev backend).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant / conflict (WriteConflict / AlreadyExists /\n * Internal / InvalidResponse / AmbiguousCommit).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess, isJsonMode } from \"./output.ts\";\nimport {\n costProfileFor,\n defaultCostProfileFor,\n detectProvider,\n GCS_ALWAYS_FREE_REGIONS,\n gcsPricingForRegion,\n pricingFor,\n type ProviderTag,\n} from \"./cost/provider.ts\";\nimport {\n project,\n type CostProfileTag,\n type ProjectedUsdBand,\n type ProviderPricing,\n type Trajectory,\n} from \"./cost/project.ts\";\nimport { estimateWritesPerMin } from \"./admin/usage.ts\";\nimport {\n APP_ARG,\n assertCollectionArg,\n BUCKET_ARG,\n COLLECTION_ARG,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"./subcommand.ts\";\n\nconst COST_ARGS = {\n bucket: BUCKET_ARG,\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: COLLECTION_ARG,\n provider: {\n type: \"string\",\n required: false,\n description:\n \"Override pricing provider (r2|aws-s3|gcs|self-hosted|dev). Auto-detected from bucket URI + BAERLY_S3_ENDPOINT.\",\n valueHint: \"r2|aws-s3|gcs|self-hosted|dev\",\n },\n profile: {\n type: \"string\",\n required: false,\n description:\n \"Override host maintenance profile (cf-free|node). Inferred as cf-free for R2 and node otherwise.\",\n valueHint: \"cf-free|node\",\n },\n region: {\n type: \"string\",\n required: false,\n description:\n \"GCS bucket location (e.g. us-central1). The Always Free allowance applies only in us-west1, us-central1 and us-east1; omit it to keep the disclosed assumption. GCS only.\",\n valueHint: \"region\",\n },\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst PROVIDER_TAGS: ReadonlySet<string> = new Set([\"r2\", \"aws-s3\", \"gcs\", \"self-hosted\", \"dev\"]);\nconst PROFILE_TAGS: ReadonlySet<string> = new Set([\"cf-free\", \"node\"]);\n\nconst GCS_PRICING_BASIS = {\n storageClass: \"Standard\",\n namespace: \"flat\",\n locationPricing: \"regional\",\n freeAllowance: {\n classAOperationsPerMonth: 5_000,\n storageGbMonth: 5,\n eligibleRegions: GCS_ALWAYS_FREE_REGIONS,\n },\n} as const;\n\nconst GCS_UNMODELED = [\n \"hierarchical-namespace\",\n \"dual-or-multi-region-pricing\",\n \"egress\",\n \"soft-delete-retention\",\n] as const;\n\n/** One-line disclosure of whether the GCS always-free allowance applies. */\nconst renderGcsAllowance = (region: string | undefined): string => {\n const indent = \" \";\n if (region === undefined) {\n return `${indent}5,000 Class A ops and 5 GB-month free allowance assumes us-west1, us-central1, or us-east1`;\n }\n if (GCS_ALWAYS_FREE_REGIONS.includes(region)) {\n return `${indent}5,000 Class A ops and 5 GB-month free allowance applies in ${region}`;\n }\n return `${indent}no free allowance in ${region} (it applies only in us-west1, us-central1, or us-east1); US-regional rates assumed`;\n};\n\n/** Compact `1.5M` / `22k` / `842` rendering for Class A op counts. */\nconst formatOps = (n: number): string => {\n if (n >= 1_000_000) {\n return `${(n / 1_000_000).toFixed(1)}M`;\n }\n if (n >= 1_000) {\n return `${(n / 1_000).toFixed(0)}k`;\n }\n return n.toFixed(0);\n};\n\nconst providerDisplayName = (provider: ProviderTag): string => {\n switch (provider) {\n case \"r2\": {\n return \"R2\";\n }\n case \"aws-s3\": {\n return \"S3\";\n }\n case \"gcs\": {\n return \"GCS\";\n }\n case \"self-hosted\": {\n return \"self-hosted\";\n }\n case \"dev\": {\n return \"dev\";\n }\n }\n};\n\nconst renderUsdBand = (band: ProjectedUsdBand): string => {\n if (band === \"$0\") {\n return \"$0\";\n }\n if (band === \"<$25\") {\n return \"<$25/mo\";\n }\n return `~${band}/mo`;\n};\n\n/** Advisory rendered after 100 writes/min and before the hard trigger. */\nconst renderAdvisoryLine = (trajectory: Trajectory, pricing: ProviderPricing): string => {\n if (trajectory.percentOfAdvisory < 100 || trajectory.percentOfGraduation >= 100) {\n return \"\";\n }\n if (trajectory.projectedUsdBand === null) {\n return (\n ` advisory: ~100 writes/min crossed. Object storage buys zero ops, no on-call,\\n` +\n ` no migration; a managed DB trades those dollars for schema + SQL + ops.\\n` +\n ` Hard graduation trigger: 50M Class A/mo. Self-hosted — bill model not modelled.\\n`\n );\n }\n const atAdvisory = project(100, 0, pricing, costProfileFor(trajectory.profile));\n const costNote = `${renderUsdBand(atAdvisory!.projectedUsdBand!)} on ${providerDisplayName(trajectory.provider)}`;\n return (\n ` advisory: ~100 writes/min crossed (${costNote}, object-storage ops). Object storage buys\\n` +\n ` zero ops, no on-call, and no migration for your bytes. A managed DB trades those\\n` +\n ` dollars for a schema, SQL, and an ops surface. Review if that tradeoff\\n` +\n ` makes sense for your workload. Hard graduation trigger: 50M Class A/mo.\\n`\n );\n};\n\nconst renderTrajectory = (trajectory: Trajectory, pricing: ProviderPricing): string => {\n const writesPerMin = trajectory.writesPerMin.toFixed(trajectory.writesPerMin < 10 ? 1 : 0);\n const classA = formatOps(trajectory.classAPerMonth);\n if (trajectory.projectedUsdBand === null) {\n const advisory = renderAdvisoryLine(trajectory, pricing);\n return [\n ` trajectory: ~${writesPerMin} writes/min → ~${classA} Class A/mo`,\n ` ${trajectory.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger. Self-hosted — bill model not modelled.`,\n ...(advisory ? [advisory] : []),\n ].join(\"\\n\");\n }\n\n const providerLabel = providerDisplayName(trajectory.provider);\n const usd = trajectory.withinFreeTier\n ? `${renderUsdBand(trajectory.projectedUsdBand)} (${providerLabel} free tier)`\n : renderUsdBand(trajectory.projectedUsdBand);\n const tail = trajectory.withinFreeTier\n ? `${trajectory.percentOfFreeTier!.toFixed(0)}% of free-tier Class A budget. ${trajectory.percentOfFreeTier! < 50 ? \"Well inside the promise.\" : \"Approaching free-tier ceiling.\"}`\n : `${trajectory.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger.`;\n const advisory = renderAdvisoryLine(trajectory, pricing);\n return [\n ` trajectory: ~${writesPerMin} writes/min → ~${classA} Class A/mo → ${usd}`,\n ` ${tail}`,\n ...(advisory ? [advisory] : []),\n ].join(\"\\n\");\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"cost\",\n meta: {\n description: \"Project a collection's monthly Class A write-operation trajectory.\",\n },\n args: COST_ARGS,\n handler: async (args, ctx) => {\n if (typeof args.provider === \"string\" && args.provider.length > 0) {\n if (!PROVIDER_TAGS.has(args.provider)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: --provider must be one of r2|aws-s3|gcs|self-hosted|dev (got ${JSON.stringify(args.provider)})`,\n );\n }\n }\n if (typeof args.profile === \"string\" && args.profile.length > 0) {\n if (!PROFILE_TAGS.has(args.profile)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: --profile must be one of cf-free|node (got ${JSON.stringify(args.profile)})`,\n );\n }\n }\n\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly cost\");\n\n const providerOverride =\n typeof args.provider === \"string\" && args.provider.length > 0\n ? (args.provider as ProviderTag)\n : undefined;\n const region =\n typeof args.region === \"string\" && args.region.length > 0\n ? args.region.toLowerCase()\n : undefined;\n const provider = detectProvider({\n bucketUri: args.bucket,\n s3Endpoint: process.env[\"BAERLY_S3_ENDPOINT\"],\n override: providerOverride,\n });\n if (region !== undefined && provider !== \"gcs\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: --region applies only to GCS buckets (provider is ${provider})`,\n );\n }\n if (provider === \"dev\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly cost: dev backends (file://, memory://) have no $ model; pass --provider=r2|aws-s3|gcs|self-hosted to project against one.\",\n );\n }\n\n const profileOverride =\n typeof args.profile === \"string\" && args.profile.length > 0\n ? (args.profile as CostProfileTag)\n : undefined;\n const profileTag = profileOverride ?? defaultCostProfileFor(provider);\n\n const verdict = await estimateWritesPerMin(bucket.storage, app, tenant, args.collection, {\n keyPrefix: bucket.keyPrefix,\n });\n const pricing = provider === \"gcs\" ? gcsPricingForRegion(region) : pricingFor(provider);\n const trajectory = project(verdict.writesPerMin, 0, pricing, costProfileFor(profileTag));\n if (trajectory === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: not enough log entries under ${args.collection} to estimate writes/min (need >= 2)`,\n );\n }\n\n const scope = {\n kind: \"collection\" as const,\n collection: args.collection,\n includesOtherAccountUsage: false as const,\n includesStoredBytes: false as const,\n };\n const commonAssumptions = {\n pricingProvider: provider,\n maintenanceProfile: profileTag,\n maintenanceProfileSource:\n profileOverride === undefined ? (\"inferred\" as const) : (\"explicit\" as const),\n otherAccountClassAPerMonth: 0,\n storedBytes: 0,\n };\n const assumptions =\n provider === \"gcs\"\n ? {\n ...commonAssumptions,\n // A known region states whether the allowance applies; an unknown\n // one keeps the disclosure and the allowance.\n pricingBasis:\n region === undefined\n ? GCS_PRICING_BASIS\n : {\n ...GCS_PRICING_BASIS,\n freeAllowance: {\n ...GCS_PRICING_BASIS.freeAllowance,\n applies: GCS_ALWAYS_FREE_REGIONS.includes(region),\n },\n },\n ...(region === undefined ? {} : { bucketRegion: region }),\n unmodeled: GCS_UNMODELED,\n }\n : commonAssumptions;\n\n if (isJsonMode()) {\n emitSuccess({ command: \"cost\", collection: args.collection, scope, assumptions, trajectory });\n } else {\n process.stdout.write(\n `baerly cost ${args.collection}\\n` +\n ` scope: selected collection only; storage and other account usage excluded\\n` +\n ` assumptions: provider=${provider}; profile=${profileTag} (${assumptions.maintenanceProfileSource}); free-tier and dollar projection assumes 0 other account Class A ops and 0 stored bytes\\n` +\n (provider === \"gcs\"\n ? ` GCS pricing basis: GCS Standard storage; flat namespace; regional pricing\\n` +\n `${renderGcsAllowance(region)}\\n` +\n ` actual HNS, dual/multi-region pricing, egress, and soft-delete retention are not detected or modeled\\n`\n : \"\") +\n `${renderTrajectory(trajectory, pricing)}\\n`,\n );\n }\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly cost`. */\nexport const cost = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runCost = bundle.run;\n"],"mappings":";;;;;AAgCA,MAAa,kBAAkB,SAAkC;CAC/D,IAAI,KAAK,aAAa,KAAA,GACpB,OAAO,KAAK;CAEd,IAAI,KAAK,UAAU,WAAW,SAAS,GACrC,OAAO;CAET,IAAI,KAAK,UAAU,WAAW,WAAW,GACvC,OAAO;CAET,IAAI,KAAK,UAAU,WAAW,QAA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