@gusto/baerly-storage 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -5
- package/dist/API.md +161 -10
- package/dist/{app-config-Cb5dO2s9.d.ts → app-config-C0Bbw_Z6.d.ts} +18 -9
- package/dist/app-config.d.ts +1 -1
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js +11 -0
- package/dist/bytes-BXdamO3L.js.map +1 -0
- package/dist/{client-BLf3Ae5s.d.ts → client-DYZfoZb9.d.ts} +3 -3
- package/dist/client-react.d.ts +3 -3
- package/dist/client.d.ts +3 -3
- package/dist/cloudflare.d.ts +31 -4
- package/dist/cloudflare.js +72 -6
- package/dist/cloudflare.js.map +1 -1
- package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
- package/dist/config-DVfDGyw1.js.map +1 -0
- package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
- package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
- package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
- package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
- package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
- package/dist/current-json-C-EyJqs0.js.map +1 -0
- package/dist/{db-D62JguBc.d.ts → db-BM3y2JQw.d.ts} +3 -3
- package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
- package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
- package/dist/dev-vite.d.ts +3 -3
- package/dist/dev-vite.js +3 -3
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
- package/dist/doctor-Db-hzPmE.js.map +1 -0
- package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
- package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
- package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
- package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
- package/dist/fsck-CPPZWt9p.js.map +1 -0
- package/dist/{http-CjUO1Bec.js → http-Cw8p6y5b.js} +8 -8
- package/dist/{http-CjUO1Bec.js.map → http-Cw8p6y5b.js.map} +1 -1
- package/dist/http.d.ts +6 -6
- package/dist/http.js +1 -1
- package/dist/{index-BYv0hb8M.d.ts → index-C3JAH1Yo.d.ts} +14 -2
- package/dist/{index-BGC-ENnj.d.ts → index-DSvwEUeF.d.ts} +63 -54
- package/dist/{index-BquQkhJi.d.ts → index-DwDTWPSU.d.ts} +2 -2
- package/dist/{index-COsQ-Mlz.d.ts → index-cUY-36AN.d.ts} +3 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/{indexes-DwOXkn1Y.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
- package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
- package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
- package/dist/maintenance-BRrThz8V.d.ts +449 -0
- package/dist/maintenance-BvOv6BMM.js +1295 -0
- package/dist/maintenance-BvOv6BMM.js.map +1 -0
- package/dist/maintenance-ClzBC1Vv.js +1895 -0
- package/dist/maintenance-ClzBC1Vv.js.map +1 -0
- package/dist/maintenance.d.ts +2 -323
- package/dist/maintenance.js +2 -2
- package/dist/node.d.ts +20 -79
- package/dist/node.js +2 -2
- package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
- package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +2 -2
- package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
- package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
- package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
- package/dist/query-BmiQy328.js.map +1 -0
- package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
- package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
- package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
- package/dist/restore-C6IcmLeA.js.map +1 -0
- package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
- package/dist/snapshot-SS8USDUF.js.map +1 -0
- package/dist/{src-DyET_VPP.js → src-DU1sCMlr.js} +315 -278
- package/dist/src-DU1sCMlr.js.map +1 -0
- package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
- package/dist/src-QQ7jDeL2.js.map +1 -0
- package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
- package/dist/src-zhEAmmF7.js.map +1 -0
- package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
- package/dist/subcommand-DZcHcsYp.js.map +1 -0
- package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
- package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
- package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
- package/dist/validate-DCq_0DIn.js.map +1 -0
- package/package.json +13 -6
- package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
- package/dist/config-Bsg8wgwo.js.map +0 -1
- package/dist/current-json-BkatBzF7.js.map +0 -1
- package/dist/doctor-B8h9GCN9.js.map +0 -1
- package/dist/fsck-DEz9lyCy.js.map +0 -1
- package/dist/indexes-BXn7a06a.js +0 -297
- package/dist/indexes-BXn7a06a.js.map +0 -1
- package/dist/log-walk-DIru96UT.js.map +0 -1
- package/dist/maintenance-Bn6ul9aV.js +0 -758
- package/dist/maintenance-Bn6ul9aV.js.map +0 -1
- package/dist/query-DcSbFLJt.js.map +0 -1
- package/dist/rebuild-index-C5gTXryd.js +0 -119
- package/dist/rebuild-index-C5gTXryd.js.map +0 -1
- package/dist/restore-CbKVMMpm.js.map +0 -1
- package/dist/snapshot-D7C4_FSl.js +0 -71
- package/dist/snapshot-D7C4_FSl.js.map +0 -1
- package/dist/snapshot-z_N9hpTe.js +0 -917
- package/dist/snapshot-z_N9hpTe.js.map +0 -1
- package/dist/src-Chafbw8r.js.map +0 -1
- package/dist/src-DyET_VPP.js.map +0 -1
- package/dist/src-n0Te1r98.js.map +0 -1
- package/dist/subcommand-BWs6K7zb.js +0 -110
- package/dist/subcommand-BWs6K7zb.js.map +0 -1
- package/dist/validate-DhH1lO8I.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as CURRENT_JSON_CONTENT_TYPE } from "./config-
|
|
1
|
+
import { n as encodeJsonBytes, t as decodeJsonBytes } from "./bytes-BXdamO3L.js";
|
|
2
|
+
import { r as CURRENT_JSON_CONTENT_TYPE } from "./config-DVfDGyw1.js";
|
|
3
3
|
import { o as BaerlyError } from "./baerly.js";
|
|
4
4
|
//#region ../protocol/src/coordination/current-json.ts
|
|
5
5
|
/**
|
|
@@ -89,6 +89,45 @@ async function createCurrentJson(storage, key, initial, opts) {
|
|
|
89
89
|
};
|
|
90
90
|
}
|
|
91
91
|
/**
|
|
92
|
+
* Read-modify-write `current.json` under CAS. The `mutator` receives
|
|
93
|
+
* a deep clone of the current parsed JSON (mutate freely) and returns
|
|
94
|
+
* the new state. The new state is written with `If-Match:
|
|
95
|
+
* <currentEtag>`; on conflict, throws.
|
|
96
|
+
*
|
|
97
|
+
* `mutator` MUST be synchronous and deterministic — it may be called
|
|
98
|
+
* multiple times if the caller wraps this in a retry loop, so it
|
|
99
|
+
* must not have side effects.
|
|
100
|
+
*
|
|
101
|
+
* @throws BaerlyError{code:"Conflict"} — another writer landed a write
|
|
102
|
+
* between this function's read and write. Caller decides
|
|
103
|
+
* whether to retry (read + remutate + rewrite).
|
|
104
|
+
* @throws BaerlyError{code:"InvalidResponse"} — `key` does not exist
|
|
105
|
+
* (use {@link createCurrentJson} instead) or body doesn't
|
|
106
|
+
* parse / fails the shape guard.
|
|
107
|
+
*/
|
|
108
|
+
async function casUpdateCurrentJson(storage, key, mutator, opts) {
|
|
109
|
+
const existing = await readCurrentJson(storage, key, opts);
|
|
110
|
+
if (existing === null) throw new BaerlyError("InvalidResponse", `current.json at ${key} does not exist; use createCurrentJson first`);
|
|
111
|
+
const next = mutator(structuredClone(existing.json));
|
|
112
|
+
assertCurrentJson(next, key);
|
|
113
|
+
const body = encodeJson(next);
|
|
114
|
+
const putOpts = {
|
|
115
|
+
ifMatch: existing.etag,
|
|
116
|
+
contentType: CURRENT_JSON_CONTENT_TYPE,
|
|
117
|
+
...opts?.signal !== void 0 && { signal: opts.signal }
|
|
118
|
+
};
|
|
119
|
+
let result;
|
|
120
|
+
try {
|
|
121
|
+
result = await storage.put(key, body, putOpts);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
throw translateCasError(error, key);
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
json: next,
|
|
127
|
+
etag: result.etag
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
92
131
|
* Read `current.json.log_seq_start` — the low-water mark of the live
|
|
93
132
|
* log range `[log_seq_start, next_seq)`. The field is always present
|
|
94
133
|
* on disk (every `createCurrentJson` write seeds it; the compactor
|
|
@@ -100,13 +139,15 @@ const logSeqStartOf = (c) => c.log_seq_start;
|
|
|
100
139
|
const encodeJson = (json) => encodeJsonBytes(json);
|
|
101
140
|
/**
|
|
102
141
|
* Runtime guard for `parsed` to be a {@link CurrentJson}. Throws
|
|
103
|
-
* `BaerlyError{code:"InvalidResponse"}` rather than coercing
|
|
104
|
-
*
|
|
142
|
+
* `BaerlyError{code:"InvalidResponse"}` rather than coercing. Tolerant
|
|
143
|
+
* reader: unknown keys ignored, new required fields bump
|
|
144
|
+
* `schema_version` (move (b), ADR-007).
|
|
105
145
|
*/
|
|
106
146
|
const assertCurrentJson = (parsed, key) => {
|
|
107
147
|
if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: parsed body is not an object`);
|
|
108
148
|
const r = parsed;
|
|
109
|
-
if (r["schema_version"]
|
|
149
|
+
if (r["schema_version"] === 1) throw new BaerlyError("InvalidResponse", `current.json at ${key} is schema v1 (pre-maintenance); this build requires v2. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`);
|
|
150
|
+
if (r["schema_version"] !== 2) throw new BaerlyError("InvalidResponse", `current.json at ${key}: unsupported schema_version ${String(r["schema_version"])}; expected 2`);
|
|
110
151
|
if (!(typeof r["snapshot"] === "string" || r["snapshot"] === null)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot must be string|null`);
|
|
111
152
|
if (typeof r["next_seq"] !== "number" || !Number.isInteger(r["next_seq"]) || r["next_seq"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: next_seq must be a non-negative integer`);
|
|
112
153
|
if (typeof r["log_seq_start"] !== "number" || !Number.isInteger(r["log_seq_start"]) || r["log_seq_start"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_seq_start must be a non-negative integer`);
|
|
@@ -118,6 +159,10 @@ const assertCurrentJson = (parsed, key) => {
|
|
|
118
159
|
if (typeof f["owner"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.owner must be a string`);
|
|
119
160
|
if (typeof f["claimed_at"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.claimed_at must be a string`);
|
|
120
161
|
if (f["lease_until"] !== void 0 && typeof f["lease_until"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.lease_until must be string if present`);
|
|
162
|
+
if (typeof r["tail_bytes"] !== "number" || !Number.isInteger(r["tail_bytes"]) || r["tail_bytes"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: tail_bytes must be a non-negative integer`);
|
|
163
|
+
if (typeof r["snapshot_bytes"] !== "number" || !Number.isInteger(r["snapshot_bytes"]) || r["snapshot_bytes"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_bytes must be a non-negative integer`);
|
|
164
|
+
if (typeof r["snapshot_rows"] !== "number" || !Number.isInteger(r["snapshot_rows"]) || r["snapshot_rows"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_rows must be a non-negative integer`);
|
|
165
|
+
if (r["last_warned_seq"] !== void 0 && (typeof r["last_warned_seq"] !== "number" || !Number.isInteger(r["last_warned_seq"]) || r["last_warned_seq"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: last_warned_seq must be a non-negative integer if present`);
|
|
121
166
|
return parsed;
|
|
122
167
|
};
|
|
123
168
|
/**
|
|
@@ -133,6 +178,27 @@ const translateCasError = (e, key) => {
|
|
|
133
178
|
return new BaerlyError("InvalidResponse", `current.json write at ${key} failed: ${String(e)}`, e);
|
|
134
179
|
};
|
|
135
180
|
//#endregion
|
|
181
|
+
//#region ../protocol/src/snapshot-hash.ts
|
|
182
|
+
/**
|
|
183
|
+
* SHA-256 of `bytes` as a 64-char lowercase hex string. Used to seal
|
|
184
|
+
* snapshot filenames so a crashed mid-PUT can't produce a body that
|
|
185
|
+
* readers consume as truth: the filename embeds the hash; readers
|
|
186
|
+
* recompute on load and reject any mismatch as "file missing."
|
|
187
|
+
*
|
|
188
|
+
* Distinct from {@link versionFromContent} (truncated to 32 chars for
|
|
189
|
+
* content keys) — snapshot bodies are larger and longer-lived;
|
|
190
|
+
* 256-bit collision resistance matters here.
|
|
191
|
+
*/
|
|
192
|
+
const snapshotHash = async (bytes) => {
|
|
193
|
+
const view = new Uint8Array(bytes.byteLength);
|
|
194
|
+
view.set(bytes);
|
|
195
|
+
const digest = await crypto.subtle.digest("SHA-256", view);
|
|
196
|
+
const out = new Uint8Array(digest);
|
|
197
|
+
let hex = "";
|
|
198
|
+
for (let i = 0; i < out.length; i++) hex += out[i].toString(16).padStart(2, "0");
|
|
199
|
+
return hex;
|
|
200
|
+
};
|
|
201
|
+
//#endregion
|
|
136
202
|
//#region ../server/src/log-walk.ts
|
|
137
203
|
/**
|
|
138
204
|
* Shared log-walk primitives consumed by the read path (`query.ts`),
|
|
@@ -170,10 +236,32 @@ const translateCasError = (e, key) => {
|
|
|
170
236
|
* valid JSON.
|
|
171
237
|
*/
|
|
172
238
|
const readLogEntry = async (storage, key, opts) => {
|
|
239
|
+
return (await readLogEntryWithBytes(storage, key, opts)).entry;
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* Like {@link readLogEntry}, but also surfaces `bytes` — the
|
|
243
|
+
* byteLength of the STORED log-object body exactly as it was GET back
|
|
244
|
+
* from storage (`got.body.byteLength`).
|
|
245
|
+
*
|
|
246
|
+
* The compactor uses this to subtract from `current.json.tail_bytes`
|
|
247
|
+
* the EXACT bytes the writer PUT for the folded slice. The writer
|
|
248
|
+
* accumulated `encodeJsonBytes(entry).byteLength` per committed entry
|
|
249
|
+
* (`writer.ts` Step 6); the stored body IS those bytes, so summing
|
|
250
|
+
* `got.body.byteLength` over the folded range == the writer's
|
|
251
|
+
* accumulated total for that range — no re-encode, no round-trip
|
|
252
|
+
* assumption (a re-encode of the parsed `LogEntry` could drift if
|
|
253
|
+
* key-order/whitespace ever diverged from what was PUT).
|
|
254
|
+
*
|
|
255
|
+
* Same error semantics as {@link readLogEntry}.
|
|
256
|
+
*/
|
|
257
|
+
const readLogEntryWithBytes = async (storage, key, opts) => {
|
|
173
258
|
const got = await storage.get(key, opts?.signal !== void 0 ? { signal: opts.signal } : void 0);
|
|
174
259
|
if (got === null) throw new BaerlyError("Internal", `log-walk: missing log entry at ${key}; protocol invariant violation`);
|
|
175
260
|
try {
|
|
176
|
-
return
|
|
261
|
+
return {
|
|
262
|
+
entry: decodeJsonBytes(got.body),
|
|
263
|
+
bytes: got.body.byteLength
|
|
264
|
+
};
|
|
177
265
|
} catch (error) {
|
|
178
266
|
throw new BaerlyError("InvalidResponse", `log-walk: malformed log entry at ${key}`, error);
|
|
179
267
|
}
|
|
@@ -190,6 +278,20 @@ const readLogEntry = async (storage, key, opts) => {
|
|
|
190
278
|
* throws `Internal`, a malformed body throws `InvalidResponse`.
|
|
191
279
|
*/
|
|
192
280
|
const walkLogRange = async (storage, logPrefix, fromSeq, toSeqExclusive, opts) => {
|
|
281
|
+
return (await walkLogRangeWithBytes(storage, logPrefix, fromSeq, toSeqExclusive, opts)).map((r) => r.entry);
|
|
282
|
+
};
|
|
283
|
+
/**
|
|
284
|
+
* Like {@link walkLogRange}, but each element also carries `bytes` —
|
|
285
|
+
* the STORED log-object body byteLength (see {@link readLogEntryWithBytes}).
|
|
286
|
+
* Same seq-order, empty-range, error, and bounded-parallelism
|
|
287
|
+
* ({@link MAX_PARALLEL_LOG_READS}) guarantees as {@link walkLogRange};
|
|
288
|
+
* this is the bytes-aware core `walkLogRange` is implemented on top of.
|
|
289
|
+
*
|
|
290
|
+
* The compactor consumes this so it gets BOTH the parsed entries (for
|
|
291
|
+
* the fold) AND the exact byte sum (to decrement `tail_bytes`) from a
|
|
292
|
+
* single walk.
|
|
293
|
+
*/
|
|
294
|
+
const walkLogRangeWithBytes = async (storage, logPrefix, fromSeq, toSeqExclusive, opts) => {
|
|
193
295
|
if (fromSeq >= toSeqExclusive) return [];
|
|
194
296
|
const total = toSeqExclusive - fromSeq;
|
|
195
297
|
const out = Array.from({ length: total });
|
|
@@ -199,7 +301,7 @@ const walkLogRange = async (storage, logPrefix, fromSeq, toSeqExclusive, opts) =
|
|
|
199
301
|
const promises = [];
|
|
200
302
|
for (let i = chunkStart; i < chunkEnd; i++) {
|
|
201
303
|
const seq = fromSeq + i;
|
|
202
|
-
promises.push(
|
|
304
|
+
promises.push(readLogEntryWithBytes(storage, `${logPrefix}/log/${seq}.json`, opts));
|
|
203
305
|
}
|
|
204
306
|
const results = await Promise.all(promises);
|
|
205
307
|
for (let i = 0; i < results.length; i++) out[chunkStart + i] = results[i];
|
|
@@ -210,14 +312,12 @@ const walkLogRange = async (storage, logPrefix, fromSeq, toSeqExclusive, opts) =
|
|
|
210
312
|
* Fold a sequence of `LogEntry` records onto a doc-id-keyed map,
|
|
211
313
|
* applying the protocol's per-doc-replace semantics:
|
|
212
314
|
*
|
|
213
|
-
* - `I` / `U`: when `entry.
|
|
214
|
-
* `map.set(entry.doc_id, entry.
|
|
315
|
+
* - `I` / `U`: when `entry.after !== undefined`, set
|
|
316
|
+
* `map.set(entry.doc_id, entry.after)`. Entries with `after ===
|
|
215
317
|
* undefined` (the partial-merge writer's future patch-only shape)
|
|
216
|
-
* are ignored — today's writer always emits `
|
|
318
|
+
* are ignored — today's writer always emits `after`, so this is a
|
|
217
319
|
* forward-compat guard, not a live branch.
|
|
218
320
|
* - `D`: tombstone — `map.delete(entry.doc_id)`.
|
|
219
|
-
* - `T` / `M`: ignored. `T` (TRUNCATE) is not yet wired; `M`
|
|
220
|
-
* (MESSAGE) is a marker. The emitter never produces them today.
|
|
221
321
|
*
|
|
222
322
|
* Entries whose `collection` does not match `opts.collection`, or
|
|
223
323
|
* whose `doc_id` is `undefined`, are skipped. When
|
|
@@ -229,8 +329,7 @@ const walkLogRange = async (storage, logPrefix, fromSeq, toSeqExclusive, opts) =
|
|
|
229
329
|
* This is the canonical fold used by the read path
|
|
230
330
|
* (`query.ts`) and the index reconciler (`rebuild-index.ts`).
|
|
231
331
|
* Centralising it keeps the
|
|
232
|
-
* "
|
|
233
|
-
* invariant in one place.
|
|
332
|
+
* "straight `set` on I/U; tombstone on D" protocol invariant in one place.
|
|
234
333
|
*
|
|
235
334
|
* @see ../../../docs/spec/sync-protocol.md
|
|
236
335
|
*/
|
|
@@ -243,18 +342,86 @@ const foldLogEntriesOnto = (map, entries, opts) => {
|
|
|
243
342
|
switch (entry.op) {
|
|
244
343
|
case "I":
|
|
245
344
|
case "U":
|
|
246
|
-
if (entry.
|
|
247
|
-
map.set(entry.doc_id, entry.
|
|
345
|
+
if (entry.after === void 0) continue;
|
|
346
|
+
map.set(entry.doc_id, entry.after);
|
|
248
347
|
break;
|
|
249
348
|
case "D":
|
|
250
349
|
map.delete(entry.doc_id);
|
|
251
350
|
break;
|
|
252
|
-
case "T":
|
|
253
|
-
case "M": break;
|
|
254
351
|
}
|
|
255
352
|
}
|
|
256
353
|
};
|
|
354
|
+
const MAX_SEQ = 10 ** 12 - 1;
|
|
355
|
+
/**
|
|
356
|
+
* Build the on-bucket key for a snapshot file. `sha256` must be the
|
|
357
|
+
* lowercase hex digest of the canonical body
|
|
358
|
+
* ({@link encodeSnapshotBody}); the filename embeds it so a crashed
|
|
359
|
+
* mid-PUT body that doesn't match its own filename hash is rejected
|
|
360
|
+
* by readers as "missing."
|
|
361
|
+
*
|
|
362
|
+
* @throws BaerlyError code="InvalidConfig" — `minSeq`/`maxSeq` are
|
|
363
|
+
* out of range or `sha256` is not 64 hex chars.
|
|
364
|
+
*/
|
|
365
|
+
const snapshotKey = (collectionPrefix, minSeq, maxSeq, sha256) => {
|
|
366
|
+
if (minSeq < 0 || maxSeq < 0 || minSeq > maxSeq || maxSeq > MAX_SEQ) throw new BaerlyError("InvalidConfig", `snapshotKey: invalid range [${minSeq}, ${maxSeq})`);
|
|
367
|
+
if (!/^[0-9a-f]{64}$/.test(sha256)) throw new BaerlyError("InvalidConfig", "snapshotKey: sha256 must be 64 hex chars");
|
|
368
|
+
const pad = (n) => n.toString().padStart(12, "0");
|
|
369
|
+
return `${collectionPrefix}/snapshot/L9/${pad(minSeq)}-${pad(maxSeq)}-${sha256}.json`;
|
|
370
|
+
};
|
|
371
|
+
/**
|
|
372
|
+
* Canonical byte encoding of a {@link SnapshotBody}. Only the
|
|
373
|
+
* compactor produces snapshots, and only this function does the
|
|
374
|
+
* serialisation — so the byte output is deterministic for a given
|
|
375
|
+
* `SnapshotBody` (identical input ⇒ identical bytes ⇒ identical
|
|
376
|
+
* filename hash).
|
|
377
|
+
*/
|
|
378
|
+
const encodeSnapshotBody = (s) => encodeJsonBytes(s);
|
|
379
|
+
/**
|
|
380
|
+
* Load a snapshot file as a `Map<_id, DocumentData>`. Verifies the
|
|
381
|
+
* body hash against the filename, checks the schema version, and
|
|
382
|
+
* cross-checks `body.collection` against the caller's expectation.
|
|
383
|
+
*
|
|
384
|
+
* @example
|
|
385
|
+
* ```ts
|
|
386
|
+
* import { loadSnapshotAsMap } from "@gusto/baerly-storage";
|
|
387
|
+
*
|
|
388
|
+
* const map =
|
|
389
|
+
* srcCurrent.snapshot === null
|
|
390
|
+
* ? new Map<string, DocumentData>()
|
|
391
|
+
* : await loadSnapshotAsMap(src.storage, srcCurrent.snapshot, "tickets");
|
|
392
|
+
* ```
|
|
393
|
+
*
|
|
394
|
+
* @throws BaerlyError code="Internal" — pointer resolves to no body,
|
|
395
|
+
* or the body's SHA-256 doesn't match the hash embedded in the
|
|
396
|
+
* filename. (Protocol invariant violation; a corrupted snapshot
|
|
397
|
+
* the reader cannot continue past.)
|
|
398
|
+
* @throws BaerlyError code="InvalidResponse" — body isn't valid JSON,
|
|
399
|
+
* isn't an object, has an unsupported `schema_version`, or carries a
|
|
400
|
+
* `collection` that doesn't match `expectedCollection`.
|
|
401
|
+
*/
|
|
402
|
+
const loadSnapshotAsMap = async (storage, key, expectedCollection, signal) => {
|
|
403
|
+
const got = await storage.get(key, signal !== void 0 ? { signal } : void 0);
|
|
404
|
+
if (got === null) throw new BaerlyError("Internal", `compact: snapshot pointer ${key} resolves to no body; protocol violation`);
|
|
405
|
+
const filename = key.slice(key.lastIndexOf("/") + 1).replace(/\.json$/, "");
|
|
406
|
+
const lastDash = filename.lastIndexOf("-");
|
|
407
|
+
const expectedHash = filename.slice(lastDash + 1);
|
|
408
|
+
const actualHash = await snapshotHash(got.body);
|
|
409
|
+
if (actualHash !== expectedHash) throw new BaerlyError("Internal", `compact: snapshot ${key} body hash mismatch (got ${actualHash}); protocol violation`);
|
|
410
|
+
let parsed;
|
|
411
|
+
try {
|
|
412
|
+
parsed = decodeJsonBytes(got.body);
|
|
413
|
+
} catch (error) {
|
|
414
|
+
throw new BaerlyError("InvalidResponse", `compact: snapshot ${key} body is not valid JSON`, error);
|
|
415
|
+
}
|
|
416
|
+
if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `compact: snapshot ${key} body is not an object`);
|
|
417
|
+
const body = parsed;
|
|
418
|
+
if (body.schema_version !== 1) throw new BaerlyError("InvalidResponse", `compact: snapshot ${key} has unsupported schema_version ${String(body.schema_version)}`);
|
|
419
|
+
if (body.collection !== expectedCollection) throw new BaerlyError("InvalidResponse", `compact: snapshot ${key} carries collection ${body.collection}, expected ${expectedCollection}`);
|
|
420
|
+
const out = /* @__PURE__ */ new Map();
|
|
421
|
+
for (const row of body.docs) out.set(row._id, row.body);
|
|
422
|
+
return out;
|
|
423
|
+
};
|
|
257
424
|
//#endregion
|
|
258
|
-
export {
|
|
425
|
+
export { readLogEntry as a, snapshotHash as c, logSeqStartOf as d, readCurrentJson as f, foldLogEntriesOnto as i, casUpdateCurrentJson as l, loadSnapshotAsMap as n, walkLogRange as o, snapshotKey as r, walkLogRangeWithBytes as s, encodeSnapshotBody as t, createCurrentJson as u };
|
|
259
426
|
|
|
260
|
-
//# sourceMappingURL=
|
|
427
|
+
//# sourceMappingURL=snapshot-SS8USDUF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snapshot-SS8USDUF.js","names":[],"sources":["../packages/protocol/src/coordination/current-json.ts","../packages/protocol/src/snapshot-hash.ts","../packages/server/src/log-walk.ts","../packages/server/src/snapshot.ts"],"sourcesContent":["/**\n * `current.json` — the per-collection CAS-protected control object — and\n * its embedded {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps\n * snapshot generations by CAS-writing this object; the\n * Writer reads it on every commit to find the snapshot\n * pointer; the sweeper reads `writer_fence` to decide which log\n * entries are eligible for GC.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `2`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 2;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Sequence number of the next log entry. Monotonic per\n * collection. The Writer reads this on commit to mint the\n * next log filename; CAS-write back with `next_seq + 1` ensures\n * no two writers pick the same sequence.\n */\n next_seq: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, next_seq)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= next_seq`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n\n // New in v2:\n\n /** EXACT byte size of the live log tail [log_seq_start, next_seq). Maintained exactly\n * by the full-fence CAS on BOTH paths: each write adds its log bytes; a successful\n * fold (which proves no concurrent write) resets to 0 from a known-empty tail. */\n tail_bytes: number;\n\n /** Byte size of the snapshot pointed to by `snapshot`. */\n snapshot_bytes: number;\n\n /** Row count of the snapshot (= compactor `base.size`, free). With next_seq - log_seq_start\n * (tail entries) this gives the fold's entry count for the ENTRY ceiling `E`. Seeded 0. */\n snapshot_rows: number;\n\n /** Baseline for rate-limiting the graduation defer-warn off SHARED durable state, not\n * per-isolate memory. The warn fires when next_seq - last_warned_seq >=\n * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes last_warned_seq = next_seq.\n * Absent → 0. */\n last_warned_seq?: number;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is the server response date at claim time, NOT the\n * local clock; `lease_until` is reserved for manual rotation and\n * is not consumed by any ticket in this batch.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. The mechanism is the same in all three: every commit\n * checks the epoch on the control object; an entry stamped with\n * a stale epoch is discarded at replay.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Triggers per design: (a) detected\n * CAS conflict the writer wants to claim through, (b) admin\n * rotation. The sweeper discards log entries whose stamped epoch\n * is `< current.writer_fence.epoch`.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the write fence by bumping `epoch` and stamping\n * `claimed_at` from `StoragePutResult.serverDate`. The common call\n * site is \"I detected a CAS conflict during a commit and want to\n * claim the fence before retrying\"; admin rotation is the other call\n * site.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n // Stryker disable next-line ConditionalExpression: `→true` spreads `{lease_until: undefined}` which JSON.stringify omits, so the stored bytes are identical to the normal `→false` path (no key emitted). Genuine equivalent mutant.\n ...(existing.json.writer_fence.lease_until !== undefined && {\n lease_until: existing.json.writer_fence.lease_until,\n }),\n },\n };\n const body = encodeJson(provisional);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n // No server clock surfaced — leave `claimed_at` empty. The epoch\n // bump is durable; safety is unaffected.\n if (result.serverDate === undefined) {\n return { json: provisional, etag: result.etag };\n }\n // Stamp the server clock through a second CAS-on-our-own-etag. A\n // peer landing between the two writes loses cleanly with Conflict\n // (the fence is safe — next claim will bump past both).\n const stamped: CurrentJson = {\n ...provisional,\n writer_fence: {\n ...provisional.writer_fence,\n claimed_at: result.serverDate.toISOString(),\n },\n };\n const stampedBody = encodeJson(stamped);\n const stampPutOpts: StoragePutOptions = {\n ifMatch: result.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let stampResult: StoragePutResult;\n try {\n stampResult = await storage.put(key, stampedBody, stampPutOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: stamped, etag: stampResult.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, next_seq)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing. Tolerant\n * reader: unknown keys ignored, new required fields bump\n * `schema_version` (move (b), ADR-007).\n */\nconst assertCurrentJson = (parsed: unknown, key: string): CurrentJson => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] === 1) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} is schema v1 (pre-maintenance); this build requires v2. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`,\n );\n }\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; expected ${CURRENT_JSON_SCHEMA_VERSION}`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n // Stryker disable next-line ConditionalExpression,StringLiteral: three equivalent mutants on this line — (1) `typeof r[\"next_seq\"] !== \"number\"` → false is subsumed by !Number.isInteger (which rejects all non-numbers); (2) `r[\"next_seq\"] < 0` → false is subsumed by the downstream `log_seq_start > next_seq` cross-check (log_seq_start ≥ 0, so log_seq_start > negative_next_seq always fires); (3) StringLiteral \"next_seq\" → \"\" turns r[\"\"] → undefined → !Number.isInteger(undefined) still true → still throws.\n if (typeof r[\"next_seq\"] !== \"number\" || !Number.isInteger(r[\"next_seq\"]) || r[\"next_seq\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: next_seq must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"log_seq_start\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers anyway, making the typeof check fully subsumed.\n typeof r[\"log_seq_start\"] !== \"number\" ||\n !Number.isInteger(r[\"log_seq_start\"]) ||\n r[\"log_seq_start\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start must be a non-negative integer`,\n );\n }\n if (r[\"log_seq_start\"] > r[\"next_seq\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > next_seq ${String(r[\"next_seq\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n // Stryker disable next-line ConditionalExpression: `typeof f[\"epoch\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof guard fully subsumed.\n if (typeof f[\"epoch\"] !== \"number\" || !Number.isInteger(f[\"epoch\"]) || f[\"epoch\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.epoch must be a non-negative integer`,\n );\n }\n if (typeof f[\"owner\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.owner must be a string`,\n );\n }\n if (typeof f[\"claimed_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.claimed_at must be a string`,\n );\n }\n if (f[\"lease_until\"] !== undefined && typeof f[\"lease_until\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.lease_until must be string if present`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"tail_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"tail_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"tail_bytes\"]) ||\n r[\"tail_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: tail_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_bytes\"]) ||\n r[\"snapshot_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_rows\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_rows\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_rows\"]) ||\n r[\"snapshot_rows\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_rows must be a non-negative integer`,\n );\n }\n if (\n r[\"last_warned_seq\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: `typeof r[\"last_warned_seq\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n (typeof r[\"last_warned_seq\"] !== \"number\" ||\n !Number.isInteger(r[\"last_warned_seq\"]) ||\n r[\"last_warned_seq\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: last_warned_seq must be a non-negative integer if present`,\n );\n }\n return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n","/**\n * SHA-256 of `bytes` as a 64-char lowercase hex string. Used to seal\n * snapshot filenames so a crashed mid-PUT can't produce a body that\n * readers consume as truth: the filename embeds the hash; readers\n * recompute on load and reject any mismatch as \"file missing.\"\n *\n * Distinct from {@link versionFromContent} (truncated to 32 chars for\n * content keys) — snapshot bodies are larger and longer-lived;\n * 256-bit collision resistance matters here.\n */\nexport const snapshotHash = async (bytes: Uint8Array): Promise<string> => {\n // Copy via fresh ArrayBuffer: tsgo narrows `Uint8Array` to\n // `Uint8Array<ArrayBufferLike>`, which `crypto.subtle.digest` rejects\n // (wants `ArrayBufferView<ArrayBuffer>`). See microsoft/TypeScript#61375\n // and `versionFromContent` in ./hashing.ts for the same workaround.\n const view = new Uint8Array(bytes.byteLength);\n view.set(bytes);\n const digest = await crypto.subtle.digest(\"SHA-256\", view);\n const out = new Uint8Array(digest);\n let hex = \"\";\n for (let i = 0; i < out.length; i++) {\n hex += out[i]!.toString(16).padStart(2, \"0\");\n }\n return hex;\n};\n","/**\n * Shared log-walk primitives consumed by the read path (`query.ts`),\n * the compactor (`compactor.ts`), and the optional integrity walk in\n * `Writer.#singleAttemptCommit` (`writer.ts`).\n *\n * Two operations: read one log entry, or walk a contiguous range of\n * log entries with bounded parallelism. Each kernel call site\n * previously inlined the same range-build + unbounded `Promise.all`\n * pattern; on a free-tier collection where the compactor lags the\n * tail to 50-100 entries, that fans out 50-100 concurrent GETs per\n * call — and a contended writer multiplies that by the CAS retry\n * budget. `walkLogRange` caps concurrency at\n * {@link MAX_PARALLEL_LOG_READS} so a single call costs at most that\n * many simultaneous GETs against the storage backend.\n *\n * Order invariant: results are returned in seq order regardless of\n * resolution order. The read-side fold is order-sensitive (`U` then\n * `D` on the same doc must apply in that order); callers may iterate\n * the returned array as-is.\n *\n * Signal invariant: when the caller's `AbortSignal` fires, no further\n * chunks dispatch. In-flight reads see the signal via the underlying\n * `Storage.get` call.\n */\n\nimport {\n type DocumentData,\n type LogEntry,\n type Storage,\n BaerlyError,\n decodeJsonBytes,\n MAX_PARALLEL_LOG_READS,\n} from \"@baerly/protocol\";\n\n/**\n * Fetch a single log entry. Centralises the \"missing entry inside the\n * visible log range is a protocol-invariant violation\" rule used by\n * every caller.\n *\n * @throws BaerlyError code=\"Internal\" when the key resolves to no\n * body — a hole inside `[log_seq_start, next_seq)` is a corruption\n * the kernel can't continue past.\n * @throws BaerlyError code=\"InvalidResponse\" when the body isn't\n * valid JSON.\n */\nexport const readLogEntry = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry> => {\n const got = await readLogEntryWithBytes(storage, key, opts);\n return got.entry;\n};\n\n/**\n * Like {@link readLogEntry}, but also surfaces `bytes` — the\n * byteLength of the STORED log-object body exactly as it was GET back\n * from storage (`got.body.byteLength`).\n *\n * The compactor uses this to subtract from `current.json.tail_bytes`\n * the EXACT bytes the writer PUT for the folded slice. The writer\n * accumulated `encodeJsonBytes(entry).byteLength` per committed entry\n * (`writer.ts` Step 6); the stored body IS those bytes, so summing\n * `got.body.byteLength` over the folded range == the writer's\n * accumulated total for that range — no re-encode, no round-trip\n * assumption (a re-encode of the parsed `LogEntry` could drift if\n * key-order/whitespace ever diverged from what was PUT).\n *\n * Same error semantics as {@link readLogEntry}.\n */\nexport const readLogEntryWithBytes = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<{ entry: LogEntry; bytes: number }> => {\n const got = await storage.get(\n key,\n opts?.signal !== undefined ? { signal: opts.signal } : undefined,\n );\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `log-walk: missing log entry at ${key}; protocol invariant violation`,\n );\n }\n try {\n return { entry: decodeJsonBytes<LogEntry>(got.body), bytes: got.body.byteLength };\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `log-walk: malformed log entry at ${key}`, error);\n }\n};\n\n/**\n * Walk `[fromSeq, toSeqExclusive)` of `${logPrefix}/log/<seq>.json`\n * in chunks of {@link MAX_PARALLEL_LOG_READS} concurrent GETs.\n * Returns the materialised entries in seq order.\n *\n * Empty range (`fromSeq >= toSeqExclusive`) returns `[]` and issues\n * zero GETs.\n *\n * Same error semantics as {@link readLogEntry}: a missing entry\n * throws `Internal`, a malformed body throws `InvalidResponse`.\n */\nexport const walkLogRange = async (\n storage: Storage,\n logPrefix: string,\n fromSeq: number,\n toSeqExclusive: number,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry[]> => {\n const withBytes = await walkLogRangeWithBytes(storage, logPrefix, fromSeq, toSeqExclusive, opts);\n return withBytes.map((r) => r.entry);\n};\n\n/**\n * Like {@link walkLogRange}, but each element also carries `bytes` —\n * the STORED log-object body byteLength (see {@link readLogEntryWithBytes}).\n * Same seq-order, empty-range, error, and bounded-parallelism\n * ({@link MAX_PARALLEL_LOG_READS}) guarantees as {@link walkLogRange};\n * this is the bytes-aware core `walkLogRange` is implemented on top of.\n *\n * The compactor consumes this so it gets BOTH the parsed entries (for\n * the fold) AND the exact byte sum (to decrement `tail_bytes`) from a\n * single walk.\n */\nexport const walkLogRangeWithBytes = async (\n storage: Storage,\n logPrefix: string,\n fromSeq: number,\n toSeqExclusive: number,\n opts?: { signal?: AbortSignal },\n): Promise<Array<{ entry: LogEntry; bytes: number }>> => {\n if (fromSeq >= toSeqExclusive) {\n return [];\n }\n const total = toSeqExclusive - fromSeq;\n const out: Array<{ entry: LogEntry; bytes: number }> = Array.from({ length: total });\n for (let chunkStart = 0; chunkStart < total; chunkStart += MAX_PARALLEL_LOG_READS) {\n opts?.signal?.throwIfAborted();\n const chunkEnd = Math.min(chunkStart + MAX_PARALLEL_LOG_READS, total);\n const promises: Array<Promise<{ entry: LogEntry; bytes: number }>> = [];\n for (let i = chunkStart; i < chunkEnd; i++) {\n const seq = fromSeq + i;\n promises.push(readLogEntryWithBytes(storage, `${logPrefix}/log/${seq}.json`, opts));\n }\n const results = await Promise.all(promises);\n for (let i = 0; i < results.length; i++) {\n out[chunkStart + i] = results[i]!;\n }\n }\n return out;\n};\n\n/**\n * Fold a sequence of `LogEntry` records onto a doc-id-keyed map,\n * applying the protocol's per-doc-replace semantics:\n *\n * - `I` / `U`: when `entry.after !== undefined`, set\n * `map.set(entry.doc_id, entry.after)`. Entries with `after ===\n * undefined` (the partial-merge writer's future patch-only shape)\n * are ignored — today's writer always emits `after`, so this is a\n * forward-compat guard, not a live branch.\n * - `D`: tombstone — `map.delete(entry.doc_id)`.\n *\n * Entries whose `collection` does not match `opts.collection`, or\n * whose `doc_id` is `undefined`, are skipped. When\n * `opts.docIdFilter` is provided, only entries whose `doc_id` is\n * present in the filter set are folded — used by the index-walk\n * read path to scope the fold to the docs the planner already\n * resolved.\n *\n * This is the canonical fold used by the read path\n * (`query.ts`) and the index reconciler (`rebuild-index.ts`).\n * Centralising it keeps the\n * \"straight `set` on I/U; tombstone on D\" protocol invariant in one place.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\nexport const foldLogEntriesOnto = <T extends DocumentData>(\n map: Map<string, T>,\n entries: Iterable<LogEntry>,\n opts: {\n readonly collection: string;\n readonly docIdFilter?: ReadonlySet<string>;\n },\n): void => {\n const { collection, docIdFilter } = opts;\n for (const entry of entries) {\n if (entry.collection !== collection) {\n continue;\n }\n if (entry.doc_id === undefined) {\n continue;\n }\n if (docIdFilter !== undefined && !docIdFilter.has(entry.doc_id)) {\n continue;\n }\n switch (entry.op) {\n case \"I\":\n case \"U\": {\n if (entry.after === undefined) {\n continue;\n }\n map.set(entry.doc_id, entry.after as T);\n break;\n }\n case \"D\": {\n map.delete(entry.doc_id);\n break;\n }\n }\n }\n};\n","/**\n * Snapshot file shape + parse. Lifted out of `./compactor.ts` so that\n * the kernel barrel (`packages/server/src/index.ts`) — which re-exports\n * these four symbols — does not transitively pull `withObservability`\n * via `compact()`. `./compactor.ts` imports its own snapshot primitives\n * back from this module; the public API surface is unchanged.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\n\nimport {\n BaerlyError,\n decodeJsonBytes,\n type DocumentData,\n encodeJsonBytes,\n snapshotHash,\n type Storage,\n} from \"@baerly/protocol\";\n\n/**\n * Single-level snapshot at L9; the level prefix is forward-compatible\n * with future L0..L9 rolling merges without a wire change.\n */\nexport const SNAPSHOT_LEVEL = 9 as const;\n\n/**\n * `minSeq` and `maxSeq` are padded to {@link SEQ_DIGITS} digits so\n * `list(prefix)` returns snapshots in seq order without needing to\n * parse the filename. 12 digits caps at ~10^12 entries per collection;\n * a real bucket hits S3's per-prefix QPS ceiling long before that.\n */\nexport const SEQ_DIGITS = 12 as const;\n\nconst MAX_SEQ = 10 ** SEQ_DIGITS - 1;\n\n/**\n * Build the on-bucket key for a snapshot file. `sha256` must be the\n * lowercase hex digest of the canonical body\n * ({@link encodeSnapshotBody}); the filename embeds it so a crashed\n * mid-PUT body that doesn't match its own filename hash is rejected\n * by readers as \"missing.\"\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `minSeq`/`maxSeq` are\n * out of range or `sha256` is not 64 hex chars.\n */\nexport const snapshotKey = (\n collectionPrefix: string,\n minSeq: number,\n maxSeq: number,\n sha256: string,\n): string => {\n if (minSeq < 0 || maxSeq < 0 || minSeq > maxSeq || maxSeq > MAX_SEQ) {\n throw new BaerlyError(\"InvalidConfig\", `snapshotKey: invalid range [${minSeq}, ${maxSeq})`);\n }\n if (!/^[0-9a-f]{64}$/.test(sha256)) {\n throw new BaerlyError(\"InvalidConfig\", \"snapshotKey: sha256 must be 64 hex chars\");\n }\n const pad = (n: number): string => n.toString().padStart(SEQ_DIGITS, \"0\");\n return `${collectionPrefix}/snapshot/L${SNAPSHOT_LEVEL}/${pad(minSeq)}-${pad(maxSeq)}-${sha256}.json`;\n};\n\n/**\n * On-bucket body of a snapshot file. The reader recomputes the SHA-256\n * over the canonical serialisation ({@link encodeSnapshotBody}) and\n * rejects any mismatch with the filename hash.\n *\n * `docs` is sorted by `_id` for deterministic byte output — two\n * compactions over the same fold produce byte-identical snapshots,\n * which means same filename, which means an idempotent re-run never\n * leaves an orphan.\n */\nexport interface SnapshotBody {\n readonly schema_version: 1;\n readonly min_seq: number;\n readonly max_seq: number;\n readonly collection: string;\n readonly docs: ReadonlyArray<{\n readonly _id: string;\n readonly body: DocumentData;\n }>;\n}\n\n/**\n * Canonical byte encoding of a {@link SnapshotBody}. Only the\n * compactor produces snapshots, and only this function does the\n * serialisation — so the byte output is deterministic for a given\n * `SnapshotBody` (identical input ⇒ identical bytes ⇒ identical\n * filename hash).\n */\nexport const encodeSnapshotBody = (s: SnapshotBody): Uint8Array => encodeJsonBytes(s);\n\n/**\n * Load a snapshot file as a `Map<_id, DocumentData>`. Verifies the\n * body hash against the filename, checks the schema version, and\n * cross-checks `body.collection` against the caller's expectation.\n *\n * @example\n * ```ts\n * import { loadSnapshotAsMap } from \"@gusto/baerly-storage\";\n *\n * const map =\n * srcCurrent.snapshot === null\n * ? new Map<string, DocumentData>()\n * : await loadSnapshotAsMap(src.storage, srcCurrent.snapshot, \"tickets\");\n * ```\n *\n * @throws BaerlyError code=\"Internal\" — pointer resolves to no body,\n * or the body's SHA-256 doesn't match the hash embedded in the\n * filename. (Protocol invariant violation; a corrupted snapshot\n * the reader cannot continue past.)\n * @throws BaerlyError code=\"InvalidResponse\" — body isn't valid JSON,\n * isn't an object, has an unsupported `schema_version`, or carries a\n * `collection` that doesn't match `expectedCollection`.\n */\nexport const loadSnapshotAsMap = async (\n storage: Storage,\n key: string,\n expectedCollection: string,\n signal?: AbortSignal,\n): Promise<Map<string, DocumentData>> => {\n const got = await storage.get(key, signal !== undefined ? { signal } : undefined);\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot pointer ${key} resolves to no body; protocol violation`,\n );\n }\n // Verify hash: the filename shape is\n // `<...>/snapshot/L<n>/<min>-<max>-<sha256>.json`. The sha256 is\n // the segment after the LAST `-` (the two seq fields don't contain\n // dashes), with `.json` stripped.\n const filename = key.slice(key.lastIndexOf(\"/\") + 1).replace(/\\.json$/, \"\");\n const lastDash = filename.lastIndexOf(\"-\");\n const expectedHash = filename.slice(lastDash + 1);\n const actualHash = await snapshotHash(got.body);\n if (actualHash !== expectedHash) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot ${key} body hash mismatch (got ${actualHash}); protocol violation`,\n );\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} body is not valid JSON`,\n error,\n );\n }\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `compact: snapshot ${key} body is not an object`);\n }\n const body = parsed as SnapshotBody;\n if (body.schema_version !== 1) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} has unsupported schema_version ${String(body.schema_version)}`,\n );\n }\n if (body.collection !== expectedCollection) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} carries collection ${body.collection}, expected ${expectedCollection}`,\n );\n }\n const out = new Map<string, DocumentData>();\n for (const row of body.docs) {\n out.set(row._id, row.body);\n }\n return out;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgMA,eAAsB,gBACpB,SACA,KACA,MACiC;CACjC,MAAM,MAAM,MAAM,QAAQ,IAAI,KAAK,IAAI;CACvC,IAAI,QAAQ,MACV,OAAO;CAET,MAAM,OAAO,IAAI,YAAY,EAAE,OAAO,IAAI,IAAI;CAC9C,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,IAAI;CAC1B,SAAS,OAAO;EACd,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,2BACvB,KACF;CACF;CACA,OAAO;EAAE,MAAM,kBAAkB,QAAQ,GAAG;EAAG,MAAM,IAAI;CAAK;AAChE;;;;;;;;;;;AAYA,eAAsB,kBACpB,SACA,KACA,SACA,MAC0B;CAE1B,kBAAkB,SAAS,GAAG;CAC9B,MAAM,OAAO,WAAW,OAAO;CAC/B,MAAM,UAA6B;EACjC,aAAa;EACb,aAAa;EACb,GAAI,MAAM,WAAW,KAAA,KAAa,EAAE,QAAQ,KAAK,OAAO;CAC1D;CACA,IAAI;CACJ,IAAI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