@gusto/baerly-storage 0.2.0 → 0.4.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/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +176 -70
- package/dist/API.md +213 -139
- package/dist/CHANGELOG.md +434 -0
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +238 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-DyiFK3_k.d.ts} +55 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +301 -301
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-Fe8CwB73.d.ts} +10 -10
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-DzKBrUlg.js} +178 -2
- package/dist/cloudflare-DzKBrUlg.js.map +1 -0
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +59 -26
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-DSMIVqzL.js} +43 -42
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/current-json-C6nhPOm1.js +190 -0
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-DsPkOVEH.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-DonTr-CV.js} +12 -5
- package/dist/deploy-DonTr-CV.js.map +1 -0
- package/dist/dev-vite.d.ts +11 -7
- package/dist/dev-vite.js +7 -6
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-DSIyCDg_.js} +14 -136
- package/dist/doctor-DSIyCDg_.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-Bh5k26VQ.js} +10 -31
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-Bhbz90-z.js → export-DtF5tDIM.js} +11 -32
- package/dist/{export-Bhbz90-z.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-D_djMO5D.js} +28 -39
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-DxM9MflO.js} +151 -79
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DwDTWPSU.d.ts → index-0rZcMBwy.d.ts} +10 -7
- package/dist/{index-C3JAH1Yo.d.ts → index-B6oexfOB.d.ts} +9 -9
- package/dist/{index-cUY-36AN.d.ts → index-BNRh23K9.d.ts} +21 -5
- package/dist/{index-DSvwEUeF.d.ts → index-BYk9oCNf.d.ts} +240 -202
- package/dist/index.d.ts +6 -6
- package/dist/index.js +5 -5
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-6WZ-pC7-.js} +21 -36
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-D98U1JBo.js} +179 -84
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-B4Dki6Ig.js} +438 -176
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-B_e0T99L.d.ts} +114 -26
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C7coQp4c.js} +217 -94
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +176 -68
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-CpOiEN0k.js → observability-wzs3-BL_.js} +279 -109
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-a7PJHBCy.js} +7 -4
- package/dist/plan-a7PJHBCy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-rAtXNQQB.js} +1063 -1202
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-BVzQSZlm.js} +10 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/restore-R-4rbciV.js +778 -0
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-qL3_lTTU.js +391 -0
- package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/src-BG20LZs7.js +2271 -0
- package/dist/src-BG20LZs7.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-CYHFDrKz.js} +82 -99
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-QQ7jDeL2.js → src-DYZ4H1aF.js} +44 -23
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/subcommand-DoDA-K7d.js +197 -0
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +77 -42
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js +0 -354
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js +0 -771
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js +0 -6236
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js +0 -5122
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
- package/dist/usage-CLjirdD-.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cost-CQt1YRkA.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 * - `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 { ProviderPricing } from \"./project.ts\";\n\nexport type ProviderTag = ProviderPricing[\"provider\"];\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(\"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\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\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 \"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 inspect` cost-trajectory\n * footer. Zero I/O. Price tables live as top-level constants; every\n * change MUST be paired with a `docs/about/pricing-log.md` entry.\n *\n * Three rules:\n * 1. `classAPerMonth = writesPerMin × 60 × 24 × 30 × 3`. The `× 3`\n * is the protocol's enforced write-amp ceiling\n * (`docs/about/cost-model.md:43-44`); snapshot writes\n * amortize and are excluded from the headline.\n * 2. `projectedUsdPerMonth = 0` exactly when both `classAPerMonth\n * ≤ pricing.freeClassAPerMonth` AND `storedBytes ≤\n * pricing.freeStorageGb × 1GB`. Say `$0`, not `$0.00`. `null`\n * for self-hosted/dev (no $ model).\n * 3. Returns `null` when `writesPerMin` is non-finite (no-data case\n * from `estimateWritesPerMin`); inspect renders no footer.\n */\n\n/** R2 / AWS S3 / self-hosted / dev price table. */\nexport interface ProviderPricing {\n readonly provider: \"r2\" | \"aws-s3\" | \"self-hosted\" | \"dev\";\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/**\n * Graduation triggers — sustained for 7 days, any one of these\n * means the workload has outgrown Baerly's positioning.\n *\n * Source: `docs/about/cost-model.md:159-163`.\n */\nexport const GRADUATION_CLASS_A_PER_MONTH = 50_000_000;\n// GRADUATION_WRITE_AMP = 6 — sustained write-amp at this level\n// suggests the workload is too bursty for the M-size positioning.\n// Not yet wired into project(); kept for the storedBytes follow-up.\n// GRADUATION_STORED_BYTES = 5 * 1024 * 1024 * 1024 — storage graduation\n// trigger (~5 GB). Not yet wired; deferred alongside write-amp gating.\n\n/** What the inspect footer renders from. */\nexport interface Trajectory {\n readonly writesPerMin: number;\n readonly classAPerMonth: number;\n /** Percent of provider's free-tier Class A budget. `null` when the provider has no free tier (aws-s3) or no $ model (self-hosted/dev). */\n readonly percentOfFreeTier: number | null;\n /** Percent of the 50M/mo graduation trigger. Always a finite number. */\n readonly percentOfGraduation: number;\n /** Projected USD/month. `0` when fully inside the free tier. `null` when the provider has no $ model (self-hosted/dev). */\n readonly projectedUsdPerMonth: number | null;\n readonly withinFreeTier: boolean;\n readonly provider: ProviderPricing[\"provider\"];\n}\n\n/**\n * Protocol write-amp ceiling: every logical write produces exactly\n * 3 Class A ops (PUT content + PUT log entry + CAS-advance\n * current.json). Source: `docs/about/cost-model.md:43-44`.\n */\nconst PROTOCOL_WRITE_AMP = 3;\n\n/** Minutes per month × write-amp = Class A ops/month per write/min. */\nconst OPS_PER_WPM_PER_MONTH = 60 * 24 * 30 * PROTOCOL_WRITE_AMP;\n\n/**\n * Project a `writesPerMin` rate (typically from\n * `estimateWritesPerMin`) into a monthly cost trajectory.\n *\n * Returns `null` when `writesPerMin` is non-finite. The caller\n * (inspect) renders no footer in that case.\n */\nexport const project = (\n writesPerMin: number,\n storedBytes: number,\n pricing: ProviderPricing,\n): Trajectory | null => {\n if (!Number.isFinite(writesPerMin)) {\n return null;\n }\n\n const classAPerMonth = writesPerMin * OPS_PER_WPM_PER_MONTH;\n\n const percentOfGraduation = (classAPerMonth / GRADUATION_CLASS_A_PER_MONTH) * 100;\n\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 projectedUsdPerMonth: number | null;\n if (Number.isNaN(pricing.usdPerMillionClassA)) {\n projectedUsdPerMonth = null;\n } else if (withinFreeTier) {\n projectedUsdPerMonth = 0;\n } else {\n const classAOverage = Math.max(0, classAPerMonth - pricing.freeClassAPerMonth);\n const storageOverage = Math.max(0, storedGb - pricing.freeStorageGb);\n projectedUsdPerMonth =\n (classAOverage / 1_000_000) * pricing.usdPerMillionClassA +\n storageOverage * pricing.usdPerGbMonth;\n }\n\n return {\n writesPerMin,\n classAPerMonth,\n percentOfFreeTier,\n percentOfGraduation,\n projectedUsdPerMonth,\n withinFreeTier,\n provider: pricing.provider,\n };\n};\n","/**\n * `baerly cost` — projected cost trajectory for one collection.\n *\n * Sniffs the writes/min rate over the trailing log sample for one\n * collection and projects it into a free-tier-aware monthly Class A\n * + storage cost projection vs. the M-size graduation trigger\n * (50M Class A/mo). Read-only; never mutates anything.\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. r2 | aws-s3 | self-hosted | dev. Overrides\n * the auto-detected provider (bucket URI +\n * BAERLY_S3_ENDPOINT).\n * --json JSON envelope.\n *\n * Cost shape:\n * 1 LIST log/ prefix\n * + up to 120 GETs for trailing log entries (`SAMPLE_SIZE`)\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 / Internal / InvalidResponse).\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 { detectProvider, pricingFor, type ProviderTag } from \"./cost/provider.ts\";\nimport { project, type Trajectory } from \"./cost/project.ts\";\nimport { estimateWritesPerMin } from \"./admin/usage.ts\";\nimport { defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst COST_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n provider: {\n type: \"string\",\n required: false,\n description:\n \"Override pricing provider (r2|aws-s3|self-hosted|dev). Auto-detected from bucket URI + BAERLY_S3_ENDPOINT.\",\n valueHint: \"r2|aws-s3|self-hosted|dev\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\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\n/** Two-line trajectory block. Three output states per design spec §4.2. */\nconst renderTrajectory = (t: Trajectory): string => {\n const wpm = t.writesPerMin.toFixed(t.writesPerMin < 10 ? 1 : 0);\n const classA = formatOps(t.classAPerMonth);\n // State 2: ops-only — provider known but no $ model. Today only\n // self-hosted reaches this (dev is filtered out upstream).\n if (t.projectedUsdPerMonth === null) {\n return [\n ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo`,\n ` ${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger. Self-hosted — bill model not modelled.`,\n ].join(\"\\n\");\n }\n // Only \"r2\" can reach withinFreeTier===true (aws-s3 has freeClassAPerMonth: 0).\n // self-hosted/dev are filtered upstream.\n const usd = t.withinFreeTier\n ? `~$0 (R2 free tier)`\n : `~$${t.projectedUsdPerMonth!.toFixed(2)}/mo`;\n // Invariant: withinFreeTier===true implies pricing.freeClassAPerMonth>0,\n // which in turn implies percentOfFreeTier!==null (see project.ts).\n const tail = t.withinFreeTier\n ? `${t.percentOfFreeTier!.toFixed(0)}% of free-tier Class A budget. ${t.percentOfFreeTier! < 50 ? \"Well inside the promise.\" : \"Approaching free-tier ceiling.\"}`\n : `${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger.`;\n return [\n ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo → ${usd}`,\n ` ${tail}`,\n ].join(\"\\n\");\n};\n\nconst PROVIDER_TAGS: ReadonlySet<string> = new Set([\"r2\", \"aws-s3\", \"self-hosted\", \"dev\"]);\n\nconst bundle = defineBaerlySubcommand({\n name: \"cost\",\n meta: {\n description: \"Project a collection's monthly Class A + storage cost 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|self-hosted|dev (got ${JSON.stringify(args.provider)})`,\n );\n }\n }\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n\n const override =\n typeof args.provider === \"string\" && args.provider.length > 0\n ? (args.provider as ProviderTag)\n : undefined;\n const provider = detectProvider({\n bucketUri: args.bucket,\n s3Endpoint: process.env[\"BAERLY_S3_ENDPOINT\"],\n override,\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|self-hosted to project against one.`,\n );\n }\n\n const verdict = await estimateWritesPerMin(bucket.storage, app, tenant, args.collection, {\n keyPrefix: bucket.keyPrefix,\n });\n const trajectory = project(verdict.writesPerMin, 0, pricingFor(provider));\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 if (isJsonMode()) {\n emitSuccess({ command: \"cost\", collection: args.collection, trajectory });\n } else {\n process.stdout.write(`baerly cost ${args.collection}\\n${renderTrajectory(trajectory)}\\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":";;;;AA+BA,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,CAAC,KAAK,UAAU,WAAW,OAAO,GACpC,OAAO;CAGT,MAAM,WAAW,KAAK,cAAc;CACpC,IAAI,aAAa,IACf,OAAO;CAET,IAAI,2CAA2C,KAAK,QAAQ,GAC1D,OAAO;CAET,IAAI,+BAA+B,KAAK,QAAQ,GAC9C,OAAO;CAET,OAAO;AACT;;;;;;AAOA,MAAM,aAA8B;CAClC,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;AACjB;;;;;;;AAQA,MAAM,iBAAkC;CACtC,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;AACjB;AAEA,MAAM,sBAAuC;CAC3C,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;AACjB;AAEA,MAAM,cAA+B;CACnC,UAAU;C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AK,QAAQ,EAAE,EACzG;EAAA;EAGJ,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;EAC/C,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EAEzF,MAAM,WACJ,OAAO,KAAK,aAAa,YAAY,KAAK,SAAS,SAAS,IACvD,KAAK,WACN,KAAA;EACN,MAAM,WAAW,eAAe;GAC9B,WAAW,KAAK;GAChB,YAAY,QAAQ,IAAI;GACxB;EACF,CAAC;EACD,IAAI,aAAa,OACf,MAAM,IAAI,YACR,iBACA,+HACF;EAMF,MAAM,aAAa,SAAQ,MAHL,qBAAqB,OAAO,SAAS,KAAK,QAAQ,KAAK,YAAY,EACvF,WAAW,OAAO,UACpB,CAAC,GACkC,cAAc,GAAG,WAAW,QAAQ,CAAC;EACxE,IAAI,eAAe,MACjB,MAAM,IAAI,YACR,iBACA,6CAA6C,KAAK,WAAW,oCAC/D;EAGF,IAAI,WAAW,GACb,YAAY;GAAE,SAAS;GAAQ,YAAY,KAAK;GAAY;EAAW,CAAC;OAExE,QAAQ,OAAO,MAAM,eAAe,KAAK,WAAW,IAAI,iBAAiB,UAAU,EAAE,GAAG;EAE1F,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,OAAO,OAAO;AAOJ,OAAO"}
|
|
@@ -1,354 +0,0 @@
|
|
|
1
|
-
import { t as BaerlyError } from "./errors-DOdL95kK.js";
|
|
2
|
-
//#region packages/protocol/src/bytes.ts
|
|
3
|
-
/**
|
|
4
|
-
* UTF-8 JSON byte helpers — names the encode/decode idiom used by
|
|
5
|
-
* every content body, log entry, snapshot, and current.json payload.
|
|
6
|
-
*/
|
|
7
|
-
const encodeJsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value));
|
|
8
|
-
const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
|
|
9
|
-
//#endregion
|
|
10
|
-
//#region packages/protocol/src/constants.ts
|
|
11
|
-
/**
|
|
12
|
-
* Backoff (in milliseconds) inserted between LIST attempts when S3
|
|
13
|
-
* returns 429 (rate-limited).
|
|
14
|
-
*/
|
|
15
|
-
const RATE_LIMIT_BACKOFF_MILLIS = 1e3;
|
|
16
|
-
/**
|
|
17
|
-
* MIME type written for `current.json` PUTs. S3 round-trips this on
|
|
18
|
-
* subsequent GETs; useful for diagnostics when staring at a bucket
|
|
19
|
-
* via the AWS console.
|
|
20
|
-
*
|
|
21
|
-
* @see packages/protocol/src/coordination/current-json.ts
|
|
22
|
-
*/
|
|
23
|
-
const CURRENT_JSON_CONTENT_TYPE = "application/json";
|
|
24
|
-
/**
|
|
25
|
-
* MIME type written for `gc/pending.json` PUTs.
|
|
26
|
-
*
|
|
27
|
-
* @see packages/protocol/src/coordination/gc-pending.ts
|
|
28
|
-
*/
|
|
29
|
-
const GC_PENDING_CONTENT_TYPE = "application/json";
|
|
30
|
-
/**
|
|
31
|
-
* Default grace period between "marking" a key for GC and "sweeping"
|
|
32
|
-
* (deleting) it. 7 days, chosen to span the worst plausible writer-
|
|
33
|
-
* retry window (a paused-process writer that resumes hours later
|
|
34
|
-
* should still find its idempotency anchor on the bucket). The
|
|
35
|
-
* `runGc()` function accepts an override for tests.
|
|
36
|
-
*
|
|
37
|
-
* Why 7 days specifically:
|
|
38
|
-
* - **1 day is too aggressive for batch workloads.** Worker isolate
|
|
39
|
-
* scheduling pauses, cross-region replication lag, and
|
|
40
|
-
* {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly
|
|
41
|
-
* exceed an hour under pathological conditions.
|
|
42
|
-
* - **30 days is conservative beyond the worst plausible pause.**
|
|
43
|
-
* Doubles `gc/pending.json` size at steady state and slows
|
|
44
|
-
* visibility into "did GC actually run?" by 4×.
|
|
45
|
-
* - **7 days spans the realistic upper bound** — long-running batch
|
|
46
|
-
* jobs, multi-region propagation delays, queue backlogs, and
|
|
47
|
-
* downstream outages the writer is retrying through. The protocol
|
|
48
|
-
* is unaffected by the choice of value within the [hours, weeks]
|
|
49
|
-
* range; this constant is the operator-tunable knob.
|
|
50
|
-
*
|
|
51
|
-
* Production code MUST NOT call `runGc` with `graceMillis` below the
|
|
52
|
-
* default outside maintenance windows — going below the longest
|
|
53
|
-
* plausible writer-retry latency risks deleting an anchor a writer
|
|
54
|
-
* is about to find on retry. Test code that sets `graceMillis: 0` is
|
|
55
|
-
* exercising the sweep path deliberately, not modelling production.
|
|
56
|
-
*
|
|
57
|
-
* @see packages/server/src/gc.ts
|
|
58
|
-
*/
|
|
59
|
-
const GC_GRACE_PERIOD_MILLIS = 10080 * 60 * 1e3;
|
|
60
|
-
/**
|
|
61
|
-
* Cap on candidates kept in `gc/pending.json` to bound the size of
|
|
62
|
-
* the file. The compactor marks at most this many candidates per
|
|
63
|
-
* pass; subsequent passes pick up the rest. Larger collections will
|
|
64
|
-
* lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which
|
|
65
|
-
* is acceptable.
|
|
66
|
-
*
|
|
67
|
-
* @see packages/server/src/gc.ts
|
|
68
|
-
*/
|
|
69
|
-
const GC_MAX_PENDING_CANDIDATES = 1e3;
|
|
70
|
-
/**
|
|
71
|
-
* Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also
|
|
72
|
-
* sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.
|
|
73
|
-
*
|
|
74
|
-
* @see packages/server/src/maintenance.ts
|
|
75
|
-
*/
|
|
76
|
-
const MAINTENANCE_MIN_LIVE_BYTES = 64 * 1024;
|
|
77
|
-
/**
|
|
78
|
-
* SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized
|
|
79
|
-
* ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable
|
|
80
|
-
* hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).
|
|
81
|
-
*
|
|
82
|
-
* @see docs/about/graduation.md
|
|
83
|
-
* @see packages/server/src/maintenance.ts
|
|
84
|
-
*/
|
|
85
|
-
const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT = 512 * 1024;
|
|
86
|
-
/**
|
|
87
|
-
* The largest snapshot a Cloudflare **free-tier** isolate can safely
|
|
88
|
-
* rebuild in ONE fold under the ~10 ms CPU budget. This is the WARN
|
|
89
|
-
* THRESHOLD, not a runtime cap: an operator who raises
|
|
90
|
-
* `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` ABOVE this value on a free Worker
|
|
91
|
-
* risks a snapshot rebuild that exceeds the ~10 ms CPU limit and gets
|
|
92
|
-
* CPU-killed MID-REBUILD — the CAS never lands, so the fold silently
|
|
93
|
-
* never advances `log_seq_start` and the tail grows unbounded.
|
|
94
|
-
*
|
|
95
|
-
* Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The default
|
|
96
|
-
* (512 KiB) rebuilds in ~5.5 ms under the CF-free ~10 ms budget
|
|
97
|
-
* (constants.ts default JSDoc); linear-extrapolating, ~1 MiB is the
|
|
98
|
-
* point where one-shot rebuild fills the budget with little margin, so
|
|
99
|
-
* anything strictly larger is no longer free-tier-safe. On CF **paid**
|
|
100
|
-
* (raised CPU limits), Node, or once §11 chunked snapshots land, a
|
|
101
|
-
* larger ceiling is fine — hence this is a one-time `console.warn` at
|
|
102
|
-
* handler init, NOT a hard rejection.
|
|
103
|
-
*
|
|
104
|
-
* @see packages/adapter-cloudflare/src/worker.ts
|
|
105
|
-
* @see packages/server/src/maintenance.ts
|
|
106
|
-
* @see docs/about/graduation.md
|
|
107
|
-
*/
|
|
108
|
-
const CF_FREE_MAX_SAFE_FOLD_BYTES = 1024 * 1024;
|
|
109
|
-
/**
|
|
110
|
-
* SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry
|
|
111
|
-
* parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021
|
|
112
|
-
* Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — calibrate via the
|
|
113
|
-
* Task 3 bench, pin in graduation.md.
|
|
114
|
-
*
|
|
115
|
-
* @see docs/about/graduation.md
|
|
116
|
-
* @see packages/server/src/maintenance.ts
|
|
117
|
-
*/
|
|
118
|
-
const MAINTENANCE_MAX_FOLD_ROWS = 2048;
|
|
119
|
-
/**
|
|
120
|
-
* Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate
|
|
121
|
-
* memory — CF recycles isolates). ~once per this many writes.
|
|
122
|
-
*
|
|
123
|
-
* @see packages/protocol/src/coordination/current-json.ts
|
|
124
|
-
* @see packages/server/src/maintenance.ts
|
|
125
|
-
*/
|
|
126
|
-
const MAINTENANCE_WARN_INTERVAL_WRITES = 1e3;
|
|
127
|
-
/**
|
|
128
|
-
* Placeholder for `CurrentJson.snapshot === null` in the
|
|
129
|
-
* `_meta.manifest_pointer` cursor emitted on read responses. The
|
|
130
|
-
* wire format is `"<snapshot>@<next_seq>"`, and `null` snapshots
|
|
131
|
-
* serialise as this literal so the cursor is never empty and stays
|
|
132
|
-
* byte-stable when destructured by operators.
|
|
133
|
-
*
|
|
134
|
-
* @see packages/server/src/contract.ts (HttpOkMeta)
|
|
135
|
-
*/
|
|
136
|
-
const MANIFEST_POINTER_EMPTY_SNAPSHOT = "none";
|
|
137
|
-
/**
|
|
138
|
-
* Keys that must never propagate through {@link merge}: assigning to
|
|
139
|
-
* them on a plain object pollutes the prototype chain. The literal
|
|
140
|
-
* `{ __proto__: ... }` syntax is a prototype-setter (not an own key)
|
|
141
|
-
* and bypasses `Object.keys`, but `JSON.parse('{"__proto__":...}')`
|
|
142
|
-
* produces a real own property — which is exactly how a malicious
|
|
143
|
-
* HTTP PATCH body would arrive on the wire.
|
|
144
|
-
*
|
|
145
|
-
* Lifted to a constant so every iteration path that touches a
|
|
146
|
-
* caller-supplied object can re-use the same defence without
|
|
147
|
-
* duplicating the keyword list.
|
|
148
|
-
*
|
|
149
|
-
* @see packages/protocol/src/json.ts (merge)
|
|
150
|
-
* @see docs/spec/json-merge-patch.md
|
|
151
|
-
*/
|
|
152
|
-
const FORBIDDEN_MERGE_KEYS = new Set([
|
|
153
|
-
"__proto__",
|
|
154
|
-
"constructor",
|
|
155
|
-
"prototype"
|
|
156
|
-
]);
|
|
157
|
-
/**
|
|
158
|
-
* Locked error wording for the "no auth configured" failure mode. The
|
|
159
|
-
* adapter throws this when neither `config.auth` nor `verifier:`
|
|
160
|
-
* resolves a real `Verifier`. Pinned via a regression test so future
|
|
161
|
-
* refactors do not drift the operator-facing wording.
|
|
162
|
-
*
|
|
163
|
-
* Consumed by:
|
|
164
|
-
* - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)
|
|
165
|
-
* - `packages/adapter-node/src/server.ts` (first-fetch throw)
|
|
166
|
-
* - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)
|
|
167
|
-
*/
|
|
168
|
-
const NO_AUTH_CONFIGURED_MESSAGE = "baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.";
|
|
169
|
-
/**
|
|
170
|
-
* Locked error wording for `auth: "shared-secret"` + missing env var.
|
|
171
|
-
* Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.
|
|
172
|
-
*/
|
|
173
|
-
const SHARED_SECRET_MISSING_MESSAGE = "baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.";
|
|
174
|
-
//#endregion
|
|
175
|
-
//#region packages/protocol/src/coordination/current-json.ts
|
|
176
|
-
/**
|
|
177
|
-
* `current.json` — the per-collection CAS-protected control object — and
|
|
178
|
-
* its embedded {@link WriterFence} epoch token.
|
|
179
|
-
*
|
|
180
|
-
* A dedicated `coordination/` namespace (parallel to `storage/`) holds
|
|
181
|
-
* primitives whose contract is "atomic agreement over a small JSON
|
|
182
|
-
* object" rather than "byte I/O." Future siblings (compactor
|
|
183
|
-
* manifest, sweeper checkpoint) join here, not at the top
|
|
184
|
-
* level. The module lives inside `@baerly/protocol` because it is pure
|
|
185
|
-
* (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,
|
|
186
|
-
* no implicit globals) and must remain Worker-bundleable — every byte
|
|
187
|
-
* of network traffic threads through the {@link Storage} seam.
|
|
188
|
-
*
|
|
189
|
-
* Contract surface:
|
|
190
|
-
* - {@link readCurrentJson} — fetch + parse + validate
|
|
191
|
-
* - {@link createCurrentJson} — create-only (CAS via `If-None-Match:"*"`)
|
|
192
|
-
* - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)
|
|
193
|
-
* - {@link claimWriter} — bump epoch + stamp server-clock claim time
|
|
194
|
-
*
|
|
195
|
-
* Why the two-round-trip claim protocol: `claimed_at` MUST come from
|
|
196
|
-
* `StoragePutResult.serverDate` (the single shared clock across
|
|
197
|
-
* instances), not the local clock. `serverDate` is only known *after*
|
|
198
|
-
* the CAS PUT lands, so {@link claimWriter} writes the record with
|
|
199
|
-
* `claimed_at: ""` first, then overwrites itself with the correct
|
|
200
|
-
* `serverDate.toISOString()` in a second CAS. The epoch bump is
|
|
201
|
-
* already durable from the first put either way; a peer landing
|
|
202
|
-
* between the two writes loses cleanly with `Conflict`.
|
|
203
|
-
*
|
|
204
|
-
* Why CAS errors are wrapped: every in-tree {@link Storage} impl
|
|
205
|
-
* surfaces a lost CAS as `BaerlyError{code:"Conflict"}`. Downstream
|
|
206
|
-
* callers — the Writer, the compactor, the sweeper —
|
|
207
|
-
* discriminate by `code` to decide whether to retry.
|
|
208
|
-
* We re-wrap here only to add the `current.json at <key>` location
|
|
209
|
-
* context to the message; the `code` is unchanged.
|
|
210
|
-
*/
|
|
211
|
-
/**
|
|
212
|
-
* Read + parse `current.json` at `key`. Returns `null` on not-found.
|
|
213
|
-
*
|
|
214
|
-
* @throws BaerlyError{code:"InvalidResponse"} — body is not valid
|
|
215
|
-
* JSON, or `schema_version` is unknown, or the shape fails
|
|
216
|
-
* the runtime guard.
|
|
217
|
-
*/
|
|
218
|
-
async function readCurrentJson(storage, key, opts) {
|
|
219
|
-
const got = await storage.get(key, opts);
|
|
220
|
-
if (got === null) return null;
|
|
221
|
-
const text = new TextDecoder().decode(got.body);
|
|
222
|
-
let parsed;
|
|
223
|
-
try {
|
|
224
|
-
parsed = JSON.parse(text);
|
|
225
|
-
} catch (error) {
|
|
226
|
-
throw new BaerlyError("InvalidResponse", `current.json at ${key}: body is not valid JSON`, error);
|
|
227
|
-
}
|
|
228
|
-
return {
|
|
229
|
-
json: assertCurrentJson(parsed, key),
|
|
230
|
-
etag: got.etag
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
/**
|
|
234
|
-
* Create `current.json` if-and-only-if it does not exist (S3
|
|
235
|
-
* `If-None-Match: "*"`). Use this once per collection at provisioning
|
|
236
|
-
* time; subsequent updates go through {@link casUpdateCurrentJson}.
|
|
237
|
-
*
|
|
238
|
-
* @throws BaerlyError{code:"Conflict"} — the key already exists.
|
|
239
|
-
* Caller decides whether to read + reconcile or surface.
|
|
240
|
-
* @throws BaerlyError{code:"InvalidResponse"} — `initial` fails the
|
|
241
|
-
* runtime shape guard.
|
|
242
|
-
*/
|
|
243
|
-
async function createCurrentJson(storage, key, initial, opts) {
|
|
244
|
-
assertCurrentJson(initial, key);
|
|
245
|
-
const body = encodeJson(initial);
|
|
246
|
-
const putOpts = {
|
|
247
|
-
ifNoneMatch: "*",
|
|
248
|
-
contentType: CURRENT_JSON_CONTENT_TYPE,
|
|
249
|
-
...opts?.signal !== void 0 && { signal: opts.signal }
|
|
250
|
-
};
|
|
251
|
-
let result;
|
|
252
|
-
try {
|
|
253
|
-
result = await storage.put(key, body, putOpts);
|
|
254
|
-
} catch (error) {
|
|
255
|
-
throw translateCasError(error, key);
|
|
256
|
-
}
|
|
257
|
-
return {
|
|
258
|
-
json: initial,
|
|
259
|
-
etag: result.etag
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
|
-
/**
|
|
263
|
-
* Read-modify-write `current.json` under CAS. The `mutator` receives
|
|
264
|
-
* a deep clone of the current parsed JSON (mutate freely) and returns
|
|
265
|
-
* the new state. The new state is written with `If-Match:
|
|
266
|
-
* <currentEtag>`; on conflict, throws.
|
|
267
|
-
*
|
|
268
|
-
* `mutator` MUST be synchronous and deterministic — it may be called
|
|
269
|
-
* multiple times if the caller wraps this in a retry loop, so it
|
|
270
|
-
* must not have side effects.
|
|
271
|
-
*
|
|
272
|
-
* @throws BaerlyError{code:"Conflict"} — another writer landed a write
|
|
273
|
-
* between this function's read and write. Caller decides
|
|
274
|
-
* whether to retry (read + remutate + rewrite).
|
|
275
|
-
* @throws BaerlyError{code:"InvalidResponse"} — `key` does not exist
|
|
276
|
-
* (use {@link createCurrentJson} instead) or body doesn't
|
|
277
|
-
* parse / fails the shape guard.
|
|
278
|
-
*/
|
|
279
|
-
async function casUpdateCurrentJson(storage, key, mutator, opts) {
|
|
280
|
-
const existing = await readCurrentJson(storage, key, opts);
|
|
281
|
-
if (existing === null) throw new BaerlyError("InvalidResponse", `current.json at ${key} does not exist; use createCurrentJson first`);
|
|
282
|
-
const next = mutator(structuredClone(existing.json));
|
|
283
|
-
assertCurrentJson(next, key);
|
|
284
|
-
const body = encodeJson(next);
|
|
285
|
-
const putOpts = {
|
|
286
|
-
ifMatch: existing.etag,
|
|
287
|
-
contentType: CURRENT_JSON_CONTENT_TYPE,
|
|
288
|
-
...opts?.signal !== void 0 && { signal: opts.signal }
|
|
289
|
-
};
|
|
290
|
-
let result;
|
|
291
|
-
try {
|
|
292
|
-
result = await storage.put(key, body, putOpts);
|
|
293
|
-
} catch (error) {
|
|
294
|
-
throw translateCasError(error, key);
|
|
295
|
-
}
|
|
296
|
-
return {
|
|
297
|
-
json: next,
|
|
298
|
-
etag: result.etag
|
|
299
|
-
};
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Read `current.json.log_seq_start` — the low-water mark of the live
|
|
303
|
-
* log range `[log_seq_start, next_seq)`. The field is always present
|
|
304
|
-
* on disk (every `createCurrentJson` write seeds it; the compactor
|
|
305
|
-
* advances it on every fold); this helper exists to document intent
|
|
306
|
-
* at call sites that walk the log range or assert the snapshot
|
|
307
|
-
* invariants.
|
|
308
|
-
*/
|
|
309
|
-
const logSeqStartOf = (c) => c.log_seq_start;
|
|
310
|
-
const encodeJson = (json) => encodeJsonBytes(json);
|
|
311
|
-
/**
|
|
312
|
-
* Runtime guard for `parsed` to be a {@link CurrentJson}. Throws
|
|
313
|
-
* `BaerlyError{code:"InvalidResponse"}` rather than coercing. Tolerant
|
|
314
|
-
* reader: unknown keys ignored, new required fields bump
|
|
315
|
-
* `schema_version` (move (b), ADR-007).
|
|
316
|
-
*/
|
|
317
|
-
const assertCurrentJson = (parsed, key) => {
|
|
318
|
-
if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: parsed body is not an object`);
|
|
319
|
-
const r = parsed;
|
|
320
|
-
if (r["schema_version"] === 1) throw new BaerlyError("InvalidResponse", `current.json at ${key} is schema v1 (pre-maintenance); this build requires v2. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`);
|
|
321
|
-
if (r["schema_version"] !== 2) throw new BaerlyError("InvalidResponse", `current.json at ${key}: unsupported schema_version ${String(r["schema_version"])}; expected 2`);
|
|
322
|
-
if (!(typeof r["snapshot"] === "string" || r["snapshot"] === null)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot must be string|null`);
|
|
323
|
-
if (typeof r["next_seq"] !== "number" || !Number.isInteger(r["next_seq"]) || r["next_seq"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: next_seq must be a non-negative integer`);
|
|
324
|
-
if (typeof r["log_seq_start"] !== "number" || !Number.isInteger(r["log_seq_start"]) || r["log_seq_start"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_seq_start must be a non-negative integer`);
|
|
325
|
-
if (r["log_seq_start"] > r["next_seq"]) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_seq_start ${String(r["log_seq_start"])} > next_seq ${String(r["next_seq"])}`);
|
|
326
|
-
const fence = r["writer_fence"];
|
|
327
|
-
if (fence === null || typeof fence !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence missing`);
|
|
328
|
-
const f = fence;
|
|
329
|
-
if (typeof f["epoch"] !== "number" || !Number.isInteger(f["epoch"]) || f["epoch"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.epoch must be a non-negative integer`);
|
|
330
|
-
if (typeof f["owner"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.owner must be a string`);
|
|
331
|
-
if (typeof f["claimed_at"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.claimed_at must be a string`);
|
|
332
|
-
if (f["lease_until"] !== void 0 && typeof f["lease_until"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.lease_until must be string if present`);
|
|
333
|
-
if (typeof r["tail_bytes"] !== "number" || !Number.isInteger(r["tail_bytes"]) || r["tail_bytes"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: tail_bytes must be a non-negative integer`);
|
|
334
|
-
if (typeof r["snapshot_bytes"] !== "number" || !Number.isInteger(r["snapshot_bytes"]) || r["snapshot_bytes"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_bytes must be a non-negative integer`);
|
|
335
|
-
if (typeof r["snapshot_rows"] !== "number" || !Number.isInteger(r["snapshot_rows"]) || r["snapshot_rows"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_rows must be a non-negative integer`);
|
|
336
|
-
if (r["last_warned_seq"] !== void 0 && (typeof r["last_warned_seq"] !== "number" || !Number.isInteger(r["last_warned_seq"]) || r["last_warned_seq"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: last_warned_seq must be a non-negative integer if present`);
|
|
337
|
-
return parsed;
|
|
338
|
-
};
|
|
339
|
-
/**
|
|
340
|
-
* Wrap a storage-level error with `current.json at <key>` location
|
|
341
|
-
* context. `Conflict` (the storage layer's CAS-lost signal) is
|
|
342
|
-
* re-thrown with an annotated message; other `BaerlyError`s pass
|
|
343
|
-
* through; non-`BaerlyError` falls through as `InvalidResponse` (in
|
|
344
|
-
* practice unreachable — every in-tree `Storage` impl wraps).
|
|
345
|
-
*/
|
|
346
|
-
const translateCasError = (e, key) => {
|
|
347
|
-
if (e instanceof BaerlyError && e.code === "Conflict") return new BaerlyError("Conflict", `current.json CAS lost at ${key}: ${e.message}`, e);
|
|
348
|
-
if (e instanceof BaerlyError) return e;
|
|
349
|
-
return new BaerlyError("InvalidResponse", `current.json write at ${key} failed: ${String(e)}`, e);
|
|
350
|
-
};
|
|
351
|
-
//#endregion
|
|
352
|
-
export { SHARED_SECRET_MISSING_MESSAGE as _, CF_FREE_MAX_SAFE_FOLD_BYTES as a, GC_MAX_PENDING_CANDIDATES as c, MAINTENANCE_MAX_FOLD_ROWS as d, MAINTENANCE_MIN_LIVE_BYTES as f, RATE_LIMIT_BACKOFF_MILLIS as g, NO_AUTH_CONFIGURED_MESSAGE as h, readCurrentJson as i, GC_PENDING_CONTENT_TYPE as l, MANIFEST_POINTER_EMPTY_SNAPSHOT as m, createCurrentJson as n, FORBIDDEN_MERGE_KEYS as o, MAINTENANCE_WARN_INTERVAL_WRITES as p, logSeqStartOf as r, GC_GRACE_PERIOD_MILLIS as s, casUpdateCurrentJson as t, MAINTENANCE_MAX_FOLD_BYTES_DEFAULT as u, decodeJsonBytes as v, encodeJsonBytes as y };
|
|
353
|
-
|
|
354
|
-
//# sourceMappingURL=current-json-C-EyJqs0.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"current-json-C-EyJqs0.js","names":[],"sources":["../packages/protocol/src/bytes.ts","../packages/protocol/src/constants.ts","../packages/protocol/src/coordination/current-json.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — names the encode/decode idiom used by\n * every content body, log entry, snapshot, and current.json payload.\n */\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n new TextEncoder().encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(new TextDecoder().decode(bytes)) as T;\n","/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * Maximum attempts `S3HttpStorage.list` will make per page when the\n * server replies 429 (rate-limited). After this many in a row, it\n * gives up with `NetworkError`. Separate from the inner transient-\n * failure budget so a single hot page can't burn the whole retry\n * allowance.\n */\nexport const LIST_OBJECT_MAX_RETRIES: number = 10;\n\n/**\n * Backoff (in milliseconds) inserted between LIST attempts when S3\n * returns 429 (rate-limited).\n */\nexport const RATE_LIMIT_BACKOFF_MILLIS: number = 1000;\n\n/**\n * Upper clamp on a server-provided `Retry-After` hint, in seconds.\n * RFC 7231 §7.1.3 allows arbitrary delta-seconds or HTTP-dates, but a\n * client that blindly honours a multi-hour hint hands a misbehaving\n * proxy a denial-of-service primitive. 60s covers any plausible S3-\n * compatible throttle while keeping the worst-case bounded.\n *\n * @see packages/protocol/src/storage/s3-http.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Default retry budget for `S3HttpStorage.retry` (the wrapper around\n * each of the four `Storage` methods). Bounded so that permanent\n * failures (CORS misconfig, NXDOMAIN, persistent 5xx) surface to\n * callers as rejected promises instead of retrying forever and\n * leaving `Writer.commit()` permanently pending.\n *\n * 8 attempts at the existing 100ms→×1.5→10s schedule covers ~30s of\n * transient turbulence, which is enough to ride out a leader election\n * or a brief network blip without papering over a real outage.\n */\nexport const S3_REQUEST_MAX_RETRIES: number = 8;\n\n/**\n * Maximum concurrent log-entry GETs issued by a single `walkLogRange`\n * call. Bounds Class-B fan-out per read and per CAS attempt — without\n * a bound, a reader on a collection whose compactor has fallen behind\n * fans out one GET per live-tail entry (typically 50-100 on the free-\n * tier profile), and a contended writer multiplies that by the CAS\n * retry budget ({@link S3_REQUEST_MAX_RETRIES}).\n *\n * 16 keeps the worst-case under retry to `16 * 8 = 128` concurrent\n * GETs — comfortably under the Workers subrequest cap (50 concurrent\n * / 1000 total) and leaving headroom for the writer's content / index\n * / log / CAS PUTs sharing the same isolate.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 2 as const;\n\n/**\n * MIME type written for `current.json` PUTs. S3 round-trips this on\n * subsequent GETs; useful for diagnostics when staring at a bucket\n * via the AWS console.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Current major version of the `gc/pending.json` control-object\n * schema. Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `GcPending` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `gc/pending.json` PUTs.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Default grace period between \"marking\" a key for GC and \"sweeping\"\n * (deleting) it. 7 days, chosen to span the worst plausible writer-\n * retry window (a paused-process writer that resumes hours later\n * should still find its idempotency anchor on the bucket). The\n * `runGc()` function accepts an override for tests.\n *\n * Why 7 days specifically:\n * - **1 day is too aggressive for batch workloads.** Worker isolate\n * scheduling pauses, cross-region replication lag, and\n * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly\n * exceed an hour under pathological conditions.\n * - **30 days is conservative beyond the worst plausible pause.**\n * Doubles `gc/pending.json` size at steady state and slows\n * visibility into \"did GC actually run?\" by 4×.\n * - **7 days spans the realistic upper bound** — long-running batch\n * jobs, multi-region propagation delays, queue backlogs, and\n * downstream outages the writer is retrying through. The protocol\n * is unaffected by the choice of value within the [hours, weeks]\n * range; this constant is the operator-tunable knob.\n *\n * Production code MUST NOT call `runGc` with `graceMillis` below the\n * default outside maintenance windows — going below the longest\n * plausible writer-retry latency risks deleting an anchor a writer\n * is about to find on retry. Test code that sets `graceMillis: 0` is\n * exercising the sweep path deliberately, not modelling production.\n *\n * @see packages/server/src/gc.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const GC_GRACE_PERIOD_MILLIS: number = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Cap on candidates kept in `gc/pending.json` to bound the size of\n * the file. The compactor marks at most this many candidates per\n * pass; subsequent passes pick up the rest. Larger collections will\n * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which\n * is acceptable.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_MAX_PENDING_CANDIDATES: number = 1000;\n\n/**\n * Fold-trigger ratio: fold fires at tail ≥ R×snapshot. Pure READ-AMP / fold-frequency\n * knob — with the ceiling on the snapshot axis (Decision 3a, tail sliced) the\n * auto-maintained snapshot ceiling is S_max = C, NOT C/(1+R). R=1.0 caps steady-state\n * read-amp at ~2× and keeps compaction write-amp (≈1+1/R) moderate. See\n * docs/about/graduation.md for the derivation.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TARGET_RATIO: number = 1;\n\n/**\n * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also\n * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.\n *\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MIN_LIVE_BYTES: number = 64 * 1024;\n\n/**\n * Per-tick GC budget — these are DEFAULTS (= the most-constrained tier, CF free, reusing\n * the TESTED `CLOUDFLARE_FREE_TIER` values in maintenance.ts / maintenance.budget.test.ts).\n * The adapter THREADS per-tier overrides into the context (§8.4); Node/CF-paid raise them.\n * NOT universal constants — a Node-sized value here would silently kill every CF-free fold\n * (round-4 Tier-1). gc pass ≈ 6 + maxMarks + maxSweeps subrequests (both GET/DELETE the\n * bucket — §3.1). Cadence is BOUNDARY-CROSSING (§3.1), not modulo.\n *\n * @see packages/server/src/maintenance.ts\n * @see packages/server/src/maintenance.budget.test.ts\n */\nexport const WRITE_TICK_GC_INTERVAL: number = 4; // tuned so maxSweeps/interval ≥ p (§7.1)\n\n/**\n * Fold-starvation guard (critique A): on `phasesPerTick:\"single\"`, every Nth GC-interval is a\n * HARD GC boundary the fold may NOT preempt, so a long fold-heavy drain can't starve GC to zero.\n * Stateless (seq-derived) — no per-isolate preemption counter (CF recycles isolates). At 4 a\n * sustained drain still yields ~1 GC tick per 4 GC-intervals.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const GC_STARVATION_GUARD: number = 4;\n\n/**\n * Maximum GC marks per write-tick pass (M in 6+M+S; GETs the live tail to hash).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_MARKS: number = 20;\n\n/**\n * Maximum GC sweeps per write-tick pass (S in 6+M+S; DELETE subrequests).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_SWEEPS: number = 10;\n\n/**\n * Per-pass tail SLICE default — compact()'s maxEntriesPerRun. Fold ≤ this+3 subrequests, so\n * a large tail drains incrementally over write-ticks (Decision 3). Adapter-overridable.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_FOLD_ENTRIES_PER_PASS: number = 20;\n\n/**\n * compact()'s minEntriesToCompact, set EXPLICITLY by the runner so it agrees with Gate 1\n * rather than inheriting compact()'s silent default 100 (which would contradict the 64 KB\n * first-fold story — round-4 Tier-3). Adapter-overridable; CF-free value.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_MIN_ENTRIES_TO_COMPACT: number = 50;\n\n/**\n * Node-tier write-tick maintenance caps — a MODERATE multiple of the CF-free `WRITE_TICK_*`\n * defaults, threaded into the per-request observability context by `baerlyNode` /\n * `createFetchHandler` (§8.4). Node v1 runs maintenance INLINE on the commit path (no\n * `waitUntil`), so the cap is NOT the CF subrequest wall — it's the worst-case single-write\n * added latency. A maintenance tick only fires on a ratio/boundary trip (rare), and when it\n * does it costs ~`maxFoldEntriesPerPass` + (6 + `gcMaxMarks` + `gcMaxSweeps`) storage\n * round-trips against a co-located S3/R2 — sub-second on the occasional boundary write at a\n * 10× multiple. These are deliberately BOUNDED (10× CF-free), NOT unbounded: the deleted\n * scheduled full-tail sweep folded the entire live tail in one shot, which a 100× multiple here\n * would reintroduce as multi-second commit stalls. Raise the snapshot ceiling separately via\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; these caps slice the per-pass work, not the ceiling.\n *\n * @see packages/adapter-node/src/server.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\nexport const NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS: number = 200;\n\n/** Node-tier GC marks per pass (M in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_MARKS: number = 200;\n\n/** Node-tier GC sweeps per pass (S in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_SWEEPS: number = 100;\n\n/**\n * Node-tier GC cadence (boundary-crossing). Shorter than the CF-free `WRITE_TICK_GC_INTERVAL`\n * (4) so the per-write sweep budget keeps up: `gcMaxSweeps / gcInterval = 100 / 2 = 50`\n * comfortably clears the garbage-per-write rate `p` (the `maxSweeps/interval ≥ p` invariant,\n * §7.1) with a wide margin.\n *\n * @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS}\n */\nexport const NODE_MAINTENANCE_GC_INTERVAL: number = 2;\n\n/**\n * SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized\n * ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable\n * hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT: number = 512 * 1024;\n\n/**\n * The largest snapshot a Cloudflare **free-tier** isolate can safely\n * rebuild in ONE fold under the ~10 ms CPU budget. This is the WARN\n * THRESHOLD, not a runtime cap: an operator who raises\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` ABOVE this value on a free Worker\n * risks a snapshot rebuild that exceeds the ~10 ms CPU limit and gets\n * CPU-killed MID-REBUILD — the CAS never lands, so the fold silently\n * never advances `log_seq_start` and the tail grows unbounded.\n *\n * Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The default\n * (512 KiB) rebuilds in ~5.5 ms under the CF-free ~10 ms budget\n * (constants.ts default JSDoc); linear-extrapolating, ~1 MiB is the\n * point where one-shot rebuild fills the budget with little margin, so\n * anything strictly larger is no longer free-tier-safe. On CF **paid**\n * (raised CPU limits), Node, or once §11 chunked snapshots land, a\n * larger ceiling is fine — hence this is a one-time `console.warn` at\n * handler init, NOT a hard rejection.\n *\n * @see packages/adapter-cloudflare/src/worker.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const CF_FREE_MAX_SAFE_FOLD_BYTES: number = 1024 * 1024;\n\n/**\n * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry\n * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021\n * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — calibrate via the\n * Task 3 bench, pin in graduation.md.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_MAX_FOLD_ROWS: number = 2048;\n\n/**\n * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate\n * memory — CF recycles isolates). ~once per this many writes.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_WARN_INTERVAL_WRITES: number = 1000;\n\n/**\n * Placeholder for `CurrentJson.snapshot === null` in the\n * `_meta.manifest_pointer` cursor emitted on read responses. The\n * wire format is `\"<snapshot>@<next_seq>\"`, and `null` snapshots\n * serialise as this literal so the cursor is never empty and stays\n * byte-stable when destructured by operators.\n *\n * @see packages/server/src/contract.ts (HttpOkMeta)\n */\nexport const MANIFEST_POINTER_EMPTY_SNAPSHOT: string = \"none\";\n\n/**\n * Keys that must never propagate through {@link merge}: assigning to\n * them on a plain object pollutes the prototype chain. The literal\n * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)\n * and bypasses `Object.keys`, but `JSON.parse('{\"__proto__\":...}')`\n * produces a real own property — which is exactly how a malicious\n * HTTP PATCH body would arrive on the wire.\n *\n * Lifted to a constant so every iteration path that touches a\n * caller-supplied object can re-use the same defence without\n * duplicating the keyword list.\n *\n * @see packages/protocol/src/json.ts (merge)\n * @see docs/spec/json-merge-patch.md\n */\nexport const FORBIDDEN_MERGE_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Architecturally-enforced ceiling: storage ops per logical write.\n *\n * Three Class A ops: PUT content, PUT log entry, CAS-advance\n * `current.json`. The cost-model page derives the free-tier write\n * budget from this multiplier; the phase-5 end-to-end test asserts it\n * at CI time. Changing this constant is a cost-model-breaking change.\n *\n * @see docs/about/cost-model.md §\"Cost ceiling\"\n * @see tests/integration/phase5-end-to-end.test.ts\n */\nexport const STORAGE_OPS_PER_LOGICAL_WRITE: number = 3;\n\n/**\n * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,\n * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,\n * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.\n *\n * - `\"none\"` — no header check; pin every request to `config.tenant`.\n * For local dev, intranet, CLI tools — contexts where the network\n * seam itself is the trust boundary.\n * - `\"shared-secret\"` — bearer-token check; reads `SHARED_SECRET` from\n * the runtime env and pins every request to `config.tenant`.\n *\n * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass\n * this enum — pass a `Verifier` to the adapter factory's `verifier:`\n * option instead.\n */\nexport const AUTH_CONFIG_VALUES = [\"none\", \"shared-secret\"] as const;\n\n/**\n * Locked error wording for the \"no auth configured\" failure mode. The\n * adapter throws this when neither `config.auth` nor `verifier:`\n * resolves a real `Verifier`. Pinned via a regression test so future\n * refactors do not drift the operator-facing wording.\n *\n * Consumed by:\n * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)\n * - `packages/adapter-node/src/server.ts` (first-fetch throw)\n * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)\n */\nexport const NO_AUTH_CONFIGURED_MESSAGE: string =\n 'baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.';\n\n/**\n * Locked error wording for `auth: \"shared-secret\"` + missing env var.\n * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.\n */\nexport const SHARED_SECRET_MISSING_MESSAGE: string =\n 'baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.';\n","/**\n * `current.json` — the per-collection CAS-protected control object — and\n * its embedded {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps\n * snapshot generations by CAS-writing this object; the\n * Writer reads it on every commit to find the snapshot\n * pointer; the sweeper reads `writer_fence` to decide which log\n * entries are eligible for GC.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `2`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 2;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Sequence number of the next log entry. Monotonic per\n * collection. The Writer reads this on commit to mint the\n * next log filename; CAS-write back with `next_seq + 1` ensures\n * no two writers pick the same sequence.\n */\n next_seq: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, next_seq)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= next_seq`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n\n // New in v2:\n\n /** EXACT byte size of the live log tail [log_seq_start, next_seq). Maintained exactly\n * by the full-fence CAS on BOTH paths: each write adds its log bytes; a successful\n * fold (which proves no concurrent write) resets to 0 from a known-empty tail. */\n tail_bytes: number;\n\n /** Byte size of the snapshot pointed to by `snapshot`. */\n snapshot_bytes: number;\n\n /** Row count of the snapshot (= compactor `base.size`, free). With next_seq - log_seq_start\n * (tail entries) this gives the fold's entry count for the ENTRY ceiling `E`. Seeded 0. */\n snapshot_rows: number;\n\n /** Baseline for rate-limiting the graduation defer-warn off SHARED durable state, not\n * per-isolate memory. The warn fires when next_seq - last_warned_seq >=\n * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes last_warned_seq = next_seq.\n * Absent → 0. */\n last_warned_seq?: number;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is the server response date at claim time, NOT the\n * local clock; `lease_until` is reserved for manual rotation and\n * is not consumed by any ticket in this batch.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. The mechanism is the same in all three: every commit\n * checks the epoch on the control object; an entry stamped with\n * a stale epoch is discarded at replay.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Triggers per design: (a) detected\n * CAS conflict the writer wants to claim through, (b) admin\n * rotation. The sweeper discards log entries whose stamped epoch\n * is `< current.writer_fence.epoch`.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the write fence by bumping `epoch` and stamping\n * `claimed_at` from `StoragePutResult.serverDate`. The common call\n * site is \"I detected a CAS conflict during a commit and want to\n * claim the fence before retrying\"; admin rotation is the other call\n * site.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n // Stryker disable next-line ConditionalExpression: `→true` spreads `{lease_until: undefined}` which JSON.stringify omits, so the stored bytes are identical to the normal `→false` path (no key emitted). Genuine equivalent mutant.\n ...(existing.json.writer_fence.lease_until !== undefined && {\n lease_until: existing.json.writer_fence.lease_until,\n }),\n },\n };\n const body = encodeJson(provisional);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n // No server clock surfaced — leave `claimed_at` empty. The epoch\n // bump is durable; safety is unaffected.\n if (result.serverDate === undefined) {\n return { json: provisional, etag: result.etag };\n }\n // Stamp the server clock through a second CAS-on-our-own-etag. A\n // peer landing between the two writes loses cleanly with Conflict\n // (the fence is safe — next claim will bump past both).\n const stamped: CurrentJson = {\n ...provisional,\n writer_fence: {\n ...provisional.writer_fence,\n claimed_at: result.serverDate.toISOString(),\n },\n };\n const stampedBody = encodeJson(stamped);\n const stampPutOpts: StoragePutOptions = {\n ifMatch: result.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let stampResult: StoragePutResult;\n try {\n stampResult = await storage.put(key, stampedBody, stampPutOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: stamped, etag: stampResult.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, next_seq)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing. Tolerant\n * reader: unknown keys ignored, new required fields bump\n * `schema_version` (move (b), ADR-007).\n */\nconst assertCurrentJson = (parsed: unknown, key: string): CurrentJson => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] === 1) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} is schema v1 (pre-maintenance); this build requires v2. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`,\n );\n }\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; expected ${CURRENT_JSON_SCHEMA_VERSION}`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n // Stryker disable next-line ConditionalExpression,StringLiteral: three equivalent mutants on this line — (1) `typeof r[\"next_seq\"] !== \"number\"` → false is subsumed by !Number.isInteger (which rejects all non-numbers); (2) `r[\"next_seq\"] < 0` → false is subsumed by the downstream `log_seq_start > next_seq` cross-check (log_seq_start ≥ 0, so log_seq_start > negative_next_seq always fires); (3) StringLiteral \"next_seq\" → \"\" turns r[\"\"] → undefined → !Number.isInteger(undefined) still true → still throws.\n if (typeof r[\"next_seq\"] !== \"number\" || !Number.isInteger(r[\"next_seq\"]) || r[\"next_seq\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: next_seq must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"log_seq_start\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers anyway, making the typeof check fully subsumed.\n typeof r[\"log_seq_start\"] !== \"number\" ||\n !Number.isInteger(r[\"log_seq_start\"]) ||\n r[\"log_seq_start\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start must be a non-negative integer`,\n );\n }\n if (r[\"log_seq_start\"] > r[\"next_seq\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > next_seq ${String(r[\"next_seq\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n // Stryker disable next-line ConditionalExpression: `typeof f[\"epoch\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof guard fully subsumed.\n if (typeof f[\"epoch\"] !== \"number\" || !Number.isInteger(f[\"epoch\"]) || f[\"epoch\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.epoch must be a non-negative integer`,\n );\n }\n if (typeof f[\"owner\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.owner must be a string`,\n );\n }\n if (typeof f[\"claimed_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.claimed_at must be a string`,\n );\n }\n if (f[\"lease_until\"] !== undefined && typeof f[\"lease_until\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.lease_until must be string if present`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"tail_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"tail_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"tail_bytes\"]) ||\n r[\"tail_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: tail_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_bytes\"]) ||\n r[\"snapshot_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_rows\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_rows\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_rows\"]) ||\n r[\"snapshot_rows\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_rows must be a non-negative integer`,\n );\n }\n if (\n r[\"last_warned_seq\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: `typeof r[\"last_warned_seq\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n (typeof r[\"last_warned_seq\"] !== \"number\" ||\n !Number.isInteger(r[\"last_warned_seq\"]) ||\n r[\"last_warned_seq\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: last_warned_seq must be a non-negative integer if present`,\n );\n }\n return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n"],"mappings":";;;;;;AAKA,MAAa,mBAAmB,UAC9B,IAAI,YAAY,EAAE,OAAO,KAAK,UA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AmB,IAAI,4CACzB;CAEF,IAEE,OAAO,EAAE,sBAAsB,YAC/B,CAAC,OAAO,UAAU,EAAE,iBAAiB,KACrC,EAAE,oBAAoB,GAEtB,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,gDACzB;CAEF,IAEE,OAAO,EAAE,qBAAqB,YAC9B,CAAC,OAAO,UAAU,EAAE,gBAAgB,KACpC,EAAE,mBAAmB,GAErB,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,+CACzB;CAEF,IACE,EAAE,uBAAuB,KAAA,MAExB,OAAO,EAAE,uBAAuB,YAC/B,CAAC,OAAO,UAAU,EAAE,kBAAkB,KACtC,EAAE,qBAAqB,IAEzB,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,4DACzB;CAEF,OAAO;AACT;;;;;;;;AASA,MAAM,qBAAqB,GAAY,QAA6B;CAClE,IAAI,aAAa,eAAe,EAAE,SAAS,YACzC,OAAO,IAAI,YAAY,YAAY,4BAA4B,IAAI,IAAI,EAAE,WAAW,CAAC;CAEvF,IAAI,aAAa,aACf,OAAO;CAET,OAAO,IAAI,YAAY,mBAAmB,yBAAyB,IAAI,WAAW,OAAO,CAAC,KAAK,CAAC;AAClG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"deploy-CrAbfgCq.js","names":[],"sources":["../packages/cli/src/deploy.ts"],"sourcesContent":["/**\n * `baerly deploy` — citty dispatcher.\n *\n * Reads `baerly.config.ts:target` and routes to the matching\n * deploy backend. Today: `cloudflare` only — the `node` example\n * embodies its deployment shape directly (self-host via `node\n * server.js` after your PaaS or container build), so `baerly\n * deploy` rejects `target: \"node\"` with an actionable InvalidConfig.\n *\n * Exit-code contract (standard CLI shape):\n * - 0 success.\n * - 1 user error (InvalidConfig, missing config, unknown target).\n * - 2 storage / external error (NetworkError, Wrangler returned\n * non-zero, anything non-BaerlyError).\n * - 3 protocol invariant (Conflict, Internal, InvalidResponse —\n * should not happen here unless someone hand-edited mid-flight).\n */\n\nimport { defineCommand, type ArgsDef, type ParsedArgs } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { deployCloudflare } from \"./deploy/cloudflare.ts\";\nimport { emitError, emitSuccess, setJsonMode } from \"./output.ts\";\n\nconst DEPLOY_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (\"node\" self-deploys via your PaaS or container build).',\n valueHint: \"cloudflare\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\"target\", \"json\", \"_\"]);\n\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\nconst handleDeploy = async (args: ParsedArgs<typeof DEPLOY_ARGS>): Promise<number> => {\n setJsonMode(args.json === true);\n try {\n for (const k of Object.keys(args)) {\n if (!KNOWN_KEYS.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly deploy: unknown flag --${k}`);\n }\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const exit = await deployCloudflare(config);\n if (exit === 0) {\n emitSuccess({ command: \"deploy\", status: \"ok\", target });\n }\n return exit;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: target ${JSON.stringify(target)} has no deploy backend. ` +\n `Self-host: \\`node server.js\\` after your PaaS or container build. ` +\n `Cloudflare Workers is the only managed deploy backend today.`,\n );\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(\"deploy\", error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(\"deploy\", \"Unknown\", (error as Error).message);\n return 2;\n }\n};\n\n/** citty `defineCommand` block for `baerly deploy`. */\nexport const deploy = defineCommand({\n meta: {\n name: \"deploy\",\n description: \"Deploy this baerly app. Dispatches by baerly.config.ts:target.\",\n },\n args: DEPLOY_ARGS,\n run: async ({ args }) => {\n const code = await handleDeploy(args);\n if (code !== 0) {\n process.exit(code);\n }\n },\n});\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 runDeploy = async (argv: readonly string[]): Promise<number> => {\n const { parseArgs } = await import(\"citty\");\n let parsed: ParsedArgs<typeof DEPLOY_ARGS>;\n try {\n parsed = parseArgs<typeof DEPLOY_ARGS>(argv as string[], DEPLOY_ARGS);\n } catch (error) {\n setJsonMode(argv.includes(\"--json\"));\n emitError(\"deploy\", \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return handleDeploy(parsed);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,cAAc;CAClB,QAAQ;EACN,MAAM;EACN,aACE;EACF,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;AACF;AAEA,MAAM,aAAkC,IAAI,IAAI;CAAC;CAAU;CAAQ;AAAG,CAAC;AAEvE,MAAM,mBAAmB,SAAyB;CAChD,IAAI,SAAS,iBACX,OAAO;CAET,IAAI,SAAS,cAAc,SAAS,cAAc,SAAS,mBACzD,OAAO;CAET,OAAO;AACT;AAEA,MAAM,eAAe,OAAO,SAA0D;CACpF,YAAY,KAAK,SAAS,IAAI;CAC9B,IAAI;EACF,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,GAC9B,IAAI,CAAC,WAAW,IAAI,CAAC,GACnB,MAAM,IAAI,YAAY,iBAAiB,iCAAiC,GAAG;EAG/E,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAC3B,MAAM,OAAO,MAAM,iBAAiB,MAAM;GAC1C,IAAI,SAAS,GACX,YAAY;IAAE,SAAS;IAAU,QAAQ;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