@gusto/baerly-storage 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +3 -2
  2. package/dist/API.md +59 -7
  3. package/dist/{app-config-Dj_nGBfj.d.ts → app-config-C0Bbw_Z6.d.ts} +9 -9
  4. package/dist/app-config.d.ts +1 -1
  5. package/dist/auth.d.ts +1 -1
  6. package/dist/baerly.js +10 -10
  7. package/dist/baerly.js.map +1 -1
  8. package/dist/bytes-BXdamO3L.js +11 -0
  9. package/dist/bytes-BXdamO3L.js.map +1 -0
  10. package/dist/{client-CC5yVs1S.d.ts → client-DYZfoZb9.d.ts} +3 -3
  11. package/dist/client-react.d.ts +3 -3
  12. package/dist/client.d.ts +3 -3
  13. package/dist/cloudflare.d.ts +31 -4
  14. package/dist/cloudflare.js +72 -6
  15. package/dist/cloudflare.js.map +1 -1
  16. package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
  17. package/dist/config-DVfDGyw1.js.map +1 -0
  18. package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
  19. package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
  20. package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
  21. package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
  22. package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
  23. package/dist/current-json-C-EyJqs0.js.map +1 -0
  24. package/dist/{db-aRMK_0R0.d.ts → db-BM3y2JQw.d.ts} +3 -3
  25. package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
  26. package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
  27. package/dist/dev-vite.d.ts +3 -3
  28. package/dist/dev-vite.js +3 -3
  29. package/dist/dev.d.ts +1 -1
  30. package/dist/dev.js +1 -1
  31. package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
  32. package/dist/doctor-Db-hzPmE.js.map +1 -0
  33. package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
  34. package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
  35. package/dist/errors-DOdL95kK.js.map +1 -1
  36. package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
  37. package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
  38. package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
  39. package/dist/fsck-CPPZWt9p.js.map +1 -0
  40. package/dist/{http-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
  41. package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
  42. package/dist/http.d.ts +3 -3
  43. package/dist/http.js +1 -1
  44. package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
  45. package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
  46. package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
  47. package/dist/{index-spCBsIwm.d.ts → index-cUY-36AN.d.ts} +3 -3
  48. package/dist/index.d.ts +5 -5
  49. package/dist/index.js +3 -3
  50. package/dist/{indexes-BIH73Uv4.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
  51. package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
  52. package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
  53. package/dist/maintenance-BRrThz8V.d.ts +449 -0
  54. package/dist/maintenance-BvOv6BMM.js +1295 -0
  55. package/dist/maintenance-BvOv6BMM.js.map +1 -0
  56. package/dist/maintenance-ClzBC1Vv.js +1895 -0
  57. package/dist/maintenance-ClzBC1Vv.js.map +1 -0
  58. package/dist/maintenance.d.ts +2 -323
  59. package/dist/maintenance.js +2 -2
  60. package/dist/node.d.ts +20 -79
  61. package/dist/node.js +2 -2
  62. package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
  63. package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
  64. package/dist/observability.d.ts +2 -2
  65. package/dist/observability.js +2 -2
  66. package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
  67. package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
  68. package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
  69. package/dist/query-BmiQy328.js.map +1 -0
  70. package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
  71. package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
  72. package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
  73. package/dist/restore-C6IcmLeA.js.map +1 -0
  74. package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
  75. package/dist/snapshot-SS8USDUF.js.map +1 -0
  76. package/dist/{src-Cr9C7_tT.js → src-DU1sCMlr.js} +315 -278
  77. package/dist/src-DU1sCMlr.js.map +1 -0
  78. package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
  79. package/dist/src-QQ7jDeL2.js.map +1 -0
  80. package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
  81. package/dist/src-zhEAmmF7.js.map +1 -0
  82. package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
  83. package/dist/subcommand-DZcHcsYp.js.map +1 -0
  84. package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
  85. package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
  86. package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
  87. package/dist/validate-DCq_0DIn.js.map +1 -0
  88. package/package.json +13 -6
  89. package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
  90. package/dist/config-Bsg8wgwo.js.map +0 -1
  91. package/dist/current-json-BkatBzF7.js.map +0 -1
  92. package/dist/doctor-B8h9GCN9.js.map +0 -1
  93. package/dist/fsck-DEz9lyCy.js.map +0 -1
  94. package/dist/indexes-BXn7a06a.js +0 -297
  95. package/dist/indexes-BXn7a06a.js.map +0 -1
  96. package/dist/log-walk-DIru96UT.js.map +0 -1
  97. package/dist/maintenance-Bn6ul9aV.js +0 -758
  98. package/dist/maintenance-Bn6ul9aV.js.map +0 -1
  99. package/dist/query-DcSbFLJt.js.map +0 -1
  100. package/dist/rebuild-index-C5gTXryd.js +0 -119
  101. package/dist/rebuild-index-C5gTXryd.js.map +0 -1
  102. package/dist/restore-CbKVMMpm.js.map +0 -1
  103. package/dist/snapshot-D7C4_FSl.js +0 -71
  104. package/dist/snapshot-D7C4_FSl.js.map +0 -1
  105. package/dist/snapshot-z_N9hpTe.js +0 -917
  106. package/dist/snapshot-z_N9hpTe.js.map +0 -1
  107. package/dist/src-Chafbw8r.js.map +0 -1
  108. package/dist/src-Cr9C7_tT.js.map +0 -1
  109. package/dist/src-n0Te1r98.js.map +0 -1
  110. package/dist/subcommand-BWs6K7zb.js +0 -110
  111. package/dist/subcommand-BWs6K7zb.js.map +0 -1
  112. package/dist/validate-DhH1lO8I.js.map +0 -1
@@ -0,0 +1,1295 @@
1
+ import { n as encodeJsonBytes, t as decodeJsonBytes } from "./bytes-BXdamO3L.js";
2
+ import { a as GC_MAX_PENDING_CANDIDATES, c as MAINTENANCE_MAX_FOLD_ROWS, o as GC_PENDING_CONTENT_TYPE } from "./config-DVfDGyw1.js";
3
+ import { c as snapshotHash, d as logSeqStartOf, f as readCurrentJson, i as foldLogEntriesOnto, l as casUpdateCurrentJson, n as loadSnapshotAsMap, o as walkLogRange, r as snapshotKey, s as walkLogRangeWithBytes, t as encodeSnapshotBody } from "./snapshot-SS8USDUF.js";
4
+ import { n as matchesWire, t as validateWire } from "./validate-DCq_0DIn.js";
5
+ import { o as BaerlyError } from "./baerly.js";
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
+ //#region ../protocol/src/coordination/gc-pending.ts
8
+ /**
9
+ * `gc/pending.json` — the per-collection GC candidate ledger. CAS-
10
+ * protected; one per `(tenant, collection)` key — for example
11
+ * `<tenant>/<collection>/gc/pending.json`. `runGc()` in
12
+ * `packages/server/src/gc.ts` is the single writer that adds and
13
+ * removes entries. Stays small in steady state because every
14
+ * candidate is deleted once `due_at` passes.
15
+ *
16
+ * "Mark" appends candidates with a future `due_at`; "sweep" deletes
17
+ * candidates whose `due_at` is in the past. The two phases run in
18
+ * the same compactor pass — see `runGc()` in
19
+ * `packages/server/src/gc.ts`.
20
+ *
21
+ * Lives next to {@link CurrentJson} in `coordination/` — same shape
22
+ * of "CAS-protected small control object." Pure module; no Node
23
+ * imports; Worker-bundleable.
24
+ *
25
+ * @see packages/server/src/gc.ts
26
+ */
27
+ /**
28
+ * Read + parse `gc/pending.json` at `key`. Returns `null` on
29
+ * not-found.
30
+ *
31
+ * @throws BaerlyError{code:"InvalidResponse"} — body is not valid
32
+ * JSON, or `schema_version` is unknown, or the shape fails
33
+ * the runtime guard.
34
+ */
35
+ const readGcPending = async (storage, key, opts) => {
36
+ const got = await storage.get(key, opts);
37
+ if (got === null) return null;
38
+ let parsed;
39
+ try {
40
+ parsed = decodeJsonBytes(got.body);
41
+ } catch (error) {
42
+ throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: body is not valid JSON`, error);
43
+ }
44
+ return {
45
+ json: assertGcPending(parsed, key),
46
+ etag: got.etag
47
+ };
48
+ };
49
+ /**
50
+ * Create `gc/pending.json` if-and-only-if it does not exist (S3
51
+ * `If-None-Match: "*"`). Use this once per collection at first GC
52
+ * run; subsequent updates go through {@link casUpdateGcPending}.
53
+ *
54
+ * @throws BaerlyError{code:"Conflict"} — the key already exists.
55
+ * @throws BaerlyError{code:"InvalidResponse"} — `initial` fails the
56
+ * runtime shape guard.
57
+ */
58
+ const createGcPending = async (storage, key, initial, opts) => {
59
+ assertGcPending(initial, key);
60
+ const body = encodeJsonBytes(initial);
61
+ const putOpts = {
62
+ ifNoneMatch: "*",
63
+ contentType: GC_PENDING_CONTENT_TYPE,
64
+ ...opts?.signal !== void 0 && { signal: opts.signal }
65
+ };
66
+ let result;
67
+ try {
68
+ result = await storage.put(key, body, putOpts);
69
+ } catch (error) {
70
+ throw translateCasError(error, key);
71
+ }
72
+ return {
73
+ json: initial,
74
+ etag: result.etag
75
+ };
76
+ };
77
+ /**
78
+ * Read-modify-write `gc/pending.json` under CAS. The `mutator`
79
+ * receives a deep clone of the current parsed JSON and returns the
80
+ * new state. The new state is written with `If-Match: <currentEtag>`;
81
+ * on conflict, throws `BaerlyError{code:"Conflict"}`.
82
+ *
83
+ * `mutator` MUST be deterministic — it may be called multiple times
84
+ * if the caller wraps this in a retry loop, so it must not have side
85
+ * effects.
86
+ *
87
+ * @throws BaerlyError{code:"Conflict"} — another writer landed a write
88
+ * between this function's read and write.
89
+ * @throws BaerlyError{code:"InvalidResponse"} — `key` does not exist
90
+ * (use {@link createGcPending} instead) or body doesn't
91
+ * parse / fails the shape guard.
92
+ */
93
+ const casUpdateGcPending = async (storage, key, mutator, opts) => {
94
+ const existing = await readGcPending(storage, key, opts);
95
+ if (existing === null) throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key} does not exist; use createGcPending first`);
96
+ const next = mutator(structuredClone(existing.json));
97
+ assertGcPending(next, key);
98
+ const body = encodeJsonBytes(next);
99
+ const putOpts = {
100
+ ifMatch: existing.etag,
101
+ contentType: GC_PENDING_CONTENT_TYPE,
102
+ ...opts?.signal !== void 0 && { signal: opts.signal }
103
+ };
104
+ let result;
105
+ try {
106
+ result = await storage.put(key, body, putOpts);
107
+ } catch (error) {
108
+ throw translateCasError(error, key);
109
+ }
110
+ return {
111
+ json: next,
112
+ etag: result.etag
113
+ };
114
+ };
115
+ const VALID_REASONS = new Set([
116
+ "stale-log",
117
+ "orphan-snapshot",
118
+ "orphan-content"
119
+ ]);
120
+ /**
121
+ * Runtime guard for `parsed` to be a {@link GcPending}. Throws
122
+ * `BaerlyError{code:"InvalidResponse"}` rather than coercing.
123
+ */
124
+ const assertGcPending = (parsed, key) => {
125
+ if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: parsed body is not an object`);
126
+ const r = parsed;
127
+ if (r["schema_version"] !== 1) throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: unsupported schema_version ${String(r["schema_version"])}; expected 1`);
128
+ if (!Array.isArray(r["candidates"])) throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: candidates must be an array`);
129
+ for (let i = 0; i < r["candidates"].length; i++) {
130
+ const c = r["candidates"][i];
131
+ if (c === null || typeof c !== "object") throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: candidates[${String(i)}] is not an object`);
132
+ const cr = c;
133
+ if (typeof cr["key"] !== "string" || cr["key"].length === 0) throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: candidates[${String(i)}].key must be a non-empty string`);
134
+ if (typeof cr["due_at"] !== "string") throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: candidates[${String(i)}].due_at must be a string`);
135
+ if (typeof cr["reason"] !== "string" || !VALID_REASONS.has(cr["reason"])) throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: candidates[${String(i)}].reason must be one of stale-log|orphan-snapshot|orphan-content`);
136
+ }
137
+ if (typeof r["last_swept_at"] !== "string") throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: last_swept_at must be a string`);
138
+ if (r["content_scan_cursor"] !== void 0 && typeof r["content_scan_cursor"] !== "string") throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: content_scan_cursor must be a string when present`);
139
+ return parsed;
140
+ };
141
+ /**
142
+ * Wrap a storage-level error with `gc/pending.json at <key>`
143
+ * location context. `Conflict` (the storage layer's CAS-lost signal)
144
+ * is re-thrown with an annotated message; other `BaerlyError`s pass
145
+ * through; non-`BaerlyError` falls through as `InvalidResponse`.
146
+ */
147
+ const translateCasError = (e, key) => {
148
+ if (e instanceof BaerlyError && e.code === "Conflict") return new BaerlyError("Conflict", `gc/pending.json CAS lost at ${key}: ${e.message}`, e);
149
+ if (e instanceof BaerlyError) return e;
150
+ return new BaerlyError("InvalidResponse", `gc/pending.json write at ${key} failed: ${String(e)}`, e);
151
+ };
152
+ //#endregion
153
+ //#region ../protocol/src/hashing.ts
154
+ /**
155
+ * Width of the {@link ContentVersionId} hex strings produced by
156
+ * {@link versionFromContent}. 32 hex chars = 128 bits, matching the
157
+ * information content of a v4 UUID. Birthday-bound collision probability
158
+ * at N=10⁹ writes is ~1.5 × 10⁻²¹ (≈ N² / 2¹²⁹); ample for a
159
+ * content-addressed version id. A collision is not detected at runtime —
160
+ * two distinct bodies that share a truncated hash would alias to the same
161
+ * content key, so a reader could observe the wrong body. The bound above
162
+ * is the sole guard, and it sits far below any plausible write volume.
163
+ *
164
+ * @see docs/spec/log-entry-shape.md §"Content body layout"
165
+ */
166
+ const VERSION_HEX_LENGTH = 32;
167
+ /**
168
+ * Content-addressed {@link ContentVersionId}: SHA-256 of `body`,
169
+ * lowercase hex, truncated to {@link VERSION_HEX_LENGTH}. Same body
170
+ * bytes ⇒ same ContentVersionId — scoped to **single-writer idempotent
171
+ * replay** (a crash-recovery rewrite of the same in-memory value by the
172
+ * same writer reproduces the content key the manifest already
173
+ * referenced). `body` is non-canonical (`JSON.stringify`, insertion
174
+ * key order — see `encodeJsonBytes`), so this is NOT cross-writer
175
+ * content dedup: different key order ⇒ different key for an equal value.
176
+ *
177
+ * Async because {@link crypto.subtle.digest} returns an `ArrayBuffer`
178
+ * via Promise. Workers and browsers both expose `crypto.subtle`
179
+ * synchronously enough that the await fits naturally in the write
180
+ * pipeline.
181
+ *
182
+ * @see docs/spec/log-entry-shape.md §"Content body layout"
183
+ */
184
+ const versionFromContent = async (body) => {
185
+ const view = new Uint8Array(body.byteLength);
186
+ view.set(body);
187
+ const digest = await crypto.subtle.digest("SHA-256", view);
188
+ const bytes = new Uint8Array(digest);
189
+ let hex = "";
190
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
191
+ return hex.slice(0, VERSION_HEX_LENGTH);
192
+ };
193
+ //#endregion
194
+ //#region ../protocol/src/metrics.ts
195
+ /**
196
+ * No-op recorder. Safe default when no operator sink is wired —
197
+ * emission sites that read `getCurrentContext()?.recorder` fall
198
+ * back to this outside an active `runWithContext` scope.
199
+ */
200
+ const noopMetricsRecorder = {
201
+ counter: () => {},
202
+ gauge: () => {},
203
+ histogram: () => {}
204
+ };
205
+ //#endregion
206
+ //#region ../server/src/names.ts
207
+ /** Reject names in the system-reserved leading-"_" namespace. See docs/adr/007-layout-versioning-cordon.md. */
208
+ const assertNameNotReserved = (name, context) => {
209
+ if (name.startsWith("_")) throw new BaerlyError("InvalidConfig", `${context}: "${name}" is reserved — names beginning with "_" are reserved for system use. See docs/adr/007-layout-versioning-cordon.md.`);
210
+ };
211
+ //#endregion
212
+ //#region ../server/src/indexes.ts
213
+ /**
214
+ * Secondary indexes — declarative collection-config-driven
215
+ * index entries that the writer emits inside the same CAS fence as
216
+ * the log entry and content body.
217
+ *
218
+ * The {@link IndexDefinition} TYPE lives in `@baerly/protocol`
219
+ * (cross-platform). This module owns the runtime helpers that
220
+ * operate on that shape:
221
+ *
222
+ * - {@link validateIndexDefinition} — synchronous schema check
223
+ * for path-segment safety; thrown at `Writer` construction.
224
+ * - {@link encodeIndexValue} — value-order-preserving base-32 of a
225
+ * type-tagged byte stream (null/bool tag-only, numbers as sortable
226
+ * IEEE 754, strings as raw UTF-8, objects as `JSON.stringify`
227
+ * bytes for equality only).
228
+ * - {@link indexKeyFor} / {@link indexKeyPrefix} — the wire-key
229
+ * shape consumed by the writer's index PUTs and the rebuild
230
+ * command's idempotent reconciliation.
231
+ * - {@link projectIndexValues} / {@link allIndexKeysFor} — pure
232
+ * projections from a doc body to the set of index keys it
233
+ * produces under a collection's declared indexes.
234
+ *
235
+ * Wire shape (single-field):
236
+ *
237
+ * `<logPrefix>/index/<indexName>/<value-b32>/<docId>.json`
238
+ *
239
+ * Wire shape (composite — accepted by the encoder, not consulted by
240
+ * the read path today):
241
+ *
242
+ * `<logPrefix>/index/<indexName>/<a-b32>/<b-b32>/<docId>.json`
243
+ *
244
+ * Body is zero bytes. Each entry is a fact ("doc `<docId>` has
245
+ * `<field> = <value>`"), not data. Readers list the prefix, extract
246
+ * the doc id from each key, then issue a content GET on each.
247
+ *
248
+ * Encoding is RFC-4648 base-32 (lowercase alphabet `[0-9a-v]`,
249
+ * matching `packages/protocol/src/log.ts:str2uintDesc` style) on a
250
+ * type-tagged byte stream (see {@link encodeIndexValue}) so that:
251
+ *
252
+ * - String "5" and number 5 produce distinct encodings
253
+ * (type-tag prefix keeps the slots disjoint).
254
+ * - Equal-by-value inputs produce byte-equal segments.
255
+ * - Lex order under storage `list(prefix)` matches value order:
256
+ * `null < false < true < number < string < object`, with
257
+ * numeric values ordered by IEEE 754 magnitude (range walks
258
+ * and `$in` walks over numeric fields are first-class — no
259
+ * planner fall-back to full-scan).
260
+ *
261
+ * Locked: single-field indexes only on the read path. Composite
262
+ * shape is documented and reserved (the path encoder accepts it).
263
+ *
264
+ * @see docs/spec/sync-protocol.md — fence model these PUTs land
265
+ * inside (between log PUT and `current.json` CAS-advance).
266
+ */
267
+ /** Path-safe segment name. */
268
+ const INDEX_NAME_RE = /^[a-z][a-z0-9_]*$/;
269
+ /**
270
+ * Lowercase base-32 alphabet, RFC 4648 variant matching the
271
+ * `packages/protocol/src/log.ts:str2uintDesc` style (`[0-9a-v]`).
272
+ * Lex-order-preserving under storage `list(prefix)` semantics.
273
+ */
274
+ const B32_ALPHABET = "0123456789abcdefghijklmnopqrstuv";
275
+ /**
276
+ * Reject malformed {@link IndexDefinition} shapes synchronously, at
277
+ * writer construction. See docs/adr/007-layout-versioning-cordon.md.
278
+ *
279
+ * @throws BaerlyError code="InvalidConfig" — reserved leading-`_` `name`.
280
+ * @throws BaerlyError code="SchemaError" — `name` fails the regex, or `on` is empty.
281
+ */
282
+ const validateIndexDefinition = (def) => {
283
+ assertNameNotReserved(def.name, "index.name");
284
+ if (!INDEX_NAME_RE.test(def.name)) throw new BaerlyError("SchemaError", `index.name must match /^[a-z][a-z0-9_]*$/; got ${JSON.stringify(def.name)}`);
285
+ if (typeof def.on === "string") {
286
+ if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty`);
287
+ } else if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty array`);
288
+ if (def.predicate !== void 0) try {
289
+ validateWire(def.predicate);
290
+ } catch (error) {
291
+ if (error instanceof BaerlyError) throw new BaerlyError("SchemaError", `index ${def.name}.predicate is invalid: ${error.message}`, error);
292
+ throw error;
293
+ }
294
+ };
295
+ /**
296
+ * Type-tag bytes for the value-order-preserving wire format. The
297
+ * tag is the LEADING byte of the encoded payload; the values are
298
+ * picked so the type order under byte-wise lex is
299
+ * `null < false < true < number < string < object`.
300
+ *
301
+ * | Type | Byte-prefix | Payload |
302
+ * |---------|-------------|----------------------------------------------------|
303
+ * | null | 0x10 | (none) |
304
+ * | false | 0x20 | (none) |
305
+ * | true | 0x21 | (none) |
306
+ * | number | 0x30 | 8-byte sortable big-endian IEEE 754 |
307
+ * | string | 0x40 | UTF-8 bytes of the string (no quotes, no escapes) |
308
+ * | object | 0x50 | UTF-8 bytes of `JSON.stringify(v)` |
309
+ *
310
+ * Local to the encoder by design — these are wire shape, not
311
+ * cross-package protocol constants (see `CLAUDE.md` § "Magic
312
+ * values").
313
+ */
314
+ const TYPE_NULL = 16;
315
+ const TYPE_FALSE = 32;
316
+ const TYPE_TRUE = 33;
317
+ const TYPE_NUMBER = 48;
318
+ const TYPE_STRING = 64;
319
+ const TYPE_OBJECT = 80;
320
+ /**
321
+ * Encode a JS double as an 8-byte big-endian sortable IEEE 754
322
+ * payload. Byte-wise lex order on the result matches numeric order
323
+ * across all finite doubles plus `±Infinity`:
324
+ *
325
+ * 1. Get the 8-byte big-endian view of the double.
326
+ * 2. If the sign bit is `0` (zero or positive), flip the sign bit
327
+ * (XOR `0x80` on byte 0) so positives sort above negatives.
328
+ * 3. If the sign bit is `1` (negative), flip every bit in all 8
329
+ * bytes so more-negative sorts lower.
330
+ *
331
+ * `NaN` has no order-preserving slot and is rejected — see the
332
+ * `encodeIndexValue` JSDoc for the wire-contract rationale.
333
+ * `-0` and `+0` collapse because the `n === 0 ? 0 : n` coercion below
334
+ * forces both into the positive-zero branch before `setFloat64`.
335
+ */
336
+ const encodeNumberPayload = (n) => {
337
+ if (Number.isNaN(n)) throw new BaerlyError("SchemaError", `encodeIndexValue: NaN is not indexable (the byte encoding has no order-preserving slot for it)`);
338
+ const buf = /* @__PURE__ */ new ArrayBuffer(8);
339
+ new DataView(buf).setFloat64(0, n === 0 ? 0 : n, false);
340
+ const bytes = new Uint8Array(buf);
341
+ if ((bytes[0] & 128) === 0) bytes[0] = bytes[0] ^ 128;
342
+ else for (let i = 0; i < 8; i++) bytes[i] = bytes[i] ^ 255;
343
+ return bytes;
344
+ };
345
+ /**
346
+ * Compose the typed byte stream for one value. The leading byte is
347
+ * the type tag (see {@link TYPE_NULL} et al.); the payload shape is
348
+ * type-dependent. Strings are emitted as their raw UTF-8 bytes (no
349
+ * JSON quoting / escaping) so byte-wise lex order on encoded strings
350
+ * matches byte-wise lex order on the source UTF-8. Objects fall back
351
+ * to `JSON.stringify` for equality only.
352
+ */
353
+ const encodeBytes = (v) => {
354
+ if (v === null || v === void 0) return new Uint8Array([TYPE_NULL]);
355
+ if (v === false) return new Uint8Array([TYPE_FALSE]);
356
+ if (v === true) return new Uint8Array([TYPE_TRUE]);
357
+ if (typeof v === "number") {
358
+ const payload = encodeNumberPayload(v);
359
+ const out = new Uint8Array(1 + payload.length);
360
+ out[0] = TYPE_NUMBER;
361
+ out.set(payload, 1);
362
+ return out;
363
+ }
364
+ if (typeof v === "string") {
365
+ const utf8 = new TextEncoder().encode(v);
366
+ const out = new Uint8Array(1 + utf8.length);
367
+ out[0] = TYPE_STRING;
368
+ out.set(utf8, 1);
369
+ return out;
370
+ }
371
+ const utf8 = encodeJsonBytes(v);
372
+ const out = new Uint8Array(1 + utf8.length);
373
+ out[0] = TYPE_OBJECT;
374
+ out.set(utf8, 1);
375
+ return out;
376
+ };
377
+ /**
378
+ * Encode an arbitrary `DocumentValue` value as a path-safe segment.
379
+ *
380
+ * Type-tagged byte stream, base-32-encoded for path safety. Lex
381
+ * order on encoded bytes matches:
382
+ *
383
+ * - **Type order**: `null < false < true < number < string < object`.
384
+ * - **Within numbers**: IEEE 754 numeric order (sortable
385
+ * big-endian payload, sign-bit-flipped or all-bits-flipped).
386
+ * `-Infinity` sorts lowest, `+Infinity` highest.
387
+ * - **Within strings**: UTF-8 byte order.
388
+ * - **Within objects**: byte-equality only (still
389
+ * `JSON.stringify`-insertion-order dependent).
390
+ *
391
+ * Numbers ARE range-safe under this encoder — `9` sorts below `10`
392
+ * as expected. The query planner's old
393
+ * `numeric-range-on-byte-encoder` guard has been removed; range
394
+ * walks and `$in` walks over numeric fields are routed normally.
395
+ *
396
+ * `NaN` throws `BaerlyError{code:"SchemaError"}` at write time —
397
+ * the byte encoding has no order-preserving slot for it, and a
398
+ * silent collapse to the `null` key (as the prior
399
+ * `JSON.stringify`-based encoder did, since
400
+ * `JSON.stringify(NaN) === "null"`) is a worse failure mode than
401
+ * a loud reject.
402
+ *
403
+ * `-0` and `+0` collapse to the same encoding.
404
+ *
405
+ * Equal-by-value inputs (e.g. two `{a:1, b:2}` objects with the
406
+ * same key insertion order) produce byte-equal segments;
407
+ * structurally-different but visually-similar inputs (`"5"` vs `5`)
408
+ * are kept apart by the type-tag prefix.
409
+ *
410
+ * String ranges remain safe: `"2026-05-13" < "2026-05-14"`
411
+ * byte-wise matches semantic order. ISO 8601 timestamps,
412
+ * alphabetical priorities like `"p1"/"p2"/"p3"`, and any
413
+ * fixed-width string encoding are usable as range-walked indexed
414
+ * fields.
415
+ */
416
+ const encodeIndexValue = (v) => {
417
+ const bytes = encodeBytes(v);
418
+ let out = "";
419
+ let bits = 0;
420
+ let value = 0;
421
+ for (const b of bytes) {
422
+ value = value << 8 | b;
423
+ bits += 8;
424
+ while (bits >= 5) {
425
+ bits -= 5;
426
+ out += B32_ALPHABET[value >> bits & 31];
427
+ }
428
+ }
429
+ if (bits > 0) out += B32_ALPHABET[value << 5 - bits & 31];
430
+ return out;
431
+ };
432
+ /**
433
+ * Storage `list(prefix)` boundary for every entry under one index
434
+ * of a collection: `<logPrefix>/index/<name>/`. Used by the rebuild
435
+ * command's reconciliation walk and by the read-path index hint.
436
+ */
437
+ const indexKeyPrefix = (logPrefix, indexName) => `${logPrefix}/index/${indexName}/`;
438
+ /**
439
+ * Build the per-doc index key for one `(def, values, docId)`.
440
+ *
441
+ * Single-field: `<logPrefix>/index/<name>/<v0-b32>/<docId>.json`.
442
+ * Composite: `<logPrefix>/index/<name>/<v0-b32>/<v1-b32>/.../<docId>.json`.
443
+ *
444
+ * Composite shape is accepted but the read path today only
445
+ * consults single-field entries.
446
+ */
447
+ const indexKeyFor = (logPrefix, def, values, docId) => {
448
+ const segments = values.map(encodeIndexValue).join("/");
449
+ return `${logPrefix}/index/${def.name}/${segments}/${docId}.json`;
450
+ };
451
+ /**
452
+ * Project the value tuple a doc body produces under one index
453
+ * definition. Returns `undefined` when any indexed field is
454
+ * null / undefined / missing — no index entry for that doc under
455
+ * that index (SQL "NULL values don't enter the index" semantics).
456
+ *
457
+ * @throws BaerlyError code="SchemaError" — `on` contains a dotted
458
+ * path, or the indexed field's value is an array. Both restrictions
459
+ * are pre-launch; multi-value (array) indexes are a follow-up.
460
+ */
461
+ const projectIndexValues = (def, body) => {
462
+ if (body === void 0) return;
463
+ const fields = typeof def.on === "string" ? [def.on] : def.on;
464
+ const values = [];
465
+ for (const field of fields) {
466
+ if (field.includes(".")) throw new BaerlyError("SchemaError", `index ${def.name}: dotted-path "on" fields not yet supported (got ${JSON.stringify(field)})`);
467
+ const v = body[field];
468
+ if (v === null || v === void 0) return;
469
+ if (Array.isArray(v)) throw new BaerlyError("SchemaError", `index ${def.name}: cannot index array field "${field}" — multi-value indexes are not supported yet`);
470
+ values.push(v);
471
+ }
472
+ return values;
473
+ };
474
+ /**
475
+ * Compute the full index-key set a single doc produces under every
476
+ * declared index of its collection. Skips indexes whose projection
477
+ * yields `undefined` (null/missing indexed field). Used by both
478
+ * the writer (to PUT new keys) and the rebuild command (to compute
479
+ * the expected key set across the live doc map).
480
+ *
481
+ * Filter-aware (T4): when `def.predicate !== undefined`, the doc
482
+ * must satisfy `matchesWire(def.predicate, body)` or the def contributes
483
+ * zero keys. The writer's diff `oldKeys` vs `newKeys` then covers
484
+ * all four U-quadrants automatically — see the JSDoc on
485
+ * `writer.ts` above the index-emission block. `body ===
486
+ * undefined` short-circuits ahead of the filter check (no keys for
487
+ * an unknown pre-image, regardless of filter), preserving the prior
488
+ * D-quadrant behaviour.
489
+ */
490
+ const allIndexKeysFor = (logPrefix, defs, body, docId) => {
491
+ const keys = [];
492
+ for (const def of defs) {
493
+ if (def.predicate !== void 0 && body !== void 0) {
494
+ if (!matchesWire(def.predicate, body)) continue;
495
+ }
496
+ const values = projectIndexValues(def, body);
497
+ if (values !== void 0) keys.push(indexKeyFor(logPrefix, def, values, docId));
498
+ }
499
+ return keys;
500
+ };
501
+ //#endregion
502
+ //#region ../server/src/observability/context.ts
503
+ /**
504
+ * Per-request observability context.
505
+ *
506
+ * One `ObservabilityContext` is created at the entry of each unit-of-
507
+ * work (HTTP request, maintenance tick, GC sweep, rebuild run) and
508
+ * carried through the call tree via {@link runWithContext} /
509
+ * {@link getCurrentContext}, which delegates to a single module-level
510
+ * `AsyncLocalStorage` instance.
511
+ *
512
+ * The context is intentionally tiny: an externally-set
513
+ * {@link request_id}, a high-resolution `started_at`, and a mutable
514
+ * {@link fields} bag used to accumulate canonical-line attributes
515
+ * during the unit's lifecycle.
516
+ *
517
+ * The context shape is `readonly` everywhere it can be — only the
518
+ * contents of `fields` are intended to mutate during a request. The
519
+ * {@link fields} map itself is not `readonly` because callers (the
520
+ * canonical-line emitter, middleware, the collection API once Dispatch
521
+ * 3+ wires it up) need to set entries.
522
+ *
523
+ * The context carries no sampling state — every unit-of-work emits
524
+ * one canonical line unconditionally; there is nothing to gate.
525
+ *
526
+ * ## Time source
527
+ *
528
+ * `started_at` uses `performance.now()` so durations can be
529
+ * computed without worrying about wall-clock skew (NTP step,
530
+ * leap-second smearing). `performance.now()` is part of both Node
531
+ * 18+ and the Workers Runtime; we don't fall back to `Date.now()`.
532
+ *
533
+ * @example
534
+ * ```ts
535
+ * const ctx = createObservabilityContext({});
536
+ * await runWithContext(ctx, async () => {
537
+ * const inner = getCurrentContext();
538
+ * inner?.fields.set("collection", "tickets");
539
+ * await doWork();
540
+ * });
541
+ * ```
542
+ */
543
+ /**
544
+ * Module-level slot. One instance per process — the Workers
545
+ * Runtime's `nodejs_compat` flag wires `node:async_hooks` to a
546
+ * per-request scope, so cross-request bleed is impossible there.
547
+ */
548
+ const als = new AsyncLocalStorage();
549
+ /** Returns the currently-active context, or `undefined` outside one. */
550
+ const getCurrentContext = () => als.getStore();
551
+ //#endregion
552
+ //#region ../server/src/compactor.ts
553
+ /**
554
+ * Compactor: fold a prefix of the live log into a content-
555
+ * hashed snapshot file and CAS-advance `current.json` to swap the
556
+ * pointer.
557
+ *
558
+ * The hard correctness requirement is **atomic snapshot generation**:
559
+ * a compactor that crashes mid-write must not leave a corrupted body
560
+ * that readers consume as truth. The design: every snapshot's filename
561
+ * embeds the SHA-256 of its body. A crashed mid-PUT leaves a body that
562
+ * doesn't match its own filename hash, and readers reject it as
563
+ * "missing." The atomic moment is the CAS-swap of
564
+ * `current.json.snapshot`, which is a single conditional PUT.
565
+ *
566
+ * Order of operations (matches `Writer.commit`'s manifest-first-
567
+ * REVERSED ordering): PUT snapshot body → CAS-advance `current.json`.
568
+ * A crash before the swap leaves an orphan snapshot file; the swap
569
+ * succeeds iff our captured ETag still matches.
570
+ *
571
+ * Why level-prefixed chunked snapshots over the alternatives: a
572
+ * single monolithic snapshot (every compaction rewrites one well-
573
+ * known key) makes partial writes catastrophic and serializes every
574
+ * writer on one key. WAL-checkpointing in the rqlite / Raft tradition
575
+ * requires a consensus layer Baerly doesn't have. The Litestream-
576
+ * style multi-level scheme — small fixed number of levels, chunked
577
+ * files keyed by sequence range — keeps random GETs cheap on
578
+ * S3-compatible storage and avoids LIST. Current ship is single-
579
+ * level at L9 (one snapshot replaces the prior; no multi-level merge
580
+ * yet); the key format is forward-compatible with future L0..L9
581
+ * rolling merges without a wire change.
582
+ *
583
+ * @see ../../../docs/spec/sync-protocol.md
584
+ */
585
+ const ctxMetrics$2 = () => getCurrentContext()?.recorder ?? noopMetricsRecorder;
586
+ const DEFAULT_MAX_PER_RUN = Number.MAX_SAFE_INTEGER;
587
+ const DEFAULT_MIN_TO_COMPACT = 100;
588
+ const APPLICATION_JSON$1 = "application/json";
589
+ /**
590
+ * Fold a prefix of the live log into a new snapshot and CAS-advance
591
+ * `current.json`. Idempotent: a second run with no new writes is a
592
+ * no-op (below-min-threshold).
593
+ *
594
+ * Single-attempt: on CAS conflict we return
595
+ * `{written: false, skippedReason: "cas-lost", newSnapshotKey}` — the
596
+ * caller (the cron handler invoking `runScheduledMaintenance` from
597
+ * `./maintenance.ts`) decides whether to schedule another run. The
598
+ * orphan snapshot file just written will be swept by `runGc()`.
599
+ *
600
+ * @throws BaerlyError code="InvalidResponse" — `current.json` is
601
+ * present but malformed, or a snapshot body fails its schema /
602
+ * collection cross-check.
603
+ * @throws BaerlyError code="Internal" — protocol-invariant violation:
604
+ * a log entry missing inside `[log_seq_start, foldEnd)`, or the
605
+ * prior-snapshot pointer resolves to no body / a body whose hash
606
+ * doesn't match its filename.
607
+ *
608
+ * @example
609
+ * ```ts
610
+ * import { compact } from "@gusto/baerly-storage";
611
+ *
612
+ * const res = await compact(
613
+ * { storage, currentJsonKey: "app/x/tenant/t/manifests/tickets/current.json" },
614
+ * { minEntriesToCompact: 100, maxEntriesPerRun: 40 },
615
+ * );
616
+ * if (res.written) console.log("snapshot landed at", res.newSnapshotKey);
617
+ * ```
618
+ */
619
+ const compact = async (args, options = {}) => {
620
+ const { storage, currentJsonKey } = args;
621
+ const internal = options;
622
+ const maxPerRun = internal.maxEntriesPerRun ?? DEFAULT_MAX_PER_RUN;
623
+ const minToCompact = options.minEntriesToCompact ?? DEFAULT_MIN_TO_COMPACT;
624
+ const ceilingBytes = internal.ceilingBytes ?? Number.POSITIVE_INFINITY;
625
+ const ceilingEntries = internal.ceilingEntries ?? Number.POSITIVE_INFINITY;
626
+ const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf("/"));
627
+ const collectionName = collectionPrefix.slice(collectionPrefix.lastIndexOf("/") + 1);
628
+ const read = await readCurrentJson(storage, currentJsonKey, options.signal !== void 0 ? { signal: options.signal } : void 0);
629
+ if (read === null) return {
630
+ written: false,
631
+ skippedReason: "current-json-missing",
632
+ previousSnapshotKey: null,
633
+ logSeqStartBefore: 0,
634
+ logSeqStartAfter: 0,
635
+ entriesFolded: 0
636
+ };
637
+ const current = read.json;
638
+ const baseEtag = read.etag;
639
+ const logSeqStartBefore = logSeqStartOf(current);
640
+ const nextSeq = current.next_seq;
641
+ if (nextSeq - logSeqStartBefore < minToCompact) return {
642
+ written: false,
643
+ skippedReason: "below-min-threshold",
644
+ previousSnapshotKey: current.snapshot,
645
+ logSeqStartBefore,
646
+ logSeqStartAfter: logSeqStartBefore,
647
+ entriesFolded: 0
648
+ };
649
+ const foldEnd = Math.min(nextSeq, logSeqStartBefore + maxPerRun);
650
+ const base = current.snapshot === null ? /* @__PURE__ */ new Map() : await loadSnapshotAsMap(storage, current.snapshot, collectionName, options.signal);
651
+ const fetched = await walkLogRangeWithBytes(storage, collectionPrefix, logSeqStartBefore, foldEnd, { signal: options.signal });
652
+ const foldedSliceBytes = fetched.reduce((sum, f) => sum + f.bytes, 0);
653
+ for (const { entry } of fetched) {
654
+ if (entry.collection !== collectionName) continue;
655
+ if (entry.doc_id === void 0) continue;
656
+ switch (entry.op) {
657
+ case "I":
658
+ case "U":
659
+ if (entry.after !== void 0) base.set(entry.doc_id, entry.after);
660
+ break;
661
+ case "D":
662
+ base.delete(entry.doc_id);
663
+ break;
664
+ }
665
+ }
666
+ const bodyBytes = encodeSnapshotBody({
667
+ schema_version: 1,
668
+ min_seq: 0,
669
+ max_seq: foldEnd,
670
+ collection: collectionName,
671
+ docs: Array.from(base.entries()).toSorted(([a], [b]) => {
672
+ if (a < b) return -1;
673
+ if (a > b) return 1;
674
+ return 0;
675
+ }).map(([id, body]) => ({
676
+ _id: id,
677
+ body
678
+ }))
679
+ });
680
+ if (bodyBytes.byteLength > ceilingBytes || base.size > ceilingEntries) {
681
+ ctxMetrics$2().counter("db.compaction.deferred_total", 1, {
682
+ collection: collectionName,
683
+ dimension: bodyBytes.byteLength > ceilingBytes ? "bytes" : "rows"
684
+ });
685
+ return {
686
+ written: false,
687
+ skippedReason: "deferred",
688
+ deferred: true,
689
+ previousSnapshotKey: current.snapshot,
690
+ logSeqStartBefore,
691
+ logSeqStartAfter: logSeqStartBefore,
692
+ entriesFolded: 0
693
+ };
694
+ }
695
+ const newKey = snapshotKey(collectionPrefix, 0, foldEnd, await snapshotHash(bodyBytes));
696
+ const putOpts = {
697
+ contentType: APPLICATION_JSON$1,
698
+ ...options.signal !== void 0 && { signal: options.signal }
699
+ };
700
+ await storage.put(newKey, bodyBytes, putOpts);
701
+ const nextBody = encodeJsonBytes({
702
+ ...current,
703
+ snapshot: newKey,
704
+ log_seq_start: foldEnd,
705
+ snapshot_bytes: bodyBytes.byteLength,
706
+ snapshot_rows: base.size,
707
+ tail_bytes: current.tail_bytes - foldedSliceBytes
708
+ });
709
+ const casOpts = {
710
+ ifMatch: baseEtag,
711
+ contentType: APPLICATION_JSON$1,
712
+ ...options.signal !== void 0 && { signal: options.signal }
713
+ };
714
+ try {
715
+ await storage.put(currentJsonKey, nextBody, casOpts);
716
+ } catch (error) {
717
+ if (isCasConflict(error)) {
718
+ ctxMetrics$2().counter("db.compaction.cas_lost_total", 1, { collection: collectionName });
719
+ return {
720
+ written: false,
721
+ skippedReason: "cas-lost",
722
+ previousSnapshotKey: current.snapshot,
723
+ newSnapshotKey: newKey,
724
+ logSeqStartBefore,
725
+ logSeqStartAfter: logSeqStartBefore,
726
+ entriesFolded: foldEnd - logSeqStartBefore
727
+ };
728
+ }
729
+ throw error;
730
+ }
731
+ const entriesFolded = foldEnd - logSeqStartBefore;
732
+ const metrics = ctxMetrics$2();
733
+ metrics.histogram("db.compact.entries_folded", entriesFolded, { collection: collectionName });
734
+ metrics.gauge("db.manifest.lag_window_depth", current.next_seq - foldEnd, { collection: collectionName });
735
+ return {
736
+ written: true,
737
+ previousSnapshotKey: current.snapshot,
738
+ newSnapshotKey: newKey,
739
+ logSeqStartBefore,
740
+ logSeqStartAfter: foldEnd,
741
+ entriesFolded
742
+ };
743
+ };
744
+ /**
745
+ * `true` when an `If-Match` CAS guard lost. Every in-tree
746
+ * {@link Storage} impl surfaces a lost CAS as
747
+ * `BaerlyError{code:"Conflict"}`.
748
+ */
749
+ const isCasConflict = (err) => err instanceof BaerlyError && err.code === "Conflict";
750
+ //#endregion
751
+ //#region ../server/src/gc.ts
752
+ /**
753
+ * GC mark + sweep.
754
+ *
755
+ * `runGc` is a single-pass garbage collector that:
756
+ * 1. Reads `current.json` (and bootstraps `gc/pending.json` on first
757
+ * run).
758
+ * 2. Marks new orphan candidates by LISTing the three artifact
759
+ * prefixes — log, snapshot, content — and classifying each key.
760
+ * 3. Sweeps any already-pending candidate whose `due_at` has passed.
761
+ * 4. CAS-writes the updated `gc/pending.json`.
762
+ *
763
+ * Two-phase by design: every candidate sits in `gc/pending.json` for a
764
+ * grace period (default 7 days, see {@link GC_GRACE_PERIOD_MILLIS})
765
+ * before it is deleted. The grace bounds the worst plausible
766
+ * writer-retry window — a paused-process writer that resumes hours
767
+ * later still finds its idempotency anchor on the bucket.
768
+ *
769
+ * Idempotent: same input bucket state ⇒ same `pending.json` output.
770
+ * Unbounded by default — the run marks and sweeps the entire eligible
771
+ * set in one pass. Callers on the Cloudflare 50-subrequest free-tier
772
+ * budget opt INTO caps via the `CLOUDFLARE_FREE_TIER` profile's
773
+ * `gc.maxMarksPerRun` / `maxSweepsPerRun` knobs (`InternalRunGcOptions`,
774
+ * not on the public `RunGcOptions`).
775
+ *
776
+ * Three categories of orphan:
777
+ * - `stale-log`: `<collectionPrefix>/log/<seq>.json` with
778
+ * `seq < log_seq_start`. After `compact()` folds these into a
779
+ * snapshot, they're unreferenced.
780
+ * - `orphan-snapshot`: a `<collectionPrefix>/snapshot/L<n>/...` key not
781
+ * equal to `current.snapshot`. Each compactor run replaces the
782
+ * pointer; the prior file becomes unreferenced.
783
+ * - `orphan-content`: `<collectionPrefix>/content/<sha>.json` whose
784
+ * 32-hex truncated-SHA-256 hash is not in the live content-hash
785
+ * set (computed by hashing every live `entry.after` post-image —
786
+ * the same hash the writer's step 4 produces). Surfaces writer
787
+ * crashes between the content PUT and the log-entry PUT. Because
788
+ * content keys are hash-named (random lex order) and live content
789
+ * is never deleted, a bounded pass cannot rely on deletion to
790
+ * advance its LIST window the way `stale-log` does — so the
791
+ * orphan-content LIST carries a persisted rotation cursor
792
+ * (`content_scan_cursor` in `gc/pending.json`): each bounded pass
793
+ * resumes `startAfter` the prior pass's last examined key and wraps
794
+ * at end-of-keyspace, so the whole `content/` keyspace is swept
795
+ * over a rotation within the per-pass `maxMarksPerRun` budget.
796
+ *
797
+ * CAS-lost on `gc/pending.json` is non-fatal: the DELETEs already
798
+ * issued are durable, so we return a successful result and the next
799
+ * pass will pick up any work this pass lost.
800
+ */
801
+ const ctxMetrics$1 = () => getCurrentContext()?.recorder ?? noopMetricsRecorder;
802
+ const DEFAULT_MAX_MARKS = Number.MAX_SAFE_INTEGER;
803
+ const DEFAULT_MAX_SWEEPS = Number.MAX_SAFE_INTEGER;
804
+ /**
805
+ * Single GC pass — mark new orphans, sweep due-elapsed candidates,
806
+ * persist via CAS-update on `gc/pending.json`.
807
+ *
808
+ * Returns immediately if `current.json` is missing — there's nothing
809
+ * to do until a writer has bootstrapped the collection.
810
+ *
811
+ * @example
812
+ * ```ts
813
+ * import { runGc } from "@gusto/baerly-storage";
814
+ *
815
+ * const r = await runGc({ storage, currentJsonKey });
816
+ * console.log(`marked ${r.marked.stale_log} stale logs, swept ${r.swept}`);
817
+ * ```
818
+ */
819
+ const runGc = async (args, options = {}) => {
820
+ const { storage, currentJsonKey } = args;
821
+ const internal = options;
822
+ const grace = internal.graceMillis ?? 6048e5;
823
+ const maxMarks = internal.maxMarksPerRun ?? DEFAULT_MAX_MARKS;
824
+ const maxSweeps = internal.maxSweepsPerRun ?? DEFAULT_MAX_SWEEPS;
825
+ const now = internal.now ?? (() => /* @__PURE__ */ new Date());
826
+ const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf("/"));
827
+ const collectionName = collectionPrefix.slice(collectionPrefix.lastIndexOf("/") + 1);
828
+ const gcPendingKey = `${collectionPrefix}/gc/pending.json`;
829
+ const signal = options.signal;
830
+ const signalOpts = signal !== void 0 ? { signal } : void 0;
831
+ const cur = await readCurrentJson(storage, currentJsonKey, signalOpts);
832
+ if (cur === null) return {
833
+ marked: {
834
+ stale_log: 0,
835
+ orphan_snapshot: 0,
836
+ orphan_content: 0
837
+ },
838
+ swept: 0,
839
+ pendingDepth: 0
840
+ };
841
+ const current = cur.json;
842
+ const logSeqStart = logSeqStartOf(current);
843
+ let pending = await readGcPending(storage, gcPendingKey, signalOpts);
844
+ if (pending === null) {
845
+ const initial = {
846
+ schema_version: 1,
847
+ candidates: [],
848
+ last_swept_at: ""
849
+ };
850
+ try {
851
+ pending = await createGcPending(storage, gcPendingKey, initial, signalOpts);
852
+ } catch (error) {
853
+ if (error instanceof BaerlyError && error.code === "Conflict") {
854
+ pending = await readGcPending(storage, gcPendingKey, signalOpts);
855
+ if (pending === null) throw error;
856
+ } else throw error;
857
+ }
858
+ }
859
+ const known = new Set(pending.json.candidates.map((c) => c.key));
860
+ const newCandidates = [];
861
+ let markedStaleLog = 0;
862
+ if (logSeqStart > 0) for await (const entry of listBounded(storage, `${collectionPrefix}/log/`, maxMarks, signal)) {
863
+ if (markedStaleLog >= maxMarks) break;
864
+ const seq = parseSeqFromLogKey(entry.key);
865
+ if (seq === null || seq >= logSeqStart) continue;
866
+ if (known.has(entry.key)) continue;
867
+ newCandidates.push({
868
+ key: entry.key,
869
+ due_at: computeDueAt(entry, now, grace),
870
+ reason: "stale-log"
871
+ });
872
+ markedStaleLog++;
873
+ }
874
+ let markedOrphanSnapshot = 0;
875
+ for await (const entry of listBounded(storage, `${collectionPrefix}/snapshot/`, maxMarks, signal)) {
876
+ if (markedOrphanSnapshot >= maxMarks) break;
877
+ if (entry.key === current.snapshot) continue;
878
+ if (known.has(entry.key)) continue;
879
+ newCandidates.push({
880
+ key: entry.key,
881
+ due_at: computeDueAt(entry, now, grace),
882
+ reason: "orphan-snapshot"
883
+ });
884
+ markedOrphanSnapshot++;
885
+ }
886
+ const liveHashes = await collectLiveContentHashes(storage, collectionPrefix, collectionName, current, logSeqStart, signal);
887
+ const cursor = pending.json.content_scan_cursor;
888
+ const contentPrefix = `${collectionPrefix}/content/`;
889
+ let markedOrphanContent = 0;
890
+ let examinedThisPass = 0;
891
+ let lastExaminedKey;
892
+ const listOpts = {
893
+ maxKeys: maxMarks,
894
+ ...cursor !== void 0 && { startAfter: cursor },
895
+ ...signal !== void 0 && { signal }
896
+ };
897
+ for await (const entry of storage.list(contentPrefix, listOpts)) {
898
+ examinedThisPass++;
899
+ lastExaminedKey = entry.key;
900
+ const hash = parseHashFromContentKey(entry.key);
901
+ if (hash === null || liveHashes.has(hash)) continue;
902
+ if (known.has(entry.key)) continue;
903
+ newCandidates.push({
904
+ key: entry.key,
905
+ due_at: computeDueAt(entry, now, grace),
906
+ reason: "orphan-content"
907
+ });
908
+ markedOrphanContent++;
909
+ }
910
+ const nextContentCursor = examinedThisPass < maxMarks ? void 0 : lastExaminedKey;
911
+ const nowMs = now().getTime();
912
+ const sweepCandidates = [...pending.json.candidates, ...newCandidates];
913
+ const toSweep = [];
914
+ const remaining = [];
915
+ for (const cand of sweepCandidates) if (toSweep.length < maxSweeps && Date.parse(cand.due_at) <= nowMs) toSweep.push(cand);
916
+ else remaining.push(cand);
917
+ await Promise.all(toSweep.map((c) => storage.delete(c.key, signalOpts)));
918
+ const merged = remaining.slice(0, GC_MAX_PENDING_CANDIDATES);
919
+ const lastSweptAt = toSweep.length > 0 ? now().toISOString() : pending.json.last_swept_at;
920
+ const markedSummary = {
921
+ stale_log: markedStaleLog,
922
+ orphan_snapshot: markedOrphanSnapshot,
923
+ orphan_content: markedOrphanContent
924
+ };
925
+ let pendingDepth;
926
+ try {
927
+ pendingDepth = (await casUpdateGcPending(storage, gcPendingKey, () => ({
928
+ schema_version: 1,
929
+ candidates: merged,
930
+ last_swept_at: lastSweptAt,
931
+ ...nextContentCursor !== void 0 && { content_scan_cursor: nextContentCursor }
932
+ }), signalOpts)).json.candidates.length;
933
+ } catch (error) {
934
+ if (error instanceof BaerlyError && error.code === "Conflict") pendingDepth = remaining.length;
935
+ else throw error;
936
+ }
937
+ const labels = { collection: collectionName };
938
+ const metrics = ctxMetrics$1();
939
+ metrics.gauge("db.orphan.candidate_count", pendingDepth, labels);
940
+ metrics.gauge("db.gc.entries_swept_per_second", toSweep.length, labels);
941
+ if (toSweep.length > 0) {
942
+ const byReason = /* @__PURE__ */ new Map();
943
+ for (const c of toSweep) byReason.set(c.reason, (byReason.get(c.reason) ?? 0) + 1);
944
+ for (const [reason, count] of byReason) metrics.counter("db.gc.swept_total", count, {
945
+ collection: collectionName,
946
+ reason
947
+ });
948
+ }
949
+ return {
950
+ marked: markedSummary,
951
+ swept: toSweep.length,
952
+ pendingDepth
953
+ };
954
+ };
955
+ /**
956
+ * `Storage.list` with a hard ceiling — bounds the I/O cost of a
957
+ * single pass when a runaway prefix has accumulated many keys.
958
+ */
959
+ const listBounded = async function* (storage, prefix, cap, signal) {
960
+ let yielded = 0;
961
+ const opts = signal !== void 0 ? { signal } : void 0;
962
+ for await (const entry of storage.list(prefix, opts)) {
963
+ if (yielded >= cap) return;
964
+ yield entry;
965
+ yielded++;
966
+ }
967
+ };
968
+ /**
969
+ * Parse `<...>/log/<seq>.json` and return `seq`. Returns `null` on
970
+ * any shape that doesn't look like a log entry key — defensively
971
+ * tolerates an unrelated key under the log prefix.
972
+ */
973
+ const parseSeqFromLogKey = (key) => {
974
+ const match = /\/log\/(\d+)\.json$/.exec(key);
975
+ if (match === null) return null;
976
+ const n = Number.parseInt(match[1], 10);
977
+ return Number.isFinite(n) && n >= 0 ? n : null;
978
+ };
979
+ /**
980
+ * Parse `<...>/content/<sha-32>.json` and return the 32-hex hash.
981
+ * Returns `null` on any shape that doesn't match the writer's
982
+ * `versionFromContent`-produced key format.
983
+ */
984
+ const parseHashFromContentKey = (key) => {
985
+ const match = /\/content\/([0-9a-f]{32})\.json$/.exec(key);
986
+ return match === null ? null : match[1];
987
+ };
988
+ /**
989
+ * Anchor `due_at` to `lastModified` when the storage adapter
990
+ * surfaces it; fall back to the injected `now` so a Storage impl
991
+ * without a server clock still GCs after `grace` from the mark
992
+ * moment.
993
+ */
994
+ const computeDueAt = (entry, now, graceMs) => {
995
+ const base = entry.lastModified ?? now();
996
+ return new Date(base.getTime() + graceMs).toISOString();
997
+ };
998
+ /**
999
+ * Build the live content-hash set. The set covers every live
1000
+ * post-image: every `entry.after` in `[logSeqStart, next_seq)` plus
1001
+ * every row body in the current snapshot.
1002
+ *
1003
+ * A snapshot read that throws (corrupt body, hash mismatch) is
1004
+ * tolerated — the worst-case effect is missing some live hashes,
1005
+ * which could mark a live content blob as orphan. The grace period
1006
+ * absorbs the false-positive: a retry that re-PUTs the same hash
1007
+ * recreates the key before the sweep deletes it.
1008
+ */
1009
+ const collectLiveContentHashes = async (storage, collectionPrefix, collectionName, current, logSeqStart, signal) => {
1010
+ const hashes = /* @__PURE__ */ new Set();
1011
+ const getOpts = signal !== void 0 ? { signal } : void 0;
1012
+ const logReads = [];
1013
+ for (let s = logSeqStart; s < current.next_seq; s++) logReads.push((async () => {
1014
+ const got = await storage.get(`${collectionPrefix}/log/${s}.json`, getOpts);
1015
+ if (got === null) return;
1016
+ let entry;
1017
+ try {
1018
+ entry = decodeJsonBytes(got.body);
1019
+ } catch {
1020
+ return;
1021
+ }
1022
+ if (entry.after === void 0) return;
1023
+ const bodyBytes = encodeJsonBytes(entry.after);
1024
+ hashes.add(await versionFromContent(bodyBytes));
1025
+ })());
1026
+ await Promise.all(logReads);
1027
+ if (current.snapshot !== null) try {
1028
+ const map = await loadSnapshotAsMap(storage, current.snapshot, collectionName, signal);
1029
+ const rowReads = [];
1030
+ for (const body of map.values()) rowReads.push((async () => {
1031
+ const bytes = encodeJsonBytes(body);
1032
+ hashes.add(await versionFromContent(bytes));
1033
+ })());
1034
+ await Promise.all(rowReads);
1035
+ } catch {}
1036
+ return hashes;
1037
+ };
1038
+ //#endregion
1039
+ //#region ../server/src/rebuild-index.ts
1040
+ /**
1041
+ * Idempotent reconciliation for one secondary index.
1042
+ *
1043
+ * {@link rebuildIndex} folds the live `(snapshot, log_tail)` of a
1044
+ * collection into the doc set the writer's index emission would
1045
+ * have produced, then PUTs every missing index key and DELETEs every
1046
+ * orphaned one. Same-key zero-byte PUTs are no-ops (the entries are
1047
+ * content-addressed by composition); same-key DELETEs are
1048
+ * contractually idempotent.
1049
+ *
1050
+ * Invariants:
1051
+ *
1052
+ * - **Re-running on a healthy index is a no-op.** `added = 0`,
1053
+ * `removed = 0`.
1054
+ * - **Re-running after a crashed mid-commit** reconciles toward
1055
+ * the live `current.json` view — orphans deleted, missing keys
1056
+ * PUT.
1057
+ * - **Re-running while writes are in flight** is safe up to a
1058
+ * race window: a write that lands during the rebuild may
1059
+ * produce a transient "orphan" the rebuild sweeps, which the
1060
+ * next live write then re-PUTs. The race converges on the next
1061
+ * commit.
1062
+ *
1063
+ * The function reads the same fold the writer / reader use
1064
+ * (snapshot via {@link loadSnapshotAsMap}; log tail by direct
1065
+ * `get(<logPrefix>/log/<seq>.json)`) so it MUST agree with the
1066
+ * writer on the live doc set by construction.
1067
+ *
1068
+ * @see ./indexes.ts — `IndexDefinition`, `allIndexKeysFor`,
1069
+ * `indexKeyPrefix`.
1070
+ * @see ./writer.ts — the fence-time emission path this
1071
+ * command reconciles.
1072
+ */
1073
+ const EMPTY_BODY = new Uint8Array(0);
1074
+ const APPLICATION_JSON = "application/json";
1075
+ /**
1076
+ * Idempotently reconcile one secondary index for one collection.
1077
+ *
1078
+ * @param storage Storage handle (any in-tree `Storage`).
1079
+ * @param currentJsonKey The collection's `current.json` key.
1080
+ * @param def The index to reconcile. Single-field today;
1081
+ * composite definitions are accepted by the
1082
+ * key encoder but the read path only consults
1083
+ * single-field keys.
1084
+ * @param opts Optional knobs — see {@link RebuildIndexOptions}.
1085
+ * Strictly additive: existing positional-arg
1086
+ * callers compile and behave unchanged when
1087
+ * omitted.
1088
+ *
1089
+ * @throws BaerlyError code="InvalidResponse" — `current.json` missing.
1090
+ * @throws BaerlyError code="Internal" — protocol-invariant
1091
+ * violation (snapshot hash mismatch, missing log entry inside
1092
+ * `[log_seq_start, next_seq)`).
1093
+ */
1094
+ const rebuildIndex = async (storage, currentJsonKey, def, opts = {}) => {
1095
+ const read = await readCurrentJson(storage, currentJsonKey);
1096
+ if (read === null) throw new BaerlyError("InvalidResponse", `rebuildIndex: current.json missing at ${JSON.stringify(currentJsonKey)}`);
1097
+ const lastSlash = currentJsonKey.lastIndexOf("/");
1098
+ if (lastSlash < 0) throw new BaerlyError("InvalidResponse", `rebuildIndex: currentJsonKey ${JSON.stringify(currentJsonKey)} must contain "/"`);
1099
+ const collectionPrefix = currentJsonKey.slice(0, lastSlash);
1100
+ const collection = collectionPrefix.slice(collectionPrefix.lastIndexOf("/") + 1);
1101
+ const logSeqStart = logSeqStartOf(read.json);
1102
+ const nextSeq = read.json.next_seq;
1103
+ const live = read.json.snapshot === null ? /* @__PURE__ */ new Map() : await loadSnapshotAsMap(storage, read.json.snapshot, collection);
1104
+ foldLogEntriesOnto(live, await walkLogRange(storage, collectionPrefix, logSeqStart, nextSeq), { collection });
1105
+ const expected = /* @__PURE__ */ new Set();
1106
+ for (const [docId, body] of live) for (const k of allIndexKeysFor(collectionPrefix, [def], body, docId)) expected.add(k);
1107
+ const actual = /* @__PURE__ */ new Set();
1108
+ const listOpts = {};
1109
+ if (opts.signal !== void 0) listOpts.signal = opts.signal;
1110
+ for await (const entry of storage.list(indexKeyPrefix(collectionPrefix, def.name), listOpts)) actual.add(entry.key);
1111
+ const dryRun = opts.dryRun === true;
1112
+ let added = 0;
1113
+ let removed = 0;
1114
+ let kept = 0;
1115
+ for (const k of expected) {
1116
+ if (actual.has(k)) {
1117
+ kept += 1;
1118
+ continue;
1119
+ }
1120
+ if (dryRun) {
1121
+ added += 1;
1122
+ continue;
1123
+ }
1124
+ try {
1125
+ await storage.put(k, EMPTY_BODY, {
1126
+ ifNoneMatch: "*",
1127
+ contentType: APPLICATION_JSON
1128
+ });
1129
+ added += 1;
1130
+ } catch (error) {
1131
+ if (error instanceof BaerlyError && error.code === "Conflict") kept += 1;
1132
+ else throw error;
1133
+ }
1134
+ }
1135
+ for (const k of actual) {
1136
+ if (expected.has(k)) continue;
1137
+ if (dryRun) {
1138
+ removed += 1;
1139
+ continue;
1140
+ }
1141
+ await storage.delete(k);
1142
+ removed += 1;
1143
+ }
1144
+ return {
1145
+ added,
1146
+ removed,
1147
+ kept
1148
+ };
1149
+ };
1150
+ //#endregion
1151
+ //#region ../server/src/maintenance.ts
1152
+ /**
1153
+ * `runScheduledMaintenance` — single-pass compose of `compact()` and
1154
+ * `runGc()` over one collection. Designed to fit a single Cloudflare
1155
+ * Cron Trigger invocation's 50-subrequest free-tier budget when
1156
+ * called with the {@link CLOUDFLARE_FREE_TIER} profile (which the
1157
+ * caller pairs with even/odd-minute alternation between compact and
1158
+ * GC ticks); unbounded on Node.
1159
+ *
1160
+ * Single-attempt: returns the combined result. The caller (cron
1161
+ * handler) is responsible for scheduling the next invocation; this
1162
+ * function does not loop or retry. `compact()` and `runGc()` are
1163
+ * already CAS-protected single-attempts — a restart safely retries
1164
+ * next tick.
1165
+ *
1166
+ * Callers that want only one phase to fire this tick should invoke
1167
+ * the underlying primitive directly (`compact()` or `runGc()` from
1168
+ * this same module's re-exports). The even/odd-minute CF cron
1169
+ * pattern uses exactly that.
1170
+ */
1171
+ const ctxMetrics = () => getCurrentContext()?.recorder ?? noopMetricsRecorder;
1172
+ /**
1173
+ * Floor-based GC-cadence boundary crossing. BATCH-SAFE: a
1174
+ * `commitBatch` that jumps `next_seq` by its whole batch size can step
1175
+ * CLEAN OVER a `next_seq % interval === 0` modulo test; this floor test
1176
+ * trips on any interval boundary inside `(prevSeq, nextSeq]`.
1177
+ */
1178
+ const crossesGcBoundary = (prevSeq, nextSeq, interval) => Math.floor(prevSeq / interval) !== Math.floor(nextSeq / interval);
1179
+ /**
1180
+ * The cheap DISPATCH gate the writer calls after a commit — zero
1181
+ * storage ops; it reads the post-CAS {@link CurrentJson} already in
1182
+ * scope. Ratio-OR-boundary, WITHOUT the entry floor (the floor is part
1183
+ * of the fold-trigger Gate 1 checked inside {@link runBoundedMaintenance}).
1184
+ * Returning `false` lets the writer skip the dispatch entirely.
1185
+ */
1186
+ const shouldFireMaintenance = (current, prevSeq, gcInterval) => crossesGcBoundary(prevSeq, current.next_seq, gcInterval) || current.tail_bytes / Math.max(current.snapshot_bytes, 65536) >= 1;
1187
+ /**
1188
+ * The write-tick maintenance runner: a bounded, single-attempt
1189
+ * composition of {@link compact} and {@link runGc} for one collection,
1190
+ * sized to fit a CPU-killable Cloudflare free-tier isolate by default.
1191
+ *
1192
+ * Never throws — the write-tick caller must never see a maintenance
1193
+ * failure. Expected signals (CAS contention, an over-ceiling deferral)
1194
+ * are swallowed quietly; unexpected throws bump
1195
+ * `db.maintenance.unexpected_error_total`, log a stack, and are
1196
+ * swallowed.
1197
+ *
1198
+ * Control flow (fold-priority with a stateless GC-starvation guard):
1199
+ * 0. `disabled` → return with zero storage ops.
1200
+ * 1. Read `current.json` once.
1201
+ * 2. Hard-GC starvation boundary (`"single"` only) → GC slice, skip fold.
1202
+ * 3. Gate 1 (ratio AND entry floor) trips → fold if viable, else
1203
+ * defer (and metric); on `"single"` a successful fold attempt is
1204
+ * this tick's one phase.
1205
+ * 4. Otherwise (or on `"both"`) → GC iff the cadence boundary crossed.
1206
+ */
1207
+ const runBoundedMaintenance = async (args, options) => {
1208
+ if (args.disabled === true) return;
1209
+ const { storage, currentJsonKey, prevSeq } = args;
1210
+ const maxFoldEntriesPerPass = options?.maxFoldEntriesPerPass ?? 20;
1211
+ const minEntriesToCompact = options?.minEntriesToCompact ?? 50;
1212
+ const gcMaxMarks = options?.gcMaxMarks ?? 20;
1213
+ const gcMaxSweeps = options?.gcMaxSweeps ?? 10;
1214
+ const gcInterval = options?.gcInterval ?? 4;
1215
+ const phasesPerTick = options?.phasesPerTick ?? "single";
1216
+ const signal = options?.signal;
1217
+ const C = args.maxFoldBytes ?? 524288;
1218
+ const E = MAINTENANCE_MAX_FOLD_ROWS;
1219
+ const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf("/"));
1220
+ const collection = collectionPrefix.slice(collectionPrefix.lastIndexOf("/") + 1);
1221
+ const gcOpts = {
1222
+ maxMarksPerRun: gcMaxMarks,
1223
+ maxSweepsPerRun: gcMaxSweeps,
1224
+ ...signal !== void 0 && { signal },
1225
+ ...options?.gcGraceMillis !== void 0 && { graceMillis: options.gcGraceMillis },
1226
+ ...options?.now !== void 0 && { now: options.now }
1227
+ };
1228
+ try {
1229
+ const read = await readCurrentJson(storage, currentJsonKey, signal !== void 0 ? { signal } : void 0);
1230
+ if (read === null) return;
1231
+ const current = read.json;
1232
+ const tailBytes = current.tail_bytes;
1233
+ const snapshotBytes = current.snapshot_bytes;
1234
+ const snapshotRows = current.snapshot_rows;
1235
+ const nextSeq = current.next_seq;
1236
+ const logSeqStart = current.log_seq_start;
1237
+ const gate1 = tailBytes / Math.max(snapshotBytes, 65536) >= 1 && nextSeq - logSeqStart >= minEntriesToCompact;
1238
+ const foldViable = snapshotBytes <= C && snapshotRows + maxFoldEntriesPerPass <= E;
1239
+ const gcDue = crossesGcBoundary(prevSeq, nextSeq, gcInterval);
1240
+ const hardGc = crossesGcBoundary(prevSeq, nextSeq, gcInterval * 4);
1241
+ if (phasesPerTick === "single" && hardGc) {
1242
+ await runGc({
1243
+ storage,
1244
+ currentJsonKey
1245
+ }, gcOpts);
1246
+ return;
1247
+ }
1248
+ if (gate1) if (foldViable) {
1249
+ await compact({
1250
+ storage,
1251
+ currentJsonKey
1252
+ }, {
1253
+ maxEntriesPerRun: maxFoldEntriesPerPass,
1254
+ minEntriesToCompact,
1255
+ ceilingBytes: C,
1256
+ ceilingEntries: E,
1257
+ ...signal !== void 0 && { signal }
1258
+ });
1259
+ if (phasesPerTick === "single") return;
1260
+ } else {
1261
+ ctxMetrics().counter("db.compaction.deferred_total", 1, {
1262
+ collection,
1263
+ dimension: snapshotBytes > C ? "bytes" : "rows"
1264
+ });
1265
+ if (nextSeq - (current.last_warned_seq ?? 0) >= 1e3) {
1266
+ console.warn(`baerly-storage: collection "${collection}" is deferring compaction — its snapshot exceeds the fold ceiling (${snapshotBytes > C ? "bytes" : "rows"}), so the tail keeps growing and read amplification will climb. This is graduation-pending: the dataset has outgrown prototype-tier maintenance. On paid Cloudflare / Node you can raise BAERLY_MAINTENANCE_MAX_FOLD_BYTES — but on Cloudflare a cap above what a single isolate can fold makes folds get CPU-killed mid-flight and silently not land (no clean metric — watch snapshot age / object count); see docs/about/graduation.md. Otherwise, graduate to a server-backed database.`);
1267
+ try {
1268
+ await casUpdateCurrentJson(storage, currentJsonKey, (c) => ({
1269
+ ...c,
1270
+ last_warned_seq: nextSeq
1271
+ }), signal !== void 0 ? { signal } : void 0);
1272
+ } catch {}
1273
+ }
1274
+ }
1275
+ if (gcDue) await runGc({
1276
+ storage,
1277
+ currentJsonKey
1278
+ }, gcOpts);
1279
+ } catch (error) {
1280
+ if (error instanceof BaerlyError && error.code === "Conflict") return;
1281
+ ctxMetrics().counter("db.maintenance.unexpected_error_total", 1, { collection });
1282
+ console.error(error);
1283
+ }
1284
+ };
1285
+ /**
1286
+ * Default maintenance dispatcher: run the task inline and await it.
1287
+ * Adapters that can keep running after the response (Cloudflare:
1288
+ * `ctx.waitUntil`) override this with a fire-and-forget variant that
1289
+ * returns `void`.
1290
+ */
1291
+ const dispatchInlineAwaited = (task) => task();
1292
+ //#endregion
1293
+ export { getCurrentContext as a, noopMetricsRecorder as c, rebuildIndex as i, versionFromContent as l, runBoundedMaintenance as n, allIndexKeysFor as o, shouldFireMaintenance as r, validateIndexDefinition as s, dispatchInlineAwaited as t };
1294
+
1295
+ //# sourceMappingURL=maintenance-BvOv6BMM.js.map