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