@gusto/baerly-storage 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +176 -70
- package/dist/API.md +213 -139
- package/dist/CHANGELOG.md +434 -0
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +238 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-DyiFK3_k.d.ts} +55 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +301 -301
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-Fe8CwB73.d.ts} +10 -10
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-DzKBrUlg.js} +178 -2
- package/dist/cloudflare-DzKBrUlg.js.map +1 -0
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +59 -26
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-DSMIVqzL.js} +43 -42
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/current-json-C6nhPOm1.js +190 -0
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-DsPkOVEH.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-DonTr-CV.js} +12 -5
- package/dist/deploy-DonTr-CV.js.map +1 -0
- package/dist/dev-vite.d.ts +11 -7
- package/dist/dev-vite.js +7 -6
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-DSIyCDg_.js} +14 -136
- package/dist/doctor-DSIyCDg_.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-Bh5k26VQ.js} +10 -31
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-Bhbz90-z.js → export-DtF5tDIM.js} +11 -32
- package/dist/{export-Bhbz90-z.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-D_djMO5D.js} +28 -39
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-DxM9MflO.js} +151 -79
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DwDTWPSU.d.ts → index-0rZcMBwy.d.ts} +10 -7
- package/dist/{index-C3JAH1Yo.d.ts → index-B6oexfOB.d.ts} +9 -9
- package/dist/{index-cUY-36AN.d.ts → index-BNRh23K9.d.ts} +21 -5
- package/dist/{index-DSvwEUeF.d.ts → index-BYk9oCNf.d.ts} +240 -202
- package/dist/index.d.ts +6 -6
- package/dist/index.js +5 -5
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-6WZ-pC7-.js} +21 -36
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-D98U1JBo.js} +179 -84
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-B4Dki6Ig.js} +438 -176
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-B_e0T99L.d.ts} +114 -26
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C7coQp4c.js} +217 -94
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +176 -68
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-CpOiEN0k.js → observability-wzs3-BL_.js} +279 -109
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-a7PJHBCy.js} +7 -4
- package/dist/plan-a7PJHBCy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-rAtXNQQB.js} +1063 -1202
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-BVzQSZlm.js} +10 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/restore-R-4rbciV.js +778 -0
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-qL3_lTTU.js +391 -0
- package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/src-BG20LZs7.js +2271 -0
- package/dist/src-BG20LZs7.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-CYHFDrKz.js} +82 -99
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-QQ7jDeL2.js → src-DYZ4H1aF.js} +44 -23
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/subcommand-DoDA-K7d.js +197 -0
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +77 -42
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js +0 -354
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js +0 -771
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js +0 -6236
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js +0 -5122
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
- package/dist/usage-CLjirdD-.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
package/dist/cloudflare.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as
|
|
3
|
-
import {
|
|
1
|
+
import { c as configureObservability, l as getLogger, n as flushCanonicalLine, o as deriveOutcome, r as flushUnauthorizedAndRespond, s as CATEGORY, t as observableStorage } from "./observability-wzs3-BL_.js";
|
|
2
|
+
import { l as MAINTENANCE_PROFILE_CF_FREE, t as CF_FREE_MAX_SAFE_FOLD_BYTES, u as MAINTENANCE_PROFILE_CF_PAID } from "./constants-CfeMWQWk.js";
|
|
3
|
+
import { t as BaerlyError } from "./errors-Dfa3p78c.js";
|
|
4
|
+
import { o as parseMaintenanceEnv } from "./maintenance-B4Dki6Ig.js";
|
|
5
|
+
import { n as resolveVerifier, t as Db } from "./src-CYHFDrKz.js";
|
|
6
|
+
import { t as assertValidStorageKey } from "./key-Di6yyxFu.js";
|
|
7
|
+
import { n as createRouter } from "./http-DxM9MflO.js";
|
|
4
8
|
import { r as runWithContext, t as createObservabilityContext } from "./context-DRZ3tZ5l.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { r as renderDevLanding } from "./src-QQ7jDeL2.js";
|
|
9
|
+
import { r as renderDevLanding } from "./src-DYZ4H1aF.js";
|
|
10
|
+
import { t as handleSpecRequest } from "./runtime-spec-qL3_lTTU.js";
|
|
8
11
|
//#region packages/adapter-cloudflare/src/r2-binding-storage.ts
|
|
9
12
|
/**
|
|
10
13
|
* R2's binding API returns bare-hex ETags (`R2Object.etag`). The
|
|
@@ -21,6 +24,7 @@ var R2BindingStorageImpl = class {
|
|
|
21
24
|
this.#bucket = bucket;
|
|
22
25
|
}
|
|
23
26
|
async get(key, opts) {
|
|
27
|
+
assertValidStorageKey(key);
|
|
24
28
|
opts?.signal?.throwIfAborted();
|
|
25
29
|
const getOpts = {};
|
|
26
30
|
if (opts?.ifNoneMatch !== void 0) getOpts.onlyIf = { etagDoesNotMatch: stripQuotes(opts.ifNoneMatch) };
|
|
@@ -33,6 +37,7 @@ var R2BindingStorageImpl = class {
|
|
|
33
37
|
};
|
|
34
38
|
}
|
|
35
39
|
async put(key, body, opts) {
|
|
40
|
+
assertValidStorageKey(key);
|
|
36
41
|
opts?.signal?.throwIfAborted();
|
|
37
42
|
const putOpts = {};
|
|
38
43
|
if (opts?.contentType !== void 0) putOpts.httpMetadata = { contentType: opts.contentType };
|
|
@@ -46,6 +51,7 @@ var R2BindingStorageImpl = class {
|
|
|
46
51
|
};
|
|
47
52
|
}
|
|
48
53
|
async delete(key, opts) {
|
|
54
|
+
assertValidStorageKey(key);
|
|
49
55
|
opts?.signal?.throwIfAborted();
|
|
50
56
|
await this.#callBinding(() => this.#bucket.delete(key), `DELETE ${key}`);
|
|
51
57
|
}
|
|
@@ -173,7 +179,7 @@ function r2BindingStorage(bucket) {
|
|
|
173
179
|
* list narrow — adding a method to `WRITE_METHODS` doubles the
|
|
174
180
|
* invalidation surface and matters for correctness.
|
|
175
181
|
*/
|
|
176
|
-
const WRITE_METHODS = new Set([
|
|
182
|
+
const WRITE_METHODS = /* @__PURE__ */ new Set([
|
|
177
183
|
"POST",
|
|
178
184
|
"PATCH",
|
|
179
185
|
"DELETE"
|
|
@@ -294,6 +300,21 @@ async function invalidateOnWrite(req, tenantPrefix, responseStatus) {
|
|
|
294
300
|
await caches.default.delete(cacheKeyFor(req, tenantPrefix));
|
|
295
301
|
}
|
|
296
302
|
//#endregion
|
|
303
|
+
//#region packages/adapter-cloudflare/src/resolve-storage.ts
|
|
304
|
+
/**
|
|
305
|
+
* Resolve the request-time {@link Storage} for a Worker.
|
|
306
|
+
*
|
|
307
|
+
* Precedence: an explicitly injected `options.storage` (the S3-over-HTTP
|
|
308
|
+
* / cross-account path) wins; otherwise the same-account R2 binding
|
|
309
|
+
* `env.BUCKET`. With neither, fail closed with `InvalidConfig` rather
|
|
310
|
+
* than silently serving nothing.
|
|
311
|
+
*/
|
|
312
|
+
function resolveWorkerStorage(options, env) {
|
|
313
|
+
if (options.storage) return options.storage;
|
|
314
|
+
if (!env.BUCKET) throw new BaerlyError("InvalidConfig", "baerlyWorker: no storage available. Bind an R2 bucket as `BUCKET`, or pass `storage` in the factory options — e.g. new S3HttpStorage(...) from \"@gusto/baerly-storage/s3\".");
|
|
315
|
+
return r2BindingStorage(env.BUCKET);
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
297
318
|
//#region packages/adapter-cloudflare/src/worker.ts
|
|
298
319
|
/**
|
|
299
320
|
* Cloudflare Workers have no TTY, so the default sink is always
|
|
@@ -308,11 +329,21 @@ const resolveCfSink = (config) => {
|
|
|
308
329
|
};
|
|
309
330
|
};
|
|
310
331
|
/**
|
|
332
|
+
* Resolve the maintenance profile from the opt-in operator env var.
|
|
333
|
+
* Default (unset / unknown) is the CPU-killable CF-free profile, so
|
|
334
|
+
* zero-config behavior is unchanged. `cf-paid` raises the per-pass
|
|
335
|
+
* caps to exploit the paid 10,000-subrequest budget; it does NOT change
|
|
336
|
+
* the snapshot ceilings. Used by BOTH the write-tick dispatch and the
|
|
337
|
+
* cron path so the two maintenance triggers stay coherent when the
|
|
338
|
+
* operator wires the recipe below into their scheduled handler.
|
|
339
|
+
*/
|
|
340
|
+
const resolveCfMaintenanceProfile = (readEnv) => readEnv("BAERLY_MAINTENANCE_PROFILE") === "cf-paid" ? MAINTENANCE_PROFILE_CF_PAID : MAINTENANCE_PROFILE_CF_FREE;
|
|
341
|
+
/**
|
|
311
342
|
* Assemble the per-request {@link MaintenanceDispatch} for a Cloudflare
|
|
312
343
|
* Worker.
|
|
313
344
|
*
|
|
314
345
|
* baerly maintains IN-BAND: the writer reads
|
|
315
|
-
* `getCurrentContext()?.maintenance` at its post-
|
|
346
|
+
* `getCurrentContext()?.maintenance` at its post-commit dispatch point and
|
|
316
347
|
* runs one bounded compact + GC slice on the (rare) write that crosses a
|
|
317
348
|
* maintenance trigger. Reads stay pure — they never tick. There is no
|
|
318
349
|
* cron, no `triggers`, no operator-installed scheduler.
|
|
@@ -326,7 +357,9 @@ const resolveCfSink = (config) => {
|
|
|
326
357
|
* under the free-tier 50-subrequest budget. An operator on CF **paid**
|
|
327
358
|
* raises the ceiling via `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; the
|
|
328
359
|
* per-pass entry/sweep caps stay fixed here (raising them toward the
|
|
329
|
-
*
|
|
360
|
+
* 10,000-subrequest paid budget — the default since 2026-02-11, up from
|
|
361
|
+
* 1,000, and configurable to 10M — is a future graduation knob, not a
|
|
362
|
+
* var). Free stays at 50 external / 1,000 internal-service subrequests.
|
|
330
363
|
*
|
|
331
364
|
* The two ops-plane vars are read off the `env` BINDING (a string map),
|
|
332
365
|
* NOT `process.env` — Workers have no process env:
|
|
@@ -340,20 +373,14 @@ const resolveCfSink = (config) => {
|
|
|
340
373
|
* exists for direct unit coverage.
|
|
341
374
|
*/
|
|
342
375
|
const cfMaintenanceDispatch = (ctx, readEnv) => {
|
|
343
|
-
const
|
|
344
|
-
const parsedFoldBytes = rawFoldBytes !== void 0 && rawFoldBytes !== "" ? Number(rawFoldBytes) : NaN;
|
|
345
|
-
const maxFoldBytes = Number.isFinite(parsedFoldBytes) ? parsedFoldBytes : void 0;
|
|
346
|
-
const rawDisable = readEnv("BAERLY_MAINTENANCE_DISABLE");
|
|
376
|
+
const { maxFoldBytes, disabled } = parseMaintenanceEnv(readEnv);
|
|
347
377
|
return {
|
|
348
378
|
dispatch: (task) => ctx.waitUntil(task()),
|
|
349
|
-
...
|
|
379
|
+
...disabled && { disabled: true },
|
|
350
380
|
...maxFoldBytes !== void 0 && { maxFoldBytes },
|
|
351
381
|
options: {
|
|
352
382
|
phasesPerTick: "single",
|
|
353
|
-
|
|
354
|
-
gcMaxMarks: 20,
|
|
355
|
-
gcMaxSweeps: 10,
|
|
356
|
-
gcInterval: 4
|
|
383
|
+
profile: resolveCfMaintenanceProfile(readEnv)
|
|
357
384
|
}
|
|
358
385
|
};
|
|
359
386
|
};
|
|
@@ -413,7 +440,8 @@ function baerlyWorker(factory) {
|
|
|
413
440
|
const value = env[k];
|
|
414
441
|
return typeof value === "string" ? value : void 0;
|
|
415
442
|
}
|
|
416
|
-
})
|
|
443
|
+
}),
|
|
444
|
+
storage: resolveWorkerStorage(options, env)
|
|
417
445
|
};
|
|
418
446
|
} catch (error) {
|
|
419
447
|
resolutionError = error;
|
|
@@ -427,17 +455,22 @@ function baerlyWorker(factory) {
|
|
|
427
455
|
if (!maintenanceCeilingWarned) {
|
|
428
456
|
maintenanceCeilingWarned = true;
|
|
429
457
|
const rawFoldBytes = env["BAERLY_MAINTENANCE_MAX_FOLD_BYTES"];
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
if (Number.isFinite(parsed) && parsed > 1048576) console.warn(`[baerly] BAERLY_MAINTENANCE_MAX_FOLD_BYTES=${rawFoldBytes} exceeds the CF free-tier safe ceiling (${CF_FREE_MAX_SAFE_FOLD_BYTES} bytes). On a free Worker a fold this large risks a mid-rebuild CPU kill (the ~10 ms limit): the current.json CAS never lands, so the fold silently does NOT advance and the tail grows unbounded. Safe remedies: run on CF PAID (raised CPU limits), self-host on NODE, or wait for §11 chunked snapshots. Leave this var unset on free CF.`);
|
|
433
|
-
}
|
|
458
|
+
const { maxFoldBytes } = parseMaintenanceEnv((k) => typeof rawFoldBytes === "string" && k === "BAERLY_MAINTENANCE_MAX_FOLD_BYTES" ? rawFoldBytes : void 0);
|
|
459
|
+
if (maxFoldBytes !== void 0 && maxFoldBytes > 1048576) console.warn(`[baerly] BAERLY_MAINTENANCE_MAX_FOLD_BYTES=${rawFoldBytes} exceeds the CF free-tier safe ceiling (${CF_FREE_MAX_SAFE_FOLD_BYTES} bytes). On a free Worker a fold this large risks a mid-rebuild CPU kill (the ~10 ms limit): the current.json CAS never lands, so the fold silently does NOT advance and the tail grows unbounded. Safe remedies: run on CF PAID (raised CPU limits), self-host on NODE, or wait for §11 chunked snapshots. Leave this var unset on free CF.`);
|
|
434
460
|
}
|
|
435
461
|
return resolved;
|
|
436
462
|
};
|
|
437
463
|
return {
|
|
438
464
|
async fetch(req, env, ctx) {
|
|
439
|
-
const { options, verifier } = await ensureResolved(env);
|
|
440
465
|
const url = new URL(req.url);
|
|
466
|
+
if (req.method === "GET" && url.pathname === "/v1/spec") return handleSpecRequest(req, async () => {
|
|
467
|
+
const { options, verifier } = await ensureResolved(env);
|
|
468
|
+
return {
|
|
469
|
+
verifier,
|
|
470
|
+
config: options.config
|
|
471
|
+
};
|
|
472
|
+
});
|
|
473
|
+
const { options, verifier, storage: baseStorage } = await ensureResolved(env);
|
|
441
474
|
if (options.dev !== void 0 && req.method === "GET") {
|
|
442
475
|
if (url.pathname === "/") return new Response(renderDevLanding(options.dev), {
|
|
443
476
|
status: 200,
|
|
@@ -460,7 +493,7 @@ function baerlyWorker(factory) {
|
|
|
460
493
|
if (result === null) return runWithContext(obsCtx, async () => flushUnauthorizedAndRespond(obsCtx, req));
|
|
461
494
|
const tenantPrefix = result.tenantPrefix;
|
|
462
495
|
return runWithContext(obsCtx, async () => {
|
|
463
|
-
const storage = observableStorage(
|
|
496
|
+
const storage = observableStorage(baseStorage);
|
|
464
497
|
const app = createRouter({
|
|
465
498
|
db: Db.create({
|
|
466
499
|
storage,
|
|
@@ -506,6 +539,6 @@ function baerlyWorker(factory) {
|
|
|
506
539
|
};
|
|
507
540
|
}
|
|
508
541
|
//#endregion
|
|
509
|
-
export { baerlyWorker, r2BindingStorage };
|
|
542
|
+
export { baerlyWorker, r2BindingStorage, resolveCfMaintenanceProfile };
|
|
510
543
|
|
|
511
544
|
//# sourceMappingURL=cloudflare.js.map
|
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 {\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;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;IAC/B,CAAC;IAED,IAAI,cAA2B;IAC/B,IAAI;IACJ,IAAI;IACJ,IAAI;KAIF,MAAM,cAAc,MAAM,cAAc,KAAK,oBAC3C,QAAQ,QAAQ,IAAI,MAAM,KAAK,KAAK,GAAG,CAAC,CAC1C;KACA,cAAc,YAAY;KAC1B,WAAW,YAAY;IACzB,SAAS,OAAO;KACd,cAAc;KACd,MAAM;IACR,UAAU;KACR,MAAM,SAAS,gBAAgB,KAAA,IAAY,MAAO,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"}
|
|
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/resolve-storage.ts","../packages/adapter-cloudflare/src/worker.ts"],"sourcesContent":["import {\n BaerlyError,\n assertValidStorageKey,\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 assertValidStorageKey(key);\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 assertValidStorageKey(key);\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 assertValidStorageKey(key);\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 { BaerlyError, type Storage } from \"@baerly/protocol\";\nimport { r2BindingStorage } from \"./r2-binding-storage.ts\";\nimport type { BaerlyEnv, BaerlyWorkerOptions } from \"./worker.ts\";\n\n/**\n * Resolve the request-time {@link Storage} for a Worker.\n *\n * Precedence: an explicitly injected `options.storage` (the S3-over-HTTP\n * / cross-account path) wins; otherwise the same-account R2 binding\n * `env.BUCKET`. With neither, fail closed with `InvalidConfig` rather\n * than silently serving nothing.\n */\nexport function resolveWorkerStorage(\n options: Pick<BaerlyWorkerOptions, \"storage\">,\n env: Pick<BaerlyEnv, \"BUCKET\">,\n): Storage {\n if (options.storage) {\n return options.storage;\n }\n if (!env.BUCKET) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerlyWorker: no storage available. Bind an R2 bucket as `BUCKET`, \" +\n \"or pass `storage` in the factory options — e.g. \" +\n 'new S3HttpStorage(...) from \"@gusto/baerly-storage/s3\".',\n );\n }\n return r2BindingStorage(env.BUCKET);\n}\n","import { type DevLandingOptions, renderDevLanding } from \"@baerly/dev\";\nimport {\n type BaerlyAppConfig,\n CF_FREE_MAX_SAFE_FOLD_BYTES,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_PROFILE_CF_PAID,\n type Storage,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { createRouter } from \"@baerly/server/http\";\nimport { handleSpecRequest } from \"@baerly/server/spec\";\nimport { type MaintenanceDispatch, parseMaintenanceEnv } 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 { resolveWorkerStorage } from \"./resolve-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 * - `BAERLY_MAINTENANCE_PROFILE` — opt-in profile selector. Set to\n * `\"cf-paid\"` on a paid Worker to raise the per-pass throughput caps\n * (GC marks/sweeps, fold entries per pass) to the Node-tier values,\n * exploiting the paid 10,000-subrequest budget. Default / unknown\n * values resolve to `cf-free` (unchanged zero-config behaviour). Does\n * NOT change the snapshot ceilings `C` / `E` — raise those separately\n * via `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`. Must be set consistently on\n * BOTH the write-tick path and the cron path (use\n * {@link resolveCfMaintenanceProfile} in your\n * {@link WorkerScheduledHandler}).\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 * Opt-in maintenance profile. `\"cf-paid\"` raises per-pass throughput\n * caps to Node-tier values on a paid Worker isolate. Default / unknown\n * values resolve to `cf-free`. Does NOT change snapshot ceilings.\n */\n BAERLY_MAINTENANCE_PROFILE?: string;\n}\n\n/**\n * Resolve the maintenance profile from the opt-in operator env var.\n * Default (unset / unknown) is the CPU-killable CF-free profile, so\n * zero-config behavior is unchanged. `cf-paid` raises the per-pass\n * caps to exploit the paid 10,000-subrequest budget; it does NOT change\n * the snapshot ceilings. Used by BOTH the write-tick dispatch and the\n * cron path so the two maintenance triggers stay coherent when the\n * operator wires the recipe below into their scheduled handler.\n */\nexport const resolveCfMaintenanceProfile = (readEnv: (key: string) => string | undefined) =>\n readEnv(\"BAERLY_MAINTENANCE_PROFILE\") === \"cf-paid\"\n ? MAINTENANCE_PROFILE_CF_PAID\n : MAINTENANCE_PROFILE_CF_FREE;\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-commit 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 * 10,000-subrequest paid budget — the default since 2026-02-11, up from\n * 1,000, and configurable to 10M — is a future graduation knob, not a\n * var). Free stays at 50 external / 1,000 internal-service subrequests.\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 { maxFoldBytes, disabled } = parseMaintenanceEnv(readEnv);\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 // Write-tick profile. The cron path (user-supplied `scheduled` callback)\n // resolves the profile via the SAME `resolveCfMaintenanceProfile` export\n // so the two maintenance triggers stay coherent when the operator wires\n // the recipe below into their `scheduled` handler.\n profile: resolveCfMaintenanceProfile(readEnv),\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 * Request-time `Storage`. **Optional.** When unset, the Worker uses\n * the same-account R2 binding `env.BUCKET` (the dominant path). Inject\n * this to talk to S3 / cross-account R2 over the S3 REST API\n * from a Worker — e.g. `new S3HttpStorage(...)` +\n * `sigV4Signer(...)` from `@gusto/baerly-storage/s3`. Resolved once\n * per isolate inside the factory (where `env` is in scope), same as\n * the R2 binding.\n */\n readonly storage?: Storage;\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 // Base Storage resolved once per isolate (injected `options.storage`\n // or the `env.BUCKET` R2 binding), same lifetime as `verifier`. The\n // per-request `observableStorage(...)` wrap still happens on every\n // request — it binds to the request's observability bag — but the\n // underlying handle is no longer reconstructed each time.\n readonly storage: Storage;\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, storage: resolveWorkerStorage(options, env) };\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 const { maxFoldBytes } = parseMaintenanceEnv((k) =>\n typeof rawFoldBytes === \"string\" && k === \"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\"\n ? rawFoldBytes\n : undefined,\n );\n if (maxFoldBytes !== undefined && maxFoldBytes > 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 return resolved;\n };\n\n return {\n async fetch(req, env, ctx): Promise<Response> {\n const url = new URL(req.url);\n\n // /v1/spec — anonymous static contract IR. Keep this before\n // `ensureResolved`: even a verifier/config-resolution failure\n // should not hide the public machine contract. Tenant collections\n // are appended only when resolution succeeds AND the verifier\n // accepts.\n if (req.method === \"GET\" && url.pathname === \"/v1/spec\") {\n return handleSpecRequest(req, async () => {\n const { options, verifier } = await ensureResolved(env);\n return { verifier, config: options.config };\n });\n }\n\n const { options, verifier, storage: baseStorage } = 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 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-commit 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. The\n // base handle is resolved once per isolate (see `ResolvedState`);\n // only the observability wrap is per-request.\n const storage = observableStorage(baseStorage);\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 // To honour BAERLY_MAINTENANCE_PROFILE on the cron path, call\n // `runScheduledMaintenance(args, CLOUDFLARE_PAID_TIER)` when the\n // profile is \"cf-paid\", or `CLOUDFLARE_FREE_TIER` (the default) —\n // both imported from `@gusto/baerly-storage/maintenance`. Use\n // `resolveCfMaintenanceProfile((k) => env[k])` (exported from this\n // module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