@gusto/baerly-storage 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -5
- package/dist/API.md +161 -10
- package/dist/{app-config-Cb5dO2s9.d.ts → app-config-C0Bbw_Z6.d.ts} +18 -9
- package/dist/app-config.d.ts +1 -1
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js +11 -0
- package/dist/bytes-BXdamO3L.js.map +1 -0
- package/dist/{client-BLf3Ae5s.d.ts → client-DYZfoZb9.d.ts} +3 -3
- package/dist/client-react.d.ts +3 -3
- package/dist/client.d.ts +3 -3
- package/dist/cloudflare.d.ts +31 -4
- package/dist/cloudflare.js +72 -6
- package/dist/cloudflare.js.map +1 -1
- package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
- package/dist/config-DVfDGyw1.js.map +1 -0
- package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
- package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
- package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
- package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
- package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
- package/dist/current-json-C-EyJqs0.js.map +1 -0
- package/dist/{db-D62JguBc.d.ts → db-BM3y2JQw.d.ts} +3 -3
- package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
- package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
- package/dist/dev-vite.d.ts +3 -3
- package/dist/dev-vite.js +3 -3
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
- package/dist/doctor-Db-hzPmE.js.map +1 -0
- package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
- package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
- package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
- package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
- package/dist/fsck-CPPZWt9p.js.map +1 -0
- package/dist/{http-CjUO1Bec.js → http-Cw8p6y5b.js} +8 -8
- package/dist/{http-CjUO1Bec.js.map → http-Cw8p6y5b.js.map} +1 -1
- package/dist/http.d.ts +6 -6
- package/dist/http.js +1 -1
- package/dist/{index-BYv0hb8M.d.ts → index-C3JAH1Yo.d.ts} +14 -2
- package/dist/{index-BGC-ENnj.d.ts → index-DSvwEUeF.d.ts} +63 -54
- package/dist/{index-BquQkhJi.d.ts → index-DwDTWPSU.d.ts} +2 -2
- package/dist/{index-COsQ-Mlz.d.ts → index-cUY-36AN.d.ts} +3 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/{indexes-DwOXkn1Y.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
- package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
- package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
- package/dist/maintenance-BRrThz8V.d.ts +449 -0
- package/dist/maintenance-BvOv6BMM.js +1295 -0
- package/dist/maintenance-BvOv6BMM.js.map +1 -0
- package/dist/maintenance-ClzBC1Vv.js +1895 -0
- package/dist/maintenance-ClzBC1Vv.js.map +1 -0
- package/dist/maintenance.d.ts +2 -323
- package/dist/maintenance.js +2 -2
- package/dist/node.d.ts +20 -79
- package/dist/node.js +2 -2
- package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
- package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +2 -2
- package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
- package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
- package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
- package/dist/query-BmiQy328.js.map +1 -0
- package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
- package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
- package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
- package/dist/restore-C6IcmLeA.js.map +1 -0
- package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
- package/dist/snapshot-SS8USDUF.js.map +1 -0
- package/dist/{src-DyET_VPP.js → src-DU1sCMlr.js} +315 -278
- package/dist/src-DU1sCMlr.js.map +1 -0
- package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
- package/dist/src-QQ7jDeL2.js.map +1 -0
- package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
- package/dist/src-zhEAmmF7.js.map +1 -0
- package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
- package/dist/subcommand-DZcHcsYp.js.map +1 -0
- package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
- package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
- package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
- package/dist/validate-DCq_0DIn.js.map +1 -0
- package/package.json +13 -6
- package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
- package/dist/config-Bsg8wgwo.js.map +0 -1
- package/dist/current-json-BkatBzF7.js.map +0 -1
- package/dist/doctor-B8h9GCN9.js.map +0 -1
- package/dist/fsck-DEz9lyCy.js.map +0 -1
- package/dist/indexes-BXn7a06a.js +0 -297
- package/dist/indexes-BXn7a06a.js.map +0 -1
- package/dist/log-walk-DIru96UT.js.map +0 -1
- package/dist/maintenance-Bn6ul9aV.js +0 -758
- package/dist/maintenance-Bn6ul9aV.js.map +0 -1
- package/dist/query-DcSbFLJt.js.map +0 -1
- package/dist/rebuild-index-C5gTXryd.js +0 -119
- package/dist/rebuild-index-C5gTXryd.js.map +0 -1
- package/dist/restore-CbKVMMpm.js.map +0 -1
- package/dist/snapshot-D7C4_FSl.js +0 -71
- package/dist/snapshot-D7C4_FSl.js.map +0 -1
- package/dist/snapshot-z_N9hpTe.js +0 -917
- package/dist/snapshot-z_N9hpTe.js.map +0 -1
- package/dist/src-Chafbw8r.js.map +0 -1
- package/dist/src-DyET_VPP.js.map +0 -1
- package/dist/src-n0Te1r98.js.map +0 -1
- package/dist/subcommand-BWs6K7zb.js +0 -110
- package/dist/subcommand-BWs6K7zb.js.map +0 -1
- package/dist/validate-DhH1lO8I.js.map +0 -1
package/dist/cloudflare.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare.js","names":["#bucket","#callBinding"],"sources":["../packages/adapter-cloudflare/src/r2-binding-storage.ts","../packages/adapter-cloudflare/src/cache.ts","../packages/adapter-cloudflare/src/worker.ts"],"sourcesContent":["import {\n BaerlyError,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\n\n/**\n * Construction options for {@link r2BindingStorage}. The factory takes\n * the `R2Bucket` binding directly, so this interface only exists to\n * document the shape consumers see in their `env`.\n */\nexport interface R2BindingStorageOptions {\n /**\n * The R2 binding from `env`. In `wrangler.toml`:\n *\n * [[r2_buckets]]\n * binding = \"BUCKET\"\n * bucket_name = \"baerly-prod\"\n *\n * Then: `r2BindingStorage(env.BUCKET)`.\n */\n bucket: R2Bucket;\n}\n\n/**\n * R2's binding API returns bare-hex ETags (`R2Object.etag`). The\n * `Storage` contract follows S3's wire format — quoted (`\"<hex>\"`).\n * `stripQuotes` is forgiving of unquoted input so external sources\n * that hand us bare hex don't break.\n */\nconst stripQuotes = (etag: string): string =>\n etag.startsWith('\"') && etag.endsWith('\"') ? etag.slice(1, -1) : etag;\nconst quoteEtag = (hex: string): string => `\"${hex}\"`;\n\nclass R2BindingStorageImpl implements Storage {\n readonly #bucket: R2Bucket;\n\n constructor(bucket: R2Bucket) {\n if (bucket === null || bucket === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"r2BindingStorage: bucket binding is null/undefined — check wrangler.toml [[r2_buckets]] and the env var name\",\n );\n }\n this.#bucket = bucket;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const getOpts: R2GetOptions = {};\n if (opts?.ifNoneMatch !== undefined) {\n getOpts.onlyIf = { etagDoesNotMatch: stripQuotes(opts.ifNoneMatch) };\n }\n const obj = await this.#callBinding(() => this.#bucket.get(key, getOpts), `GET ${key}`);\n if (obj === null) {\n return null;\n }\n // R2 returns a bare `R2Object` (no body) when a conditional GET's\n // precondition succeeds — i.e. the caller's copy is current.\n // Match the `Storage` contract's 304 → null semantics.\n if (!(\"body\" in obj) || obj.body === null) {\n return null;\n }\n const body = new Uint8Array(await obj.arrayBuffer());\n return { body, etag: quoteEtag(obj.etag) };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const putOpts: R2PutOptions = {};\n if (opts?.contentType !== undefined) {\n putOpts.httpMetadata = { contentType: opts.contentType };\n }\n if (opts?.ifMatch !== undefined) {\n putOpts.onlyIf = { etagMatches: stripQuotes(opts.ifMatch) };\n } else if (opts?.ifNoneMatch === \"*\") {\n // R2 spells \"create only\" as `etagDoesNotMatch: \"*\"` (wildcard).\n // Do NOT strip the `*` — it's the literal wildcard, not an\n // etag.\n putOpts.onlyIf = { etagDoesNotMatch: \"*\" };\n }\n const result = await this.#callBinding(\n () => this.#bucket.put(key, body, putOpts),\n `PUT ${key}`,\n );\n if (result === null) {\n // Binding signals precondition failure as `null`.\n throw new BaerlyError(\"Conflict\", `PUT ${key}: precondition failed`);\n }\n // `R2Object.uploaded` is the server-side write clock — surface it\n // verbatim. The kernel's adaptive-clock-skew loop consumes it\n // identically to `S3HttpStorage`'s `Date` header.\n return {\n etag: quoteEtag(result.etag),\n serverDate: result.uploaded,\n };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n // R2.delete is idempotent — matches the `Storage.delete` contract.\n await this.#callBinding(() => this.#bucket.delete(key), `DELETE ${key}`);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n let cursor: string | undefined = undefined;\n let yielded = 0;\n const startAfter = opts?.startAfter ?? \"\";\n const cap = opts?.maxKeys ?? Infinity;\n while (true) {\n opts?.signal?.throwIfAborted();\n // Break BEFORE the next list() call when the cap is already hit\n // — R2 rejects `limit: 0` with `MaxKeys params must be positive\n // integer <= 1000. (10022)`, so we can't just clamp.\n if (yielded >= cap) {\n return;\n }\n // R2.list: `limit` capped at 1000 per request. Page via\n // `cursor` until `truncated === false`. `startAfter` honored\n // only on the first page (one-shot cursor).\n const listOpts: R2ListOptions = { prefix };\n if (cursor !== undefined) {\n listOpts.cursor = cursor;\n } else if (startAfter !== \"\") {\n listOpts.startAfter = startAfter;\n }\n if (cap !== Infinity) {\n listOpts.limit = Math.min(cap - yielded, 1000);\n }\n const page = await this.#callBinding(() => this.#bucket.list(listOpts), `LIST ${prefix}`);\n for (const obj of page.objects) {\n if (yielded >= cap) {\n return;\n }\n yield {\n key: obj.key,\n etag: quoteEtag(obj.etag),\n lastModified: obj.uploaded,\n };\n yielded += 1;\n }\n if (!page.truncated) {\n return;\n }\n cursor = page.cursor;\n if (cursor === undefined) {\n return;\n }\n }\n }\n\n /**\n * Map binding-layer errors to `BaerlyError` codes. The R2 binding\n * surfaces failures as plain `Error` with messages; sniff the\n * common ones. If the binding ever adds typed errors, tighten the\n * sniff and keep the message fallback for older runtimes.\n */\n async #callBinding<T>(fn: () => Promise<T>, op: string): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n const msg = error instanceof Error ? error.message : String(error);\n if (/auth|permission|forbidden/i.test(msg)) {\n throw new BaerlyError(\"AccessDenied\", `${op}: ${msg}`, error);\n }\n if (/not.*found|no.*such.*bucket/i.test(msg)) {\n throw new BaerlyError(\"InvalidConfig\", `${op}: ${msg}`, error);\n }\n throw new BaerlyError(\"NetworkError\", `${op}: ${msg}`, error);\n }\n }\n}\n\n/**\n * Construct a `Storage` backed by a Cloudflare R2 binding. The R2\n * binding bypasses SigV4 entirely: requests are dispatched in-cell\n * over a Cloudflare-internal channel, so the hot path skips\n * canonical-request building, body hashing, and DNS/TLS to a\n * separate origin.\n *\n * Pick this over `S3HttpStorage` when the Worker and bucket are in\n * the same Cloudflare account. Cross-cloud (AWS, GCS) and\n * cross-account R2 stay on the HTTP path.\n *\n * Wire-format conventions:\n * - ETags returned in `\"<hex>\"` (S3 wire format) even though R2's\n * binding returns bare hex. CAS round-trips strip and re-apply\n * the quotes.\n * - `serverDate` from `R2Object.uploaded` — a real server clock,\n * suitable for the kernel's adaptive-clock-skew loop.\n * - `StorageListEntry.lastModified` from the same clock.\n *\n * Errors map to `BaerlyError` via the same convention as\n * `S3HttpStorage`: `AccessDenied` for binding-level permission\n * failures, `NetworkError` for transient R2 platform failures,\n * `InvalidResponse` for precondition (CAS) failures, `InvalidConfig`\n * if the caller hands in a null/undefined binding.\n *\n * @example\n * ```ts\n * import { r2BindingStorage } from \"@gusto/baerly-storage/cloudflare\";\n *\n * export default {\n * fetch(req, env: { BUCKET: R2Bucket }) {\n * const storage = r2BindingStorage(env.BUCKET);\n * // ...wire to Db\n * },\n * };\n * ```\n */\nexport function r2BindingStorage(bucket: R2Bucket): Storage {\n return new R2BindingStorageImpl(bucket);\n}\n","/**\n * Cloudflare Cache API integration for the Worker read path.\n * Worker-only; Node has no equivalent and runs cache-less.\n *\n * Contract:\n * - Only `GET /v1/c/:collection/:id` is cached. LIST URLs\n * (`GET /v1/c/:collection`, with or without filters) bypass the cache.\n * The Cloudflare Cache API exposes no enumeration primitive, so\n * filtered-LIST variants (`?where=...`) cannot be safely\n * invalidated on writes; rather than ship a per-isolate index\n * that only partially survives across the colo-shared cache, we\n * skip list caching entirely. If LIST caching ever becomes a\n * bottleneck, revisit with a cross-isolate primitive (CF Cache\n * Tags, KV-backed invalidation, etc).\n * - `GET /v1/since` and `GET /v1/healthz` also bypass the cache\n * (the long-poll's mutating cursor is not cacheable; healthz is\n * trivially fast and must never go stale).\n * - Cache key is the request URL + a synthetic `__t=<tenantPrefix>`\n * query param. This is the load-bearing correctness invariant:\n * the HTTP contract derives `tenant` from the `Verifier`, not the\n * URL, so two different Verifier outcomes against the same URL\n * must NOT share a cache entry. See `packages/server/src/contract.ts`.\n * - Only 200 responses with non-empty bodies are stored. 401/403/\n * 404/409/500 always bypass `cache.put`. Negative caching is out\n * of scope.\n * - `PATCH` / `DELETE` that return 2xx call `cache.delete()` on the\n * per-doc URL they hit. `POST` targets a LIST URL (uncached), so\n * nothing to bust. Best-effort — failures are swallowed.\n * - No `Cache-Control` header is added on the wire. We rely on\n * explicit invalidation, not TTLs.\n */\n\n/**\n * Methods we treat as mutating for invalidation purposes. Keep this\n * list narrow — adding a method to `WRITE_METHODS` doubles the\n * invalidation surface and matters for correctness.\n */\nconst WRITE_METHODS = new Set<string>([\"POST\", \"PATCH\", \"DELETE\"]);\n\n/** Pathname prefixes that bypass the cache entirely. */\nconst BYPASS_PREFIXES = [\"/v1/since\", \"/v1/healthz\"];\n\n/**\n * `Cache-Control: max-age=<n>` value we set on the cacheable response\n * handed to `cache.put`. workerd's `caches.default.put` silently\n * no-ops on responses without a cacheable directive, so we synthesize\n * one. The value is large because we rely on explicit per-doc\n * invalidation, not expiry — see `invalidateOnWrite`.\n */\nconst CACHE_TTL_SECONDS = 3600;\n\n/**\n * Build the canonical cache-key `Request` for a given `(req,\n * tenantPrefix)`. The synthetic `__t` query parameter scopes the\n * cache per-tenant; without it, two tenants with overlapping URLs\n * would share entries — a security bug.\n *\n * The returned `Request` is GET-only by construction — even when\n * `req.method` is POST/PATCH/DELETE we use the GET form for\n * `cache.delete()` so the read-side write and the write-side bust\n * land on the same key.\n */\nexport function cacheKeyFor(req: Request, tenantPrefix: string): Request {\n const url = new URL(req.url);\n // `set` not `append` — defends against a malicious caller-supplied\n // `?__t=spoof`. The server-controlled value always wins.\n url.searchParams.set(\"__t\", tenantPrefix);\n return new Request(url.toString(), { method: \"GET\" });\n}\n\n/**\n * Should this request bypass the cache layer entirely (both read and\n * invalidate sides)? Healthz + long-poll + anything that isn't a\n * per-doc URL (`/v1/c/:collection/:id`).\n */\nfunction bypassesCache(url: URL): boolean {\n if (BYPASS_PREFIXES.some((p) => url.pathname.startsWith(p))) {\n return true;\n }\n if (!url.pathname.startsWith(\"/v1/c/\")) {\n return true;\n }\n // LIST URLs (`/v1/c/<table>` with no `/<id>`) bypass — see header\n // docstring for why filtered-LIST caching isn't safe here.\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 4) {\n return true;\n }\n return false;\n}\n\n/**\n * Discriminator returned alongside the response so the adapter can\n * stamp `cache_status` on the canonical line. The cache itself\n * doesn't emit — the adapter owns the canonical line.\n *\n * - `\"hit\"` — the cache returned an entry (both the 304\n * If-None-Match path and the body-bearing 200 path\n * classify as hits; the cache served the request\n * without invoking the handler).\n * - `\"miss\"` — the request was cacheable but the cache had no\n * entry; the handler ran and (when the response was\n * cacheable) its output was stored.\n * - `\"bypass\"` — the request never consulted the cache (non-GET,\n * LIST URL, a path under {@link BYPASS_PREFIXES}, or\n * a path outside `/v1/c/`).\n */\nexport type CacheStatus = \"hit\" | \"miss\" | \"bypass\";\n\n/**\n * Discriminator-tagged return value of {@link withReadCache}. The\n * adapter stamps `cache_status` onto the canonical-line `extra` bag\n * before flushing — see `worker.ts`'s `fetch` handler.\n */\nexport interface ReadCacheResult {\n readonly response: Response;\n readonly cache_status: CacheStatus;\n}\n\n/**\n * Read-path wrapper. Call this in place of invoking the router\n * directly for `GET` requests. Returns `{ response, cache_status }`\n * so the adapter can stamp `cache_status` on the canonical line:\n *\n * - `cache_status: \"bypass\"` — non-GET method, LIST URL, or a path\n * under {@link BYPASS_PREFIXES} (`/v1/since`, `/v1/healthz`), or\n * a path outside `/v1/c/`. The handler runs verbatim and its\n * response is returned untouched.\n * - `cache_status: \"hit\"` — the cache had an entry. Returns\n * either a synthesized 304 (when `If-None-Match` matches the\n * cached ETag) or the cached body (200). The handler does NOT\n * run.\n * - `cache_status: \"miss\"` — the cache had no entry. The handler\n * runs and, if the response is a cacheable 200 with no\n * `Set-Cookie`, the response is stored before being returned.\n */\nexport async function withReadCache(\n req: Request,\n tenantPrefix: string,\n handler: () => Promise<Response>,\n): Promise<ReadCacheResult> {\n const url = new URL(req.url);\n if (req.method !== \"GET\" || bypassesCache(url)) {\n return { response: await handler(), cache_status: \"bypass\" };\n }\n\n // `caches.default` is Workers-only; DOM's `CacheStorage` lib type\n // doesn't expose it, so we cast through `unknown` to the shape we\n // need. miniflare provides the real binding at runtime.\n const cache = (caches as unknown as { default: Cache }).default;\n const key = cacheKeyFor(req, tenantPrefix);\n const cached = await cache.match(key);\n if (cached !== undefined) {\n const etag = cached.headers.get(\"etag\");\n const ifNoneMatch = req.headers.get(\"if-none-match\");\n if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) {\n // 304 has no body, but keeps the ETag so a CDN-aware client\n // can continue revalidating against it.\n return {\n response: new Response(null, {\n status: 304,\n headers: { etag },\n }),\n cache_status: \"hit\",\n };\n }\n // Body-bearing hit. Clone so the cache entry stays intact for\n // the next request in the same Worker isolate. Strip the\n // synthetic `Cache-Control` header we added at `cache.put` time\n // so the client never sees TTLs we don't honor (invalidation-only\n // on the wire).\n const cloned = cached.clone();\n const outHeaders = new Headers(cloned.headers);\n outHeaders.delete(\"cache-control\");\n return {\n response: new Response(cloned.body, {\n status: cloned.status,\n statusText: cloned.statusText,\n headers: outHeaders,\n }),\n cache_status: \"hit\",\n };\n }\n\n const fresh = await handler();\n // Only cache stable 200 responses with a non-empty body. The Cache\n // API silently rejects responses with `Set-Cookie`; baerly never\n // sets cookies, but the guard is cheap insurance.\n if (fresh.status === 200 && !fresh.headers.has(\"set-cookie\")) {\n // workerd's `caches.default.put` silently no-ops on responses\n // without a cacheable `Cache-Control` directive. We synthesize\n // one ONLY on the response we hand the cache — the response we\n // return to the caller is untouched (invalidation-only on the\n // wire).\n const headers = new Headers(fresh.headers);\n headers.set(\"cache-control\", `max-age=${CACHE_TTL_SECONDS}`);\n const cacheable = new Response(fresh.clone().body, {\n status: fresh.status,\n statusText: fresh.statusText,\n headers,\n });\n await cache.put(key, cacheable);\n }\n return { response: fresh, cache_status: \"miss\" };\n}\n\n/**\n * Write-path companion. Call this AFTER the handler returns a 2xx\n * for `PATCH` / `DELETE` on a per-doc URL — busts the cache entry\n * for that URL. `POST` targets a LIST URL (uncached), so nothing to\n * bust; this function returns without touching the cache. Failures\n * are swallowed; a stale entry is recoverable via the 304 path on\n * the next read.\n */\nexport async function invalidateOnWrite(\n req: Request,\n tenantPrefix: string,\n responseStatus: number,\n): Promise<void> {\n if (!WRITE_METHODS.has(req.method)) {\n return;\n }\n if (responseStatus < 200 || responseStatus >= 300) {\n return;\n }\n const url = new URL(req.url);\n if (bypassesCache(url)) {\n return;\n }\n // `caches.default` is Workers-only; DOM's `CacheStorage` lib type\n // doesn't expose it, so we cast through `unknown` to the shape we\n // need. miniflare provides the real binding at runtime.\n const cache = (caches as unknown as { default: Cache }).default;\n await cache.delete(cacheKeyFor(req, tenantPrefix));\n}\n","import { type DevLandingOptions, renderDevLanding } from \"@baerly/dev\";\nimport { type BaerlyAppConfig, type Verifier } from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { createRouter } from \"@baerly/server/http\";\nimport {\n CATEGORY,\n type ObservabilityConfig,\n configureObservability,\n createObservabilityContext,\n deriveOutcome,\n flushCanonicalLine,\n flushUnauthorizedAndRespond,\n getLogger,\n observableStorage,\n runWithContext,\n} from \"@baerly/server/observability\";\nimport { type CacheStatus, invalidateOnWrite, withReadCache } from \"./cache.ts\";\nimport { r2BindingStorage } from \"./r2-binding-storage.ts\";\n\n/**\n * Cloudflare Workers have no TTY, so the default sink is always\n * the JSON console sink — log-aggregator-shaped out of the box.\n * Callers can pass `options.observability.sink` to override.\n */\nconst resolveCfSink = (config: ObservabilityConfig | undefined): ObservabilityConfig => {\n const merged = config ?? {};\n return merged.sink !== undefined ? merged : { ...merged, sink: \"console-json\" };\n};\n\n/**\n * Worker bindings consumed by `baerlyWorker` itself. The caller\n * wires these in `wrangler.jsonc`:\n *\n * \"r2_buckets\": [{ \"binding\": \"BUCKET\", \"bucket_name\": \"<your-bucket>\" }],\n *\n * \"vars\": { \"APP\": \"tickets\" }\n *\n * Tenant resolution is owned by the configured `Verifier`; the\n * adapter never reads a tenant-shaped env var. App-specific vars\n * (`SHARED_SECRET`, `CF_ACCESS_*`, `LOG_*`, a `TENANT` literal for\n * single-tenant `sharedSecret` callers, etc.) belong on the\n * caller's own env type — extend this one:\n *\n * ```ts\n * import type { BaerlyEnv } from \"@gusto/baerly-storage/cloudflare\";\n *\n * interface AppEnv extends BaerlyEnv {\n * readonly TENANT: string;\n * readonly SHARED_SECRET?: string;\n * }\n * ```\n */\nexport interface BaerlyEnv {\n BUCKET: R2Bucket;\n APP: string;\n}\n\n/**\n * Cron Trigger handler. Called once per tick when the user has\n * declared `triggers.crons` in `wrangler.jsonc` AND passed this\n * option. The body owns its own subrequest budget — wrap any\n * outlasting work in `ctx.waitUntil(...)`. Multi-tenant deployments\n * typically iterate a list of `current.json` keys and call\n * {@link runScheduledMaintenance} per tenant.\n */\nexport type WorkerScheduledHandler = (\n event: ScheduledController,\n env: BaerlyEnv,\n ctx: ExecutionContext,\n) => Promise<void> | void;\n\nexport interface BaerlyWorkerOptions {\n /**\n * Your `baerly.config.ts`. **Required.** Carries `auth`,\n * `tenant`, and the declared `collections` (their schemas/indexes\n * flow through to per-request `Db.create` automatically).\n *\n * The adapter resolves the per-request `Verifier` from\n * `config.auth` when no `verifier:` override is supplied — see\n * resolution order on {@link verifier} below.\n *\n * Only `collections` is read for runtime kernel wiring — fields\n * like `target`, `domain`, `cloudflareAccess` are deploy-time\n * concerns that the adapter ignores.\n */\n readonly config: BaerlyAppConfig;\n /**\n * Cron Trigger handler. When unset, `scheduled()` is a no-op even\n * if `triggers.crons` is declared. See {@link WorkerScheduledHandler}.\n */\n readonly scheduled?: WorkerScheduledHandler;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides\n * `config.auth` (the \"dev default in config, prod override via env\"\n * recipe). When unset, the adapter synthesizes one from\n * `config.auth`:\n *\n * - `\"shared-secret\"` → `sharedSecret({ secret: env.SHARED_SECRET,\n * tenantPrefix: config.tenant })`. Throws `InvalidConfig` on\n * first fetch when `SHARED_SECRET` is missing/empty.\n * - `\"none\"` → pins every request to `config.tenant` with no\n * header check.\n *\n * `GET /v1/healthz` always bypasses the verifier.\n *\n * Multi-tenant deployments compose their own verifier on top of a\n * real IdP — JWT, SigV4, Cloudflare Access, etc.\n */\n readonly verifier?: Verifier;\n /**\n * Observability config (LogTape sink + level). When supplied, the\n * Worker calls {@link configureObservability} lazily on first\n * `fetch` / `scheduled` invocation (CF Worker modules can't\n * `await` at the top level). `configureObservability` is\n * idempotent — passing `{ reset: true }` to LogTape — so\n * re-invocation is harmless.\n *\n * - `level` falls through to `env.LOG_LEVEL` (when typed option\n * is undefined).\n * - `sink` defaults to `\"console-json\"` (Cloudflare's stdout is\n * ingested by Workers Logs as JSON-shaped records).\n *\n * Leave the field unset to skip configuration entirely — the\n * default LogTape configuration is a no-op sink. Adapters that\n * skip configuration still emit through the bag/operator pipe; only\n * the LogTape `console.log` side becomes silent.\n */\n readonly observability?: ObservabilityConfig;\n /**\n * Opt-in dev affordance. When set, `GET /` returns a small\n * human-readable HTML page that links to {@link DevLandingOptions.uiUrl},\n * and `GET /favicon.ico` returns 204 No Content. Leave unset on\n * production Workers — `/` falls through to the existing 404\n * envelope when this option is absent.\n */\n readonly dev?: DevLandingOptions;\n /** Override the long-poll budget. Forwarded to `longPollSince`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `longPollSince`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Build a Workers module-default export.\n *\n * Order on `fetch`: **healthz → verifier → router**. Health probes\n * don't pay for a Db construction; an auth challenge stops a bad\n * request before any Storage I/O; the router catches everything else.\n *\n * Observability: every HTTP request that flows past the verifier\n * runs inside a single `runWithContext` scope created up front in\n * this adapter — including the read-cache wrapper. The canonical\n * line emitted at end-of-request carries a top-level\n * `cache_status: \"hit\" | \"miss\" | \"bypass\"` field so operators can\n * split hit/miss/bypass directly from the log stream without\n * consulting a CDN dashboard. The router's observability middleware\n * detects the ambient context and passes through — the adapter owns\n * the flush.\n *\n * Cron Triggers are opt-in. Pass `options.scheduled` to wire one;\n * `wrangler.jsonc:triggers.crons` controls the firing cadence.\n * When `options.scheduled` is unset the cron tick is a no-op.\n *\n * The factory receives `env` on the first `fetch` or `scheduled`\n * invocation, resolves `BaerlyWorkerOptions` once, and caches the\n * result for the lifetime of the isolate. Cloudflare Workers cannot\n * `await` at the module top level — the factory pattern is the\n * supported way to read env bindings at startup.\n *\n * @example\n * ```ts\n * import { baerlyWorker } from \"@gusto/baerly-storage/cloudflare\";\n * import config from \"../../baerly.config.ts\";\n *\n * // Dev default: `auth: \"none\"` in baerly.config.ts pins every\n * // request to `config.tenant`. Switch to `auth: \"shared-secret\"`\n * // for staging/prod and `wrangler secret put SHARED_SECRET`.\n * export default baerlyWorker(() => ({ config }));\n * ```\n */\nexport function baerlyWorker<E extends BaerlyEnv = BaerlyEnv>(\n factory: (env: E) => BaerlyWorkerOptions,\n): ExportedHandler<E> {\n // Cached resolution: populated on first fetch/scheduled, reused on\n // every subsequent invocation. Cloudflare Workers can't `await` at\n // the module top level, so we lazy-init on first call to whichever\n // handler fires first.\n interface ResolvedState {\n readonly options: BaerlyWorkerOptions;\n readonly verifier: Verifier;\n }\n let resolved: ResolvedState | undefined;\n // Cached so every subsequent fetch re-throws the same error rather\n // than re-running `resolveVerifier` on every request after a\n // misconfig. Mirrors the \"first fetch errors, every fetch errors\"\n // contract documented on `auth: \"shared-secret\"` + missing env.\n let resolutionError: unknown;\n let observabilityConfigured = false;\n\n const ensureResolved = async (env: E): Promise<ResolvedState> => {\n if (resolutionError !== undefined) {\n throw resolutionError;\n }\n if (resolved === undefined) {\n try {\n const options = factory(env);\n const verifier = resolveVerifier({\n factoryVerifier: options.verifier,\n config: options.config,\n readEnv: (k) => {\n const value = (env as unknown as Record<string, unknown>)[k];\n return typeof value === \"string\" ? value : undefined;\n },\n });\n resolved = { options, verifier };\n } catch (error) {\n resolutionError = error;\n throw error;\n }\n }\n // Lazy-init flag for `configureObservability`. CF Worker modules\n // cannot `await` at the module top level, so the first fetch /\n // scheduled invocation runs the configure. LogTape's `configure`\n // is idempotent (we always pass `reset: true`); a thundering-herd\n // race on the cold-start tick just re-runs the same config.\n if (!observabilityConfigured) {\n await configureObservability(resolveCfSink(resolved.options.observability));\n observabilityConfigured = true;\n // Emit the auth=none startup banner exactly once per isolate.\n // Suppress when an explicit `verifier:` override is in play —\n // the override wins, the log would be misleading. Suppress\n // when `auth === \"shared-secret\"` — the operator already knows.\n if (resolved.options.verifier === undefined && resolved.options.config.auth === \"none\") {\n getLogger(CATEGORY.http).info(\n `[baerly] auth=none — all requests resolve to tenant=${JSON.stringify(resolved.options.config.tenant)}`,\n );\n }\n }\n return resolved;\n };\n\n return {\n async fetch(req, env, ctx): Promise<Response> {\n const { options, verifier } = await ensureResolved(env);\n\n // Opt-in dev landing page. Off in production (options.dev\n // unset); when set, GET / serves HTML and GET /favicon.ico\n // returns 204 so browsers don't pin a second JSON 404 next\n // to the landing page.\n const url = new URL(req.url);\n if (options.dev !== undefined && req.method === \"GET\") {\n if (url.pathname === \"/\") {\n return new Response(renderDevLanding(options.dev), {\n status: 200,\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n }\n if (url.pathname === \"/favicon.ico\") {\n return new Response(null, { status: 204 });\n }\n }\n\n // Healthz is always anonymous — Cloudflare's load balancer\n // probes it. Keep it ahead of the verifier check; serving it\n // here avoids a `Db.create` (and the canonical-line emission)\n // on every probe. The router no longer mounts healthz — only\n // the adapter does.\n if (req.method === \"GET\" && url.pathname === \"/v1/healthz\") {\n return new Response(JSON.stringify({ ok: true }), {\n status: 200,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // Construct the per-request observability context up front so\n // EVERYTHING downstream — verifier rejection, `Db.create`, and\n // the read-cache wrapper — runs inside the same\n // `runWithContext` scope. Without this lift, a verifier\n // rejection (or a cache-hit short-circuit) would bypass\n // canonical-line emission entirely.\n //\n // The router's observability middleware (see `router.ts`\n // \"Mode A\") detects the ambient context and passes through —\n // it never creates a competing context, and it never flushes\n // its own line. The adapter owns the flush from here on.\n const requestId = req.headers.get(\"x-request-id\") ?? crypto.randomUUID();\n const obsCtx = createObservabilityContext({\n request_id: requestId,\n });\n\n // Tenant resolution: the Verifier owns it unconditionally.\n const result = await verifier(req);\n if (result === null) {\n return runWithContext(obsCtx, async () => flushUnauthorizedAndRespond(obsCtx, req));\n }\n const tenantPrefix = result.tenantPrefix;\n\n return runWithContext(obsCtx, async (): Promise<Response> => {\n // Storage is wrapped with `observableStorage(...)` so the\n // per-call class A/B counts and per-op duration histograms\n // land in the active per-request bag. Writer / compactor / GC\n // emissions reach the same bag via `getCurrentContext()?.recorder`\n // — the canonical-line flusher reads it at end-of-request.\n const storage = observableStorage(r2BindingStorage(env.BUCKET));\n const db = Db.create({\n storage,\n app: env.APP,\n tenant: tenantPrefix,\n config: options.config,\n });\n\n const app = createRouter({\n db,\n sinceTimeoutMs: options.sinceTimeoutMs,\n sincePollIntervalMs: options.sincePollIntervalMs,\n });\n\n let cacheStatus: CacheStatus = \"bypass\";\n let response: Response | undefined;\n let caughtError: unknown;\n try {\n // Hono's `fetch` returns `Response | Promise<Response>`;\n // `withReadCache` wants a `Promise<Response>`. Normalize\n // via `Promise.resolve` so the sync-return branch is wrapped.\n const cacheResult = await withReadCache(req, tenantPrefix, () =>\n Promise.resolve(app.fetch(req, env, ctx)),\n );\n cacheStatus = cacheResult.cache_status;\n response = cacheResult.response;\n } catch (error) {\n caughtError = error;\n throw error;\n } finally {\n const status = caughtError !== undefined ? 500 : (response?.status ?? 500);\n flushCanonicalLine(obsCtx, obsCtx.recorder, {\n unit: \"http\",\n status,\n outcome: deriveOutcome(req.method, status, caughtError),\n ...(caughtError !== undefined && { error: caughtError }),\n extra: {\n method: req.method,\n path: new URL(req.url).pathname,\n cache_status: cacheStatus,\n },\n });\n }\n // `response` is defined here — the `catch` arm above rethrew,\n // so reaching this line implies the try block completed.\n // Best-effort invalidate after writes. `ctx.waitUntil` keeps\n // the Worker alive for the cache.delete without blocking\n // the response.\n ctx.waitUntil(invalidateOnWrite(req, tenantPrefix, response!.status));\n return response!;\n });\n },\n\n async scheduled(event, env, ctx): Promise<void> {\n const { options } = await ensureResolved(env);\n if (options.scheduled !== undefined) {\n await options.scheduled(event, env, ctx);\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAkCA,MAAM,eAAe,SACnB,KAAK,WAAW,IAAG,KAAK,KAAK,SAAS,IAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AACnE,MAAM,aAAa,QAAwB,IAAI,IAAI;AAEnD,IAAM,uBAAN,MAA8C;CAC5C;CAEA,YAAY,QAAkB;EAC5B,IAAI,WAAW,QAAQ,WAAW,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;AACF"}
|
|
1
|
+
{"version":3,"file":"cloudflare.js","names":["#bucket","#callBinding"],"sources":["../packages/adapter-cloudflare/src/r2-binding-storage.ts","../packages/adapter-cloudflare/src/cache.ts","../packages/adapter-cloudflare/src/worker.ts"],"sourcesContent":["import {\n BaerlyError,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\n\n/**\n * Construction options for {@link r2BindingStorage}. The factory takes\n * the `R2Bucket` binding directly, so this interface only exists to\n * document the shape consumers see in their `env`.\n */\nexport interface R2BindingStorageOptions {\n /**\n * The R2 binding from `env`. In `wrangler.toml`:\n *\n * [[r2_buckets]]\n * binding = \"BUCKET\"\n * bucket_name = \"baerly-prod\"\n *\n * Then: `r2BindingStorage(env.BUCKET)`.\n */\n bucket: R2Bucket;\n}\n\n/**\n * R2's binding API returns bare-hex ETags (`R2Object.etag`). The\n * `Storage` contract follows S3's wire format — quoted (`\"<hex>\"`).\n * `stripQuotes` is forgiving of unquoted input so external sources\n * that hand us bare hex don't break.\n */\nconst stripQuotes = (etag: string): string =>\n etag.startsWith('\"') && etag.endsWith('\"') ? etag.slice(1, -1) : etag;\nconst quoteEtag = (hex: string): string => `\"${hex}\"`;\n\nclass R2BindingStorageImpl implements Storage {\n readonly #bucket: R2Bucket;\n\n constructor(bucket: R2Bucket) {\n if (bucket === null || bucket === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"r2BindingStorage: bucket binding is null/undefined — check wrangler.toml [[r2_buckets]] and the env var name\",\n );\n }\n this.#bucket = bucket;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const getOpts: R2GetOptions = {};\n if (opts?.ifNoneMatch !== undefined) {\n getOpts.onlyIf = { etagDoesNotMatch: stripQuotes(opts.ifNoneMatch) };\n }\n const obj = await this.#callBinding(() => this.#bucket.get(key, getOpts), `GET ${key}`);\n if (obj === null) {\n return null;\n }\n // R2 returns a bare `R2Object` (no body) when a conditional GET's\n // precondition succeeds — i.e. the caller's copy is current.\n // Match the `Storage` contract's 304 → null semantics.\n if (!(\"body\" in obj) || obj.body === null) {\n return null;\n }\n const body = new Uint8Array(await obj.arrayBuffer());\n return { body, etag: quoteEtag(obj.etag) };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const putOpts: R2PutOptions = {};\n if (opts?.contentType !== undefined) {\n putOpts.httpMetadata = { contentType: opts.contentType };\n }\n if (opts?.ifMatch !== undefined) {\n putOpts.onlyIf = { etagMatches: stripQuotes(opts.ifMatch) };\n } else if (opts?.ifNoneMatch === \"*\") {\n // R2 spells \"create only\" as `etagDoesNotMatch: \"*\"` (wildcard).\n // Do NOT strip the `*` — it's the literal wildcard, not an\n // etag.\n putOpts.onlyIf = { etagDoesNotMatch: \"*\" };\n }\n const result = await this.#callBinding(\n () => this.#bucket.put(key, body, putOpts),\n `PUT ${key}`,\n );\n if (result === null) {\n // Binding signals precondition failure as `null`.\n throw new BaerlyError(\"Conflict\", `PUT ${key}: precondition failed`);\n }\n // `R2Object.uploaded` is the server-side write clock — surface it\n // verbatim. The kernel's adaptive-clock-skew loop consumes it\n // identically to `S3HttpStorage`'s `Date` header.\n return {\n etag: quoteEtag(result.etag),\n serverDate: result.uploaded,\n };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n // R2.delete is idempotent — matches the `Storage.delete` contract.\n await this.#callBinding(() => this.#bucket.delete(key), `DELETE ${key}`);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n let cursor: string | undefined = undefined;\n let yielded = 0;\n const startAfter = opts?.startAfter ?? \"\";\n const cap = opts?.maxKeys ?? Infinity;\n while (true) {\n opts?.signal?.throwIfAborted();\n // Break BEFORE the next list() call when the cap is already hit\n // — R2 rejects `limit: 0` with `MaxKeys params must be positive\n // integer <= 1000. (10022)`, so we can't just clamp.\n if (yielded >= cap) {\n return;\n }\n // R2.list: `limit` capped at 1000 per request. Page via\n // `cursor` until `truncated === false`. `startAfter` honored\n // only on the first page (one-shot cursor).\n const listOpts: R2ListOptions = { prefix };\n if (cursor !== undefined) {\n listOpts.cursor = cursor;\n } else if (startAfter !== \"\") {\n listOpts.startAfter = startAfter;\n }\n if (cap !== Infinity) {\n listOpts.limit = Math.min(cap - yielded, 1000);\n }\n const page = await this.#callBinding(() => this.#bucket.list(listOpts), `LIST ${prefix}`);\n for (const obj of page.objects) {\n if (yielded >= cap) {\n return;\n }\n yield {\n key: obj.key,\n etag: quoteEtag(obj.etag),\n lastModified: obj.uploaded,\n };\n yielded += 1;\n }\n if (!page.truncated) {\n return;\n }\n cursor = page.cursor;\n if (cursor === undefined) {\n return;\n }\n }\n }\n\n /**\n * Map binding-layer errors to `BaerlyError` codes. The R2 binding\n * surfaces failures as plain `Error` with messages; sniff the\n * common ones. If the binding ever adds typed errors, tighten the\n * sniff and keep the message fallback for older runtimes.\n */\n async #callBinding<T>(fn: () => Promise<T>, op: string): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n const msg = error instanceof Error ? error.message : String(error);\n if (/auth|permission|forbidden/i.test(msg)) {\n throw new BaerlyError(\"AccessDenied\", `${op}: ${msg}`, error);\n }\n if (/not.*found|no.*such.*bucket/i.test(msg)) {\n throw new BaerlyError(\"InvalidConfig\", `${op}: ${msg}`, error);\n }\n throw new BaerlyError(\"NetworkError\", `${op}: ${msg}`, error);\n }\n }\n}\n\n/**\n * Construct a `Storage` backed by a Cloudflare R2 binding. The R2\n * binding bypasses SigV4 entirely: requests are dispatched in-cell\n * over a Cloudflare-internal channel, so the hot path skips\n * canonical-request building, body hashing, and DNS/TLS to a\n * separate origin.\n *\n * Pick this over `S3HttpStorage` when the Worker and bucket are in\n * the same Cloudflare account. Cross-cloud (AWS, GCS) and\n * cross-account R2 stay on the HTTP path.\n *\n * Wire-format conventions:\n * - ETags returned in `\"<hex>\"` (S3 wire format) even though R2's\n * binding returns bare hex. CAS round-trips strip and re-apply\n * the quotes.\n * - `serverDate` from `R2Object.uploaded` — a real server clock,\n * suitable for the kernel's adaptive-clock-skew loop.\n * - `StorageListEntry.lastModified` from the same clock.\n *\n * Errors map to `BaerlyError` via the same convention as\n * `S3HttpStorage`: `AccessDenied` for binding-level permission\n * failures, `NetworkError` for transient R2 platform failures,\n * `InvalidResponse` for precondition (CAS) failures, `InvalidConfig`\n * if the caller hands in a null/undefined binding.\n *\n * @example\n * ```ts\n * import { r2BindingStorage } from \"@gusto/baerly-storage/cloudflare\";\n *\n * export default {\n * fetch(req, env: { BUCKET: R2Bucket }) {\n * const storage = r2BindingStorage(env.BUCKET);\n * // ...wire to Db\n * },\n * };\n * ```\n */\nexport function r2BindingStorage(bucket: R2Bucket): Storage {\n return new R2BindingStorageImpl(bucket);\n}\n","/**\n * Cloudflare Cache API integration for the Worker read path.\n * Worker-only; Node has no equivalent and runs cache-less.\n *\n * Contract:\n * - Only `GET /v1/c/:collection/:id` is cached. LIST URLs\n * (`GET /v1/c/:collection`, with or without filters) bypass the cache.\n * The Cloudflare Cache API exposes no enumeration primitive, so\n * filtered-LIST variants (`?where=...`) cannot be safely\n * invalidated on writes; rather than ship a per-isolate index\n * that only partially survives across the colo-shared cache, we\n * skip list caching entirely. If LIST caching ever becomes a\n * bottleneck, revisit with a cross-isolate primitive (CF Cache\n * Tags, KV-backed invalidation, etc).\n * - `GET /v1/since` and `GET /v1/healthz` also bypass the cache\n * (the long-poll's mutating cursor is not cacheable; healthz is\n * trivially fast and must never go stale).\n * - Cache key is the request URL + a synthetic `__t=<tenantPrefix>`\n * query param. This is the load-bearing correctness invariant:\n * the HTTP contract derives `tenant` from the `Verifier`, not the\n * URL, so two different Verifier outcomes against the same URL\n * must NOT share a cache entry. See `packages/server/src/contract.ts`.\n * - Only 200 responses with non-empty bodies are stored. 401/403/\n * 404/409/500 always bypass `cache.put`. Negative caching is out\n * of scope.\n * - `PATCH` / `DELETE` that return 2xx call `cache.delete()` on the\n * per-doc URL they hit. `POST` targets a LIST URL (uncached), so\n * nothing to bust. Best-effort — failures are swallowed.\n * - No `Cache-Control` header is added on the wire. We rely on\n * explicit invalidation, not TTLs.\n */\n\n/**\n * Methods we treat as mutating for invalidation purposes. Keep this\n * list narrow — adding a method to `WRITE_METHODS` doubles the\n * invalidation surface and matters for correctness.\n */\nconst WRITE_METHODS = new Set<string>([\"POST\", \"PATCH\", \"DELETE\"]);\n\n/** Pathname prefixes that bypass the cache entirely. */\nconst BYPASS_PREFIXES = [\"/v1/since\", \"/v1/healthz\"];\n\n/**\n * `Cache-Control: max-age=<n>` value we set on the cacheable response\n * handed to `cache.put`. workerd's `caches.default.put` silently\n * no-ops on responses without a cacheable directive, so we synthesize\n * one. The value is large because we rely on explicit per-doc\n * invalidation, not expiry — see `invalidateOnWrite`.\n */\nconst CACHE_TTL_SECONDS = 3600;\n\n/**\n * Build the canonical cache-key `Request` for a given `(req,\n * tenantPrefix)`. The synthetic `__t` query parameter scopes the\n * cache per-tenant; without it, two tenants with overlapping URLs\n * would share entries — a security bug.\n *\n * The returned `Request` is GET-only by construction — even when\n * `req.method` is POST/PATCH/DELETE we use the GET form for\n * `cache.delete()` so the read-side write and the write-side bust\n * land on the same key.\n */\nexport function cacheKeyFor(req: Request, tenantPrefix: string): Request {\n const url = new URL(req.url);\n // `set` not `append` — defends against a malicious caller-supplied\n // `?__t=spoof`. The server-controlled value always wins.\n url.searchParams.set(\"__t\", tenantPrefix);\n return new Request(url.toString(), { method: \"GET\" });\n}\n\n/**\n * Should this request bypass the cache layer entirely (both read and\n * invalidate sides)? Healthz + long-poll + anything that isn't a\n * per-doc URL (`/v1/c/:collection/:id`).\n */\nfunction bypassesCache(url: URL): boolean {\n if (BYPASS_PREFIXES.some((p) => url.pathname.startsWith(p))) {\n return true;\n }\n if (!url.pathname.startsWith(\"/v1/c/\")) {\n return true;\n }\n // LIST URLs (`/v1/c/<table>` with no `/<id>`) bypass — see header\n // docstring for why filtered-LIST caching isn't safe here.\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 4) {\n return true;\n }\n return false;\n}\n\n/**\n * Discriminator returned alongside the response so the adapter can\n * stamp `cache_status` on the canonical line. The cache itself\n * doesn't emit — the adapter owns the canonical line.\n *\n * - `\"hit\"` — the cache returned an entry (both the 304\n * If-None-Match path and the body-bearing 200 path\n * classify as hits; the cache served the request\n * without invoking the handler).\n * - `\"miss\"` — the request was cacheable but the cache had no\n * entry; the handler ran and (when the response was\n * cacheable) its output was stored.\n * - `\"bypass\"` — the request never consulted the cache (non-GET,\n * LIST URL, a path under {@link BYPASS_PREFIXES}, or\n * a path outside `/v1/c/`).\n */\nexport type CacheStatus = \"hit\" | \"miss\" | \"bypass\";\n\n/**\n * Discriminator-tagged return value of {@link withReadCache}. The\n * adapter stamps `cache_status` onto the canonical-line `extra` bag\n * before flushing — see `worker.ts`'s `fetch` handler.\n */\nexport interface ReadCacheResult {\n readonly response: Response;\n readonly cache_status: CacheStatus;\n}\n\n/**\n * Read-path wrapper. Call this in place of invoking the router\n * directly for `GET` requests. Returns `{ response, cache_status }`\n * so the adapter can stamp `cache_status` on the canonical line:\n *\n * - `cache_status: \"bypass\"` — non-GET method, LIST URL, or a path\n * under {@link BYPASS_PREFIXES} (`/v1/since`, `/v1/healthz`), or\n * a path outside `/v1/c/`. The handler runs verbatim and its\n * response is returned untouched.\n * - `cache_status: \"hit\"` — the cache had an entry. Returns\n * either a synthesized 304 (when `If-None-Match` matches the\n * cached ETag) or the cached body (200). The handler does NOT\n * run.\n * - `cache_status: \"miss\"` — the cache had no entry. The handler\n * runs and, if the response is a cacheable 200 with no\n * `Set-Cookie`, the response is stored before being returned.\n */\nexport async function withReadCache(\n req: Request,\n tenantPrefix: string,\n handler: () => Promise<Response>,\n): Promise<ReadCacheResult> {\n const url = new URL(req.url);\n if (req.method !== \"GET\" || bypassesCache(url)) {\n return { response: await handler(), cache_status: \"bypass\" };\n }\n\n // `caches.default` is Workers-only; DOM's `CacheStorage` lib type\n // doesn't expose it, so we cast through `unknown` to the shape we\n // need. miniflare provides the real binding at runtime.\n const cache = (caches as unknown as { default: Cache }).default;\n const key = cacheKeyFor(req, tenantPrefix);\n const cached = await cache.match(key);\n if (cached !== undefined) {\n const etag = cached.headers.get(\"etag\");\n const ifNoneMatch = req.headers.get(\"if-none-match\");\n if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) {\n // 304 has no body, but keeps the ETag so a CDN-aware client\n // can continue revalidating against it.\n return {\n response: new Response(null, {\n status: 304,\n headers: { etag },\n }),\n cache_status: \"hit\",\n };\n }\n // Body-bearing hit. Clone so the cache entry stays intact for\n // the next request in the same Worker isolate. Strip the\n // synthetic `Cache-Control` header we added at `cache.put` time\n // so the client never sees TTLs we don't honor (invalidation-only\n // on the wire).\n const cloned = cached.clone();\n const outHeaders = new Headers(cloned.headers);\n outHeaders.delete(\"cache-control\");\n return {\n response: new Response(cloned.body, {\n status: cloned.status,\n statusText: cloned.statusText,\n headers: outHeaders,\n }),\n cache_status: \"hit\",\n };\n }\n\n const fresh = await handler();\n // Only cache stable 200 responses with a non-empty body. The Cache\n // API silently rejects responses with `Set-Cookie`; baerly never\n // sets cookies, but the guard is cheap insurance.\n if (fresh.status === 200 && !fresh.headers.has(\"set-cookie\")) {\n // workerd's `caches.default.put` silently no-ops on responses\n // without a cacheable `Cache-Control` directive. We synthesize\n // one ONLY on the response we hand the cache — the response we\n // return to the caller is untouched (invalidation-only on the\n // wire).\n const headers = new Headers(fresh.headers);\n headers.set(\"cache-control\", `max-age=${CACHE_TTL_SECONDS}`);\n const cacheable = new Response(fresh.clone().body, {\n status: fresh.status,\n statusText: fresh.statusText,\n headers,\n });\n await cache.put(key, cacheable);\n }\n return { response: fresh, cache_status: \"miss\" };\n}\n\n/**\n * Write-path companion. Call this AFTER the handler returns a 2xx\n * for `PATCH` / `DELETE` on a per-doc URL — busts the cache entry\n * for that URL. `POST` targets a LIST URL (uncached), so nothing to\n * bust; this function returns without touching the cache. Failures\n * are swallowed; a stale entry is recoverable via the 304 path on\n * the next read.\n */\nexport async function invalidateOnWrite(\n req: Request,\n tenantPrefix: string,\n responseStatus: number,\n): Promise<void> {\n if (!WRITE_METHODS.has(req.method)) {\n return;\n }\n if (responseStatus < 200 || responseStatus >= 300) {\n return;\n }\n const url = new URL(req.url);\n if (bypassesCache(url)) {\n return;\n }\n // `caches.default` is Workers-only; DOM's `CacheStorage` lib type\n // doesn't expose it, so we cast through `unknown` to the shape we\n // need. miniflare provides the real binding at runtime.\n const cache = (caches as unknown as { default: Cache }).default;\n await cache.delete(cacheKeyFor(req, tenantPrefix));\n}\n","import { type DevLandingOptions, renderDevLanding } from \"@baerly/dev\";\nimport {\n type BaerlyAppConfig,\n CF_FREE_MAX_SAFE_FOLD_BYTES,\n type Verifier,\n WRITE_TICK_FOLD_ENTRIES_PER_PASS,\n WRITE_TICK_GC_INTERVAL,\n WRITE_TICK_GC_MAX_MARKS,\n WRITE_TICK_GC_MAX_SWEEPS,\n} from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { createRouter } from \"@baerly/server/http\";\nimport type { MaintenanceDispatch } from \"@baerly/server/maintenance\";\nimport {\n CATEGORY,\n type ObservabilityConfig,\n configureObservability,\n createObservabilityContext,\n deriveOutcome,\n flushCanonicalLine,\n flushUnauthorizedAndRespond,\n getLogger,\n observableStorage,\n runWithContext,\n} from \"@baerly/server/observability\";\nimport { type CacheStatus, invalidateOnWrite, withReadCache } from \"./cache.ts\";\nimport { r2BindingStorage } from \"./r2-binding-storage.ts\";\n\n/**\n * Cloudflare Workers have no TTY, so the default sink is always\n * the JSON console sink — log-aggregator-shaped out of the box.\n * Callers can pass `options.observability.sink` to override.\n */\nconst resolveCfSink = (config: ObservabilityConfig | undefined): ObservabilityConfig => {\n const merged = config ?? {};\n return merged.sink !== undefined ? merged : { ...merged, sink: \"console-json\" };\n};\n\n/**\n * Worker bindings consumed by `baerlyWorker` itself. The caller\n * wires these in `wrangler.jsonc`:\n *\n * \"r2_buckets\": [{ \"binding\": \"BUCKET\", \"bucket_name\": \"<your-bucket>\" }],\n *\n * \"vars\": { \"APP\": \"tickets\" }\n *\n * Tenant resolution is owned by the configured `Verifier`; the\n * adapter never reads a tenant-shaped env var. App-specific vars\n * (`SHARED_SECRET`, `CF_ACCESS_*`, `LOG_*`, a `TENANT` literal for\n * single-tenant `sharedSecret` callers, etc.) belong on the\n * caller's own env type — extend this one:\n *\n * ```ts\n * import type { BaerlyEnv } from \"@gusto/baerly-storage/cloudflare\";\n *\n * interface AppEnv extends BaerlyEnv {\n * readonly TENANT: string;\n * readonly SHARED_SECRET?: string;\n * }\n * ```\n *\n * ## In-band maintenance ops-plane vars\n *\n * Two OPTIONAL `vars` tune the write-tick maintenance the adapter\n * dispatches via `ctx.waitUntil` (CF `vars` are always strings):\n *\n * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` — raise the snapshot-rebuild\n * ceiling `C`. The default ({@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT},\n * 512 KiB) is sized to rebuild in ~5.5 ms under the CF-free ~10 ms\n * CPU budget. On CF **paid** (raised CPU limits) an operator raises\n * this to fold larger snapshots in one shot. A value above\n * {@link CF_FREE_MAX_SAFE_FOLD_BYTES} warns LOUDLY once at init —\n * on a free isolate that fold risks a mid-rebuild CPU kill.\n * - `BAERLY_MAINTENANCE_DISABLE` — kill switch. Any non-empty value\n * other than `\"0\"` / `\"false\"` disables write-tick maintenance.\n */\nexport interface BaerlyEnv {\n BUCKET: R2Bucket;\n APP: string;\n /**\n * Raise the snapshot-rebuild ceiling `C`. Parsed as a number;\n * ignored when unset / non-numeric. Default\n * {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. A value above\n * {@link CF_FREE_MAX_SAFE_FOLD_BYTES} warns once at init.\n */\n BAERLY_MAINTENANCE_MAX_FOLD_BYTES?: string;\n /**\n * Write-tick maintenance kill switch. Truthy (non-empty, not\n * `\"0\"` / `\"false\"`) disables the in-band fold + GC dispatch.\n */\n BAERLY_MAINTENANCE_DISABLE?: string;\n}\n\n/**\n * Assemble the per-request {@link MaintenanceDispatch} for a Cloudflare\n * Worker.\n *\n * baerly maintains IN-BAND: the writer reads\n * `getCurrentContext()?.maintenance` at its post-CAS dispatch point and\n * runs one bounded compact + GC slice on the (rare) write that crosses a\n * maintenance trigger. Reads stay pure — they never tick. There is no\n * cron, no `triggers`, no operator-installed scheduler.\n *\n * On Cloudflare the fold runs in a `ctx.waitUntil` continuation — FIRE\n * AND FORGET off the response ack, so the commit never blocks on it. The\n * isolate stays alive long enough to drain the continuation; the\n * per-pass caps are the TESTED CF-free `WRITE_TICK_*` defaults\n * (`phasesPerTick: \"single\"` — a CPU-killable free isolate does ONE of\n * fold/GC per request, never both), sized so a single pass stays well\n * under the free-tier 50-subrequest budget. An operator on CF **paid**\n * raises the ceiling via `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; the\n * per-pass entry/sweep caps stay fixed here (raising them toward the\n * 1000-subrequest paid budget is a future graduation knob, not a var).\n *\n * The two ops-plane vars are read off the `env` BINDING (a string map),\n * NOT `process.env` — Workers have no process env:\n *\n * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (`C`). Parsed\n * as a number; ignored when unset / NaN.\n * - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Truthy\n * when set to a non-empty value other than `\"0\"` / `\"false\"`.\n *\n * `readEnv` defaults to reading off the bound `env`; the parameter\n * exists for direct unit coverage.\n */\nexport const cfMaintenanceDispatch = (\n ctx: ExecutionContext,\n readEnv: (key: string) => string | undefined,\n): MaintenanceDispatch => {\n const rawFoldBytes = readEnv(\"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\");\n const parsedFoldBytes =\n rawFoldBytes !== undefined && rawFoldBytes !== \"\" ? Number(rawFoldBytes) : Number.NaN;\n const maxFoldBytes = Number.isFinite(parsedFoldBytes) ? parsedFoldBytes : undefined;\n\n const rawDisable = readEnv(\"BAERLY_MAINTENANCE_DISABLE\");\n const disabled =\n rawDisable !== undefined &&\n rawDisable !== \"\" &&\n rawDisable !== \"0\" &&\n rawDisable.toLowerCase() !== \"false\";\n\n return {\n // CF dispatches the fold off the ack via `ctx.waitUntil` — the\n // isolate stays alive to drain it without blocking the response.\n dispatch: (task: () => Promise<void>): void => ctx.waitUntil(task()),\n ...(disabled && { disabled: true }),\n ...(maxFoldBytes !== undefined && { maxFoldBytes }),\n options: {\n // A CPU-killable free isolate does ONE phase per request.\n phasesPerTick: \"single\",\n maxFoldEntriesPerPass: WRITE_TICK_FOLD_ENTRIES_PER_PASS,\n gcMaxMarks: WRITE_TICK_GC_MAX_MARKS,\n gcMaxSweeps: WRITE_TICK_GC_MAX_SWEEPS,\n gcInterval: WRITE_TICK_GC_INTERVAL,\n },\n };\n};\n\n/**\n * Cron Trigger handler. Called once per tick when the user has\n * declared `triggers.crons` in `wrangler.jsonc` AND passed this\n * option. The body owns its own subrequest budget — wrap any\n * outlasting work in `ctx.waitUntil(...)`. Multi-tenant deployments\n * typically iterate a list of `current.json` keys and call\n * {@link runScheduledMaintenance} per tenant.\n */\nexport type WorkerScheduledHandler = (\n event: ScheduledController,\n env: BaerlyEnv,\n ctx: ExecutionContext,\n) => Promise<void> | void;\n\nexport interface BaerlyWorkerOptions {\n /**\n * Your `baerly.config.ts`. **Required.** Carries `auth`,\n * `tenant`, and the declared `collections` (their schemas/indexes\n * flow through to per-request `Db.create` automatically).\n *\n * The adapter resolves the per-request `Verifier` from\n * `config.auth` when no `verifier:` override is supplied — see\n * resolution order on {@link verifier} below.\n *\n * Only `collections` is read for runtime kernel wiring — fields\n * like `target`, `domain`, `cloudflareAccess` are deploy-time\n * concerns that the adapter ignores.\n */\n readonly config: BaerlyAppConfig;\n /**\n * Cron Trigger handler. When unset, `scheduled()` is a no-op even\n * if `triggers.crons` is declared. See {@link WorkerScheduledHandler}.\n */\n readonly scheduled?: WorkerScheduledHandler;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides\n * `config.auth` (the \"dev default in config, prod override via env\"\n * recipe). When unset, the adapter synthesizes one from\n * `config.auth`:\n *\n * - `\"shared-secret\"` → `sharedSecret({ secret: env.SHARED_SECRET,\n * tenantPrefix: config.tenant })`. Throws `InvalidConfig` on\n * first fetch when `SHARED_SECRET` is missing/empty.\n * - `\"none\"` → pins every request to `config.tenant` with no\n * header check.\n *\n * `GET /v1/healthz` always bypasses the verifier.\n *\n * Multi-tenant deployments compose their own verifier on top of a\n * real IdP — JWT, SigV4, Cloudflare Access, etc.\n */\n readonly verifier?: Verifier;\n /**\n * Observability config (LogTape sink + level). When supplied, the\n * Worker calls {@link configureObservability} lazily on first\n * `fetch` / `scheduled` invocation (CF Worker modules can't\n * `await` at the top level). `configureObservability` is\n * idempotent — passing `{ reset: true }` to LogTape — so\n * re-invocation is harmless.\n *\n * - `level` falls through to `env.LOG_LEVEL` (when typed option\n * is undefined).\n * - `sink` defaults to `\"console-json\"` (Cloudflare's stdout is\n * ingested by Workers Logs as JSON-shaped records).\n *\n * Leave the field unset to skip configuration entirely — the\n * default LogTape configuration is a no-op sink. Adapters that\n * skip configuration still emit through the bag/operator pipe; only\n * the LogTape `console.log` side becomes silent.\n */\n readonly observability?: ObservabilityConfig;\n /**\n * Opt-in dev affordance. When set, `GET /` returns a small\n * human-readable HTML page that links to {@link DevLandingOptions.uiUrl},\n * and `GET /favicon.ico` returns 204 No Content. Leave unset on\n * production Workers — `/` falls through to the existing 404\n * envelope when this option is absent.\n */\n readonly dev?: DevLandingOptions;\n /** Override the long-poll budget. Forwarded to `longPollSince`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `longPollSince`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Build a Workers module-default export.\n *\n * Order on `fetch`: **healthz → verifier → router**. Health probes\n * don't pay for a Db construction; an auth challenge stops a bad\n * request before any Storage I/O; the router catches everything else.\n *\n * Observability: every HTTP request that flows past the verifier\n * runs inside a single `runWithContext` scope created up front in\n * this adapter — including the read-cache wrapper. The canonical\n * line emitted at end-of-request carries a top-level\n * `cache_status: \"hit\" | \"miss\" | \"bypass\"` field so operators can\n * split hit/miss/bypass directly from the log stream without\n * consulting a CDN dashboard. The router's observability middleware\n * detects the ambient context and passes through — the adapter owns\n * the flush.\n *\n * Cron Triggers are opt-in. Pass `options.scheduled` to wire one;\n * `wrangler.jsonc:triggers.crons` controls the firing cadence.\n * When `options.scheduled` is unset the cron tick is a no-op.\n *\n * The factory receives `env` on the first `fetch` or `scheduled`\n * invocation, resolves `BaerlyWorkerOptions` once, and caches the\n * result for the lifetime of the isolate. Cloudflare Workers cannot\n * `await` at the module top level — the factory pattern is the\n * supported way to read env bindings at startup.\n *\n * @example\n * ```ts\n * import { baerlyWorker } from \"@gusto/baerly-storage/cloudflare\";\n * import config from \"../../baerly.config.ts\";\n *\n * // Dev default: `auth: \"none\"` in baerly.config.ts pins every\n * // request to `config.tenant`. Switch to `auth: \"shared-secret\"`\n * // for staging/prod and `wrangler secret put SHARED_SECRET`.\n * export default baerlyWorker(() => ({ config }));\n * ```\n */\nexport function baerlyWorker<E extends BaerlyEnv = BaerlyEnv>(\n factory: (env: E) => BaerlyWorkerOptions,\n): ExportedHandler<E> {\n // Cached resolution: populated on first fetch/scheduled, reused on\n // every subsequent invocation. Cloudflare Workers can't `await` at\n // the module top level, so we lazy-init on first call to whichever\n // handler fires first.\n interface ResolvedState {\n readonly options: BaerlyWorkerOptions;\n readonly verifier: Verifier;\n }\n let resolved: ResolvedState | undefined;\n // Cached so every subsequent fetch re-throws the same error rather\n // than re-running `resolveVerifier` on every request after a\n // misconfig. Mirrors the \"first fetch errors, every fetch errors\"\n // contract documented on `auth: \"shared-secret\"` + missing env.\n let resolutionError: unknown;\n let observabilityConfigured = false;\n // Fired at most once per isolate: an operator who raised the snapshot\n // ceiling above what a free CF isolate can rebuild in one shot gets a\n // loud warning. Init-scoped (not per-request) so a busy Worker doesn't\n // spam the log stream.\n let maintenanceCeilingWarned = false;\n\n const ensureResolved = async (env: E): Promise<ResolvedState> => {\n if (resolutionError !== undefined) {\n throw resolutionError;\n }\n if (resolved === undefined) {\n try {\n const options = factory(env);\n const verifier = resolveVerifier({\n factoryVerifier: options.verifier,\n config: options.config,\n readEnv: (k) => {\n const value = (env as unknown as Record<string, unknown>)[k];\n return typeof value === \"string\" ? value : undefined;\n },\n });\n resolved = { options, verifier };\n } catch (error) {\n resolutionError = error;\n throw error;\n }\n }\n // Lazy-init flag for `configureObservability`. CF Worker modules\n // cannot `await` at the module top level, so the first fetch /\n // scheduled invocation runs the configure. LogTape's `configure`\n // is idempotent (we always pass `reset: true`); a thundering-herd\n // race on the cold-start tick just re-runs the same config.\n if (!observabilityConfigured) {\n await configureObservability(resolveCfSink(resolved.options.observability));\n observabilityConfigured = true;\n // Emit the auth=none startup banner exactly once per isolate.\n // Suppress when an explicit `verifier:` override is in play —\n // the override wins, the log would be misleading. Suppress\n // when `auth === \"shared-secret\"` — the operator already knows.\n if (resolved.options.verifier === undefined && resolved.options.config.auth === \"none\") {\n getLogger(CATEGORY.http).info(\n `[baerly] auth=none — all requests resolve to tenant=${JSON.stringify(resolved.options.config.tenant)}`,\n );\n }\n }\n // Ops-plane guardrail, init-scoped: if the operator raised the\n // snapshot-rebuild ceiling above what a CF FREE isolate can rebuild\n // under its ~10 ms CPU budget, warn LOUDLY exactly once. A fold over\n // this size on a free isolate gets CPU-killed mid-rebuild — the CAS\n // never lands, so the fold silently never advances `log_seq_start`\n // and the tail grows unbounded. `console.warn` (not LogTape) so the\n // signal survives even when observability is unconfigured.\n if (!maintenanceCeilingWarned) {\n maintenanceCeilingWarned = true;\n const rawFoldBytes = (env as unknown as Record<string, unknown>)[\n \"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\"\n ];\n if (typeof rawFoldBytes === \"string\" && rawFoldBytes !== \"\") {\n const parsed = Number(rawFoldBytes);\n if (Number.isFinite(parsed) && parsed > CF_FREE_MAX_SAFE_FOLD_BYTES) {\n console.warn(\n `[baerly] BAERLY_MAINTENANCE_MAX_FOLD_BYTES=${rawFoldBytes} exceeds the ` +\n `CF free-tier safe ceiling (${CF_FREE_MAX_SAFE_FOLD_BYTES} bytes). On a free ` +\n `Worker a fold this large risks a mid-rebuild CPU kill (the ~10 ms limit): the ` +\n `current.json CAS never lands, so the fold silently does NOT advance and the tail ` +\n `grows unbounded. Safe remedies: run on CF PAID (raised CPU limits), self-host on ` +\n `NODE, or wait for §11 chunked snapshots. Leave this var unset on free CF.`,\n );\n }\n }\n }\n return resolved;\n };\n\n return {\n async fetch(req, env, ctx): Promise<Response> {\n const { options, verifier } = await ensureResolved(env);\n\n // Opt-in dev landing page. Off in production (options.dev\n // unset); when set, GET / serves HTML and GET /favicon.ico\n // returns 204 so browsers don't pin a second JSON 404 next\n // to the landing page.\n const url = new URL(req.url);\n if (options.dev !== undefined && req.method === \"GET\") {\n if (url.pathname === \"/\") {\n return new Response(renderDevLanding(options.dev), {\n status: 200,\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n }\n if (url.pathname === \"/favicon.ico\") {\n return new Response(null, { status: 204 });\n }\n }\n\n // Healthz is always anonymous — Cloudflare's load balancer\n // probes it. Keep it ahead of the verifier check; serving it\n // here avoids a `Db.create` (and the canonical-line emission)\n // on every probe. The router no longer mounts healthz — only\n // the adapter does.\n if (req.method === \"GET\" && url.pathname === \"/v1/healthz\") {\n return new Response(JSON.stringify({ ok: true }), {\n status: 200,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // Construct the per-request observability context up front so\n // EVERYTHING downstream — verifier rejection, `Db.create`, and\n // the read-cache wrapper — runs inside the same\n // `runWithContext` scope. Without this lift, a verifier\n // rejection (or a cache-hit short-circuit) would bypass\n // canonical-line emission entirely.\n //\n // The router's observability middleware (see `router.ts`\n // \"Mode A\") detects the ambient context and passes through —\n // it never creates a competing context, and it never flushes\n // its own line. The adapter owns the flush from here on.\n const requestId = req.headers.get(\"x-request-id\") ?? crypto.randomUUID();\n // In-band write-tick maintenance: the writer reads\n // `getCurrentContext()?.maintenance` at its post-CAS dispatch\n // point. On CF the fold is dispatched via `ctx.waitUntil` (off the\n // ack) with the CF-free caps + `phasesPerTick: \"single\"`; the\n // ops-plane vars are read off the `env` binding (strings). Built\n // per request so a hot-swapped `env` is observed at call time.\n const obsCtx = createObservabilityContext({\n request_id: requestId,\n maintenance: cfMaintenanceDispatch(ctx, (k) => {\n const value = (env as unknown as Record<string, unknown>)[k];\n return typeof value === \"string\" ? value : undefined;\n }),\n });\n\n // Tenant resolution: the Verifier owns it unconditionally.\n const result = await verifier(req);\n if (result === null) {\n return runWithContext(obsCtx, async () => flushUnauthorizedAndRespond(obsCtx, req));\n }\n const tenantPrefix = result.tenantPrefix;\n\n return runWithContext(obsCtx, async (): Promise<Response> => {\n // Storage is wrapped with `observableStorage(...)` so the\n // per-call class A/B counts and per-op duration histograms\n // land in the active per-request bag. Writer / compactor / GC\n // emissions reach the same bag via `getCurrentContext()?.recorder`\n // — the canonical-line flusher reads it at end-of-request.\n const storage = observableStorage(r2BindingStorage(env.BUCKET));\n const db = Db.create({\n storage,\n app: env.APP,\n tenant: tenantPrefix,\n config: options.config,\n });\n\n const app = createRouter({\n db,\n sinceTimeoutMs: options.sinceTimeoutMs,\n sincePollIntervalMs: options.sincePollIntervalMs,\n });\n\n let cacheStatus: CacheStatus = \"bypass\";\n let response: Response | undefined;\n let caughtError: unknown;\n try {\n // Hono's `fetch` returns `Response | Promise<Response>`;\n // `withReadCache` wants a `Promise<Response>`. Normalize\n // via `Promise.resolve` so the sync-return branch is wrapped.\n const cacheResult = await withReadCache(req, tenantPrefix, () =>\n Promise.resolve(app.fetch(req, env, ctx)),\n );\n cacheStatus = cacheResult.cache_status;\n response = cacheResult.response;\n } catch (error) {\n caughtError = error;\n throw error;\n } finally {\n const status = caughtError !== undefined ? 500 : (response?.status ?? 500);\n flushCanonicalLine(obsCtx, obsCtx.recorder, {\n unit: \"http\",\n status,\n outcome: deriveOutcome(req.method, status, caughtError),\n ...(caughtError !== undefined && { error: caughtError }),\n extra: {\n method: req.method,\n path: new URL(req.url).pathname,\n cache_status: cacheStatus,\n },\n });\n }\n // `response` is defined here — the `catch` arm above rethrew,\n // so reaching this line implies the try block completed.\n // Best-effort invalidate after writes. `ctx.waitUntil` keeps\n // the Worker alive for the cache.delete without blocking\n // the response.\n ctx.waitUntil(invalidateOnWrite(req, tenantPrefix, response!.status));\n return response!;\n });\n },\n\n async scheduled(event, env, ctx): Promise<void> {\n const { options } = await ensureResolved(env);\n if (options.scheduled !== undefined) {\n await options.scheduled(event, env, ctx);\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAkCA,MAAM,eAAe,SACnB,KAAK,WAAW,IAAG,KAAK,KAAK,SAAS,IAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AACnE,MAAM,aAAa,QAAwB,IAAI,IAAI;AAEnD,IAAM,uBAAN,MAA8C;CAC5C;CAEA,YAAY,QAAkB;EAC5B,IAAI,WAAW,QAAQ,WAAW,KAAA,GAChC,MAAM,IAAI,YACR,iBACA,8GACF;EAEF,KAAKA,UAAU;CACjB;CAEA,MAAM,IAAI,KAAa,MAA4D;EACjF,MAAM,QAAQ,eAAe;EAC7B,MAAM,UAAwB,CAAC;EAC/B,IAAI,MAAM,gBAAgB,KAAA,GACxB,QAAQ,SAAS,EAAE,kBAAkB,YAAY,KAAK,WAAW,EAAE;EAErE,MAAM,MAAM,MAAM,KAAKC,mBAAmB,KAAKD,QAAQ,IAAI,KAAK,OAAO,GAAG,OAAO,KAAK;EACtF,IAAI,QAAQ,MACV,OAAO;EAKT,IAAI,EAAE,UAAU,QAAQ,IAAI,SAAS,MACnC,OAAO;EAGT,O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,UAAU,UAAU;KACtE,mBAAmB,QAAQ,OAAO,UAAU;MAC1C,MAAM;MACN;MACA,SAAS,cAAc,IAAI,QAAQ,QAAQ,WAAW;MACtD,GAAI,gBAAgB,KAAA,KAAa,EAAE,OAAO,YAAY;MACtD,OAAO;OACL,QAAQ,IAAI;OACZ,MAAM,IAAI,IAAI,IAAI,GAAG,EAAE;OACvB,cAAc;MAChB;KACF,CAAC;IACH;IAMA,IAAI,UAAU,kBAAkB,KAAK,cAAc,SAAU,MAAM,CAAC;IACpE,OAAO;GACT,CAAC;EACH;EAEA,MAAM,UAAU,OAAO,KAAK,KAAoB;GAC9C,MAAM,EAAE,YAAY,MAAM,eAAe,GAAG;GAC5C,IAAI,QAAQ,cAAc,KAAA,GACxB,MAAM,QAAQ,UAAU,OAAO,KAAK,GAAG;EAE3C;CACF;AACF"}
|
|
@@ -18,6 +18,86 @@ const RATE_LIMIT_BACKOFF_MILLIS = 1e3;
|
|
|
18
18
|
*/
|
|
19
19
|
const CURRENT_JSON_CONTENT_TYPE = "application/json";
|
|
20
20
|
/**
|
|
21
|
+
* MIME type written for `gc/pending.json` PUTs.
|
|
22
|
+
*
|
|
23
|
+
* @see packages/protocol/src/coordination/gc-pending.ts
|
|
24
|
+
*/
|
|
25
|
+
const GC_PENDING_CONTENT_TYPE = "application/json";
|
|
26
|
+
/**
|
|
27
|
+
* Default grace period between "marking" a key for GC and "sweeping"
|
|
28
|
+
* (deleting) it. 7 days, chosen to span the worst plausible writer-
|
|
29
|
+
* retry window (a paused-process writer that resumes hours later
|
|
30
|
+
* should still find its idempotency anchor on the bucket). The
|
|
31
|
+
* `runGc()` function accepts an override for tests.
|
|
32
|
+
*
|
|
33
|
+
* Why 7 days specifically:
|
|
34
|
+
* - **1 day is too aggressive for batch workloads.** Worker isolate
|
|
35
|
+
* scheduling pauses, cross-region replication lag, and
|
|
36
|
+
* {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly
|
|
37
|
+
* exceed an hour under pathological conditions.
|
|
38
|
+
* - **30 days is conservative beyond the worst plausible pause.**
|
|
39
|
+
* Doubles `gc/pending.json` size at steady state and slows
|
|
40
|
+
* visibility into "did GC actually run?" by 4×.
|
|
41
|
+
* - **7 days spans the realistic upper bound** — long-running batch
|
|
42
|
+
* jobs, multi-region propagation delays, queue backlogs, and
|
|
43
|
+
* downstream outages the writer is retrying through. The protocol
|
|
44
|
+
* is unaffected by the choice of value within the [hours, weeks]
|
|
45
|
+
* range; this constant is the operator-tunable knob.
|
|
46
|
+
*
|
|
47
|
+
* Production code MUST NOT call `runGc` with `graceMillis` below the
|
|
48
|
+
* default outside maintenance windows — going below the longest
|
|
49
|
+
* plausible writer-retry latency risks deleting an anchor a writer
|
|
50
|
+
* is about to find on retry. Test code that sets `graceMillis: 0` is
|
|
51
|
+
* exercising the sweep path deliberately, not modelling production.
|
|
52
|
+
*
|
|
53
|
+
* @see packages/server/src/gc.ts
|
|
54
|
+
*/
|
|
55
|
+
const GC_GRACE_PERIOD_MILLIS = 10080 * 60 * 1e3;
|
|
56
|
+
/**
|
|
57
|
+
* Cap on candidates kept in `gc/pending.json` to bound the size of
|
|
58
|
+
* the file. The compactor marks at most this many candidates per
|
|
59
|
+
* pass; subsequent passes pick up the rest. Larger collections will
|
|
60
|
+
* lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which
|
|
61
|
+
* is acceptable.
|
|
62
|
+
*
|
|
63
|
+
* @see packages/server/src/gc.ts
|
|
64
|
+
*/
|
|
65
|
+
const GC_MAX_PENDING_CANDIDATES = 1e3;
|
|
66
|
+
/**
|
|
67
|
+
* Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also
|
|
68
|
+
* sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.
|
|
69
|
+
*
|
|
70
|
+
* @see packages/server/src/maintenance.ts
|
|
71
|
+
*/
|
|
72
|
+
const MAINTENANCE_MIN_LIVE_BYTES = 64 * 1024;
|
|
73
|
+
/**
|
|
74
|
+
* SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized
|
|
75
|
+
* ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable
|
|
76
|
+
* hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).
|
|
77
|
+
*
|
|
78
|
+
* @see docs/about/graduation.md
|
|
79
|
+
* @see packages/server/src/maintenance.ts
|
|
80
|
+
*/
|
|
81
|
+
const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT = 512 * 1024;
|
|
82
|
+
/**
|
|
83
|
+
* SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry
|
|
84
|
+
* parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021
|
|
85
|
+
* Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — calibrate via the
|
|
86
|
+
* Task 3 bench, pin in graduation.md.
|
|
87
|
+
*
|
|
88
|
+
* @see docs/about/graduation.md
|
|
89
|
+
* @see packages/server/src/maintenance.ts
|
|
90
|
+
*/
|
|
91
|
+
const MAINTENANCE_MAX_FOLD_ROWS = 2048;
|
|
92
|
+
/**
|
|
93
|
+
* Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate
|
|
94
|
+
* memory — CF recycles isolates). ~once per this many writes.
|
|
95
|
+
*
|
|
96
|
+
* @see packages/protocol/src/coordination/current-json.ts
|
|
97
|
+
* @see packages/server/src/maintenance.ts
|
|
98
|
+
*/
|
|
99
|
+
const MAINTENANCE_WARN_INTERVAL_WRITES = 1e3;
|
|
100
|
+
/**
|
|
21
101
|
* Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,
|
|
22
102
|
* the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,
|
|
23
103
|
* `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.
|
|
@@ -193,6 +273,6 @@ const loadCollectionIndexes = async (configPath, collection, commandName) => {
|
|
|
193
273
|
return cfg.collections?.[collection]?.indexes ?? [];
|
|
194
274
|
};
|
|
195
275
|
//#endregion
|
|
196
|
-
export {
|
|
276
|
+
export { GC_MAX_PENDING_CANDIDATES as a, MAINTENANCE_MAX_FOLD_ROWS as c, RATE_LIMIT_BACKOFF_MILLIS as d, SHARED_SECRET_MISSING_MESSAGE as f, GC_GRACE_PERIOD_MILLIS as i, MAINTENANCE_MIN_LIVE_BYTES as l, loadCollectionIndexes as n, GC_PENDING_CONTENT_TYPE as o, CURRENT_JSON_CONTENT_TYPE as r, MAINTENANCE_MAX_FOLD_BYTES_DEFAULT as s, loadAppConfig as t, MAINTENANCE_WARN_INTERVAL_WRITES as u };
|
|
197
277
|
|
|
198
|
-
//# sourceMappingURL=config-
|
|
278
|
+
//# sourceMappingURL=config-DVfDGyw1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-DVfDGyw1.js","names":[],"sources":["../packages/protocol/src/constants.ts","../packages/cli/src/config.ts"],"sourcesContent":["/**\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 * `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.\n *\n * Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`\n * but lives in `@baerly/cli` so the validator/loader doesn't depend on\n * the rolldown'd umbrella bundle. The scaffolder emits the config file;\n * the CLI reads it. Both sides agree on the wire shape (informally —\n * the duplication is small and intentional).\n *\n * Resolution order:\n * 1. `<cwd>/baerly.config.ts`\n * 2. `<cwd>/baerly.config.js`\n * 3. `<cwd>/baerly.config.mjs`\n * 4. `<cwd>/baerly.config.json`\n *\n * The `.ts` form requires the user to have a TS-aware Node entry\n * point (`tsx`, `--experimental-strip-types`, or a build step that\n * produced the `.js` alongside). If `import()` throws on the `.ts`\n * file, we re-wrap as `InvalidConfig` with a hint pointing at the\n * `.js` / `.json` fallbacks.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport {\n AUTH_CONFIG_VALUES,\n type AuthConfig,\n type BaerlyConfig,\n BaerlyError,\n type IndexDefinition,\n} from \"@baerly/protocol\";\n\nexport interface AppConfig {\n readonly app: string;\n readonly tenant: string;\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Required. See `AuthConfig` for the per-value semantics. The loader\n * throws `BaerlyError(\"InvalidConfig\", ...)` when `auth` is missing or\n * not a member of `AUTH_CONFIG_VALUES`.\n */\n readonly auth: AuthConfig;\n readonly domain?: string;\n readonly requiredSecrets?: readonly string[];\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /** Absolute path to the repo root that contained the config. */\n readonly repoRoot: string;\n}\n\nconst CONFIG_BASENAMES: readonly string[] = [\n \"baerly.config.ts\",\n \"baerly.config.js\",\n \"baerly.config.mjs\",\n \"baerly.config.json\",\n];\n\n/**\n * Locate the first `baerly.config.*` file under `cwd`. Returns the\n * absolute path or `null` if none exists.\n *\n * Exported so the collection-aware loader (and future consumers) can\n * reuse the same resolution order without re-implementing it.\n */\nexport const locateConfig = (cwd: string): string | null => {\n for (const base of CONFIG_BASENAMES) {\n const abs = resolve(cwd, base);\n if (existsSync(abs)) {\n return abs;\n }\n }\n return null;\n};\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to\n * `process.cwd()`). Validates the required fields and the\n * locked-shape optionals; returns an `AppConfig` decorated with the\n * `repoRoot` it was loaded from.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — file missing, default\n * export missing, or any field has the wrong shape / type.\n */\nexport const loadAppConfig = async (cwd: string = process.cwd()): Promise<AppConfig> => {\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`,\n );\n }\n\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to read ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n try {\n raw = JSON.parse(text) as unknown;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to parse ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n } else {\n let mod: { default?: unknown };\n try {\n mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n } catch (error) {\n const hint = cfgPath.endsWith(\".ts\")\n ? \" (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)\"\n : \"\";\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to load ${cfgPath}: ${(error as Error).message}${hint}`,\n error,\n );\n }\n raw = mod.default;\n }\n\n if (raw === undefined || typeof raw !== \"object\" || raw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`,\n );\n }\n\n const obj = raw as Record<string, unknown>;\n const app = obj[\"app\"];\n const tenant = obj[\"tenant\"];\n const target = obj[\"target\"];\n if (typeof app !== \"string\" || app.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`app\\` must be a non-empty string`,\n );\n }\n if (typeof tenant !== \"string\" || tenant.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`tenant\\` must be a non-empty string`,\n );\n }\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`target\\` must be \"cloudflare\" or \"node\" (got ${JSON.stringify(target)})`,\n );\n }\n\n // `auth` is a required typed posture as of the graduated-auth\n // redesign. The widening cast to `readonly string[]` is needed\n // because `.includes` on a tuple narrows its parameter to the\n // tuple's element type; widening locally is the standard idiom.\n const authRaw = obj[\"auth\"];\n if (typeof authRaw !== \"string\" || !(AUTH_CONFIG_VALUES as readonly string[]).includes(authRaw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`auth\\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`,\n );\n }\n const auth = authRaw as AuthConfig;\n\n const domainRaw = obj[\"domain\"];\n if (domainRaw !== undefined && typeof domainRaw !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`domain\\` must be a string when set`,\n );\n }\n\n const secretsRaw = obj[\"requiredSecrets\"];\n let requiredSecrets: readonly string[] | undefined;\n if (secretsRaw !== undefined) {\n if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === \"string\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`requiredSecrets\\` must be an array of strings`,\n );\n }\n requiredSecrets = secretsRaw as readonly string[];\n }\n\n const cfaRaw = obj[\"cloudflareAccess\"];\n let cloudflareAccess: AppConfig[\"cloudflareAccess\"];\n if (cfaRaw !== undefined) {\n if (typeof cfaRaw !== \"object\" || cfaRaw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess\\` must be an object when set`,\n );\n }\n const cfa = cfaRaw as Record<string, unknown>;\n const td = cfa[\"teamDomain\"];\n const aud = cfa[\"audienceTag\"];\n if (typeof td !== \"string\" || td.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.teamDomain\\` must be a non-empty string`,\n );\n }\n if (typeof aud !== \"string\" || aud.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.audienceTag\\` must be a non-empty string`,\n );\n }\n cloudflareAccess = { teamDomain: td, audienceTag: aud };\n }\n\n return {\n app,\n tenant,\n target,\n auth,\n ...(domainRaw !== undefined && { domain: domainRaw }),\n ...(requiredSecrets !== undefined && { requiredSecrets }),\n ...(cloudflareAccess !== undefined && { cloudflareAccess }),\n repoRoot: cwd,\n };\n};\n\n/**\n * Lightweight per-collection index reflection. Mirrors the shape the\n * runtime `BaerlyConfig` carries, but only the fields the doctor needs.\n *\n * `indexes` is an empty array when the collection declared none.\n */\nexport interface LoadedCollection {\n readonly name: string;\n readonly indexes: readonly IndexDefinition[];\n}\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` AND return the parsed\n * `collections[*]` shape alongside the narrow {@link AppConfig}. Lets\n * the doctor reflect on declared indexes without forcing every consumer\n * to widen `AppConfig`. Returns `undefined` for `collections` when the\n * config doesn't declare any (the doctor downgrades the drift check to\n * a no-op `info` finding in that case).\n *\n * Re-uses {@link loadAppConfig}'s parse/validate path, so the\n * `AppConfig` invariants are still enforced.\n */\nexport const loadAppConfigWithCollections = async (\n cwd: string = process.cwd(),\n): Promise<{\n readonly config: AppConfig;\n readonly collections: readonly LoadedCollection[] | undefined;\n}> => {\n const config = await loadAppConfig(cwd);\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n return { config, collections: undefined };\n }\n\n // Re-parse the raw default-export to pluck `collections[*]`. We\n // don't validate the inner shape here — at the doctor surface,\n // anything that isn't an object is reported as \"no filtered\n // indexes\" rather than throwing, so a partially-typed config\n // doesn't fail the whole check.\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch {\n return { config, collections: undefined };\n }\n try {\n raw = JSON.parse(text);\n } catch {\n return { config, collections: undefined };\n }\n } else {\n try {\n const mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n raw = mod.default;\n } catch {\n // Node can't `import` a .ts file without a TS loader. The\n // narrow `loadAppConfig` already surfaced the InvalidConfig if\n // that path was unreadable; here we silently downgrade to\n // \"no collections\" rather than re-throw.\n return { config, collections: undefined };\n }\n }\n\n if (raw === undefined || raw === null || typeof raw !== \"object\") {\n return { config, collections: undefined };\n }\n const colsRaw = (raw as { collections?: unknown }).collections;\n if (colsRaw === undefined || colsRaw === null || typeof colsRaw !== \"object\") {\n return { config, collections: undefined };\n }\n\n const out: LoadedCollection[] = [];\n for (const [name, decl] of Object.entries(colsRaw as Record<string, unknown>)) {\n if (decl === null || typeof decl !== \"object\") {\n continue;\n }\n const indexes = (decl as { indexes?: unknown }).indexes;\n if (!Array.isArray(indexes)) {\n out.push({ name, indexes: [] });\n continue;\n }\n // Pass-through cast: the runtime IndexDefinition validation\n // lives in `@baerly/server`; the doctor only reads `name`, `on`,\n // and `predicate`, so a partial shape still gives an actionable\n // finding rather than a SchemaError throw at config-load time.\n out.push({ name, indexes: indexes as readonly IndexDefinition[] });\n }\n return { config, collections: out };\n};\n\n/**\n * Load the declared `IndexDefinition[]` for a single collection from a\n * `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count\n * probes) and `baerly admin rebuild-index` (resolving the `on` field).\n *\n * `.ts` configs are rejected — Node can't `import` them without a TS\n * loader; point at the compiled `.js` output instead.\n *\n * `commandName` is woven into thrown error messages so the operator\n * sees the calling command name in the prefix.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `.ts` extension, JSON\n * parse error, missing default export, or missing\n * `collections[collection]`.\n */\nexport const loadCollectionIndexes = async (\n configPath: string,\n collection: string,\n commandName: string,\n): Promise<readonly IndexDefinition[]> => {\n if (configPath.endsWith(\".ts\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`,\n );\n }\n let cfg: BaerlyConfig;\n if (configPath.endsWith(\".json\")) {\n const text = await readFile(configPath, \"utf8\");\n try {\n cfg = JSON.parse(text) as BaerlyConfig;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${(error as Error).message}`,\n );\n }\n } else {\n const abs = configPath.startsWith(\"file://\") ? fileURLToPath(configPath) : resolve(configPath);\n const mod = (await import(pathToFileURL(abs).href)) as { default?: BaerlyConfig };\n if (mod.default === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config ${JSON.stringify(configPath)} has no default export`,\n );\n }\n cfg = mod.default;\n }\n return cfg.collections?.[collection]?.indexes ?? [];\n};\n"],"mappings":";;;;;;;;;;AA0DA,MAAa,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,UAAU,EAAE,uBACzD;EAEF,MAAM,IAAI;CACZ;CACA,OAAO,IAAI,cAAc,aAAa,WAAW,CAAC;AACpD"}
|
|
@@ -157,7 +157,8 @@ const createObservabilityContext = (init = {}) => ({
|
|
|
157
157
|
request_id: init.request_id ?? crypto.randomUUID(),
|
|
158
158
|
started_at: performance.now(),
|
|
159
159
|
fields: /* @__PURE__ */ new Map(),
|
|
160
|
-
recorder: init.recorder ?? new RequestScopedMetricsRecorder()
|
|
160
|
+
recorder: init.recorder ?? new RequestScopedMetricsRecorder(),
|
|
161
|
+
...init.maintenance !== void 0 && { maintenance: init.maintenance }
|
|
161
162
|
});
|
|
162
163
|
/**
|
|
163
164
|
* Module-level slot. One instance per process — the Workers
|
|
@@ -184,4 +185,4 @@ const getCurrentContext = () => als.getStore();
|
|
|
184
185
|
//#endregion
|
|
185
186
|
export { noopMetricsRecorder as i, getCurrentContext as n, runWithContext as r, createObservabilityContext as t };
|
|
186
187
|
|
|
187
|
-
//# sourceMappingURL=context-
|
|
188
|
+
//# sourceMappingURL=context-DRZ3tZ5l.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-Oj7ffwD-.js","names":["#counters","#gauges","#histograms"],"sources":["../packages/protocol/src/metrics.ts","../packages/server/src/observability/recorder.ts","../packages/server/src/observability/context.ts"],"sourcesContent":["/**\n * `MetricsRecorder` — internal emission contract for the six\n * load-bearing kernel metrics. Writer / compactor / GC emit through\n * an instance of this interface; in production the instance is the\n * per-request `RequestScopedMetricsRecorder` on the active\n * `ObservabilityContext`, and emissions flow onto the canonical line\n * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and\n * wrap their workload in `runWithContext` to attach it.\n *\n * Operators do not wire a custom sink against this interface — the\n * operator's view of kernel emissions is the canonical line on\n * stdout (one JSON object per HTTP request).\n *\n * **Naming convention** matches the load-bearing metrics:\n * - `db.write.class_a_ops_per_logical_write` — histogram (p99 alert at 5).\n * Includes one Class A op per index PUT + index DELETE emitted\n * in the commit's fence. Idle-reader cost is unchanged.\n * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)\n * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)\n * - `db.write.index_ops_per_logical_write` — histogram.\n * `K (PUT) + L (DELETE)` per commit. Per-collection label.\n * - `db.manifest.lag_window_depth` — gauge (alert at >100)\n * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)\n * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)\n * - `db.compact.entries_folded` — histogram (entries folded per run)\n * - `db.gc.swept_total` — counter (labelled by reason)\n *\n * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase\n * snake_case segments. Labels are flat\n * `Readonly<Record<string, string>>` — no numbers, no nested objects.\n *\n * Metric emissions never throw on the hot path; the default\n * `noopMetricsRecorder` cannot throw.\n */\nexport interface MetricsRecorder {\n /** Monotonically-incrementing event count. */\n counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Point-in-time value. */\n gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Distribution sample. */\n histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n}\n\n/**\n * No-op recorder. Safe default when no operator sink is wired —\n * emission sites that read `getCurrentContext()?.recorder` fall\n * back to this outside an active `runWithContext` scope.\n */\nexport const noopMetricsRecorder: MetricsRecorder = {\n counter: (): void => {},\n gauge: (): void => {},\n histogram: (): void => {},\n};\n","/**\n * Per-request `MetricsRecorder` whose primary product is the\n * canonical-line attribute set.\n *\n * `RequestScopedMetricsRecorder` is a deliberately tiny extension to\n * the {@link MetricsRecorder} interface that adds two readers\n * (`snapshot()` for tests / debug, `summarize()` for the canonical\n * log line). Every method just appends a row to a flat array — no\n * sorting, no JSON, no aggregation on the hot path. The work happens\n * once at end-of-request inside `summarize()`.\n *\n * The shape mirrors {@link InMemoryMetricsRecorder} from\n * `../_internal/in-memory-metrics.ts` but adds the per-request product. We do\n * NOT extend that class — composition over inheritance, and the\n * observability layer wants `summarize()` to be the only side-channel.\n */\n\nimport type { MetricsRecorder } from \"@baerly/protocol\";\n\n/** One observation row, kept in insertion order. */\nexport interface ObservationRow {\n readonly name: string;\n readonly value: number;\n readonly labels: Readonly<Record<string, string>>;\n}\n\n/** Result of {@link RequestScopedMetricsRecorder.snapshot}. */\nexport interface MetricsSnapshot {\n readonly counters: readonly ObservationRow[];\n readonly gauges: readonly ObservationRow[];\n readonly histograms: readonly ObservationRow[];\n}\n\n/** Flat per-metric aggregation as consumed by the canonical line. */\nexport type MetricsSummary = Record<string, number>;\n\n/**\n * Implementation. Allocations:\n *\n * - Three arrays at construction time, grown on each emission.\n * - On `summarize()` we materialize one extra `Map` per metric-\n * family (counter / gauge / histogram) plus a copy of each\n * histogram's values for sorting.\n *\n * CPU-ms budget on Workers is tight; we deliberately defer all of\n * that to flush time.\n */\nexport class RequestScopedMetricsRecorder implements MetricsRecorder {\n readonly #counters: ObservationRow[] = [];\n readonly #gauges: ObservationRow[] = [];\n readonly #histograms: ObservationRow[] = [];\n\n counter(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#counters.push({ name, value, labels });\n }\n gauge(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#gauges.push({ name, value, labels });\n }\n histogram(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#histograms.push({ name, value, labels });\n }\n\n /**\n * Read-only view of every observation seen so far. Intended for\n * tests + structured debugging; the canonical-line flusher uses\n * {@link summarize} instead.\n *\n * @internal Not part of the published observability surface; tests\n * import via relative path. Production reads via {@link summarize}.\n */\n snapshot(): MetricsSnapshot {\n return {\n counters: this.#counters.slice(),\n gauges: this.#gauges.slice(),\n histograms: this.#histograms.slice(),\n };\n }\n\n /**\n * Flat aggregation, keyed by metric name with suffixes baked in:\n *\n * - Counter `db.foo.bar` → `db.foo.bar_total` (sum of all observations)\n * - Gauge `db.foo.bar` → `db.foo.bar` (last value seen)\n * - Histogram `db.foo.bar` → `db.foo.bar_count` (number of observations)\n * + `db.foo.bar_sum` (sum of values)\n *\n * Histogram aggregation is a single pass in insertion order — no\n * sort. Returns numbers only — labels are NOT collapsed into keys;\n * if a metric is emitted with different label sets, its\n * observations are aggregated together by `name` alone. The\n * canonical line is per-request anyway; per-label fan-out belongs\n * to the operator's long-term recorder.\n */\n summarize(): MetricsSummary {\n const out: MetricsSummary = {};\n\n // Counters: sum.\n for (const row of this.#counters) {\n // Counter convention: prefer the emitter's name verbatim. If the\n // emitter already namespaced its counter with `_total` (Prometheus\n // convention — see packages/server/src/observability/storage.ts),\n // do not double-append. Otherwise append for canonical-line\n // consumers that key off the `_total` suffix.\n const key = row.name.endsWith(\"_total\") ? row.name : `${row.name}_total`;\n out[key] = (out[key] ?? 0) + row.value;\n }\n\n // Gauges: last write wins per name (observations are in\n // insertion order; iterate forward and overwrite).\n for (const row of this.#gauges) {\n out[row.name] = row.value;\n }\n\n // Histograms: bucket-by-name, then emit `_count` + `_sum`.\n const buckets = new Map<string, { count: number; sum: number }>();\n for (const row of this.#histograms) {\n let agg = buckets.get(row.name);\n if (agg === undefined) {\n agg = { count: 0, sum: 0 };\n buckets.set(row.name, agg);\n }\n agg.count += 1;\n agg.sum += row.value;\n }\n for (const [name, { count, sum }] of buckets) {\n out[`${name}_count`] = count;\n out[`${name}_sum`] = sum;\n }\n\n return out;\n }\n}\n","/**\n * Per-request observability context.\n *\n * One `ObservabilityContext` is created at the entry of each unit-of-\n * work (HTTP request, maintenance tick, GC sweep, rebuild run) and\n * carried through the call tree via {@link runWithContext} /\n * {@link getCurrentContext}, which delegates to a single module-level\n * `AsyncLocalStorage` instance.\n *\n * The context is intentionally tiny: an externally-set\n * {@link request_id}, a high-resolution `started_at`, and a mutable\n * {@link fields} bag used to accumulate canonical-line attributes\n * during the unit's lifecycle.\n *\n * The context shape is `readonly` everywhere it can be — only the\n * contents of `fields` are intended to mutate during a request. The\n * {@link fields} map itself is not `readonly` because callers (the\n * canonical-line emitter, middleware, the collection API once Dispatch\n * 3+ wires it up) need to set entries.\n *\n * The context carries no sampling state — every unit-of-work emits\n * one canonical line unconditionally; there is nothing to gate.\n *\n * ## Time source\n *\n * `started_at` uses `performance.now()` so durations can be\n * computed without worrying about wall-clock skew (NTP step,\n * leap-second smearing). `performance.now()` is part of both Node\n * 18+ and the Workers Runtime; we don't fall back to `Date.now()`.\n *\n * @example\n * ```ts\n * const ctx = createObservabilityContext({});\n * await runWithContext(ctx, async () => {\n * const inner = getCurrentContext();\n * inner?.fields.set(\"collection\", \"tickets\");\n * await doWork();\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { RequestScopedMetricsRecorder } from \"./recorder.ts\";\n\n/** Read-mostly per-request observability state. */\nexport interface ObservabilityContext {\n /** Externally-correlatable request identifier (UUID-ish). */\n readonly request_id: string;\n /** Monotonic `performance.now()` reading captured at construction. */\n readonly started_at: number;\n /**\n * Mutable bag for canonical-line attributes. Callers `obs.fields.set(\"k\", v)`;\n * the canonical-line flusher spreads this onto the emitted properties at\n * end-of-request.\n */\n readonly fields: Map<string, unknown>;\n /**\n * Per-request metrics bag. Lives on the context so adapters can\n * reach it from inside the `Db`'s `MetricsRecorder` callback via\n * `getCurrentContext()?.recorder` — no parallel `AsyncLocalStorage`\n * lookup. The canonical-line flusher reads its `summarize()` at\n * end-of-request and spreads the result onto the emitted line.\n */\n readonly recorder: RequestScopedMetricsRecorder;\n}\n\n/**\n * Optional construction inputs. All fields are optional so callers in\n * unit-of-work entry middleware (HTTP router, maintenance scheduler)\n * can pass only what they have. Defaults:\n *\n * - `request_id`: a fresh `crypto.randomUUID()`. Pass an externally-\n * supplied id (`X-Request-Id` header, scheduler-supplied tag) to\n * propagate correlation downstream.\n * - `recorder`: a fresh {@link RequestScopedMetricsRecorder}. Tests can\n * pass an externally-constructed recorder to assert on its\n * `snapshot()` after the unit-of-work completes; production callers\n * should accept the default.\n */\nexport interface ObservabilityContextInit {\n readonly request_id?: string;\n readonly recorder?: RequestScopedMetricsRecorder;\n}\n\n/**\n * Factory for {@link ObservabilityContext}. We use a factory rather\n * than a class so consumers can structural-type the result and so\n * the `AsyncLocalStorage` slot type stays a plain interface — no\n * surprises around `instanceof` across realms (Workers vs Node).\n */\nexport const createObservabilityContext = (\n init: ObservabilityContextInit = {},\n): ObservabilityContext => ({\n request_id: init.request_id ?? crypto.randomUUID(),\n started_at: performance.now(),\n fields: new Map(),\n recorder: init.recorder ?? new RequestScopedMetricsRecorder(),\n});\n\n/**\n * Module-level slot. One instance per process — the Workers\n * Runtime's `nodejs_compat` flag wires `node:async_hooks` to a\n * per-request scope, so cross-request bleed is impossible there.\n */\nconst als = new AsyncLocalStorage<ObservabilityContext>();\n\n/**\n * Run `fn` with `ctx` active as the current observability context.\n * Inside `fn` (and any `await`-chained continuation rooted in `fn`),\n * {@link getCurrentContext} returns `ctx`. Outside, it returns the\n * previously-active context (or `undefined`).\n *\n * `runWithContext` is async-safe via `AsyncLocalStorage`; it propagates\n * through `await`, `Promise.all`, `setTimeout`, and `queueMicrotask`.\n *\n * Returns `fn`'s return value verbatim — including its promise\n * identity, so callers can `await` or chain off it without extra\n * indirection.\n */\nexport const runWithContext = <T>(\n ctx: ObservabilityContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> => als.run(ctx, fn);\n\n/** Returns the currently-active context, or `undefined` outside one. */\nexport const getCurrentContext = (): ObservabilityContext | undefined => als.getStore();\n"],"mappings":";;;;;;;AAgDA,MAAa,sBAAuC;CAClD,eAAqB,CAAC;CACtB,aAAmB,CAAC;CACpB,iBAAuB,CAAC;AAC1B;;;;;;;;;;;;;;ACLA,IAAa,+BAAb,MAAqE;CACnE,YAAuC,CAAC;CACxC,UAAqC,CAAC;CACtC,cAAyC,CAAC;CAE1C,QAAQ,MAAc,OAAe,SAA2C,CAAC,GAAS;EACxF,KAAKA,UAAU,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC7C;CACA,MAAM,MAAc,OAAe,SAA2C,CAAC,GA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AAY,IAAI,6BAA6B;AAC9D;;;;;;AAOA,MAAM,MAAM,IAAI,kBAAwC;;;;;;;;;;;;;;AAexD,MAAa,kBACX,KACA,OACmB,IAAI,IAAI,KAAK,EAAE;;AAGpC,MAAa,0BAA4D,IAAI,SAAS"}
|
|
1
|
+
{"version":3,"file":"context-DRZ3tZ5l.js","names":["#counters","#gauges","#histograms"],"sources":["../packages/protocol/src/metrics.ts","../packages/server/src/observability/recorder.ts","../packages/server/src/observability/context.ts"],"sourcesContent":["/**\n * `MetricsRecorder` — internal emission contract for the six\n * load-bearing kernel metrics. Writer / compactor / GC emit through\n * an instance of this interface; in production the instance is the\n * per-request `RequestScopedMetricsRecorder` on the active\n * `ObservabilityContext`, and emissions flow onto the canonical line\n * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and\n * wrap their workload in `runWithContext` to attach it.\n *\n * Operators do not wire a custom sink against this interface — the\n * operator's view of kernel emissions is the canonical line on\n * stdout (one JSON object per HTTP request).\n *\n * **Naming convention** matches the load-bearing metrics:\n * - `db.write.class_a_ops_per_logical_write` — histogram (p99 alert at 5).\n * Includes one Class A op per index PUT + index DELETE emitted\n * in the commit's fence. Idle-reader cost is unchanged.\n * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)\n * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)\n * - `db.write.index_ops_per_logical_write` — histogram.\n * `K (PUT) + L (DELETE)` per commit. Per-collection label.\n * - `db.manifest.lag_window_depth` — gauge (alert at >100)\n * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)\n * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)\n * - `db.compact.entries_folded` — histogram (entries folded per run)\n * - `db.gc.swept_total` — counter (labelled by reason)\n *\n * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase\n * snake_case segments. Labels are flat\n * `Readonly<Record<string, string>>` — no numbers, no nested objects.\n *\n * Metric emissions never throw on the hot path; the default\n * `noopMetricsRecorder` cannot throw.\n */\nexport interface MetricsRecorder {\n /** Monotonically-incrementing event count. */\n counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Point-in-time value. */\n gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Distribution sample. */\n histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n}\n\n/**\n * No-op recorder. Safe default when no operator sink is wired —\n * emission sites that read `getCurrentContext()?.recorder` fall\n * back to this outside an active `runWithContext` scope.\n */\nexport const noopMetricsRecorder: MetricsRecorder = {\n counter: (): void => {},\n gauge: (): void => {},\n histogram: (): void => {},\n};\n","/**\n * Per-request `MetricsRecorder` whose primary product is the\n * canonical-line attribute set.\n *\n * `RequestScopedMetricsRecorder` is a deliberately tiny extension to\n * the {@link MetricsRecorder} interface that adds two readers\n * (`snapshot()` for tests / debug, `summarize()` for the canonical\n * log line). Every method just appends a row to a flat array — no\n * sorting, no JSON, no aggregation on the hot path. The work happens\n * once at end-of-request inside `summarize()`.\n *\n * The shape mirrors {@link InMemoryMetricsRecorder} from\n * `../_internal/in-memory-metrics.ts` but adds the per-request product. We do\n * NOT extend that class — composition over inheritance, and the\n * observability layer wants `summarize()` to be the only side-channel.\n */\n\nimport type { MetricsRecorder } from \"@baerly/protocol\";\n\n/** One observation row, kept in insertion order. */\nexport interface ObservationRow {\n readonly name: string;\n readonly value: number;\n readonly labels: Readonly<Record<string, string>>;\n}\n\n/** Result of {@link RequestScopedMetricsRecorder.snapshot}. */\nexport interface MetricsSnapshot {\n readonly counters: readonly ObservationRow[];\n readonly gauges: readonly ObservationRow[];\n readonly histograms: readonly ObservationRow[];\n}\n\n/** Flat per-metric aggregation as consumed by the canonical line. */\nexport type MetricsSummary = Record<string, number>;\n\n/**\n * Implementation. Allocations:\n *\n * - Three arrays at construction time, grown on each emission.\n * - On `summarize()` we materialize one extra `Map` per metric-\n * family (counter / gauge / histogram) plus a copy of each\n * histogram's values for sorting.\n *\n * CPU-ms budget on Workers is tight; we deliberately defer all of\n * that to flush time.\n */\nexport class RequestScopedMetricsRecorder implements MetricsRecorder {\n readonly #counters: ObservationRow[] = [];\n readonly #gauges: ObservationRow[] = [];\n readonly #histograms: ObservationRow[] = [];\n\n counter(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#counters.push({ name, value, labels });\n }\n gauge(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#gauges.push({ name, value, labels });\n }\n histogram(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#histograms.push({ name, value, labels });\n }\n\n /**\n * Read-only view of every observation seen so far. Intended for\n * tests + structured debugging; the canonical-line flusher uses\n * {@link summarize} instead.\n *\n * @internal Not part of the published observability surface; tests\n * import via relative path. Production reads via {@link summarize}.\n */\n snapshot(): MetricsSnapshot {\n return {\n counters: this.#counters.slice(),\n gauges: this.#gauges.slice(),\n histograms: this.#histograms.slice(),\n };\n }\n\n /**\n * Flat aggregation, keyed by metric name with suffixes baked in:\n *\n * - Counter `db.foo.bar` → `db.foo.bar_total` (sum of all observations)\n * - Gauge `db.foo.bar` → `db.foo.bar` (last value seen)\n * - Histogram `db.foo.bar` → `db.foo.bar_count` (number of observations)\n * + `db.foo.bar_sum` (sum of values)\n *\n * Histogram aggregation is a single pass in insertion order — no\n * sort. Returns numbers only — labels are NOT collapsed into keys;\n * if a metric is emitted with different label sets, its\n * observations are aggregated together by `name` alone. The\n * canonical line is per-request anyway; per-label fan-out belongs\n * to the operator's long-term recorder.\n */\n summarize(): MetricsSummary {\n const out: MetricsSummary = {};\n\n // Counters: sum.\n for (const row of this.#counters) {\n // Counter convention: prefer the emitter's name verbatim. If the\n // emitter already namespaced its counter with `_total` (Prometheus\n // convention — see packages/server/src/observability/storage.ts),\n // do not double-append. Otherwise append for canonical-line\n // consumers that key off the `_total` suffix.\n const key = row.name.endsWith(\"_total\") ? row.name : `${row.name}_total`;\n out[key] = (out[key] ?? 0) + row.value;\n }\n\n // Gauges: last write wins per name (observations are in\n // insertion order; iterate forward and overwrite).\n for (const row of this.#gauges) {\n out[row.name] = row.value;\n }\n\n // Histograms: bucket-by-name, then emit `_count` + `_sum`.\n const buckets = new Map<string, { count: number; sum: number }>();\n for (const row of this.#histograms) {\n let agg = buckets.get(row.name);\n if (agg === undefined) {\n agg = { count: 0, sum: 0 };\n buckets.set(row.name, agg);\n }\n agg.count += 1;\n agg.sum += row.value;\n }\n for (const [name, { count, sum }] of buckets) {\n out[`${name}_count`] = count;\n out[`${name}_sum`] = sum;\n }\n\n return out;\n }\n}\n","/**\n * Per-request observability context.\n *\n * One `ObservabilityContext` is created at the entry of each unit-of-\n * work (HTTP request, maintenance tick, GC sweep, rebuild run) and\n * carried through the call tree via {@link runWithContext} /\n * {@link getCurrentContext}, which delegates to a single module-level\n * `AsyncLocalStorage` instance.\n *\n * The context is intentionally tiny: an externally-set\n * {@link request_id}, a high-resolution `started_at`, and a mutable\n * {@link fields} bag used to accumulate canonical-line attributes\n * during the unit's lifecycle.\n *\n * The context shape is `readonly` everywhere it can be — only the\n * contents of `fields` are intended to mutate during a request. The\n * {@link fields} map itself is not `readonly` because callers (the\n * canonical-line emitter, middleware, the collection API once Dispatch\n * 3+ wires it up) need to set entries.\n *\n * The context carries no sampling state — every unit-of-work emits\n * one canonical line unconditionally; there is nothing to gate.\n *\n * ## Time source\n *\n * `started_at` uses `performance.now()` so durations can be\n * computed without worrying about wall-clock skew (NTP step,\n * leap-second smearing). `performance.now()` is part of both Node\n * 18+ and the Workers Runtime; we don't fall back to `Date.now()`.\n *\n * @example\n * ```ts\n * const ctx = createObservabilityContext({});\n * await runWithContext(ctx, async () => {\n * const inner = getCurrentContext();\n * inner?.fields.set(\"collection\", \"tickets\");\n * await doWork();\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n// Type-only import — `maintenance.ts` imports this module's runtime\n// values (`getCurrentContext`), so a value import here would form a\n// runtime cycle. A type-only edge erases at build time, so tsgo /\n// rolldown see no cycle.\nimport type { MaintenanceDispatch } from \"../maintenance.ts\";\nimport { RequestScopedMetricsRecorder } from \"./recorder.ts\";\n\n/** Read-mostly per-request observability state. */\nexport interface ObservabilityContext {\n /** Externally-correlatable request identifier (UUID-ish). */\n readonly request_id: string;\n /** Monotonic `performance.now()` reading captured at construction. */\n readonly started_at: number;\n /**\n * Mutable bag for canonical-line attributes. Callers `obs.fields.set(\"k\", v)`;\n * the canonical-line flusher spreads this onto the emitted properties at\n * end-of-request.\n */\n readonly fields: Map<string, unknown>;\n /**\n * Per-request metrics bag. Lives on the context so adapters can\n * reach it from inside the `Db`'s `MetricsRecorder` callback via\n * `getCurrentContext()?.recorder` — no parallel `AsyncLocalStorage`\n * lookup. The canonical-line flusher reads its `summarize()` at\n * end-of-request and spreads the result onto the emitted line.\n */\n readonly recorder: RequestScopedMetricsRecorder;\n /**\n * Per-request write-tick maintenance dispatch config. Set by the\n * adapter (NOT `Db.create`) so the inherently-per-request\n * `dispatch = ctx.waitUntil` and the env-var-derived caps ride the\n * same scope the kernel write-tick reads from. The {@link Writer}\n * consults `getCurrentContext()?.maintenance` at the post-CAS\n * dispatch point. Absent ⇒ inline dispatch + CF-free-safe caps.\n */\n readonly maintenance?: MaintenanceDispatch;\n}\n\n/**\n * Optional construction inputs. All fields are optional so callers in\n * unit-of-work entry middleware (HTTP router, maintenance scheduler)\n * can pass only what they have. Defaults:\n *\n * - `request_id`: a fresh `crypto.randomUUID()`. Pass an externally-\n * supplied id (`X-Request-Id` header, scheduler-supplied tag) to\n * propagate correlation downstream.\n * - `recorder`: a fresh {@link RequestScopedMetricsRecorder}. Tests can\n * pass an externally-constructed recorder to assert on its\n * `snapshot()` after the unit-of-work completes; production callers\n * should accept the default.\n */\nexport interface ObservabilityContextInit {\n readonly request_id?: string;\n readonly recorder?: RequestScopedMetricsRecorder;\n /** Write-tick maintenance dispatch config. See {@link ObservabilityContext.maintenance}. */\n readonly maintenance?: MaintenanceDispatch;\n}\n\n/**\n * Factory for {@link ObservabilityContext}. We use a factory rather\n * than a class so consumers can structural-type the result and so\n * the `AsyncLocalStorage` slot type stays a plain interface — no\n * surprises around `instanceof` across realms (Workers vs Node).\n */\nexport const createObservabilityContext = (\n init: ObservabilityContextInit = {},\n): ObservabilityContext => ({\n request_id: init.request_id ?? crypto.randomUUID(),\n started_at: performance.now(),\n fields: new Map(),\n recorder: init.recorder ?? new RequestScopedMetricsRecorder(),\n ...(init.maintenance !== undefined && { maintenance: init.maintenance }),\n});\n\n/**\n * Module-level slot. One instance per process — the Workers\n * Runtime's `nodejs_compat` flag wires `node:async_hooks` to a\n * per-request scope, so cross-request bleed is impossible there.\n */\nconst als = new AsyncLocalStorage<ObservabilityContext>();\n\n/**\n * Run `fn` with `ctx` active as the current observability context.\n * Inside `fn` (and any `await`-chained continuation rooted in `fn`),\n * {@link getCurrentContext} returns `ctx`. Outside, it returns the\n * previously-active context (or `undefined`).\n *\n * `runWithContext` is async-safe via `AsyncLocalStorage`; it propagates\n * through `await`, `Promise.all`, `setTimeout`, and `queueMicrotask`.\n *\n * Returns `fn`'s return value verbatim — including its promise\n * identity, so callers can `await` or chain off it without extra\n * indirection.\n */\nexport const runWithContext = <T>(\n ctx: ObservabilityContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> => als.run(ctx, fn);\n\n/** Returns the currently-active context, or `undefined` outside one. */\nexport const getCurrentContext = (): ObservabilityContext | undefined => als.getStore();\n"],"mappings":";;;;;;;AAgDA,MAAa,sBAAuC;CAClD,eAAqB,CAAC;CACtB,aAAmB,CAAC;CACpB,iBAAuB,CAAC;AAC1B;;;;;;;;;;;;;;ACLA,IAAa,+BAAb,MAAqE;CACnE,YAAuC,CAAC;CACxC,UAAqC,CAAC;CACtC,cAAyC,CAAC;CAE1C,QAAQ,MAAc,OAAe,SAA2C,CAAC,GAAS;EACxF,KAAKA,UAAU,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC7C;CACA,MAAM,MAAc,OAAe,SAA2C,CAAC,GAAS;EACtF,KAAKC,QAAQ,KA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GAAI,KAAK,gBAAgB,KAAA,KAAa,EAAE,aAAa,KAAK,YAAY;AACxE;;;;;;AAOA,MAAM,MAAM,IAAI,kBAAwC;;;;;;;;;;;;;;AAexD,MAAa,kBACX,KACA,OACmB,IAAI,IAAI,KAAK,EAAE;;AAGpC,MAAa,0BAA4D,IAAI,SAAS"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
|
|
2
2
|
import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
|
|
3
|
-
import {
|
|
4
|
-
import { estimateWritesPerMin } from "./usage-RVUQMLop.js";
|
|
3
|
+
import { estimateWritesPerMin } from "./usage-CLjirdD-.js";
|
|
5
4
|
//#region src/cost/provider.ts
|
|
6
5
|
const detectProvider = (args) => {
|
|
7
6
|
if (args.override !== void 0) return args.override;
|
|
@@ -200,4 +199,4 @@ bundle.run;
|
|
|
200
199
|
//#endregion
|
|
201
200
|
export { cost };
|
|
202
201
|
|
|
203
|
-
//# sourceMappingURL=cost-
|
|
202
|
+
//# sourceMappingURL=cost-CQt1YRkA.js.map
|