@gusto/baerly-storage 0.1.1 → 0.2.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.
Files changed (114) hide show
  1. package/README.md +27 -3
  2. package/dist/API.md +103 -22
  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 +76 -85
  12. package/dist/client-react.js +95 -53
  13. package/dist/client-react.js.map +1 -1
  14. package/dist/client.d.ts +3 -3
  15. package/dist/cloudflare.d.ts +31 -4
  16. package/dist/cloudflare.js +72 -6
  17. package/dist/cloudflare.js.map +1 -1
  18. package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
  19. package/dist/config-DVfDGyw1.js.map +1 -0
  20. package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
  21. package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
  22. package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
  23. package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
  24. package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
  25. package/dist/current-json-C-EyJqs0.js.map +1 -0
  26. package/dist/{db-aRMK_0R0.d.ts → db-BM3y2JQw.d.ts} +3 -3
  27. package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
  28. package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
  29. package/dist/dev-vite.d.ts +3 -3
  30. package/dist/dev-vite.js +3 -3
  31. package/dist/dev.d.ts +1 -1
  32. package/dist/dev.js +1 -1
  33. package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
  34. package/dist/doctor-Db-hzPmE.js.map +1 -0
  35. package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
  36. package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
  37. package/dist/errors-DOdL95kK.js.map +1 -1
  38. package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
  39. package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
  40. package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
  41. package/dist/fsck-CPPZWt9p.js.map +1 -0
  42. package/dist/{http-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
  43. package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
  44. package/dist/http.d.ts +3 -3
  45. package/dist/http.js +1 -1
  46. package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
  47. package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
  48. package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
  49. package/dist/{index-spCBsIwm.d.ts → index-cUY-36AN.d.ts} +3 -3
  50. package/dist/index.d.ts +5 -5
  51. package/dist/index.js +3 -3
  52. package/dist/{indexes-BIH73Uv4.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
  53. package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
  54. package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
  55. package/dist/maintenance-BRrThz8V.d.ts +449 -0
  56. package/dist/maintenance-BvOv6BMM.js +1295 -0
  57. package/dist/maintenance-BvOv6BMM.js.map +1 -0
  58. package/dist/maintenance-ClzBC1Vv.js +1895 -0
  59. package/dist/maintenance-ClzBC1Vv.js.map +1 -0
  60. package/dist/maintenance.d.ts +2 -323
  61. package/dist/maintenance.js +2 -2
  62. package/dist/node.d.ts +20 -79
  63. package/dist/node.js +2 -2
  64. package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
  65. package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
  66. package/dist/observability.d.ts +2 -2
  67. package/dist/observability.js +2 -2
  68. package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
  69. package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
  70. package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
  71. package/dist/query-BmiQy328.js.map +1 -0
  72. package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
  73. package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
  74. package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
  75. package/dist/restore-C6IcmLeA.js.map +1 -0
  76. package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
  77. package/dist/snapshot-SS8USDUF.js.map +1 -0
  78. package/dist/{src-Cr9C7_tT.js → src-DU1sCMlr.js} +315 -278
  79. package/dist/src-DU1sCMlr.js.map +1 -0
  80. package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
  81. package/dist/src-QQ7jDeL2.js.map +1 -0
  82. package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
  83. package/dist/src-zhEAmmF7.js.map +1 -0
  84. package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
  85. package/dist/subcommand-DZcHcsYp.js.map +1 -0
  86. package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
  87. package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
  88. package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
  89. package/dist/validate-DCq_0DIn.js.map +1 -0
  90. package/package.json +13 -6
  91. package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
  92. package/dist/config-Bsg8wgwo.js.map +0 -1
  93. package/dist/current-json-BkatBzF7.js.map +0 -1
  94. package/dist/doctor-B8h9GCN9.js.map +0 -1
  95. package/dist/fsck-DEz9lyCy.js.map +0 -1
  96. package/dist/indexes-BXn7a06a.js +0 -297
  97. package/dist/indexes-BXn7a06a.js.map +0 -1
  98. package/dist/log-walk-DIru96UT.js.map +0 -1
  99. package/dist/maintenance-Bn6ul9aV.js +0 -758
  100. package/dist/maintenance-Bn6ul9aV.js.map +0 -1
  101. package/dist/query-DcSbFLJt.js.map +0 -1
  102. package/dist/rebuild-index-C5gTXryd.js +0 -119
  103. package/dist/rebuild-index-C5gTXryd.js.map +0 -1
  104. package/dist/restore-CbKVMMpm.js.map +0 -1
  105. package/dist/snapshot-D7C4_FSl.js +0 -71
  106. package/dist/snapshot-D7C4_FSl.js.map +0 -1
  107. package/dist/snapshot-z_N9hpTe.js +0 -917
  108. package/dist/snapshot-z_N9hpTe.js.map +0 -1
  109. package/dist/src-Chafbw8r.js.map +0 -1
  110. package/dist/src-Cr9C7_tT.js.map +0 -1
  111. package/dist/src-n0Te1r98.js.map +0 -1
  112. package/dist/subcommand-BWs6K7zb.js +0 -110
  113. package/dist/subcommand-BWs6K7zb.js.map +0 -1
  114. package/dist/validate-DhH1lO8I.js.map +0 -1
@@ -0,0 +1,1895 @@
1
+ import { c as GC_MAX_PENDING_CANDIDATES, d as MAINTENANCE_MAX_FOLD_ROWS, i as readCurrentJson, l as GC_PENDING_CONTENT_TYPE, r as logSeqStartOf, t as casUpdateCurrentJson, v as decodeJsonBytes, y as encodeJsonBytes } from "./current-json-C-EyJqs0.js";
2
+ import { t as BaerlyError } from "./errors-DOdL95kK.js";
3
+ import { i as noopMetricsRecorder, n as getCurrentContext } from "./context-DRZ3tZ5l.js";
4
+ //#region packages/protocol/src/coordination/gc-pending.ts
5
+ /**
6
+ * `gc/pending.json` — the per-collection GC candidate ledger. CAS-
7
+ * protected; one per `(tenant, collection)` key — for example
8
+ * `<tenant>/<collection>/gc/pending.json`. `runGc()` in
9
+ * `packages/server/src/gc.ts` is the single writer that adds and
10
+ * removes entries. Stays small in steady state because every
11
+ * candidate is deleted once `due_at` passes.
12
+ *
13
+ * "Mark" appends candidates with a future `due_at`; "sweep" deletes
14
+ * candidates whose `due_at` is in the past. The two phases run in
15
+ * the same compactor pass — see `runGc()` in
16
+ * `packages/server/src/gc.ts`.
17
+ *
18
+ * Lives next to {@link CurrentJson} in `coordination/` — same shape
19
+ * of "CAS-protected small control object." Pure module; no Node
20
+ * imports; Worker-bundleable.
21
+ *
22
+ * @see packages/server/src/gc.ts
23
+ */
24
+ /**
25
+ * Read + parse `gc/pending.json` at `key`. Returns `null` on
26
+ * not-found.
27
+ *
28
+ * @throws BaerlyError{code:"InvalidResponse"} — body is not valid
29
+ * JSON, or `schema_version` is unknown, or the shape fails
30
+ * the runtime guard.
31
+ */
32
+ const readGcPending = async (storage, key, opts) => {
33
+ const got = await storage.get(key, opts);
34
+ if (got === null) return null;
35
+ let parsed;
36
+ try {
37
+ parsed = decodeJsonBytes(got.body);
38
+ } catch (error) {
39
+ throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: body is not valid JSON`, error);
40
+ }
41
+ return {
42
+ json: assertGcPending(parsed, key),
43
+ etag: got.etag
44
+ };
45
+ };
46
+ /**
47
+ * Create `gc/pending.json` if-and-only-if it does not exist (S3
48
+ * `If-None-Match: "*"`). Use this once per collection at first GC
49
+ * run; subsequent updates go through {@link casUpdateGcPending}.
50
+ *
51
+ * @throws BaerlyError{code:"Conflict"} — the key already exists.
52
+ * @throws BaerlyError{code:"InvalidResponse"} — `initial` fails the
53
+ * runtime shape guard.
54
+ */
55
+ const createGcPending = async (storage, key, initial, opts) => {
56
+ assertGcPending(initial, key);
57
+ const body = encodeJsonBytes(initial);
58
+ const putOpts = {
59
+ ifNoneMatch: "*",
60
+ contentType: GC_PENDING_CONTENT_TYPE,
61
+ ...opts?.signal !== void 0 && { signal: opts.signal }
62
+ };
63
+ let result;
64
+ try {
65
+ result = await storage.put(key, body, putOpts);
66
+ } catch (error) {
67
+ throw translateCasError(error, key);
68
+ }
69
+ return {
70
+ json: initial,
71
+ etag: result.etag
72
+ };
73
+ };
74
+ /**
75
+ * Read-modify-write `gc/pending.json` under CAS. The `mutator`
76
+ * receives a deep clone of the current parsed JSON and returns the
77
+ * new state. The new state is written with `If-Match: <currentEtag>`;
78
+ * on conflict, throws `BaerlyError{code:"Conflict"}`.
79
+ *
80
+ * `mutator` MUST be deterministic — it may be called multiple times
81
+ * if the caller wraps this in a retry loop, so it must not have side
82
+ * effects.
83
+ *
84
+ * @throws BaerlyError{code:"Conflict"} — another writer landed a write
85
+ * between this function's read and write.
86
+ * @throws BaerlyError{code:"InvalidResponse"} — `key` does not exist
87
+ * (use {@link createGcPending} instead) or body doesn't
88
+ * parse / fails the shape guard.
89
+ */
90
+ const casUpdateGcPending = async (storage, key, mutator, opts) => {
91
+ const existing = await readGcPending(storage, key, opts);
92
+ if (existing === null) throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key} does not exist; use createGcPending first`);
93
+ const next = mutator(structuredClone(existing.json));
94
+ assertGcPending(next, key);
95
+ const body = encodeJsonBytes(next);
96
+ const putOpts = {
97
+ ifMatch: existing.etag,
98
+ contentType: GC_PENDING_CONTENT_TYPE,
99
+ ...opts?.signal !== void 0 && { signal: opts.signal }
100
+ };
101
+ let result;
102
+ try {
103
+ result = await storage.put(key, body, putOpts);
104
+ } catch (error) {
105
+ throw translateCasError(error, key);
106
+ }
107
+ return {
108
+ json: next,
109
+ etag: result.etag
110
+ };
111
+ };
112
+ const VALID_REASONS = new Set([
113
+ "stale-log",
114
+ "orphan-snapshot",
115
+ "orphan-content"
116
+ ]);
117
+ /**
118
+ * Runtime guard for `parsed` to be a {@link GcPending}. Throws
119
+ * `BaerlyError{code:"InvalidResponse"}` rather than coercing.
120
+ */
121
+ const assertGcPending = (parsed, key) => {
122
+ if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: parsed body is not an object`);
123
+ const r = parsed;
124
+ if (r["schema_version"] !== 1) throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: unsupported schema_version ${String(r["schema_version"])}; expected 1`);
125
+ if (!Array.isArray(r["candidates"])) throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: candidates must be an array`);
126
+ for (let i = 0; i < r["candidates"].length; i++) {
127
+ const c = r["candidates"][i];
128
+ if (c === null || typeof c !== "object") throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: candidates[${String(i)}] is not an object`);
129
+ const cr = c;
130
+ 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`);
131
+ if (typeof cr["due_at"] !== "string") throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: candidates[${String(i)}].due_at must be a string`);
132
+ 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`);
133
+ }
134
+ if (typeof r["last_swept_at"] !== "string") throw new BaerlyError("InvalidResponse", `gc/pending.json at ${key}: last_swept_at must be a string`);
135
+ 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`);
136
+ return parsed;
137
+ };
138
+ /**
139
+ * Wrap a storage-level error with `gc/pending.json at <key>`
140
+ * location context. `Conflict` (the storage layer's CAS-lost signal)
141
+ * is re-thrown with an annotated message; other `BaerlyError`s pass
142
+ * through; non-`BaerlyError` falls through as `InvalidResponse`.
143
+ */
144
+ const translateCasError = (e, key) => {
145
+ if (e instanceof BaerlyError && e.code === "Conflict") return new BaerlyError("Conflict", `gc/pending.json CAS lost at ${key}: ${e.message}`, e);
146
+ if (e instanceof BaerlyError) return e;
147
+ return new BaerlyError("InvalidResponse", `gc/pending.json write at ${key} failed: ${String(e)}`, e);
148
+ };
149
+ //#endregion
150
+ //#region packages/protocol/src/query/_internals.ts
151
+ /** @internal Same primitive type for comparison purposes. */
152
+ const sameComparableType = (a, b) => typeof a === "string" && typeof b === "string" || typeof a === "number" && typeof b === "number";
153
+ /**
154
+ * @internal Returns negative / zero / positive for a<b / a==b / a>b.
155
+ */
156
+ const compareScalar = (a, b) => {
157
+ if (typeof a === "number" && typeof b === "number") return a - b;
158
+ if (typeof a === "string" && typeof b === "string") {
159
+ if (a < b) return -1;
160
+ if (a > b) return 1;
161
+ return 0;
162
+ }
163
+ return 0;
164
+ };
165
+ /** @internal Render a predicate path for use in error messages. */
166
+ const formatPath = (path) => path.length === 0 ? "<root>" : path.map((p) => JSON.stringify(p)).join(".");
167
+ /**
168
+ * Recursive structural equality for `DocumentValue` values. Lifted to
169
+ * `export` so the filtered-index implication checker (in
170
+ * `@baerly/server`'s query planner) and other callers can reuse the
171
+ * same comparison rule the validator + merger already trust. Two
172
+ * values `a` and `b` are equal iff:
173
+ *
174
+ * - they are reference-equal (covers primitives and object identity);
175
+ * - or they are both non-`null` objects with the same key set, and
176
+ * every value pair is recursively equal.
177
+ *
178
+ * Arrays are out-of-band for `DocumentValue`; this function rejects
179
+ * them implicitly via the same key-set walk (an array reads as an
180
+ * object with numeric-string keys plus a `length` exposure that
181
+ * `Object.keys` happens to skip — defensive callers should still gate
182
+ * with `Array.isArray` first).
183
+ */
184
+ const deepEqualDocumentValue = (a, b) => {
185
+ if (a === b) return true;
186
+ if (typeof a !== "object" || typeof b !== "object") return false;
187
+ const aKeys = Object.keys(a);
188
+ const bKeys = Object.keys(b);
189
+ if (aKeys.length !== bKeys.length) return false;
190
+ for (const key of aKeys) {
191
+ if (!(key in b)) return false;
192
+ const aSub = a[key];
193
+ const bSub = b[key];
194
+ if (aSub === void 0 || bSub === void 0) return false;
195
+ if (!deepEqualDocumentValue(aSub, bSub)) return false;
196
+ }
197
+ return true;
198
+ };
199
+ //#endregion
200
+ //#region packages/protocol/src/query/matches.ts
201
+ /**
202
+ * Evaluate a validated wire-form predicate against a `JSONObject`
203
+ * document. Returns `true` iff every clause holds.
204
+ *
205
+ * @example
206
+ * ```ts
207
+ * matchesWire(
208
+ * { clauses: [{ op: "eq", field: "status", value: "open" }] },
209
+ * { status: "open", priority: "p1" },
210
+ * ); // true
211
+ *
212
+ * matchesWire(
213
+ * { clauses: [{ op: "in", field: "priority", value: ["p1", "p2"] }] },
214
+ * { priority: "p3" },
215
+ * ); // false
216
+ *
217
+ * matchesWire(
218
+ * {
219
+ * clauses: [
220
+ * { op: "gte", field: "count", value: 1 },
221
+ * { op: "lt", field: "count", value: 10 },
222
+ * ],
223
+ * },
224
+ * { count: 5 },
225
+ * ); // true
226
+ * ```
227
+ */
228
+ const matchesWire = (wire, doc) => {
229
+ for (const clause of wire.clauses) if (!matchesClause(clause, lookupPath(doc, clause.field))) return false;
230
+ return true;
231
+ };
232
+ const lookupPath = (doc, field) => {
233
+ if (!field.includes(".")) return doc[field];
234
+ const segments = field.split(".");
235
+ let cursor = doc;
236
+ for (const segment of segments) {
237
+ if (cursor === void 0 || cursor === null || typeof cursor !== "object" || Array.isArray(cursor)) return;
238
+ cursor = cursor[segment];
239
+ }
240
+ return cursor;
241
+ };
242
+ const matchesClause = (clause, actual) => {
243
+ switch (clause.op) {
244
+ case "eq": return matchesEq(clause.value, actual);
245
+ case "in": return matchesIn(clause.value, actual);
246
+ case "gt": return compareGT(actual, clause.value, false);
247
+ case "gte": return compareGT(actual, clause.value, true);
248
+ case "lt": return compareLT(actual, clause.value, false);
249
+ case "lte": return compareLT(actual, clause.value, true);
250
+ }
251
+ };
252
+ const matchesEq = (expected, actual) => {
253
+ if (typeof expected === "object") {
254
+ if (actual === void 0 || actual === null || typeof actual !== "object" || Array.isArray(actual)) return false;
255
+ for (const subKey of Object.keys(expected)) {
256
+ const subExpected = expected[subKey];
257
+ if (subExpected === void 0) continue;
258
+ const subActual = actual[subKey];
259
+ if (!matchesEq(subExpected, subActual)) return false;
260
+ }
261
+ return true;
262
+ }
263
+ return expected === actual;
264
+ };
265
+ const matchesIn = (members, actual) => {
266
+ for (const m of members) if (typeof m === "object") {
267
+ if (matchesEq(m, actual)) return true;
268
+ } else if (m === actual) return true;
269
+ return false;
270
+ };
271
+ const compareGT = (actual, bound, inclusive) => {
272
+ if (typeof bound === "string") return typeof actual === "string" && (inclusive ? actual >= bound : actual > bound);
273
+ if (typeof bound === "number") return typeof actual === "number" && (inclusive ? actual >= bound : actual > bound);
274
+ return false;
275
+ };
276
+ const compareLT = (actual, bound, inclusive) => {
277
+ if (typeof bound === "string") return typeof actual === "string" && (inclusive ? actual <= bound : actual < bound);
278
+ if (typeof bound === "number") return typeof actual === "number" && (inclusive ? actual <= bound : actual < bound);
279
+ return false;
280
+ };
281
+ //#endregion
282
+ //#region packages/protocol/src/query/satisfiable.ts
283
+ /**
284
+ * Per-field satisfiability check for a {@link PredicateWire}. Groups
285
+ * clauses by field, then runs the same logic the pre-redesign
286
+ * `assertOpObjectSatisfiable` ran on a single op-object — but
287
+ * generalised across N clauses on the same field (the wire merger
288
+ * concatenates lists without coalescing).
289
+ *
290
+ * Triggers:
291
+ * - Two `eq` clauses on the same field with different values →
292
+ * `InvalidConfig` (the same conflict that pre-redesign
293
+ * `mergePredicates` threw on shared primitive keys).
294
+ * - Range bounds with `lo > hi` (or `lo == hi` with strict on
295
+ * either side) → `UnsatisfiablePredicate`.
296
+ * - `eq` value outside the residual range interval or absent from
297
+ * every `in` set on the same field → `UnsatisfiablePredicate`.
298
+ * - `in` sets that intersect to empty across multiple clauses →
299
+ * `UnsatisfiablePredicate`.
300
+ *
301
+ * Used by both `./validate.ts` (wire-arrival check) and
302
+ * `./merge.ts` (post-merge re-check, kept in lockstep).
303
+ */
304
+ const groupByField = (wire) => {
305
+ const out = /* @__PURE__ */ new Map();
306
+ for (const clause of wire.clauses) {
307
+ let group = out.get(clause.field);
308
+ if (group === void 0) {
309
+ group = {
310
+ eqs: [],
311
+ ins: []
312
+ };
313
+ out.set(clause.field, group);
314
+ }
315
+ applyClause(group, clause.field, clause);
316
+ }
317
+ return out;
318
+ };
319
+ const applyClause = (group, field, clause) => {
320
+ switch (clause.op) {
321
+ case "eq":
322
+ group.eqs.push(clause.value);
323
+ return;
324
+ case "in":
325
+ group.ins.push(clause.value);
326
+ return;
327
+ case "gt":
328
+ tightenLower(group, field, clause.value, false);
329
+ return;
330
+ case "gte":
331
+ tightenLower(group, field, clause.value, true);
332
+ return;
333
+ case "lt":
334
+ tightenUpper(group, field, clause.value, false);
335
+ return;
336
+ case "lte":
337
+ tightenUpper(group, field, clause.value, true);
338
+ return;
339
+ }
340
+ };
341
+ const tightenLower = (group, field, value, inclusive) => {
342
+ if (group.lo === void 0) {
343
+ group.lo = {
344
+ value,
345
+ inclusive
346
+ };
347
+ return;
348
+ }
349
+ if (!sameComparableType(group.lo.value, value)) throw new BaerlyError("UnsatisfiablePredicate", `Predicate on field ${formatPath([field])} has type-incompatible lower bounds (${JSON.stringify(group.lo.value)} vs ${JSON.stringify(value)}).`);
350
+ const c = compareScalar(group.lo.value, value);
351
+ if (c < 0 || c === 0 && inclusive === false && group.lo.inclusive === true) group.lo = {
352
+ value,
353
+ inclusive
354
+ };
355
+ };
356
+ const tightenUpper = (group, field, value, inclusive) => {
357
+ if (group.hi === void 0) {
358
+ group.hi = {
359
+ value,
360
+ inclusive
361
+ };
362
+ return;
363
+ }
364
+ if (!sameComparableType(group.hi.value, value)) throw new BaerlyError("UnsatisfiablePredicate", `Predicate on field ${formatPath([field])} has type-incompatible upper bounds (${JSON.stringify(group.hi.value)} vs ${JSON.stringify(value)}).`);
365
+ const c = compareScalar(group.hi.value, value);
366
+ if (c > 0 || c === 0 && inclusive === false && group.hi.inclusive === true) group.hi = {
367
+ value,
368
+ inclusive
369
+ };
370
+ };
371
+ const intersectInSets = (sets) => {
372
+ if (sets.length === 0) return [];
373
+ let acc = sets[0];
374
+ for (let i = 1; i < sets.length; i++) {
375
+ const next = [];
376
+ for (const a of acc) for (const b of sets[i]) if (deepEqualDocumentValue(a, b)) {
377
+ next.push(a);
378
+ break;
379
+ }
380
+ acc = next;
381
+ }
382
+ return acc;
383
+ };
384
+ /**
385
+ * Check that every per-field clause group on `wire` is jointly
386
+ * satisfiable. Throws `BaerlyError{code:"UnsatisfiablePredicate"}`
387
+ * (or `"InvalidConfig"` for conflicting `eq` clauses) on the
388
+ * first contradiction. Returns `void` on success.
389
+ */
390
+ const assertWireSatisfiable = (wire) => {
391
+ const groups = groupByField(wire);
392
+ for (const [field, group] of groups) {
393
+ if (group.eqs.length > 1) {
394
+ for (let i = 1; i < group.eqs.length; i++) if (!deepEqualDocumentValue(group.eqs[0], group.eqs[i])) throw new BaerlyError("InvalidConfig", `Conflicting equality clauses on field ${formatPath([field])} (${JSON.stringify(group.eqs[0])} vs ${JSON.stringify(group.eqs[i])}). Predicate chains must agree on shared equality.`);
395
+ }
396
+ const eq = group.eqs[0];
397
+ if (group.lo !== void 0 && group.hi !== void 0 && sameComparableType(group.lo.value, group.hi.value)) {
398
+ const c = compareScalar(group.lo.value, group.hi.value);
399
+ if (c > 0 || c === 0 && (!group.lo.inclusive || !group.hi.inclusive)) throw new BaerlyError("UnsatisfiablePredicate", `Predicate on field ${formatPath([field])} has empty interval (lo=${JSON.stringify(group.lo.value)} ${group.lo.inclusive ? "gte" : "gt"}, hi=${JSON.stringify(group.hi.value)} ${group.hi.inclusive ? "lte" : "lt"}).`);
400
+ }
401
+ if (eq !== void 0) {
402
+ if (group.lo !== void 0) {
403
+ if (!sameComparableType(eq, group.lo.value)) throw new BaerlyError("UnsatisfiablePredicate", `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with lower bound ${JSON.stringify(group.lo.value)} (${typeof group.lo.value}); range ops require matching primitive types.`);
404
+ const c = compareScalar(eq, group.lo.value);
405
+ if (c < 0 || c === 0 && !group.lo.inclusive) throw new BaerlyError("UnsatisfiablePredicate", `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by lower bound ${JSON.stringify(group.lo.value)} (${group.lo.inclusive ? "gte" : "gt"}).`);
406
+ }
407
+ if (group.hi !== void 0) {
408
+ if (!sameComparableType(eq, group.hi.value)) throw new BaerlyError("UnsatisfiablePredicate", `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with upper bound ${JSON.stringify(group.hi.value)} (${typeof group.hi.value}); range ops require matching primitive types.`);
409
+ const c = compareScalar(eq, group.hi.value);
410
+ if (c > 0 || c === 0 && !group.hi.inclusive) throw new BaerlyError("UnsatisfiablePredicate", `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by upper bound ${JSON.stringify(group.hi.value)} (${group.hi.inclusive ? "lte" : "lt"}).`);
411
+ }
412
+ if (group.ins.length > 0) for (const set of group.ins) {
413
+ let found = false;
414
+ for (const m of set) if (deepEqualDocumentValue(eq, m)) {
415
+ found = true;
416
+ break;
417
+ }
418
+ if (!found) throw new BaerlyError("UnsatisfiablePredicate", `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} not present in in() set.`);
419
+ }
420
+ }
421
+ if (group.ins.length > 1) {
422
+ if (intersectInSets(group.ins).length === 0) throw new BaerlyError("UnsatisfiablePredicate", `Predicate on field ${formatPath([field])} has empty in() intersection across multiple clauses.`);
423
+ }
424
+ }
425
+ };
426
+ //#endregion
427
+ //#region packages/protocol/src/query/validate.ts
428
+ /**
429
+ * Wire predicate validator. Walks a {@link PredicateWire} and throws
430
+ * on a structurally bad clause (`BaerlyError{code:"InvalidConfig"}`)
431
+ * or a per-field clause group that contradicts itself
432
+ * (`BaerlyError{code:"UnsatisfiablePredicate"}`).
433
+ *
434
+ * The object-form normaliser at `./normalize.ts` enforces shape on
435
+ * the way in (rejecting `$`-keys / non-scalars / null / undefined);
436
+ * the callback builder at `./builder.ts` enforces shape via the
437
+ * type system. This validator is the wire-arrival check: it runs
438
+ * over already-normalised clauses, defending against raw-`fetch`
439
+ * callers who bypass the typed seam and submit arbitrary JSON.
440
+ *
441
+ * Companion modules: `./matches.ts` (evaluator), `./merge.ts`
442
+ * (AND-merge). Shared helpers live in `./_internals.ts`.
443
+ */
444
+ const OP_NAMES = [
445
+ "eq",
446
+ "gt",
447
+ "gte",
448
+ "lt",
449
+ "lte",
450
+ "in"
451
+ ];
452
+ const RANGE_OPS = [
453
+ "gt",
454
+ "gte",
455
+ "lt",
456
+ "lte"
457
+ ];
458
+ /**
459
+ * Validate a normalised predicate wire. Throws
460
+ * `BaerlyError{code:"InvalidConfig"}` on a structurally bad clause,
461
+ * or `BaerlyError{code:"UnsatisfiablePredicate"}` when a clause
462
+ * group on one field contradicts itself.
463
+ *
464
+ * Returns the wire unchanged on success — callers can thread the
465
+ * validated wire forward.
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * validateWire({ clauses: [{ op: "eq", field: "status", value: "open" }] }); // ok
470
+ * validateWire({ clauses: [{ op: "in", field: "priority", value: [] }] }); // throws UnsatisfiablePredicate
471
+ * validateWire({ clauses: [{ op: "eq", field: "_id", value: "x" }] }); // throws InvalidConfig (top-level _id)
472
+ * ```
473
+ */
474
+ const validateWire = (wire) => {
475
+ if (wire === null || typeof wire !== "object" || !Array.isArray(wire.clauses)) throw new BaerlyError("InvalidConfig", `Predicate wire must be an object with a "clauses" array.`);
476
+ for (let i = 0; i < wire.clauses.length; i++) validateClause(wire.clauses[i], i);
477
+ assertWireSatisfiable(wire);
478
+ return wire;
479
+ };
480
+ const validateClause = (clause, index) => {
481
+ if (clause === null || typeof clause !== "object") throw new BaerlyError("InvalidConfig", `Predicate clause at index ${index} must be an object — got ${JSON.stringify(clause)}.`);
482
+ const { op, field, value } = clause;
483
+ if (typeof op !== "string" || !OP_NAMES.includes(op)) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${index} has unsupported op ${JSON.stringify(op)} — supported: ${OP_NAMES.join(" / ")}.`);
484
+ if (typeof field !== "string" || field.length === 0) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${index} has empty / non-string field.`);
485
+ if (field === "_id" || field.startsWith("_id.")) throw new BaerlyError("InvalidConfig", "Predicates may not key on \"_id\"; use .get(id) / .update(id, patch) / .replace(id, doc) / .delete(id) instead.");
486
+ if (op === "in") {
487
+ if (!Array.isArray(value)) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${index} (op="in", field=${JSON.stringify(field)}) must carry an array value.`);
488
+ if (value.length === 0) throw new BaerlyError("UnsatisfiablePredicate", `Predicate clause at index ${index} (op="in", field=${JSON.stringify(field)}) has empty value array — no document can match.`);
489
+ for (let i = 0; i < value.length; i++) validateMemberValue(value[i], field, index, i);
490
+ return;
491
+ }
492
+ if (Array.isArray(value)) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${index} (op=${JSON.stringify(op)}, field=${JSON.stringify(field)}) must carry a primitive value, got an array — only op="in" accepts arrays.`);
493
+ if (RANGE_OPS.includes(op)) {
494
+ validateRangeBound(value, field, index);
495
+ return;
496
+ }
497
+ validateScalar(value, field, index);
498
+ };
499
+ const validateMemberValue = (value, field, clauseIndex, memberIndex) => {
500
+ if (value === null || value === void 0) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${clauseIndex} (op="in", field=${JSON.stringify(field)}) member ${memberIndex} is ${value === null ? "null" : "undefined"} — members must be string / number / boolean / nested object.`);
501
+ if (Array.isArray(value)) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${clauseIndex} (op="in", field=${JSON.stringify(field)}) member ${memberIndex} is an array — members must be string / number / boolean / nested object.`);
502
+ const t = typeof value;
503
+ if (t === "object") return;
504
+ if (t !== "string" && t !== "number" && t !== "boolean") throw new BaerlyError("InvalidConfig", `Predicate clause at index ${clauseIndex} (op="in", field=${JSON.stringify(field)}) member ${memberIndex} has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`);
505
+ if (t === "number" && !Number.isFinite(value)) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${clauseIndex} (op="in", field=${JSON.stringify(field)}) member ${memberIndex} is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`);
506
+ };
507
+ const validateScalar = (value, field, clauseIndex) => {
508
+ if (value === null || value === void 0) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${value === null ? "null" : "undefined"} — terminal values must be string / number / boolean / nested object.`);
509
+ const t = typeof value;
510
+ if (t === "object") return;
511
+ if (t !== "string" && t !== "number" && t !== "boolean") throw new BaerlyError("InvalidConfig", `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`);
512
+ if (t === "number" && !Number.isFinite(value)) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`);
513
+ };
514
+ const validateRangeBound = (value, field, clauseIndex) => {
515
+ if (value === null || value === void 0) throw new BaerlyError("InvalidConfig", `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${value === null ? "null" : "undefined"} — range bounds must be string or finite number.`);
516
+ const t = typeof value;
517
+ if (t === "boolean") throw new BaerlyError("InvalidConfig", `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a boolean — range bounds must be string or finite number (booleans are not ordered).`);
518
+ if (t === "object") throw new BaerlyError("InvalidConfig", `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a nested object — range bounds must be string or finite number.`);
519
+ if (t !== "string" && t !== "number") throw new BaerlyError("InvalidConfig", `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) has unsupported type ${JSON.stringify(t)} — must be string or finite number.`);
520
+ if (t === "number" && !Number.isFinite(value)) throw new BaerlyError("InvalidConfig", `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`);
521
+ };
522
+ //#endregion
523
+ //#region packages/protocol/src/hashing.ts
524
+ /**
525
+ * Width of the {@link ContentVersionId} hex strings produced by
526
+ * {@link versionFromContent}. 32 hex chars = 128 bits, matching the
527
+ * information content of a v4 UUID. Birthday-bound collision probability
528
+ * at N=10⁹ writes is ~1.5 × 10⁻²¹ (≈ N² / 2¹²⁹); ample for a
529
+ * content-addressed version id. A collision is not detected at runtime —
530
+ * two distinct bodies that share a truncated hash would alias to the same
531
+ * content key, so a reader could observe the wrong body. The bound above
532
+ * is the sole guard, and it sits far below any plausible write volume.
533
+ *
534
+ * @see docs/spec/log-entry-shape.md §"Content body layout"
535
+ */
536
+ const VERSION_HEX_LENGTH = 32;
537
+ /**
538
+ * Content-addressed {@link ContentVersionId}: SHA-256 of `body`,
539
+ * lowercase hex, truncated to {@link VERSION_HEX_LENGTH}. Same body
540
+ * bytes ⇒ same ContentVersionId — scoped to **single-writer idempotent
541
+ * replay** (a crash-recovery rewrite of the same in-memory value by the
542
+ * same writer reproduces the content key the manifest already
543
+ * referenced). `body` is non-canonical (`JSON.stringify`, insertion
544
+ * key order — see `encodeJsonBytes`), so this is NOT cross-writer
545
+ * content dedup: different key order ⇒ different key for an equal value.
546
+ *
547
+ * Async because {@link crypto.subtle.digest} returns an `ArrayBuffer`
548
+ * via Promise. Workers and browsers both expose `crypto.subtle`
549
+ * synchronously enough that the await fits naturally in the write
550
+ * pipeline.
551
+ *
552
+ * @see docs/spec/log-entry-shape.md §"Content body layout"
553
+ */
554
+ const versionFromContent = async (body) => {
555
+ const view = new Uint8Array(body.byteLength);
556
+ view.set(body);
557
+ const digest = await crypto.subtle.digest("SHA-256", view);
558
+ const bytes = new Uint8Array(digest);
559
+ let hex = "";
560
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
561
+ return hex.slice(0, VERSION_HEX_LENGTH);
562
+ };
563
+ //#endregion
564
+ //#region packages/protocol/src/snapshot-hash.ts
565
+ /**
566
+ * SHA-256 of `bytes` as a 64-char lowercase hex string. Used to seal
567
+ * snapshot filenames so a crashed mid-PUT can't produce a body that
568
+ * readers consume as truth: the filename embeds the hash; readers
569
+ * recompute on load and reject any mismatch as "file missing."
570
+ *
571
+ * Distinct from {@link versionFromContent} (truncated to 32 chars for
572
+ * content keys) — snapshot bodies are larger and longer-lived;
573
+ * 256-bit collision resistance matters here.
574
+ */
575
+ const snapshotHash = async (bytes) => {
576
+ const view = new Uint8Array(bytes.byteLength);
577
+ view.set(bytes);
578
+ const digest = await crypto.subtle.digest("SHA-256", view);
579
+ const out = new Uint8Array(digest);
580
+ let hex = "";
581
+ for (let i = 0; i < out.length; i++) hex += out[i].toString(16).padStart(2, "0");
582
+ return hex;
583
+ };
584
+ //#endregion
585
+ //#region packages/server/src/names.ts
586
+ /** Reject names in the system-reserved leading-"_" namespace. See docs/adr/007-layout-versioning-cordon.md. */
587
+ const assertNameNotReserved = (name, context) => {
588
+ 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.`);
589
+ };
590
+ //#endregion
591
+ //#region packages/server/src/indexes.ts
592
+ /**
593
+ * Secondary indexes — declarative collection-config-driven
594
+ * index entries that the writer emits inside the same CAS fence as
595
+ * the log entry and content body.
596
+ *
597
+ * The {@link IndexDefinition} TYPE lives in `@baerly/protocol`
598
+ * (cross-platform). This module owns the runtime helpers that
599
+ * operate on that shape:
600
+ *
601
+ * - {@link validateIndexDefinition} — synchronous schema check
602
+ * for path-segment safety; thrown at `Writer` construction.
603
+ * - {@link encodeIndexValue} — value-order-preserving base-32 of a
604
+ * type-tagged byte stream (null/bool tag-only, numbers as sortable
605
+ * IEEE 754, strings as raw UTF-8, objects as `JSON.stringify`
606
+ * bytes for equality only).
607
+ * - {@link indexKeyFor} / {@link indexKeyPrefix} — the wire-key
608
+ * shape consumed by the writer's index PUTs and the rebuild
609
+ * command's idempotent reconciliation.
610
+ * - {@link projectIndexValues} / {@link allIndexKeysFor} — pure
611
+ * projections from a doc body to the set of index keys it
612
+ * produces under a collection's declared indexes.
613
+ *
614
+ * Wire shape (single-field):
615
+ *
616
+ * `<logPrefix>/index/<indexName>/<value-b32>/<docId>.json`
617
+ *
618
+ * Wire shape (composite — accepted by the encoder, not consulted by
619
+ * the read path today):
620
+ *
621
+ * `<logPrefix>/index/<indexName>/<a-b32>/<b-b32>/<docId>.json`
622
+ *
623
+ * Body is zero bytes. Each entry is a fact ("doc `<docId>` has
624
+ * `<field> = <value>`"), not data. Readers list the prefix, extract
625
+ * the doc id from each key, then issue a content GET on each.
626
+ *
627
+ * Encoding is RFC-4648 base-32 (lowercase alphabet `[0-9a-v]`,
628
+ * matching `packages/protocol/src/log.ts:str2uintDesc` style) on a
629
+ * type-tagged byte stream (see {@link encodeIndexValue}) so that:
630
+ *
631
+ * - String "5" and number 5 produce distinct encodings
632
+ * (type-tag prefix keeps the slots disjoint).
633
+ * - Equal-by-value inputs produce byte-equal segments.
634
+ * - Lex order under storage `list(prefix)` matches value order:
635
+ * `null < false < true < number < string < object`, with
636
+ * numeric values ordered by IEEE 754 magnitude (range walks
637
+ * and `$in` walks over numeric fields are first-class — no
638
+ * planner fall-back to full-scan).
639
+ *
640
+ * Locked: single-field indexes only on the read path. Composite
641
+ * shape is documented and reserved (the path encoder accepts it).
642
+ *
643
+ * @see docs/spec/sync-protocol.md — fence model these PUTs land
644
+ * inside (between log PUT and `current.json` CAS-advance).
645
+ */
646
+ /** Path-safe segment name. */
647
+ const INDEX_NAME_RE = /^[a-z][a-z0-9_]*$/;
648
+ /**
649
+ * Lowercase base-32 alphabet, RFC 4648 variant matching the
650
+ * `packages/protocol/src/log.ts:str2uintDesc` style (`[0-9a-v]`).
651
+ * Lex-order-preserving under storage `list(prefix)` semantics.
652
+ */
653
+ const B32_ALPHABET = "0123456789abcdefghijklmnopqrstuv";
654
+ /**
655
+ * Reject malformed {@link IndexDefinition} shapes synchronously, at
656
+ * writer construction. See docs/adr/007-layout-versioning-cordon.md.
657
+ *
658
+ * @throws BaerlyError code="InvalidConfig" — reserved leading-`_` `name`.
659
+ * @throws BaerlyError code="SchemaError" — `name` fails the regex, or `on` is empty.
660
+ */
661
+ const validateIndexDefinition = (def) => {
662
+ assertNameNotReserved(def.name, "index.name");
663
+ 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)}`);
664
+ if (typeof def.on === "string") {
665
+ if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty`);
666
+ } else if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty array`);
667
+ if (def.predicate !== void 0) try {
668
+ validateWire(def.predicate);
669
+ } catch (error) {
670
+ if (error instanceof BaerlyError) throw new BaerlyError("SchemaError", `index ${def.name}.predicate is invalid: ${error.message}`, error);
671
+ throw error;
672
+ }
673
+ };
674
+ /**
675
+ * Type-tag bytes for the value-order-preserving wire format. The
676
+ * tag is the LEADING byte of the encoded payload; the values are
677
+ * picked so the type order under byte-wise lex is
678
+ * `null < false < true < number < string < object`.
679
+ *
680
+ * | Type | Byte-prefix | Payload |
681
+ * |---------|-------------|----------------------------------------------------|
682
+ * | null | 0x10 | (none) |
683
+ * | false | 0x20 | (none) |
684
+ * | true | 0x21 | (none) |
685
+ * | number | 0x30 | 8-byte sortable big-endian IEEE 754 |
686
+ * | string | 0x40 | UTF-8 bytes of the string (no quotes, no escapes) |
687
+ * | object | 0x50 | UTF-8 bytes of `JSON.stringify(v)` |
688
+ *
689
+ * Local to the encoder by design — these are wire shape, not
690
+ * cross-package protocol constants (see `CLAUDE.md` § "Magic
691
+ * values").
692
+ */
693
+ const TYPE_NULL = 16;
694
+ const TYPE_FALSE = 32;
695
+ const TYPE_TRUE = 33;
696
+ const TYPE_NUMBER = 48;
697
+ const TYPE_STRING = 64;
698
+ const TYPE_OBJECT = 80;
699
+ /**
700
+ * Encode a JS double as an 8-byte big-endian sortable IEEE 754
701
+ * payload. Byte-wise lex order on the result matches numeric order
702
+ * across all finite doubles plus `±Infinity`:
703
+ *
704
+ * 1. Get the 8-byte big-endian view of the double.
705
+ * 2. If the sign bit is `0` (zero or positive), flip the sign bit
706
+ * (XOR `0x80` on byte 0) so positives sort above negatives.
707
+ * 3. If the sign bit is `1` (negative), flip every bit in all 8
708
+ * bytes so more-negative sorts lower.
709
+ *
710
+ * `NaN` has no order-preserving slot and is rejected — see the
711
+ * `encodeIndexValue` JSDoc for the wire-contract rationale.
712
+ * `-0` and `+0` collapse because the `n === 0 ? 0 : n` coercion below
713
+ * forces both into the positive-zero branch before `setFloat64`.
714
+ */
715
+ const encodeNumberPayload = (n) => {
716
+ if (Number.isNaN(n)) throw new BaerlyError("SchemaError", `encodeIndexValue: NaN is not indexable (the byte encoding has no order-preserving slot for it)`);
717
+ const buf = /* @__PURE__ */ new ArrayBuffer(8);
718
+ new DataView(buf).setFloat64(0, n === 0 ? 0 : n, false);
719
+ const bytes = new Uint8Array(buf);
720
+ if ((bytes[0] & 128) === 0) bytes[0] = bytes[0] ^ 128;
721
+ else for (let i = 0; i < 8; i++) bytes[i] = bytes[i] ^ 255;
722
+ return bytes;
723
+ };
724
+ /**
725
+ * Compose the typed byte stream for one value. The leading byte is
726
+ * the type tag (see {@link TYPE_NULL} et al.); the payload shape is
727
+ * type-dependent. Strings are emitted as their raw UTF-8 bytes (no
728
+ * JSON quoting / escaping) so byte-wise lex order on encoded strings
729
+ * matches byte-wise lex order on the source UTF-8. Objects fall back
730
+ * to `JSON.stringify` for equality only.
731
+ */
732
+ const encodeBytes = (v) => {
733
+ if (v === null || v === void 0) return new Uint8Array([TYPE_NULL]);
734
+ if (v === false) return new Uint8Array([TYPE_FALSE]);
735
+ if (v === true) return new Uint8Array([TYPE_TRUE]);
736
+ if (typeof v === "number") {
737
+ const payload = encodeNumberPayload(v);
738
+ const out = new Uint8Array(1 + payload.length);
739
+ out[0] = TYPE_NUMBER;
740
+ out.set(payload, 1);
741
+ return out;
742
+ }
743
+ if (typeof v === "string") {
744
+ const utf8 = new TextEncoder().encode(v);
745
+ const out = new Uint8Array(1 + utf8.length);
746
+ out[0] = TYPE_STRING;
747
+ out.set(utf8, 1);
748
+ return out;
749
+ }
750
+ const utf8 = encodeJsonBytes(v);
751
+ const out = new Uint8Array(1 + utf8.length);
752
+ out[0] = TYPE_OBJECT;
753
+ out.set(utf8, 1);
754
+ return out;
755
+ };
756
+ /**
757
+ * Encode an arbitrary `DocumentValue` value as a path-safe segment.
758
+ *
759
+ * Type-tagged byte stream, base-32-encoded for path safety. Lex
760
+ * order on encoded bytes matches:
761
+ *
762
+ * - **Type order**: `null < false < true < number < string < object`.
763
+ * - **Within numbers**: IEEE 754 numeric order (sortable
764
+ * big-endian payload, sign-bit-flipped or all-bits-flipped).
765
+ * `-Infinity` sorts lowest, `+Infinity` highest.
766
+ * - **Within strings**: UTF-8 byte order.
767
+ * - **Within objects**: byte-equality only (still
768
+ * `JSON.stringify`-insertion-order dependent).
769
+ *
770
+ * Numbers ARE range-safe under this encoder — `9` sorts below `10`
771
+ * as expected. The query planner's old
772
+ * `numeric-range-on-byte-encoder` guard has been removed; range
773
+ * walks and `$in` walks over numeric fields are routed normally.
774
+ *
775
+ * `NaN` throws `BaerlyError{code:"SchemaError"}` at write time —
776
+ * the byte encoding has no order-preserving slot for it, and a
777
+ * silent collapse to the `null` key (as the prior
778
+ * `JSON.stringify`-based encoder did, since
779
+ * `JSON.stringify(NaN) === "null"`) is a worse failure mode than
780
+ * a loud reject.
781
+ *
782
+ * `-0` and `+0` collapse to the same encoding.
783
+ *
784
+ * Equal-by-value inputs (e.g. two `{a:1, b:2}` objects with the
785
+ * same key insertion order) produce byte-equal segments;
786
+ * structurally-different but visually-similar inputs (`"5"` vs `5`)
787
+ * are kept apart by the type-tag prefix.
788
+ *
789
+ * String ranges remain safe: `"2026-05-13" < "2026-05-14"`
790
+ * byte-wise matches semantic order. ISO 8601 timestamps,
791
+ * alphabetical priorities like `"p1"/"p2"/"p3"`, and any
792
+ * fixed-width string encoding are usable as range-walked indexed
793
+ * fields.
794
+ */
795
+ const encodeIndexValue = (v) => {
796
+ const bytes = encodeBytes(v);
797
+ let out = "";
798
+ let bits = 0;
799
+ let value = 0;
800
+ for (const b of bytes) {
801
+ value = value << 8 | b;
802
+ bits += 8;
803
+ while (bits >= 5) {
804
+ bits -= 5;
805
+ out += B32_ALPHABET[value >> bits & 31];
806
+ }
807
+ }
808
+ if (bits > 0) out += B32_ALPHABET[value << 5 - bits & 31];
809
+ return out;
810
+ };
811
+ /**
812
+ * Storage `list(prefix)` boundary for every entry under one index
813
+ * of a collection: `<logPrefix>/index/<name>/`. Used by the rebuild
814
+ * command's reconciliation walk and by the read-path index hint.
815
+ */
816
+ const indexKeyPrefix = (logPrefix, indexName) => `${logPrefix}/index/${indexName}/`;
817
+ /**
818
+ * Build the per-doc index key for one `(def, values, docId)`.
819
+ *
820
+ * Single-field: `<logPrefix>/index/<name>/<v0-b32>/<docId>.json`.
821
+ * Composite: `<logPrefix>/index/<name>/<v0-b32>/<v1-b32>/.../<docId>.json`.
822
+ *
823
+ * Composite shape is accepted but the read path today only
824
+ * consults single-field entries.
825
+ */
826
+ const indexKeyFor = (logPrefix, def, values, docId) => {
827
+ const segments = values.map(encodeIndexValue).join("/");
828
+ return `${logPrefix}/index/${def.name}/${segments}/${docId}.json`;
829
+ };
830
+ /**
831
+ * Project the value tuple a doc body produces under one index
832
+ * definition. Returns `undefined` when any indexed field is
833
+ * null / undefined / missing — no index entry for that doc under
834
+ * that index (SQL "NULL values don't enter the index" semantics).
835
+ *
836
+ * @throws BaerlyError code="SchemaError" — `on` contains a dotted
837
+ * path, or the indexed field's value is an array. Both restrictions
838
+ * are pre-launch; multi-value (array) indexes are a follow-up.
839
+ */
840
+ const projectIndexValues = (def, body) => {
841
+ if (body === void 0) return;
842
+ const fields = typeof def.on === "string" ? [def.on] : def.on;
843
+ const values = [];
844
+ for (const field of fields) {
845
+ if (field.includes(".")) throw new BaerlyError("SchemaError", `index ${def.name}: dotted-path "on" fields not yet supported (got ${JSON.stringify(field)})`);
846
+ const v = body[field];
847
+ if (v === null || v === void 0) return;
848
+ if (Array.isArray(v)) throw new BaerlyError("SchemaError", `index ${def.name}: cannot index array field "${field}" — multi-value indexes are not supported yet`);
849
+ values.push(v);
850
+ }
851
+ return values;
852
+ };
853
+ /**
854
+ * Compute the full index-key set a single doc produces under every
855
+ * declared index of its collection. Skips indexes whose projection
856
+ * yields `undefined` (null/missing indexed field). Used by both
857
+ * the writer (to PUT new keys) and the rebuild command (to compute
858
+ * the expected key set across the live doc map).
859
+ *
860
+ * Filter-aware (T4): when `def.predicate !== undefined`, the doc
861
+ * must satisfy `matchesWire(def.predicate, body)` or the def contributes
862
+ * zero keys. The writer's diff `oldKeys` vs `newKeys` then covers
863
+ * all four U-quadrants automatically — see the JSDoc on
864
+ * `writer.ts` above the index-emission block. `body ===
865
+ * undefined` short-circuits ahead of the filter check (no keys for
866
+ * an unknown pre-image, regardless of filter), preserving the prior
867
+ * D-quadrant behaviour.
868
+ */
869
+ const allIndexKeysFor = (logPrefix, defs, body, docId) => {
870
+ const keys = [];
871
+ for (const def of defs) {
872
+ if (def.predicate !== void 0 && body !== void 0) {
873
+ if (!matchesWire(def.predicate, body)) continue;
874
+ }
875
+ const values = projectIndexValues(def, body);
876
+ if (values !== void 0) keys.push(indexKeyFor(logPrefix, def, values, docId));
877
+ }
878
+ return keys;
879
+ };
880
+ //#endregion
881
+ //#region packages/server/src/log-walk.ts
882
+ /**
883
+ * Shared log-walk primitives consumed by the read path (`query.ts`),
884
+ * the compactor (`compactor.ts`), and the optional integrity walk in
885
+ * `Writer.#singleAttemptCommit` (`writer.ts`).
886
+ *
887
+ * Two operations: read one log entry, or walk a contiguous range of
888
+ * log entries with bounded parallelism. Each kernel call site
889
+ * previously inlined the same range-build + unbounded `Promise.all`
890
+ * pattern; on a free-tier collection where the compactor lags the
891
+ * tail to 50-100 entries, that fans out 50-100 concurrent GETs per
892
+ * call — and a contended writer multiplies that by the CAS retry
893
+ * budget. `walkLogRange` caps concurrency at
894
+ * {@link MAX_PARALLEL_LOG_READS} so a single call costs at most that
895
+ * many simultaneous GETs against the storage backend.
896
+ *
897
+ * Order invariant: results are returned in seq order regardless of
898
+ * resolution order. The read-side fold is order-sensitive (`U` then
899
+ * `D` on the same doc must apply in that order); callers may iterate
900
+ * the returned array as-is.
901
+ *
902
+ * Signal invariant: when the caller's `AbortSignal` fires, no further
903
+ * chunks dispatch. In-flight reads see the signal via the underlying
904
+ * `Storage.get` call.
905
+ */
906
+ /**
907
+ * Fetch a single log entry. Centralises the "missing entry inside the
908
+ * visible log range is a protocol-invariant violation" rule used by
909
+ * every caller.
910
+ *
911
+ * @throws BaerlyError code="Internal" when the key resolves to no
912
+ * body — a hole inside `[log_seq_start, next_seq)` is a corruption
913
+ * the kernel can't continue past.
914
+ * @throws BaerlyError code="InvalidResponse" when the body isn't
915
+ * valid JSON.
916
+ */
917
+ const readLogEntry = async (storage, key, opts) => {
918
+ return (await readLogEntryWithBytes(storage, key, opts)).entry;
919
+ };
920
+ /**
921
+ * Like {@link readLogEntry}, but also surfaces `bytes` — the
922
+ * byteLength of the STORED log-object body exactly as it was GET back
923
+ * from storage (`got.body.byteLength`).
924
+ *
925
+ * The compactor uses this to subtract from `current.json.tail_bytes`
926
+ * the EXACT bytes the writer PUT for the folded slice. The writer
927
+ * accumulated `encodeJsonBytes(entry).byteLength` per committed entry
928
+ * (`writer.ts` Step 6); the stored body IS those bytes, so summing
929
+ * `got.body.byteLength` over the folded range == the writer's
930
+ * accumulated total for that range — no re-encode, no round-trip
931
+ * assumption (a re-encode of the parsed `LogEntry` could drift if
932
+ * key-order/whitespace ever diverged from what was PUT).
933
+ *
934
+ * Same error semantics as {@link readLogEntry}.
935
+ */
936
+ const readLogEntryWithBytes = async (storage, key, opts) => {
937
+ const got = await storage.get(key, opts?.signal !== void 0 ? { signal: opts.signal } : void 0);
938
+ if (got === null) throw new BaerlyError("Internal", `log-walk: missing log entry at ${key}; protocol invariant violation`);
939
+ try {
940
+ return {
941
+ entry: decodeJsonBytes(got.body),
942
+ bytes: got.body.byteLength
943
+ };
944
+ } catch (error) {
945
+ throw new BaerlyError("InvalidResponse", `log-walk: malformed log entry at ${key}`, error);
946
+ }
947
+ };
948
+ /**
949
+ * Walk `[fromSeq, toSeqExclusive)` of `${logPrefix}/log/<seq>.json`
950
+ * in chunks of {@link MAX_PARALLEL_LOG_READS} concurrent GETs.
951
+ * Returns the materialised entries in seq order.
952
+ *
953
+ * Empty range (`fromSeq >= toSeqExclusive`) returns `[]` and issues
954
+ * zero GETs.
955
+ *
956
+ * Same error semantics as {@link readLogEntry}: a missing entry
957
+ * throws `Internal`, a malformed body throws `InvalidResponse`.
958
+ */
959
+ const walkLogRange = async (storage, logPrefix, fromSeq, toSeqExclusive, opts) => {
960
+ return (await walkLogRangeWithBytes(storage, logPrefix, fromSeq, toSeqExclusive, opts)).map((r) => r.entry);
961
+ };
962
+ /**
963
+ * Like {@link walkLogRange}, but each element also carries `bytes` —
964
+ * the STORED log-object body byteLength (see {@link readLogEntryWithBytes}).
965
+ * Same seq-order, empty-range, error, and bounded-parallelism
966
+ * ({@link MAX_PARALLEL_LOG_READS}) guarantees as {@link walkLogRange};
967
+ * this is the bytes-aware core `walkLogRange` is implemented on top of.
968
+ *
969
+ * The compactor consumes this so it gets BOTH the parsed entries (for
970
+ * the fold) AND the exact byte sum (to decrement `tail_bytes`) from a
971
+ * single walk.
972
+ */
973
+ const walkLogRangeWithBytes = async (storage, logPrefix, fromSeq, toSeqExclusive, opts) => {
974
+ if (fromSeq >= toSeqExclusive) return [];
975
+ const total = toSeqExclusive - fromSeq;
976
+ const out = Array.from({ length: total });
977
+ for (let chunkStart = 0; chunkStart < total; chunkStart += 16) {
978
+ opts?.signal?.throwIfAborted();
979
+ const chunkEnd = Math.min(chunkStart + 16, total);
980
+ const promises = [];
981
+ for (let i = chunkStart; i < chunkEnd; i++) {
982
+ const seq = fromSeq + i;
983
+ promises.push(readLogEntryWithBytes(storage, `${logPrefix}/log/${seq}.json`, opts));
984
+ }
985
+ const results = await Promise.all(promises);
986
+ for (let i = 0; i < results.length; i++) out[chunkStart + i] = results[i];
987
+ }
988
+ return out;
989
+ };
990
+ /**
991
+ * Fold a sequence of `LogEntry` records onto a doc-id-keyed map,
992
+ * applying the protocol's per-doc-replace semantics:
993
+ *
994
+ * - `I` / `U`: when `entry.after !== undefined`, set
995
+ * `map.set(entry.doc_id, entry.after)`. Entries with `after ===
996
+ * undefined` (the partial-merge writer's future patch-only shape)
997
+ * are ignored — today's writer always emits `after`, so this is a
998
+ * forward-compat guard, not a live branch.
999
+ * - `D`: tombstone — `map.delete(entry.doc_id)`.
1000
+ *
1001
+ * Entries whose `collection` does not match `opts.collection`, or
1002
+ * whose `doc_id` is `undefined`, are skipped. When
1003
+ * `opts.docIdFilter` is provided, only entries whose `doc_id` is
1004
+ * present in the filter set are folded — used by the index-walk
1005
+ * read path to scope the fold to the docs the planner already
1006
+ * resolved.
1007
+ *
1008
+ * This is the canonical fold used by the read path
1009
+ * (`query.ts`) and the index reconciler (`rebuild-index.ts`).
1010
+ * Centralising it keeps the
1011
+ * "straight `set` on I/U; tombstone on D" protocol invariant in one place.
1012
+ *
1013
+ * @see ../../../docs/spec/sync-protocol.md
1014
+ */
1015
+ const foldLogEntriesOnto = (map, entries, opts) => {
1016
+ const { collection, docIdFilter } = opts;
1017
+ for (const entry of entries) {
1018
+ if (entry.collection !== collection) continue;
1019
+ if (entry.doc_id === void 0) continue;
1020
+ if (docIdFilter !== void 0 && !docIdFilter.has(entry.doc_id)) continue;
1021
+ switch (entry.op) {
1022
+ case "I":
1023
+ case "U":
1024
+ if (entry.after === void 0) continue;
1025
+ map.set(entry.doc_id, entry.after);
1026
+ break;
1027
+ case "D":
1028
+ map.delete(entry.doc_id);
1029
+ break;
1030
+ }
1031
+ }
1032
+ };
1033
+ const MAX_SEQ = 10 ** 12 - 1;
1034
+ /**
1035
+ * Build the on-bucket key for a snapshot file. `sha256` must be the
1036
+ * lowercase hex digest of the canonical body
1037
+ * ({@link encodeSnapshotBody}); the filename embeds it so a crashed
1038
+ * mid-PUT body that doesn't match its own filename hash is rejected
1039
+ * by readers as "missing."
1040
+ *
1041
+ * @throws BaerlyError code="InvalidConfig" — `minSeq`/`maxSeq` are
1042
+ * out of range or `sha256` is not 64 hex chars.
1043
+ */
1044
+ const snapshotKey = (collectionPrefix, minSeq, maxSeq, sha256) => {
1045
+ if (minSeq < 0 || maxSeq < 0 || minSeq > maxSeq || maxSeq > MAX_SEQ) throw new BaerlyError("InvalidConfig", `snapshotKey: invalid range [${minSeq}, ${maxSeq})`);
1046
+ if (!/^[0-9a-f]{64}$/.test(sha256)) throw new BaerlyError("InvalidConfig", "snapshotKey: sha256 must be 64 hex chars");
1047
+ const pad = (n) => n.toString().padStart(12, "0");
1048
+ return `${collectionPrefix}/snapshot/L9/${pad(minSeq)}-${pad(maxSeq)}-${sha256}.json`;
1049
+ };
1050
+ /**
1051
+ * Canonical byte encoding of a {@link SnapshotBody}. Only the
1052
+ * compactor produces snapshots, and only this function does the
1053
+ * serialisation — so the byte output is deterministic for a given
1054
+ * `SnapshotBody` (identical input ⇒ identical bytes ⇒ identical
1055
+ * filename hash).
1056
+ */
1057
+ const encodeSnapshotBody = (s) => encodeJsonBytes(s);
1058
+ /**
1059
+ * Load a snapshot file as a `Map<_id, DocumentData>`. Verifies the
1060
+ * body hash against the filename, checks the schema version, and
1061
+ * cross-checks `body.collection` against the caller's expectation.
1062
+ *
1063
+ * @example
1064
+ * ```ts
1065
+ * import { loadSnapshotAsMap } from "@gusto/baerly-storage";
1066
+ *
1067
+ * const map =
1068
+ * srcCurrent.snapshot === null
1069
+ * ? new Map<string, DocumentData>()
1070
+ * : await loadSnapshotAsMap(src.storage, srcCurrent.snapshot, "tickets");
1071
+ * ```
1072
+ *
1073
+ * @throws BaerlyError code="Internal" — pointer resolves to no body,
1074
+ * or the body's SHA-256 doesn't match the hash embedded in the
1075
+ * filename. (Protocol invariant violation; a corrupted snapshot
1076
+ * the reader cannot continue past.)
1077
+ * @throws BaerlyError code="InvalidResponse" — body isn't valid JSON,
1078
+ * isn't an object, has an unsupported `schema_version`, or carries a
1079
+ * `collection` that doesn't match `expectedCollection`.
1080
+ */
1081
+ const loadSnapshotAsMap = async (storage, key, expectedCollection, signal) => {
1082
+ const got = await storage.get(key, signal !== void 0 ? { signal } : void 0);
1083
+ if (got === null) throw new BaerlyError("Internal", `compact: snapshot pointer ${key} resolves to no body; protocol violation`);
1084
+ const filename = key.slice(key.lastIndexOf("/") + 1).replace(/\.json$/, "");
1085
+ const lastDash = filename.lastIndexOf("-");
1086
+ const expectedHash = filename.slice(lastDash + 1);
1087
+ const actualHash = await snapshotHash(got.body);
1088
+ if (actualHash !== expectedHash) throw new BaerlyError("Internal", `compact: snapshot ${key} body hash mismatch (got ${actualHash}); protocol violation`);
1089
+ let parsed;
1090
+ try {
1091
+ parsed = decodeJsonBytes(got.body);
1092
+ } catch (error) {
1093
+ throw new BaerlyError("InvalidResponse", `compact: snapshot ${key} body is not valid JSON`, error);
1094
+ }
1095
+ if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `compact: snapshot ${key} body is not an object`);
1096
+ const body = parsed;
1097
+ if (body.schema_version !== 1) throw new BaerlyError("InvalidResponse", `compact: snapshot ${key} has unsupported schema_version ${String(body.schema_version)}`);
1098
+ if (body.collection !== expectedCollection) throw new BaerlyError("InvalidResponse", `compact: snapshot ${key} carries collection ${body.collection}, expected ${expectedCollection}`);
1099
+ const out = /* @__PURE__ */ new Map();
1100
+ for (const row of body.docs) out.set(row._id, row.body);
1101
+ return out;
1102
+ };
1103
+ //#endregion
1104
+ //#region packages/server/src/compactor.ts
1105
+ /**
1106
+ * Compactor: fold a prefix of the live log into a content-
1107
+ * hashed snapshot file and CAS-advance `current.json` to swap the
1108
+ * pointer.
1109
+ *
1110
+ * The hard correctness requirement is **atomic snapshot generation**:
1111
+ * a compactor that crashes mid-write must not leave a corrupted body
1112
+ * that readers consume as truth. The design: every snapshot's filename
1113
+ * embeds the SHA-256 of its body. A crashed mid-PUT leaves a body that
1114
+ * doesn't match its own filename hash, and readers reject it as
1115
+ * "missing." The atomic moment is the CAS-swap of
1116
+ * `current.json.snapshot`, which is a single conditional PUT.
1117
+ *
1118
+ * Order of operations (matches `Writer.commit`'s manifest-first-
1119
+ * REVERSED ordering): PUT snapshot body → CAS-advance `current.json`.
1120
+ * A crash before the swap leaves an orphan snapshot file; the swap
1121
+ * succeeds iff our captured ETag still matches.
1122
+ *
1123
+ * Why level-prefixed chunked snapshots over the alternatives: a
1124
+ * single monolithic snapshot (every compaction rewrites one well-
1125
+ * known key) makes partial writes catastrophic and serializes every
1126
+ * writer on one key. WAL-checkpointing in the rqlite / Raft tradition
1127
+ * requires a consensus layer Baerly doesn't have. The Litestream-
1128
+ * style multi-level scheme — small fixed number of levels, chunked
1129
+ * files keyed by sequence range — keeps random GETs cheap on
1130
+ * S3-compatible storage and avoids LIST. Current ship is single-
1131
+ * level at L9 (one snapshot replaces the prior; no multi-level merge
1132
+ * yet); the key format is forward-compatible with future L0..L9
1133
+ * rolling merges without a wire change.
1134
+ *
1135
+ * @see ../../../docs/spec/sync-protocol.md
1136
+ */
1137
+ const ctxMetrics$2 = () => getCurrentContext()?.recorder ?? noopMetricsRecorder;
1138
+ const DEFAULT_MAX_PER_RUN = Number.MAX_SAFE_INTEGER;
1139
+ const DEFAULT_MIN_TO_COMPACT = 100;
1140
+ const APPLICATION_JSON$1 = "application/json";
1141
+ /**
1142
+ * Fold a prefix of the live log into a new snapshot and CAS-advance
1143
+ * `current.json`. Idempotent: a second run with no new writes is a
1144
+ * no-op (below-min-threshold).
1145
+ *
1146
+ * Single-attempt: on CAS conflict we return
1147
+ * `{written: false, skippedReason: "cas-lost", newSnapshotKey}` — the
1148
+ * caller (the cron handler invoking `runScheduledMaintenance` from
1149
+ * `./maintenance.ts`) decides whether to schedule another run. The
1150
+ * orphan snapshot file just written will be swept by `runGc()`.
1151
+ *
1152
+ * @throws BaerlyError code="InvalidResponse" — `current.json` is
1153
+ * present but malformed, or a snapshot body fails its schema /
1154
+ * collection cross-check.
1155
+ * @throws BaerlyError code="Internal" — protocol-invariant violation:
1156
+ * a log entry missing inside `[log_seq_start, foldEnd)`, or the
1157
+ * prior-snapshot pointer resolves to no body / a body whose hash
1158
+ * doesn't match its filename.
1159
+ *
1160
+ * @example
1161
+ * ```ts
1162
+ * import { compact } from "@gusto/baerly-storage";
1163
+ *
1164
+ * const res = await compact(
1165
+ * { storage, currentJsonKey: "app/x/tenant/t/manifests/tickets/current.json" },
1166
+ * { minEntriesToCompact: 100, maxEntriesPerRun: 40 },
1167
+ * );
1168
+ * if (res.written) console.log("snapshot landed at", res.newSnapshotKey);
1169
+ * ```
1170
+ */
1171
+ const compact = async (args, options = {}) => {
1172
+ const { storage, currentJsonKey } = args;
1173
+ const internal = options;
1174
+ const maxPerRun = internal.maxEntriesPerRun ?? DEFAULT_MAX_PER_RUN;
1175
+ const minToCompact = options.minEntriesToCompact ?? DEFAULT_MIN_TO_COMPACT;
1176
+ const ceilingBytes = internal.ceilingBytes ?? Number.POSITIVE_INFINITY;
1177
+ const ceilingEntries = internal.ceilingEntries ?? Number.POSITIVE_INFINITY;
1178
+ const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf("/"));
1179
+ const collectionName = collectionPrefix.slice(collectionPrefix.lastIndexOf("/") + 1);
1180
+ const read = await readCurrentJson(storage, currentJsonKey, options.signal !== void 0 ? { signal: options.signal } : void 0);
1181
+ if (read === null) return {
1182
+ written: false,
1183
+ skippedReason: "current-json-missing",
1184
+ previousSnapshotKey: null,
1185
+ logSeqStartBefore: 0,
1186
+ logSeqStartAfter: 0,
1187
+ entriesFolded: 0
1188
+ };
1189
+ const current = read.json;
1190
+ const baseEtag = read.etag;
1191
+ const logSeqStartBefore = logSeqStartOf(current);
1192
+ const nextSeq = current.next_seq;
1193
+ if (nextSeq - logSeqStartBefore < minToCompact) return {
1194
+ written: false,
1195
+ skippedReason: "below-min-threshold",
1196
+ previousSnapshotKey: current.snapshot,
1197
+ logSeqStartBefore,
1198
+ logSeqStartAfter: logSeqStartBefore,
1199
+ entriesFolded: 0
1200
+ };
1201
+ const foldEnd = Math.min(nextSeq, logSeqStartBefore + maxPerRun);
1202
+ const base = current.snapshot === null ? /* @__PURE__ */ new Map() : await loadSnapshotAsMap(storage, current.snapshot, collectionName, options.signal);
1203
+ const fetched = await walkLogRangeWithBytes(storage, collectionPrefix, logSeqStartBefore, foldEnd, { signal: options.signal });
1204
+ const foldedSliceBytes = fetched.reduce((sum, f) => sum + f.bytes, 0);
1205
+ for (const { entry } of fetched) {
1206
+ if (entry.collection !== collectionName) continue;
1207
+ if (entry.doc_id === void 0) continue;
1208
+ switch (entry.op) {
1209
+ case "I":
1210
+ case "U":
1211
+ if (entry.after !== void 0) base.set(entry.doc_id, entry.after);
1212
+ break;
1213
+ case "D":
1214
+ base.delete(entry.doc_id);
1215
+ break;
1216
+ }
1217
+ }
1218
+ const bodyBytes = encodeSnapshotBody({
1219
+ schema_version: 1,
1220
+ min_seq: 0,
1221
+ max_seq: foldEnd,
1222
+ collection: collectionName,
1223
+ docs: Array.from(base.entries()).toSorted(([a], [b]) => {
1224
+ if (a < b) return -1;
1225
+ if (a > b) return 1;
1226
+ return 0;
1227
+ }).map(([id, body]) => ({
1228
+ _id: id,
1229
+ body
1230
+ }))
1231
+ });
1232
+ if (bodyBytes.byteLength > ceilingBytes || base.size > ceilingEntries) {
1233
+ ctxMetrics$2().counter("db.compaction.deferred_total", 1, {
1234
+ collection: collectionName,
1235
+ dimension: bodyBytes.byteLength > ceilingBytes ? "bytes" : "rows"
1236
+ });
1237
+ return {
1238
+ written: false,
1239
+ skippedReason: "deferred",
1240
+ deferred: true,
1241
+ previousSnapshotKey: current.snapshot,
1242
+ logSeqStartBefore,
1243
+ logSeqStartAfter: logSeqStartBefore,
1244
+ entriesFolded: 0
1245
+ };
1246
+ }
1247
+ const newKey = snapshotKey(collectionPrefix, 0, foldEnd, await snapshotHash(bodyBytes));
1248
+ const putOpts = {
1249
+ contentType: APPLICATION_JSON$1,
1250
+ ...options.signal !== void 0 && { signal: options.signal }
1251
+ };
1252
+ await storage.put(newKey, bodyBytes, putOpts);
1253
+ const nextBody = encodeJsonBytes({
1254
+ ...current,
1255
+ snapshot: newKey,
1256
+ log_seq_start: foldEnd,
1257
+ snapshot_bytes: bodyBytes.byteLength,
1258
+ snapshot_rows: base.size,
1259
+ tail_bytes: current.tail_bytes - foldedSliceBytes
1260
+ });
1261
+ const casOpts = {
1262
+ ifMatch: baseEtag,
1263
+ contentType: APPLICATION_JSON$1,
1264
+ ...options.signal !== void 0 && { signal: options.signal }
1265
+ };
1266
+ try {
1267
+ await storage.put(currentJsonKey, nextBody, casOpts);
1268
+ } catch (error) {
1269
+ if (isCasConflict(error)) {
1270
+ ctxMetrics$2().counter("db.compaction.cas_lost_total", 1, { collection: collectionName });
1271
+ return {
1272
+ written: false,
1273
+ skippedReason: "cas-lost",
1274
+ previousSnapshotKey: current.snapshot,
1275
+ newSnapshotKey: newKey,
1276
+ logSeqStartBefore,
1277
+ logSeqStartAfter: logSeqStartBefore,
1278
+ entriesFolded: foldEnd - logSeqStartBefore
1279
+ };
1280
+ }
1281
+ throw error;
1282
+ }
1283
+ const entriesFolded = foldEnd - logSeqStartBefore;
1284
+ const metrics = ctxMetrics$2();
1285
+ metrics.histogram("db.compact.entries_folded", entriesFolded, { collection: collectionName });
1286
+ metrics.gauge("db.manifest.lag_window_depth", current.next_seq - foldEnd, { collection: collectionName });
1287
+ return {
1288
+ written: true,
1289
+ previousSnapshotKey: current.snapshot,
1290
+ newSnapshotKey: newKey,
1291
+ logSeqStartBefore,
1292
+ logSeqStartAfter: foldEnd,
1293
+ entriesFolded
1294
+ };
1295
+ };
1296
+ /**
1297
+ * `true` when an `If-Match` CAS guard lost. Every in-tree
1298
+ * {@link Storage} impl surfaces a lost CAS as
1299
+ * `BaerlyError{code:"Conflict"}`.
1300
+ */
1301
+ const isCasConflict = (err) => err instanceof BaerlyError && err.code === "Conflict";
1302
+ //#endregion
1303
+ //#region packages/server/src/gc.ts
1304
+ /**
1305
+ * GC mark + sweep.
1306
+ *
1307
+ * `runGc` is a single-pass garbage collector that:
1308
+ * 1. Reads `current.json` (and bootstraps `gc/pending.json` on first
1309
+ * run).
1310
+ * 2. Marks new orphan candidates by LISTing the three artifact
1311
+ * prefixes — log, snapshot, content — and classifying each key.
1312
+ * 3. Sweeps any already-pending candidate whose `due_at` has passed.
1313
+ * 4. CAS-writes the updated `gc/pending.json`.
1314
+ *
1315
+ * Two-phase by design: every candidate sits in `gc/pending.json` for a
1316
+ * grace period (default 7 days, see {@link GC_GRACE_PERIOD_MILLIS})
1317
+ * before it is deleted. The grace bounds the worst plausible
1318
+ * writer-retry window — a paused-process writer that resumes hours
1319
+ * later still finds its idempotency anchor on the bucket.
1320
+ *
1321
+ * Idempotent: same input bucket state ⇒ same `pending.json` output.
1322
+ * Unbounded by default — the run marks and sweeps the entire eligible
1323
+ * set in one pass. Callers on the Cloudflare 50-subrequest free-tier
1324
+ * budget opt INTO caps via the `CLOUDFLARE_FREE_TIER` profile's
1325
+ * `gc.maxMarksPerRun` / `maxSweepsPerRun` knobs (`InternalRunGcOptions`,
1326
+ * not on the public `RunGcOptions`).
1327
+ *
1328
+ * Three categories of orphan:
1329
+ * - `stale-log`: `<collectionPrefix>/log/<seq>.json` with
1330
+ * `seq < log_seq_start`. After `compact()` folds these into a
1331
+ * snapshot, they're unreferenced.
1332
+ * - `orphan-snapshot`: a `<collectionPrefix>/snapshot/L<n>/...` key not
1333
+ * equal to `current.snapshot`. Each compactor run replaces the
1334
+ * pointer; the prior file becomes unreferenced.
1335
+ * - `orphan-content`: `<collectionPrefix>/content/<sha>.json` whose
1336
+ * 32-hex truncated-SHA-256 hash is not in the live content-hash
1337
+ * set (computed by hashing every live `entry.after` post-image —
1338
+ * the same hash the writer's step 4 produces). Surfaces writer
1339
+ * crashes between the content PUT and the log-entry PUT. Because
1340
+ * content keys are hash-named (random lex order) and live content
1341
+ * is never deleted, a bounded pass cannot rely on deletion to
1342
+ * advance its LIST window the way `stale-log` does — so the
1343
+ * orphan-content LIST carries a persisted rotation cursor
1344
+ * (`content_scan_cursor` in `gc/pending.json`): each bounded pass
1345
+ * resumes `startAfter` the prior pass's last examined key and wraps
1346
+ * at end-of-keyspace, so the whole `content/` keyspace is swept
1347
+ * over a rotation within the per-pass `maxMarksPerRun` budget.
1348
+ *
1349
+ * CAS-lost on `gc/pending.json` is non-fatal: the DELETEs already
1350
+ * issued are durable, so we return a successful result and the next
1351
+ * pass will pick up any work this pass lost.
1352
+ */
1353
+ const ctxMetrics$1 = () => getCurrentContext()?.recorder ?? noopMetricsRecorder;
1354
+ const DEFAULT_MAX_MARKS = Number.MAX_SAFE_INTEGER;
1355
+ const DEFAULT_MAX_SWEEPS = Number.MAX_SAFE_INTEGER;
1356
+ /**
1357
+ * Single GC pass — mark new orphans, sweep due-elapsed candidates,
1358
+ * persist via CAS-update on `gc/pending.json`.
1359
+ *
1360
+ * Returns immediately if `current.json` is missing — there's nothing
1361
+ * to do until a writer has bootstrapped the collection.
1362
+ *
1363
+ * @example
1364
+ * ```ts
1365
+ * import { runGc } from "@gusto/baerly-storage";
1366
+ *
1367
+ * const r = await runGc({ storage, currentJsonKey });
1368
+ * console.log(`marked ${r.marked.stale_log} stale logs, swept ${r.swept}`);
1369
+ * ```
1370
+ */
1371
+ const runGc = async (args, options = {}) => {
1372
+ const { storage, currentJsonKey } = args;
1373
+ const internal = options;
1374
+ const grace = internal.graceMillis ?? 6048e5;
1375
+ const maxMarks = internal.maxMarksPerRun ?? DEFAULT_MAX_MARKS;
1376
+ const maxSweeps = internal.maxSweepsPerRun ?? DEFAULT_MAX_SWEEPS;
1377
+ const now = internal.now ?? (() => /* @__PURE__ */ new Date());
1378
+ const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf("/"));
1379
+ const collectionName = collectionPrefix.slice(collectionPrefix.lastIndexOf("/") + 1);
1380
+ const gcPendingKey = `${collectionPrefix}/gc/pending.json`;
1381
+ const signal = options.signal;
1382
+ const signalOpts = signal !== void 0 ? { signal } : void 0;
1383
+ const cur = await readCurrentJson(storage, currentJsonKey, signalOpts);
1384
+ if (cur === null) return {
1385
+ marked: {
1386
+ stale_log: 0,
1387
+ orphan_snapshot: 0,
1388
+ orphan_content: 0
1389
+ },
1390
+ swept: 0,
1391
+ pendingDepth: 0
1392
+ };
1393
+ const current = cur.json;
1394
+ const logSeqStart = logSeqStartOf(current);
1395
+ let pending = await readGcPending(storage, gcPendingKey, signalOpts);
1396
+ if (pending === null) {
1397
+ const initial = {
1398
+ schema_version: 1,
1399
+ candidates: [],
1400
+ last_swept_at: ""
1401
+ };
1402
+ try {
1403
+ pending = await createGcPending(storage, gcPendingKey, initial, signalOpts);
1404
+ } catch (error) {
1405
+ if (error instanceof BaerlyError && error.code === "Conflict") {
1406
+ pending = await readGcPending(storage, gcPendingKey, signalOpts);
1407
+ if (pending === null) throw error;
1408
+ } else throw error;
1409
+ }
1410
+ }
1411
+ const known = new Set(pending.json.candidates.map((c) => c.key));
1412
+ const newCandidates = [];
1413
+ let markedStaleLog = 0;
1414
+ if (logSeqStart > 0) for await (const entry of listBounded(storage, `${collectionPrefix}/log/`, maxMarks, signal)) {
1415
+ if (markedStaleLog >= maxMarks) break;
1416
+ const seq = parseSeqFromLogKey(entry.key);
1417
+ if (seq === null || seq >= logSeqStart) continue;
1418
+ if (known.has(entry.key)) continue;
1419
+ newCandidates.push({
1420
+ key: entry.key,
1421
+ due_at: computeDueAt(entry, now, grace),
1422
+ reason: "stale-log"
1423
+ });
1424
+ markedStaleLog++;
1425
+ }
1426
+ let markedOrphanSnapshot = 0;
1427
+ for await (const entry of listBounded(storage, `${collectionPrefix}/snapshot/`, maxMarks, signal)) {
1428
+ if (markedOrphanSnapshot >= maxMarks) break;
1429
+ if (entry.key === current.snapshot) continue;
1430
+ if (known.has(entry.key)) continue;
1431
+ newCandidates.push({
1432
+ key: entry.key,
1433
+ due_at: computeDueAt(entry, now, grace),
1434
+ reason: "orphan-snapshot"
1435
+ });
1436
+ markedOrphanSnapshot++;
1437
+ }
1438
+ const liveHashes = await collectLiveContentHashes(storage, collectionPrefix, collectionName, current, logSeqStart, signal);
1439
+ const cursor = pending.json.content_scan_cursor;
1440
+ const contentPrefix = `${collectionPrefix}/content/`;
1441
+ let markedOrphanContent = 0;
1442
+ let examinedThisPass = 0;
1443
+ let lastExaminedKey;
1444
+ const listOpts = {
1445
+ maxKeys: maxMarks,
1446
+ ...cursor !== void 0 && { startAfter: cursor },
1447
+ ...signal !== void 0 && { signal }
1448
+ };
1449
+ for await (const entry of storage.list(contentPrefix, listOpts)) {
1450
+ examinedThisPass++;
1451
+ lastExaminedKey = entry.key;
1452
+ const hash = parseHashFromContentKey(entry.key);
1453
+ if (hash === null || liveHashes.has(hash)) continue;
1454
+ if (known.has(entry.key)) continue;
1455
+ newCandidates.push({
1456
+ key: entry.key,
1457
+ due_at: computeDueAt(entry, now, grace),
1458
+ reason: "orphan-content"
1459
+ });
1460
+ markedOrphanContent++;
1461
+ }
1462
+ const nextContentCursor = examinedThisPass < maxMarks ? void 0 : lastExaminedKey;
1463
+ const nowMs = now().getTime();
1464
+ const sweepCandidates = [...pending.json.candidates, ...newCandidates];
1465
+ const toSweep = [];
1466
+ const remaining = [];
1467
+ for (const cand of sweepCandidates) if (toSweep.length < maxSweeps && Date.parse(cand.due_at) <= nowMs) toSweep.push(cand);
1468
+ else remaining.push(cand);
1469
+ await Promise.all(toSweep.map((c) => storage.delete(c.key, signalOpts)));
1470
+ const merged = remaining.slice(0, GC_MAX_PENDING_CANDIDATES);
1471
+ const lastSweptAt = toSweep.length > 0 ? now().toISOString() : pending.json.last_swept_at;
1472
+ const markedSummary = {
1473
+ stale_log: markedStaleLog,
1474
+ orphan_snapshot: markedOrphanSnapshot,
1475
+ orphan_content: markedOrphanContent
1476
+ };
1477
+ let pendingDepth;
1478
+ try {
1479
+ pendingDepth = (await casUpdateGcPending(storage, gcPendingKey, () => ({
1480
+ schema_version: 1,
1481
+ candidates: merged,
1482
+ last_swept_at: lastSweptAt,
1483
+ ...nextContentCursor !== void 0 && { content_scan_cursor: nextContentCursor }
1484
+ }), signalOpts)).json.candidates.length;
1485
+ } catch (error) {
1486
+ if (error instanceof BaerlyError && error.code === "Conflict") pendingDepth = remaining.length;
1487
+ else throw error;
1488
+ }
1489
+ const labels = { collection: collectionName };
1490
+ const metrics = ctxMetrics$1();
1491
+ metrics.gauge("db.orphan.candidate_count", pendingDepth, labels);
1492
+ metrics.gauge("db.gc.entries_swept_per_second", toSweep.length, labels);
1493
+ if (toSweep.length > 0) {
1494
+ const byReason = /* @__PURE__ */ new Map();
1495
+ for (const c of toSweep) byReason.set(c.reason, (byReason.get(c.reason) ?? 0) + 1);
1496
+ for (const [reason, count] of byReason) metrics.counter("db.gc.swept_total", count, {
1497
+ collection: collectionName,
1498
+ reason
1499
+ });
1500
+ }
1501
+ return {
1502
+ marked: markedSummary,
1503
+ swept: toSweep.length,
1504
+ pendingDepth
1505
+ };
1506
+ };
1507
+ /**
1508
+ * `Storage.list` with a hard ceiling — bounds the I/O cost of a
1509
+ * single pass when a runaway prefix has accumulated many keys.
1510
+ */
1511
+ const listBounded = async function* (storage, prefix, cap, signal) {
1512
+ let yielded = 0;
1513
+ const opts = signal !== void 0 ? { signal } : void 0;
1514
+ for await (const entry of storage.list(prefix, opts)) {
1515
+ if (yielded >= cap) return;
1516
+ yield entry;
1517
+ yielded++;
1518
+ }
1519
+ };
1520
+ /**
1521
+ * Parse `<...>/log/<seq>.json` and return `seq`. Returns `null` on
1522
+ * any shape that doesn't look like a log entry key — defensively
1523
+ * tolerates an unrelated key under the log prefix.
1524
+ */
1525
+ const parseSeqFromLogKey = (key) => {
1526
+ const match = /\/log\/(\d+)\.json$/.exec(key);
1527
+ if (match === null) return null;
1528
+ const n = Number.parseInt(match[1], 10);
1529
+ return Number.isFinite(n) && n >= 0 ? n : null;
1530
+ };
1531
+ /**
1532
+ * Parse `<...>/content/<sha-32>.json` and return the 32-hex hash.
1533
+ * Returns `null` on any shape that doesn't match the writer's
1534
+ * `versionFromContent`-produced key format.
1535
+ */
1536
+ const parseHashFromContentKey = (key) => {
1537
+ const match = /\/content\/([0-9a-f]{32})\.json$/.exec(key);
1538
+ return match === null ? null : match[1];
1539
+ };
1540
+ /**
1541
+ * Anchor `due_at` to `lastModified` when the storage adapter
1542
+ * surfaces it; fall back to the injected `now` so a Storage impl
1543
+ * without a server clock still GCs after `grace` from the mark
1544
+ * moment.
1545
+ */
1546
+ const computeDueAt = (entry, now, graceMs) => {
1547
+ const base = entry.lastModified ?? now();
1548
+ return new Date(base.getTime() + graceMs).toISOString();
1549
+ };
1550
+ /**
1551
+ * Build the live content-hash set. The set covers every live
1552
+ * post-image: every `entry.after` in `[logSeqStart, next_seq)` plus
1553
+ * every row body in the current snapshot.
1554
+ *
1555
+ * A snapshot read that throws (corrupt body, hash mismatch) is
1556
+ * tolerated — the worst-case effect is missing some live hashes,
1557
+ * which could mark a live content blob as orphan. The grace period
1558
+ * absorbs the false-positive: a retry that re-PUTs the same hash
1559
+ * recreates the key before the sweep deletes it.
1560
+ */
1561
+ const collectLiveContentHashes = async (storage, collectionPrefix, collectionName, current, logSeqStart, signal) => {
1562
+ const hashes = /* @__PURE__ */ new Set();
1563
+ const getOpts = signal !== void 0 ? { signal } : void 0;
1564
+ const logReads = [];
1565
+ for (let s = logSeqStart; s < current.next_seq; s++) logReads.push((async () => {
1566
+ const got = await storage.get(`${collectionPrefix}/log/${s}.json`, getOpts);
1567
+ if (got === null) return;
1568
+ let entry;
1569
+ try {
1570
+ entry = decodeJsonBytes(got.body);
1571
+ } catch {
1572
+ return;
1573
+ }
1574
+ if (entry.after === void 0) return;
1575
+ const bodyBytes = encodeJsonBytes(entry.after);
1576
+ hashes.add(await versionFromContent(bodyBytes));
1577
+ })());
1578
+ await Promise.all(logReads);
1579
+ if (current.snapshot !== null) try {
1580
+ const map = await loadSnapshotAsMap(storage, current.snapshot, collectionName, signal);
1581
+ const rowReads = [];
1582
+ for (const body of map.values()) rowReads.push((async () => {
1583
+ const bytes = encodeJsonBytes(body);
1584
+ hashes.add(await versionFromContent(bytes));
1585
+ })());
1586
+ await Promise.all(rowReads);
1587
+ } catch {}
1588
+ return hashes;
1589
+ };
1590
+ //#endregion
1591
+ //#region packages/server/src/rebuild-index.ts
1592
+ /**
1593
+ * Idempotent reconciliation for one secondary index.
1594
+ *
1595
+ * {@link rebuildIndex} folds the live `(snapshot, log_tail)` of a
1596
+ * collection into the doc set the writer's index emission would
1597
+ * have produced, then PUTs every missing index key and DELETEs every
1598
+ * orphaned one. Same-key zero-byte PUTs are no-ops (the entries are
1599
+ * content-addressed by composition); same-key DELETEs are
1600
+ * contractually idempotent.
1601
+ *
1602
+ * Invariants:
1603
+ *
1604
+ * - **Re-running on a healthy index is a no-op.** `added = 0`,
1605
+ * `removed = 0`.
1606
+ * - **Re-running after a crashed mid-commit** reconciles toward
1607
+ * the live `current.json` view — orphans deleted, missing keys
1608
+ * PUT.
1609
+ * - **Re-running while writes are in flight** is safe up to a
1610
+ * race window: a write that lands during the rebuild may
1611
+ * produce a transient "orphan" the rebuild sweeps, which the
1612
+ * next live write then re-PUTs. The race converges on the next
1613
+ * commit.
1614
+ *
1615
+ * The function reads the same fold the writer / reader use
1616
+ * (snapshot via {@link loadSnapshotAsMap}; log tail by direct
1617
+ * `get(<logPrefix>/log/<seq>.json)`) so it MUST agree with the
1618
+ * writer on the live doc set by construction.
1619
+ *
1620
+ * @see ./indexes.ts — `IndexDefinition`, `allIndexKeysFor`,
1621
+ * `indexKeyPrefix`.
1622
+ * @see ./writer.ts — the fence-time emission path this
1623
+ * command reconciles.
1624
+ */
1625
+ const EMPTY_BODY = new Uint8Array(0);
1626
+ const APPLICATION_JSON = "application/json";
1627
+ /**
1628
+ * Idempotently reconcile one secondary index for one collection.
1629
+ *
1630
+ * @param storage Storage handle (any in-tree `Storage`).
1631
+ * @param currentJsonKey The collection's `current.json` key.
1632
+ * @param def The index to reconcile. Single-field today;
1633
+ * composite definitions are accepted by the
1634
+ * key encoder but the read path only consults
1635
+ * single-field keys.
1636
+ * @param opts Optional knobs — see {@link RebuildIndexOptions}.
1637
+ * Strictly additive: existing positional-arg
1638
+ * callers compile and behave unchanged when
1639
+ * omitted.
1640
+ *
1641
+ * @throws BaerlyError code="InvalidResponse" — `current.json` missing.
1642
+ * @throws BaerlyError code="Internal" — protocol-invariant
1643
+ * violation (snapshot hash mismatch, missing log entry inside
1644
+ * `[log_seq_start, next_seq)`).
1645
+ */
1646
+ const rebuildIndex = async (storage, currentJsonKey, def, opts = {}) => {
1647
+ const read = await readCurrentJson(storage, currentJsonKey);
1648
+ if (read === null) throw new BaerlyError("InvalidResponse", `rebuildIndex: current.json missing at ${JSON.stringify(currentJsonKey)}`);
1649
+ const lastSlash = currentJsonKey.lastIndexOf("/");
1650
+ if (lastSlash < 0) throw new BaerlyError("InvalidResponse", `rebuildIndex: currentJsonKey ${JSON.stringify(currentJsonKey)} must contain "/"`);
1651
+ const collectionPrefix = currentJsonKey.slice(0, lastSlash);
1652
+ const collection = collectionPrefix.slice(collectionPrefix.lastIndexOf("/") + 1);
1653
+ const logSeqStart = logSeqStartOf(read.json);
1654
+ const nextSeq = read.json.next_seq;
1655
+ const live = read.json.snapshot === null ? /* @__PURE__ */ new Map() : await loadSnapshotAsMap(storage, read.json.snapshot, collection);
1656
+ foldLogEntriesOnto(live, await walkLogRange(storage, collectionPrefix, logSeqStart, nextSeq), { collection });
1657
+ const expected = /* @__PURE__ */ new Set();
1658
+ for (const [docId, body] of live) for (const k of allIndexKeysFor(collectionPrefix, [def], body, docId)) expected.add(k);
1659
+ const actual = /* @__PURE__ */ new Set();
1660
+ const listOpts = {};
1661
+ if (opts.signal !== void 0) listOpts.signal = opts.signal;
1662
+ for await (const entry of storage.list(indexKeyPrefix(collectionPrefix, def.name), listOpts)) actual.add(entry.key);
1663
+ const dryRun = opts.dryRun === true;
1664
+ let added = 0;
1665
+ let removed = 0;
1666
+ let kept = 0;
1667
+ for (const k of expected) {
1668
+ if (actual.has(k)) {
1669
+ kept += 1;
1670
+ continue;
1671
+ }
1672
+ if (dryRun) {
1673
+ added += 1;
1674
+ continue;
1675
+ }
1676
+ try {
1677
+ await storage.put(k, EMPTY_BODY, {
1678
+ ifNoneMatch: "*",
1679
+ contentType: APPLICATION_JSON
1680
+ });
1681
+ added += 1;
1682
+ } catch (error) {
1683
+ if (error instanceof BaerlyError && error.code === "Conflict") kept += 1;
1684
+ else throw error;
1685
+ }
1686
+ }
1687
+ for (const k of actual) {
1688
+ if (expected.has(k)) continue;
1689
+ if (dryRun) {
1690
+ removed += 1;
1691
+ continue;
1692
+ }
1693
+ await storage.delete(k);
1694
+ removed += 1;
1695
+ }
1696
+ return {
1697
+ added,
1698
+ removed,
1699
+ kept
1700
+ };
1701
+ };
1702
+ //#endregion
1703
+ //#region packages/server/src/maintenance.ts
1704
+ /**
1705
+ * `runScheduledMaintenance` — single-pass compose of `compact()` and
1706
+ * `runGc()` over one collection. Designed to fit a single Cloudflare
1707
+ * Cron Trigger invocation's 50-subrequest free-tier budget when
1708
+ * called with the {@link CLOUDFLARE_FREE_TIER} profile (which the
1709
+ * caller pairs with even/odd-minute alternation between compact and
1710
+ * GC ticks); unbounded on Node.
1711
+ *
1712
+ * Single-attempt: returns the combined result. The caller (cron
1713
+ * handler) is responsible for scheduling the next invocation; this
1714
+ * function does not loop or retry. `compact()` and `runGc()` are
1715
+ * already CAS-protected single-attempts — a restart safely retries
1716
+ * next tick.
1717
+ *
1718
+ * Callers that want only one phase to fire this tick should invoke
1719
+ * the underlying primitive directly (`compact()` or `runGc()` from
1720
+ * this same module's re-exports). The even/odd-minute CF cron
1721
+ * pattern uses exactly that.
1722
+ */
1723
+ const ctxMetrics = () => getCurrentContext()?.recorder ?? noopMetricsRecorder;
1724
+ /**
1725
+ * Single maintenance pass for one collection. Runs `compact()` then
1726
+ * `runGc()` (in that order; the compactor's advance of
1727
+ * `log_seq_start` produces the stale-log candidates the GC then
1728
+ * marks). Callers wanting a single phase per tick invoke
1729
+ * `compact()` or `runGc()` directly instead.
1730
+ *
1731
+ * Errors propagate — the caller's cron handler is responsible for
1732
+ * logging them. The Cloudflare runtime ships uncaught Worker errors
1733
+ * to the dashboard; Node operators wrap their `node-cron` callbacks
1734
+ * themselves.
1735
+ *
1736
+ * @example
1737
+ * ```ts
1738
+ * import { runScheduledMaintenance, CLOUDFLARE_FREE_TIER } from "@gusto/baerly-storage/maintenance";
1739
+ *
1740
+ * // Node (unbounded — defaults fold the entire live tail):
1741
+ * const res = await runScheduledMaintenance(
1742
+ * { storage, currentJsonKey: "app/x/tenant/t/manifests/tickets/current.json" },
1743
+ * );
1744
+ * console.log("compacted:", res.compact.entriesFolded, "swept:", res.gc.swept);
1745
+ *
1746
+ * // Cloudflare free tier (50-subrequest cap, single phase per tick):
1747
+ * await runScheduledMaintenance({ storage, currentJsonKey }, CLOUDFLARE_FREE_TIER);
1748
+ * ```
1749
+ */
1750
+ const runScheduledMaintenance = async (args, options = {}) => {
1751
+ return {
1752
+ compact: await compact(args, {
1753
+ ...options.compact,
1754
+ ...options.signal !== void 0 && { signal: options.signal }
1755
+ }),
1756
+ gc: await runGc(args, {
1757
+ ...options.gc,
1758
+ ...options.signal !== void 0 && { signal: options.signal }
1759
+ })
1760
+ };
1761
+ };
1762
+ const CLOUDFLARE_FREE_TIER = {
1763
+ compact: {
1764
+ maxEntriesPerRun: 20,
1765
+ minEntriesToCompact: 50
1766
+ },
1767
+ gc: {
1768
+ maxMarksPerRun: 20,
1769
+ maxSweepsPerRun: 10
1770
+ }
1771
+ };
1772
+ /**
1773
+ * Floor-based GC-cadence boundary crossing. BATCH-SAFE: a
1774
+ * `commitBatch` that jumps `next_seq` by its whole batch size can step
1775
+ * CLEAN OVER a `next_seq % interval === 0` modulo test; this floor test
1776
+ * trips on any interval boundary inside `(prevSeq, nextSeq]`.
1777
+ */
1778
+ const crossesGcBoundary = (prevSeq, nextSeq, interval) => Math.floor(prevSeq / interval) !== Math.floor(nextSeq / interval);
1779
+ /**
1780
+ * The cheap DISPATCH gate the writer calls after a commit — zero
1781
+ * storage ops; it reads the post-CAS {@link CurrentJson} already in
1782
+ * scope. Ratio-OR-boundary, WITHOUT the entry floor (the floor is part
1783
+ * of the fold-trigger Gate 1 checked inside {@link runBoundedMaintenance}).
1784
+ * Returning `false` lets the writer skip the dispatch entirely.
1785
+ */
1786
+ const shouldFireMaintenance = (current, prevSeq, gcInterval) => crossesGcBoundary(prevSeq, current.next_seq, gcInterval) || current.tail_bytes / Math.max(current.snapshot_bytes, 65536) >= 1;
1787
+ /**
1788
+ * The write-tick maintenance runner: a bounded, single-attempt
1789
+ * composition of {@link compact} and {@link runGc} for one collection,
1790
+ * sized to fit a CPU-killable Cloudflare free-tier isolate by default.
1791
+ *
1792
+ * Never throws — the write-tick caller must never see a maintenance
1793
+ * failure. Expected signals (CAS contention, an over-ceiling deferral)
1794
+ * are swallowed quietly; unexpected throws bump
1795
+ * `db.maintenance.unexpected_error_total`, log a stack, and are
1796
+ * swallowed.
1797
+ *
1798
+ * Control flow (fold-priority with a stateless GC-starvation guard):
1799
+ * 0. `disabled` → return with zero storage ops.
1800
+ * 1. Read `current.json` once.
1801
+ * 2. Hard-GC starvation boundary (`"single"` only) → GC slice, skip fold.
1802
+ * 3. Gate 1 (ratio AND entry floor) trips → fold if viable, else
1803
+ * defer (and metric); on `"single"` a successful fold attempt is
1804
+ * this tick's one phase.
1805
+ * 4. Otherwise (or on `"both"`) → GC iff the cadence boundary crossed.
1806
+ */
1807
+ const runBoundedMaintenance = async (args, options) => {
1808
+ if (args.disabled === true) return;
1809
+ const { storage, currentJsonKey, prevSeq } = args;
1810
+ const maxFoldEntriesPerPass = options?.maxFoldEntriesPerPass ?? 20;
1811
+ const minEntriesToCompact = options?.minEntriesToCompact ?? 50;
1812
+ const gcMaxMarks = options?.gcMaxMarks ?? 20;
1813
+ const gcMaxSweeps = options?.gcMaxSweeps ?? 10;
1814
+ const gcInterval = options?.gcInterval ?? 4;
1815
+ const phasesPerTick = options?.phasesPerTick ?? "single";
1816
+ const signal = options?.signal;
1817
+ const C = args.maxFoldBytes ?? 524288;
1818
+ const E = MAINTENANCE_MAX_FOLD_ROWS;
1819
+ const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf("/"));
1820
+ const collection = collectionPrefix.slice(collectionPrefix.lastIndexOf("/") + 1);
1821
+ const gcOpts = {
1822
+ maxMarksPerRun: gcMaxMarks,
1823
+ maxSweepsPerRun: gcMaxSweeps,
1824
+ ...signal !== void 0 && { signal },
1825
+ ...options?.gcGraceMillis !== void 0 && { graceMillis: options.gcGraceMillis },
1826
+ ...options?.now !== void 0 && { now: options.now }
1827
+ };
1828
+ try {
1829
+ const read = await readCurrentJson(storage, currentJsonKey, signal !== void 0 ? { signal } : void 0);
1830
+ if (read === null) return;
1831
+ const current = read.json;
1832
+ const tailBytes = current.tail_bytes;
1833
+ const snapshotBytes = current.snapshot_bytes;
1834
+ const snapshotRows = current.snapshot_rows;
1835
+ const nextSeq = current.next_seq;
1836
+ const logSeqStart = current.log_seq_start;
1837
+ const gate1 = tailBytes / Math.max(snapshotBytes, 65536) >= 1 && nextSeq - logSeqStart >= minEntriesToCompact;
1838
+ const foldViable = snapshotBytes <= C && snapshotRows + maxFoldEntriesPerPass <= E;
1839
+ const gcDue = crossesGcBoundary(prevSeq, nextSeq, gcInterval);
1840
+ const hardGc = crossesGcBoundary(prevSeq, nextSeq, gcInterval * 4);
1841
+ if (phasesPerTick === "single" && hardGc) {
1842
+ await runGc({
1843
+ storage,
1844
+ currentJsonKey
1845
+ }, gcOpts);
1846
+ return;
1847
+ }
1848
+ if (gate1) if (foldViable) {
1849
+ await compact({
1850
+ storage,
1851
+ currentJsonKey
1852
+ }, {
1853
+ maxEntriesPerRun: maxFoldEntriesPerPass,
1854
+ minEntriesToCompact,
1855
+ ceilingBytes: C,
1856
+ ceilingEntries: E,
1857
+ ...signal !== void 0 && { signal }
1858
+ });
1859
+ if (phasesPerTick === "single") return;
1860
+ } else {
1861
+ ctxMetrics().counter("db.compaction.deferred_total", 1, {
1862
+ collection,
1863
+ dimension: snapshotBytes > C ? "bytes" : "rows"
1864
+ });
1865
+ if (nextSeq - (current.last_warned_seq ?? 0) >= 1e3) {
1866
+ 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.`);
1867
+ try {
1868
+ await casUpdateCurrentJson(storage, currentJsonKey, (c) => ({
1869
+ ...c,
1870
+ last_warned_seq: nextSeq
1871
+ }), signal !== void 0 ? { signal } : void 0);
1872
+ } catch {}
1873
+ }
1874
+ }
1875
+ if (gcDue) await runGc({
1876
+ storage,
1877
+ currentJsonKey
1878
+ }, gcOpts);
1879
+ } catch (error) {
1880
+ if (error instanceof BaerlyError && error.code === "Conflict") return;
1881
+ ctxMetrics().counter("db.maintenance.unexpected_error_total", 1, { collection });
1882
+ console.error(error);
1883
+ }
1884
+ };
1885
+ /**
1886
+ * Default maintenance dispatcher: run the task inline and await it.
1887
+ * Adapters that can keep running after the response (Cloudflare:
1888
+ * `ctx.waitUntil`) override this with a fire-and-forget variant that
1889
+ * returns `void`.
1890
+ */
1891
+ const dispatchInlineAwaited = (task) => task();
1892
+ //#endregion
1893
+ export { matchesWire as C, assertWireSatisfiable as S, encodeIndexValue as _, runScheduledMaintenance as a, versionFromContent as b, runGc as c, loadSnapshotAsMap as d, snapshotKey as f, allIndexKeysFor as g, walkLogRange as h, runBoundedMaintenance as i, compact as l, readLogEntry as m, crossesGcBoundary as n, shouldFireMaintenance as o, foldLogEntriesOnto as p, dispatchInlineAwaited as r, rebuildIndex as s, CLOUDFLARE_FREE_TIER as t, encodeSnapshotBody as u, validateIndexDefinition as v, deepEqualDocumentValue as w, validateWire as x, assertNameNotReserved as y };
1894
+
1895
+ //# sourceMappingURL=maintenance-ClzBC1Vv.js.map