@gusto/baerly-storage 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/API.md +59 -7
- package/dist/{app-config-Dj_nGBfj.d.ts → app-config-C0Bbw_Z6.d.ts} +9 -9
- package/dist/app-config.d.ts +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-CC5yVs1S.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-aRMK_0R0.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-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
- package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
- package/dist/http.d.ts +3 -3
- package/dist/http.js +1 -1
- package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
- package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
- package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
- package/dist/{index-spCBsIwm.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-BIH73Uv4.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-Cr9C7_tT.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-Cr9C7_tT.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,57 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as
|
|
1
|
+
import { n as encodeJsonBytes, t as decodeJsonBytes } from "./bytes-BXdamO3L.js";
|
|
2
|
+
import { a as readLogEntry, d as logSeqStartOf, f as readCurrentJson, o as walkLogRange, u as createCurrentJson } from "./snapshot-SS8USDUF.js";
|
|
3
|
+
import { a as getCurrentContext, c as noopMetricsRecorder, l as versionFromContent, n as runBoundedMaintenance, o as allIndexKeysFor, r as shouldFireMaintenance, s as validateIndexDefinition, t as dispatchInlineAwaited } from "./maintenance-BvOv6BMM.js";
|
|
4
|
+
import { a as uuid, i as countKey, n as parseBucketUri, r as timestamp, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
|
|
3
5
|
import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
|
|
4
|
-
import { r as validateIndexDefinition, t as allIndexKeysFor } from "./indexes-BXn7a06a.js";
|
|
5
|
-
import { t as defineBaerlySubcommand } from "./subcommand-BWs6K7zb.js";
|
|
6
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
6
|
import { createInterface } from "node:readline";
|
|
8
|
-
//#region ../protocol/src/hashing.ts
|
|
9
|
-
/**
|
|
10
|
-
* Width of the {@link ContentVersionId} hex strings produced by
|
|
11
|
-
* {@link versionFromContent}. 32 hex chars = 128 bits, matching the
|
|
12
|
-
* information content of a v4 UUID. Collision probability with
|
|
13
|
-
* N=10⁹ writes is ~3 × 10⁻²⁰; ample for a content-addressed version id.
|
|
14
|
-
*
|
|
15
|
-
* @see docs/spec/log-entry-shape.md §"Content body layout"
|
|
16
|
-
*/
|
|
17
|
-
const VERSION_HEX_LENGTH = 32;
|
|
18
|
-
/**
|
|
19
|
-
* Content-addressed {@link ContentVersionId}: SHA-256 of `body`,
|
|
20
|
-
* lowercase hex, truncated to {@link VERSION_HEX_LENGTH}. Same body
|
|
21
|
-
* bytes ⇒ same ContentVersionId — the property `Writer.commit`
|
|
22
|
-
* relies on for idempotent replay (a crash-recovery rewrite of the
|
|
23
|
-
* same logical value produces the same content key the manifest
|
|
24
|
-
* already referenced).
|
|
25
|
-
*
|
|
26
|
-
* Async because {@link crypto.subtle.digest} returns an `ArrayBuffer`
|
|
27
|
-
* via Promise. Workers and browsers both expose `crypto.subtle`
|
|
28
|
-
* synchronously enough that the await fits naturally in the write
|
|
29
|
-
* pipeline.
|
|
30
|
-
*
|
|
31
|
-
* @see docs/spec/log-entry-shape.md §"Content body layout"
|
|
32
|
-
*/
|
|
33
|
-
const versionFromContent = async (body) => {
|
|
34
|
-
const view = new Uint8Array(body.byteLength);
|
|
35
|
-
view.set(body);
|
|
36
|
-
const digest = await crypto.subtle.digest("SHA-256", view);
|
|
37
|
-
const bytes = new Uint8Array(digest);
|
|
38
|
-
let hex = "";
|
|
39
|
-
for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
|
|
40
|
-
return hex.slice(0, VERSION_HEX_LENGTH);
|
|
41
|
-
};
|
|
42
|
-
//#endregion
|
|
43
|
-
//#region ../protocol/src/metrics.ts
|
|
44
|
-
/**
|
|
45
|
-
* No-op recorder. Safe default when no operator sink is wired —
|
|
46
|
-
* emission sites that read `getCurrentContext()?.recorder` fall
|
|
47
|
-
* back to this outside an active `runWithContext` scope.
|
|
48
|
-
*/
|
|
49
|
-
const noopMetricsRecorder = {
|
|
50
|
-
counter: () => {},
|
|
51
|
-
gauge: () => {},
|
|
52
|
-
histogram: () => {}
|
|
53
|
-
};
|
|
54
|
-
//#endregion
|
|
55
7
|
//#region ../server/src/log-conflict-adoption.ts
|
|
56
8
|
/**
|
|
57
9
|
* Decide whether the entry already at `/log/<seq>.json` is the
|
|
@@ -81,56 +33,6 @@ const tryAdoptOwnSessionLogEntry = (ctx) => {
|
|
|
81
33
|
};
|
|
82
34
|
};
|
|
83
35
|
//#endregion
|
|
84
|
-
//#region ../server/src/observability/context.ts
|
|
85
|
-
/**
|
|
86
|
-
* Per-request observability context.
|
|
87
|
-
*
|
|
88
|
-
* One `ObservabilityContext` is created at the entry of each unit-of-
|
|
89
|
-
* work (HTTP request, maintenance tick, GC sweep, rebuild run) and
|
|
90
|
-
* carried through the call tree via {@link runWithContext} /
|
|
91
|
-
* {@link getCurrentContext}, which delegates to a single module-level
|
|
92
|
-
* `AsyncLocalStorage` instance.
|
|
93
|
-
*
|
|
94
|
-
* The context is intentionally tiny: an externally-set
|
|
95
|
-
* {@link request_id}, a high-resolution `started_at`, and a mutable
|
|
96
|
-
* {@link fields} bag used to accumulate canonical-line attributes
|
|
97
|
-
* during the unit's lifecycle.
|
|
98
|
-
*
|
|
99
|
-
* The context shape is `readonly` everywhere it can be — only the
|
|
100
|
-
* contents of `fields` are intended to mutate during a request. The
|
|
101
|
-
* {@link fields} map itself is not `readonly` because callers (the
|
|
102
|
-
* canonical-line emitter, middleware, the collection API once Dispatch
|
|
103
|
-
* 3+ wires it up) need to set entries.
|
|
104
|
-
*
|
|
105
|
-
* The context carries no sampling state — every unit-of-work emits
|
|
106
|
-
* one canonical line unconditionally; there is nothing to gate.
|
|
107
|
-
*
|
|
108
|
-
* ## Time source
|
|
109
|
-
*
|
|
110
|
-
* `started_at` uses `performance.now()` so durations can be
|
|
111
|
-
* computed without worrying about wall-clock skew (NTP step,
|
|
112
|
-
* leap-second smearing). `performance.now()` is part of both Node
|
|
113
|
-
* 18+ and the Workers Runtime; we don't fall back to `Date.now()`.
|
|
114
|
-
*
|
|
115
|
-
* @example
|
|
116
|
-
* ```ts
|
|
117
|
-
* const ctx = createObservabilityContext({});
|
|
118
|
-
* await runWithContext(ctx, async () => {
|
|
119
|
-
* const inner = getCurrentContext();
|
|
120
|
-
* inner?.fields.set("collection", "tickets");
|
|
121
|
-
* await doWork();
|
|
122
|
-
* });
|
|
123
|
-
* ```
|
|
124
|
-
*/
|
|
125
|
-
/**
|
|
126
|
-
* Module-level slot. One instance per process — the Workers
|
|
127
|
-
* Runtime's `nodejs_compat` flag wires `node:async_hooks` to a
|
|
128
|
-
* per-request scope, so cross-request bleed is impossible there.
|
|
129
|
-
*/
|
|
130
|
-
const als = new AsyncLocalStorage();
|
|
131
|
-
/** Returns the currently-active context, or `undefined` outside one. */
|
|
132
|
-
const getCurrentContext = () => als.getStore();
|
|
133
|
-
//#endregion
|
|
134
36
|
//#region ../server/src/writer.ts
|
|
135
37
|
/**
|
|
136
38
|
* `Writer` — stateless multi-instance write engine.
|
|
@@ -369,23 +271,22 @@ var Writer = class {
|
|
|
369
271
|
const baseEtag = read.etag;
|
|
370
272
|
const expectedEpoch = current.writer_fence.epoch;
|
|
371
273
|
if (this.#verifyLogIntegrityOnCommit) await this.#walkLog(logPrefix, logSeqStartOf(current), current.next_seq);
|
|
274
|
+
const commitNowMs = Date.now();
|
|
275
|
+
const commitTs = new Date(commitNowMs).toISOString();
|
|
276
|
+
const lsnTimestamp = timestamp(commitNowMs);
|
|
372
277
|
const entries = [];
|
|
373
278
|
for (let i = 0; i < inputs.length; i++) {
|
|
374
279
|
const input = inputs[i];
|
|
375
280
|
const seq = current.next_seq + i;
|
|
376
281
|
const entry = {
|
|
377
|
-
lsn: `${
|
|
378
|
-
commit_ts:
|
|
282
|
+
lsn: `${lsnTimestamp}_${session}_${countKey(seq)}`,
|
|
283
|
+
commit_ts: commitTs,
|
|
379
284
|
op: input.op,
|
|
380
285
|
collection: input.collection,
|
|
381
286
|
doc_id: input.docId,
|
|
382
|
-
schema_version: 0,
|
|
383
287
|
session,
|
|
384
288
|
seq,
|
|
385
|
-
...input.op !== "D" && input.body !== void 0 ? {
|
|
386
|
-
new: input.body,
|
|
387
|
-
patch: input.body
|
|
388
|
-
} : {},
|
|
289
|
+
...input.op !== "D" && input.body !== void 0 ? { after: input.body } : {},
|
|
389
290
|
...input.origin !== void 0 ? { origin: input.origin } : {}
|
|
390
291
|
};
|
|
391
292
|
entries.push(entry);
|
|
@@ -472,10 +373,14 @@ var Writer = class {
|
|
|
472
373
|
else throw new BaerlyError("Conflict", `${errorPrefix}: log entry already exists at ${logEntryKey}; ${decision.reason}`);
|
|
473
374
|
} else throw new BaerlyError("Conflict", `${errorPrefix}: log entry already exists at ${logEntryKey}; peer wrote our seq`);
|
|
474
375
|
}
|
|
475
|
-
const
|
|
376
|
+
const batchLogBytes = committedEntries.reduce((sum, e) => sum + encodeJsonBytes(e).byteLength, 0);
|
|
377
|
+
const next = {
|
|
476
378
|
...current,
|
|
477
|
-
next_seq: current.next_seq + inputs.length
|
|
478
|
-
|
|
379
|
+
next_seq: current.next_seq + inputs.length,
|
|
380
|
+
tail_bytes: current.tail_bytes + batchLogBytes
|
|
381
|
+
};
|
|
382
|
+
if (next.next_seq - current.next_seq !== inputs.length) throw new BaerlyError("Internal", `${errorPrefix}: GC-cadence invariant violated — next_seq advanced by ${next.next_seq - current.next_seq} but ${inputs.length} input(s) were committed on ${this.#currentJsonKey}`);
|
|
383
|
+
const nextBody = encodeJsonBytes(next);
|
|
479
384
|
const putOpts = {
|
|
480
385
|
ifMatch: baseEtag,
|
|
481
386
|
contentType: APPLICATION_JSON
|
|
@@ -494,6 +399,16 @@ var Writer = class {
|
|
|
494
399
|
}
|
|
495
400
|
throw error;
|
|
496
401
|
}
|
|
402
|
+
const prevSeq = current.next_seq;
|
|
403
|
+
const maint = getCurrentContext()?.maintenance;
|
|
404
|
+
if (maint?.disabled !== true) {
|
|
405
|
+
if (shouldFireMaintenance(next, prevSeq, maint?.options?.gcInterval ?? 4)) await (maint?.dispatch ?? dispatchInlineAwaited)(() => runBoundedMaintenance({
|
|
406
|
+
storage: this.#storage,
|
|
407
|
+
currentJsonKey: this.#currentJsonKey,
|
|
408
|
+
prevSeq,
|
|
409
|
+
...maint?.maxFoldBytes !== void 0 && { maxFoldBytes: maint.maxFoldBytes }
|
|
410
|
+
}, maint?.options).then(() => {}, () => {}));
|
|
411
|
+
}
|
|
497
412
|
const classAOps = contentPutCount + entries.length + indexClassA + 1;
|
|
498
413
|
return {
|
|
499
414
|
entries: committedEntries,
|
|
@@ -551,7 +466,7 @@ var Writer = class {
|
|
|
551
466
|
*/
|
|
552
467
|
async #provisionCurrentJson() {
|
|
553
468
|
const initial = {
|
|
554
|
-
schema_version:
|
|
469
|
+
schema_version: 2,
|
|
555
470
|
snapshot: null,
|
|
556
471
|
next_seq: 0,
|
|
557
472
|
log_seq_start: 0,
|
|
@@ -559,7 +474,10 @@ var Writer = class {
|
|
|
559
474
|
epoch: 0,
|
|
560
475
|
owner: "",
|
|
561
476
|
claimed_at: ""
|
|
562
|
-
}
|
|
477
|
+
},
|
|
478
|
+
tail_bytes: 0,
|
|
479
|
+
snapshot_bytes: 0,
|
|
480
|
+
snapshot_rows: 0
|
|
563
481
|
};
|
|
564
482
|
try {
|
|
565
483
|
return await createCurrentJson(this.#storage, this.#currentJsonKey, initial);
|
|
@@ -583,7 +501,7 @@ var Writer = class {
|
|
|
583
501
|
}
|
|
584
502
|
if (entry.collection !== collection || entry.doc_id !== docId) continue;
|
|
585
503
|
if (entry.op === "D") return;
|
|
586
|
-
if ((entry.op === "I" || entry.op === "U") && entry.
|
|
504
|
+
if ((entry.op === "I" || entry.op === "U") && entry.after !== void 0) return entry.after;
|
|
587
505
|
}
|
|
588
506
|
}
|
|
589
507
|
/**
|
|
@@ -764,7 +682,7 @@ const bundle = defineBaerlySubcommand({
|
|
|
764
682
|
if (head !== null) {
|
|
765
683
|
const truncatedNext = head.json.next_seq;
|
|
766
684
|
const reseeded = {
|
|
767
|
-
schema_version:
|
|
685
|
+
schema_version: 2,
|
|
768
686
|
snapshot: null,
|
|
769
687
|
next_seq: truncatedNext,
|
|
770
688
|
log_seq_start: truncatedNext,
|
|
@@ -772,7 +690,10 @@ const bundle = defineBaerlySubcommand({
|
|
|
772
690
|
epoch: head.json.writer_fence.epoch + 1,
|
|
773
691
|
owner: RESTORE_OWNER,
|
|
774
692
|
claimed_at: ""
|
|
775
|
-
}
|
|
693
|
+
},
|
|
694
|
+
tail_bytes: 0,
|
|
695
|
+
snapshot_bytes: 0,
|
|
696
|
+
snapshot_rows: 0
|
|
776
697
|
};
|
|
777
698
|
try {
|
|
778
699
|
await bucket.storage.put(currentJsonKey, encodeJsonBytes(reseeded), {
|
|
@@ -785,7 +706,7 @@ const bundle = defineBaerlySubcommand({
|
|
|
785
706
|
}
|
|
786
707
|
} else {
|
|
787
708
|
const seed = {
|
|
788
|
-
schema_version:
|
|
709
|
+
schema_version: 2,
|
|
789
710
|
snapshot: null,
|
|
790
711
|
next_seq: 0,
|
|
791
712
|
log_seq_start: 0,
|
|
@@ -793,7 +714,10 @@ const bundle = defineBaerlySubcommand({
|
|
|
793
714
|
epoch: 0,
|
|
794
715
|
owner: RESTORE_OWNER,
|
|
795
716
|
claimed_at: ""
|
|
796
|
-
}
|
|
717
|
+
},
|
|
718
|
+
tail_bytes: 0,
|
|
719
|
+
snapshot_bytes: 0,
|
|
720
|
+
snapshot_rows: 0
|
|
797
721
|
};
|
|
798
722
|
await createCurrentJson(bucket.storage, currentJsonKey, seed);
|
|
799
723
|
}
|
|
@@ -844,4 +768,4 @@ bundle.run;
|
|
|
844
768
|
//#endregion
|
|
845
769
|
export { restoreCmd };
|
|
846
770
|
|
|
847
|
-
//# sourceMappingURL=restore-
|
|
771
|
+
//# sourceMappingURL=restore-C6IcmLeA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"restore-C6IcmLeA.js","names":["#storage","#currentJsonKey","#maxRetries","#initialBackoffMs","#random","#indexes","#verifyLogIntegrityOnCommit","#singleAttemptCommit","#backoff","#verifyFenceUnchanged","#emitWriteMetrics","#provisionCurrentJson","#walkLog","#observe429","#readPreImage"],"sources":["../packages/server/src/log-conflict-adoption.ts","../packages/server/src/writer.ts","../packages/cli/src/admin/restore.ts"],"sourcesContent":["/**\n * Self-session log-conflict adoption — the one decision that\n * distinguishes a retry of our own prior commit attempt from a\n * peer racing us at the same `seq`.\n *\n * Background. `Writer.#singleAttemptCommit` PUTs each log entry with\n * `If-None-Match: \"*\"`. A 412 on `/log/<seq>.json` can mean either\n *\n * (a) a peer wrote a DIFFERENT entry at the same seq — we lost\n * the race; the caller's CAS will also fail; or\n * (b) our OWN previous attempt landed the log PUT but lost the\n * subsequent `current.json` CAS-advance, and we're now\n * re-driving the same logical commit.\n *\n * This function makes the (a)/(b) call. It is callable, separately\n * testable, and patent-disclosable in isolation from the rest of the\n * commit path.\n *\n * ## Soundness invariant\n *\n * Adoption is sound iff all three hold:\n *\n * 1. **Same session.** `existing.session === self.session`. The\n * session id is a per-commit, in-RAM-only secret minted at\n * `Writer.commit` from `crypto.randomUUID().slice(0,\n * SESSION_ID_LENGTH)`; an adversary with bucket-write access\n * can forge any other field but cannot forge a value they\n * did not observe being PUT.\n * 2. **Matching seq.** `existing.seq === self.expectedSeq`. The\n * seq match is also implied by the key shape (the writer\n * reads `/log/<expectedSeq>.json`), but is re-asserted here\n * so the invariant is visible at the decision site.\n * 3. **Single-input commit.** `self.batchSize === 1`. Batches\n * surface a log-PUT 412 as `Conflict` immediately — the\n * caller (`Db.transaction`) decides whether to re-run the\n * body. Adoption inside a batch would require per-input\n * adoption decisions that don't compose with the\n * all-or-nothing CAS-advance on `current.json`.\n *\n * When any of (1)/(2)/(3) fails, the writer MUST throw\n * `BaerlyError{code:\"Conflict\"}` and let the caller's retry-or-\n * surface logic run.\n *\n * ## Threat model\n *\n * The adversary may (a) write arbitrary bytes to any key in the\n * bucket, (b) replay any PUT they previously observed on the wire,\n * (c) reorder or drop network packets between the writer and the\n * bucket. The adversary may NOT (d) read the writer's local RAM\n * and therefore cannot learn the per-commit `session` id before\n * observing the writer's own `/log/<seq>.json` PUT. Under these\n * constraints, conditions (1)+(2)+(3) close every attack path in\n * the adversarial-replay property test\n * (`tests/integration/log-conflict-adversarial.test.ts`).\n *\n * **Pinned by:** `tests/integration/log-conflict-forgery.test.ts`\n * exercises the session-id-unguessability claim under a\n * `ForgeryStorage` adversary that plants arbitrary entries at the\n * writer's expected log key. Property verified by default at\n * `numRuns: 1000`; `FC_NUM_RUNS=10000` for the hardening sweep.\n *\n * ## Prior art\n *\n * SlateDB's manifest-pivot writer protocol (rfcs/0001-manifest.md,\n * scenarios 1–4) is the closest published prior art on the broader\n * commit-protocol skeleton. SlateDB's scenario 3 — \"conflicting SST\n * has same `writer_epoch` as me\" — is explicitly labelled an\n * **illegal state that should panic**. The three-clause adoption\n * decision encoded here (same session ∧ matching seq ∧ single-input)\n * recognises that case as the writer's own prior in-flight attempt\n * and adopts it as success rather than aborting, closing the recovery\n * gap SlateDB leaves to operator intervention.\n *\n * Apache Iceberg and Delta Lake commits surface analogous failures as\n * `CommitFailedException` / commit-conflict retries; neither inspects\n * the conflicting object to determine ownership.\n *\n * See `docs/spec/prior-art.md` for the consolidated IDS-shaped\n * differentiation.\n *\n * @see docs/spec/sync-protocol.md §\"Self-session log-conflict adoption\"\n */\n\nimport type { LogEntry } from \"@baerly/protocol\";\n\n/**\n * Inputs to {@link tryAdoptOwnSessionLogEntry}. All fields are\n * required; the writer constructs this struct at the call site.\n */\nexport interface AdoptionContext {\n /**\n * The entry the writer just attempted to PUT. Carries the\n * writer's session, expected seq, and the rest of the LogEntry\n * shape minted in `Writer.#singleAttemptCommit` step 3.\n */\n readonly self: LogEntry;\n /**\n * The entry currently stored at `/log/<self.seq>.json`, as read\n * back after a 412. The caller is responsible for the GET (the\n * function is pure, no I/O).\n */\n readonly existing: LogEntry;\n /**\n * `inputs.length` for the parent commit attempt. `1` for\n * `Writer.commit`; `inputs.length` for `Writer.commitBatch`.\n * Adoption is only safe when this is exactly `1`.\n */\n readonly batchSize: number;\n}\n\n/**\n * Discriminated outcome of {@link tryAdoptOwnSessionLogEntry}.\n * `adopt: true` carries the existing entry (which by the\n * invariant is byte-identical to `self` modulo `commit_ts`); the\n * caller substitutes it for `self` so the returned `CommitResult`\n * matches what's actually stored. `adopt: false` carries a\n * machine-readable `reason` so callers and tests can discriminate\n * which clause of the invariant failed.\n */\nexport type AdoptionDecision =\n | { readonly adopt: true; readonly entry: LogEntry }\n | { readonly adopt: false; readonly reason: \"foreign-session\" | \"wrong-seq\" | \"batch\" };\n\n/**\n * Decide whether the entry already at `/log/<seq>.json` is the\n * writer's own prior in-flight attempt and may be adopted. Pure\n * function; no I/O. The caller performs the GET (when the log PUT\n * surfaces 412) and passes the read-back body in `ctx.existing`.\n *\n * @see {@link AdoptionDecision} for the return shape.\n * @see The soundness invariant in this module's header docstring.\n */\nexport const tryAdoptOwnSessionLogEntry = (ctx: AdoptionContext): AdoptionDecision => {\n // Clause (3) — single-input commit. Evaluated first so a batched\n // call short-circuits before any field comparison.\n if (ctx.batchSize !== 1) {\n return { adopt: false, reason: \"batch\" };\n }\n // Clause (1) — same session.\n if (ctx.existing.session !== ctx.self.session) {\n return { adopt: false, reason: \"foreign-session\" };\n }\n // Clause (2) — matching seq. The seq is also implied by the\n // key the caller read from, but re-asserted here for\n // patent-disclosure clarity.\n if (ctx.existing.seq !== ctx.self.seq) {\n return { adopt: false, reason: \"wrong-seq\" };\n }\n return { adopt: true, entry: ctx.existing };\n};\n","/**\n * `Writer` — stateless multi-instance write engine.\n *\n * Each {@link Writer.commit} call reads `current.json` FRESH from\n * the bucket, mints the next {@link LogEntry}, PUTs the content body\n * and the log entry, and CAS-advances `current.json` with `If-Match`.\n * Up to {@link S3_REQUEST_MAX_RETRIES} attempts on contention before\n * surfacing `BaerlyError{code:\"Conflict\"}`. The optional integrity\n * walk over the live log tail is gated by\n * {@link WriterOptions.verifyLogIntegrityOnCommit} (default off\n * — see the option's docstring).\n *\n * The instance carries no per-write cache: every commit re-reads\n * `current.json`, so N stateless server instances writing the same\n * tenant prefix contend at exactly one place — the conditional PUT\n * on `current.json` — and one loses cleanly with a 412.\n *\n * **Manifest-first ordering is REVERSED relative to the legacy\n * `src/syncer.ts` write loop.** Old loop: PUT manifest → PUT content\n * → CAS. New loop: PUT content → PUT log entry → CAS-advance\n * `current.json`. A crashed mid-loop writer leaves an unreferenced\n * content body (no log entry points at it), not an orphan log entry\n * with missing content. The compactor sweeps the orphan content\n * later.\n *\n * **`LogEntry` shape.** Emitted entries follow the contract in\n * `packages/protocol/src/log.ts` (see {@link LogEntry}) and\n * `docs/spec/log-entry-shape.md`. The on-bucket key is\n * `log/<seq>.json` (the integer `seq` is the load-bearing\n * identifier; the `lsn` string is schema-only).\n *\n * @see docs/spec/sync-protocol.md for the protocol invariants this\n * loop preserves.\n * @see docs/spec/log-entry-shape.md for the per-field contract.\n */\n\nimport {\n CURRENT_JSON_SCHEMA_VERSION,\n type CurrentJson,\n type CurrentJsonRead,\n type DocumentData,\n type LogEntry,\n type MetricsRecorder,\n createCurrentJson,\n decodeJsonBytes,\n encodeJsonBytes,\n logSeqStartOf,\n BaerlyError,\n noopMetricsRecorder,\n type Storage,\n type StoragePutOptions,\n type StoragePutResult,\n S3_REQUEST_MAX_RETRIES,\n SESSION_ID_LENGTH,\n WRITE_TICK_GC_INTERVAL,\n countKey,\n readCurrentJson,\n timestamp,\n uuid,\n versionFromContent,\n} from \"@baerly/protocol\";\nimport { allIndexKeysFor, type IndexDefinition, validateIndexDefinition } from \"./indexes.ts\";\nimport { readLogEntry, walkLogRange } from \"./log-walk.ts\";\nimport { tryAdoptOwnSessionLogEntry } from \"./log-conflict-adoption.ts\";\nimport {\n dispatchInlineAwaited,\n runBoundedMaintenance,\n shouldFireMaintenance,\n} from \"./maintenance.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\n\nconst ctxMetrics = (): MetricsRecorder => getCurrentContext()?.recorder ?? noopMetricsRecorder;\n\n/**\n * Tunables for {@link Writer}. All optional; defaults match the\n * legacy retry budget so the new loop is a drop-in replacement.\n */\nexport interface WriterOptions {\n /**\n * Max CAS attempts on 412 before throwing `Conflict`. Default\n * {@link S3_REQUEST_MAX_RETRIES} (8). Override only in tests.\n */\n readonly maxRetries?: number;\n\n /** Initial backoff in ms; doubles per attempt, capped at 1500ms. Default 25. */\n readonly initialBackoffMs?: number;\n\n /**\n * Pure function returning a number in [0, 1). Used for jitter; tests\n * inject a deterministic generator. Defaults to `Math.random`.\n */\n readonly random?: () => number;\n\n /**\n * Optional. Indexes declared for the collection this writer\n * commits to. Each commit emits one zero-byte PUT per declared\n * index (when the indexed field is set on the doc) inside the\n * same fence as the log entry and content body. On U/D, the\n * writer reads the pre-image content body from the log (one\n * back-walk per indexed collection, NOT per index) to compute\n * the stale-key set; stale keys are DELETE'd inside the same\n * fence.\n *\n * Validated at construction via {@link validateIndexDefinition} —\n * an invalid def throws `BaerlyError{code:\"SchemaError\"}`\n * synchronously, before the first commit. Empty / undefined is\n * a no-op (writer behaves identically to the no-index path — no\n * extra GET, no extra PUTs).\n *\n * Note: `Writer` is per-collection (the `currentJsonKey`\n * is per-collection), so this array applies to one collection\n * only — adapters that serve multiple collections instantiate\n * one writer per collection.\n *\n * Emits one new metric when at least one index is declared:\n * - `db.write.index_ops_per_logical_write` (histogram,\n * labelled by `collection`) — `K (PUT) + L (DELETE)` per\n * successful commit.\n */\n readonly indexes?: ReadonlyArray<IndexDefinition>;\n\n /**\n * When `true`, every commit walks the live log range\n * `[log_seq_start, next_seq)` before minting a new entry, surfacing\n * a missing or malformed entry as `BaerlyError{code:\"Internal\"}`\n * (or `\"InvalidResponse\"` for parse failures). The walk is purely\n * observational — the per-doc fold lives in the read path\n * (`./query.ts`) and any hole inside the visible range would also\n * fire on the next read.\n *\n * Production callers default this OFF: under contention the walk\n * issues `O(tail)` Class-B GETs per CAS attempt and the retry\n * budget multiplies that by {@link S3_REQUEST_MAX_RETRIES}. Tests\n * that intentionally puncture bucket state to exercise the\n * invariant trigger opt in by passing `true`.\n *\n * Default `false`.\n */\n readonly verifyLogIntegrityOnCommit?: boolean;\n}\n\n/**\n * Single-doc mutation request. One `commit()` ↔ one {@link LogEntry}.\n */\nexport interface CommitInput {\n /** The mutation op. Maps directly to {@link LogEntry.op}. */\n readonly op: \"I\" | \"U\" | \"D\";\n\n /** The collection (table) name. Becomes {@link LogEntry.collection}. */\n readonly collection: string;\n\n /** The document primary key. Becomes {@link LogEntry.doc_id}. */\n readonly docId: string;\n\n /**\n * For `I` / `U`: the post-image. Becomes {@link LogEntry.after}. Must\n * be `undefined` for `op: \"D\"`.\n */\n readonly body?: DocumentData;\n\n /** Optional ISO-8601 origin marker; becomes {@link LogEntry.origin}. */\n readonly origin?: string;\n}\n\n/** Return shape of {@link Writer.commit}. */\nexport interface CommitResult {\n /** The committed `LogEntry`. Caller can ack on `entry.lsn`. */\n readonly entry: LogEntry;\n\n /** New ETag of `current.json` after the CAS-advance landed. */\n readonly currentEtag: string;\n\n /** How many CAS attempts it took (1 = first try won). */\n readonly attempts: number;\n}\n\n/** Return shape of {@link Writer.commitBatch}. */\nexport interface CommitBatchResult {\n /**\n * One emitted `LogEntry` per input, in input order.\n * `entries[i]` corresponds to `inputs[i]`. `entries.length ===\n * inputs.length`. On an empty input array `entries` is empty and\n * no I/O happened.\n */\n readonly entries: readonly LogEntry[];\n\n /**\n * New ETag of `current.json` after the CAS-advance landed.\n * `undefined` on an empty input array (the CAS step is skipped).\n */\n readonly currentEtag: string | undefined;\n}\n\nconst DEFAULT_INITIAL_BACKOFF_MS = 25;\nconst MAX_BACKOFF_MS = 1500;\nconst APPLICATION_JSON = \"application/json\";\n\n/**\n * Empty body for index entries. Each index entry is a fact (\"doc\n * `<docId>` has `<field> = <value>`\"), not data — readers list the\n * prefix, extract the doc id, then GET the content body separately.\n * Pre-allocated module-level constant so every index PUT shares one\n * zero-length buffer.\n */\nconst EMPTY_BODY = new Uint8Array(0);\n\n/**\n * Successful outcome of one full {@link Writer.#singleAttemptCommit}\n * attempt. Retryable failures (log-peer race, CAS 412) throw\n * `BaerlyError{code:\"Conflict\"}` directly; the caller catches via\n * {@link isPreconditionFailed} and decides whether to retry. Non-retryable\n * failures (fence bump, protocol-invariant violations, network errors)\n * also throw, but the caller verifies the fence OUTSIDE the catch arm so\n * the fence-bump `Conflict` propagates instead of being mistaken for a\n * retryable CAS loss.\n */\ninterface SingleAttemptSuccess {\n readonly entries: readonly LogEntry[];\n readonly currentEtag: string;\n readonly classAOps: number;\n readonly expectedEpoch: number;\n}\n\n/**\n * Stateless write engine for the multi-instance core.\n *\n * Construction is cheap and performs zero I/O — adapters build a\n * fresh `Writer` per request and discard it. All real work\n * happens in {@link commit}.\n *\n * @example\n * ```ts\n * import { Writer } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const writer = new Writer({\n * storage: new MemoryStorage(),\n * currentJsonKey: \"app/tickets/tenant/acme/manifests/tickets/current.json\",\n * });\n *\n * const result = await writer.commit({\n * op: \"I\",\n * collection: \"tickets\",\n * docId: \"doc-1\",\n * body: { _id: \"doc-1\", title: \"hello\" },\n * });\n * console.log(result.entry.seq, result.attempts);\n * ```\n */\nexport class Writer {\n readonly #storage: Storage;\n readonly #currentJsonKey: string;\n readonly #maxRetries: number;\n readonly #initialBackoffMs: number;\n readonly #random: () => number;\n readonly #indexes: ReadonlyArray<IndexDefinition>;\n readonly #verifyLogIntegrityOnCommit: boolean;\n\n constructor(opts: {\n storage: Storage;\n /**\n * Full bucket-relative key of the CAS pointer, e.g.\n * `app/tickets/tenant/acme/manifests/tickets/current.json`. The\n * collection-prefix half lives at\n * `currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"))` — the\n * log and content keys are derived from it.\n */\n currentJsonKey: string;\n options?: WriterOptions;\n }) {\n this.#storage = opts.storage;\n this.#currentJsonKey = opts.currentJsonKey;\n this.#maxRetries = opts.options?.maxRetries ?? S3_REQUEST_MAX_RETRIES;\n this.#initialBackoffMs = opts.options?.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS;\n this.#random = opts.options?.random ?? Math.random;\n const indexes = opts.options?.indexes ?? [];\n for (const def of indexes) {\n validateIndexDefinition(def);\n }\n this.#indexes = indexes;\n this.#verifyLogIntegrityOnCommit = opts.options?.verifyLogIntegrityOnCommit ?? false;\n }\n\n /**\n * Atomically commit one mutation. Reads `current.json` fresh, mints\n * the next log entry at `seq = current.next_seq`, PUTs the content\n * body and the log entry, then CAS-advances `current.json` with\n * `If-Match`. Retries on conflict up to `maxRetries`.\n *\n * The hot-path cost under no contention is 1 GET + 3 PUTs (4 ops);\n * an in-flight peer write costs one extra GET + the backoff sleep\n * per retry.\n *\n * Idempotency: PUT content uses `If-None-Match: \"*\"`, so a retry of\n * the same logical write produces the same content key and the\n * second PUT no-ops. PUT log entry also uses `If-None-Match: \"*\"`,\n * so two writers racing the same `next_seq` cause exactly one PUT\n * to land — the loser falls into the CAS retry path.\n *\n * @throws BaerlyError code=\"Conflict\" when the retry budget is\n * exhausted (genuine high-contention case), or when the underlying\n * `current.json` CAS PUT lost.\n * @throws BaerlyError code=\"Conflict\" — the writer fence\n * (`current.json.writer_fence.epoch`) was bumped by a concurrent\n * `claimWriter` call between this commit's read of\n * `current.json` and its CAS-advance. The stale writer aborts\n * to honour the new authority — the kernel does NOT retry under\n * the old epoch. See {@link claimWriter} for the rotation\n * recipe.\n * @throws BaerlyError code=\"Internal\" when a log entry expected in\n * `[0, next_seq)` is missing — a protocol-invariant violation\n * (compactor bug or stale `current.json`).\n * @throws BaerlyError code=\"InvalidResponse\" when a log-entry body\n * isn't valid JSON.\n *\n * **Implicit provisioning.** When `current.json` does not exist at\n * `currentJsonKey` (fresh bucket, fresh collection), the writer\n * auto-creates it with a zero-state manifest before the commit\n * lands. The cost is one extra Class A PUT on the very first\n * commit per collection; steady-state cost is unchanged. A peer\n * racing the same first-write loses cleanly on the create CAS\n * and re-reads to pick up the winner's manifest.\n */\n async commit(input: CommitInput): Promise<CommitResult> {\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n for (let attempt = 1; attempt <= this.#maxRetries; attempt++) {\n let success: SingleAttemptSuccess;\n try {\n success = await this.#singleAttemptCommit(\n [input],\n session,\n logPrefix,\n \"Writer\",\n /* adoptOwnSessionOnLogConflict */ true,\n );\n } catch (error) {\n // Only retryable conflicts (storage 412 on log PUT or\n // current.json CAS) come back as `Conflict`. The fence-bump\n // throw happens AFTER the helper returns, so it never\n // reaches this catch arm. Anything else propagates.\n if (!isPreconditionFailed(error)) {\n throw error;\n }\n await this.#backoff(attempt);\n continue;\n }\n // Fence verify lives in the caller so its `Conflict` propagates\n // past the retry-catch arm above. Bypasses the retry loop —\n // the stale writer must defer to the new authority.\n await this.#verifyFenceUnchanged(success.expectedEpoch, \"Writer\");\n // `success.classAOps` is the per-attempt base; add `(attempt\n // - 1)` to bill prior failed attempts as one PUT each (the\n // simple-and-test-locked cost model — not a precise replay\n // of every PUT in every dropped attempt).\n this.#emitWriteMetrics(input.collection, success.classAOps + (attempt - 1));\n return {\n entry: success.entries[0]!,\n currentEtag: success.currentEtag,\n attempts: attempt,\n };\n }\n\n // Retry budget exhausted.\n throw new BaerlyError(\n \"Conflict\",\n `Writer: CAS conflict on ${this.#currentJsonKey} after ${this.#maxRetries} attempts`,\n );\n }\n\n /**\n * Single-attempt batched commit. Reads `current.json` ONCE, mints\n * `inputs.length` log entries with contiguous `seq` numbers\n * starting at the current `next_seq`, PUTs each content body and\n * each log entry, then CAS-advances `current.json` from\n * `next_seq = N` to `next_seq = N + inputs.length` with\n * `If-Match`.\n *\n * NO retry on CAS loss. On `current.json` 412, throws\n * `BaerlyError{code:\"Conflict\"}` immediately — the caller (here:\n * `Db.transaction`) decides whether to retry by re-running the\n * body, or to surface to the app. Likewise on a log-entry 412\n * (a peer wrote our seq).\n *\n * Empty `inputs`: returns `{ entries: [], currentEtag: undefined }`\n * after zero storage operations.\n *\n * @throws BaerlyError code=\"Conflict\" — CAS lost on `current.json`,\n * or a log entry already exists at our seq (peer wrote ahead).\n * @throws BaerlyError code=\"Conflict\" — the writer fence\n * (`current.json.writer_fence.epoch`) was bumped by a concurrent\n * `claimWriter` call between this batch's read of\n * `current.json` and its CAS-advance. The stale writer aborts\n * to honour the new authority — the kernel does NOT retry under\n * the old epoch. See {@link claimWriter} for the rotation\n * recipe.\n * @throws BaerlyError code=\"Internal\" — protocol-invariant violation\n * (missing log entry inside `[0, next_seq)`).\n * @throws BaerlyError code=\"InvalidResponse\" — malformed log body.\n *\n * **Implicit provisioning.** Like {@link commit}, this path auto-\n * creates `current.json` with a zero-state manifest on a missing\n * read. Because `commitBatch` does NOT retry on CAS loss, a peer\n * racing the same first-write surfaces `Conflict` to the caller\n * (`Db.transaction` re-runs the body); the manifest is durable\n * regardless of which writer won the create.\n */\n async commitBatch(inputs: readonly CommitInput[]): Promise<CommitBatchResult> {\n if (inputs.length === 0) {\n return { entries: [], currentEtag: undefined };\n }\n\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n // No retry — `#singleAttemptCommit`'s `Conflict` (log-peer race\n // or `current.json` CAS loss) propagates verbatim to the caller\n // (`Db.transaction` decides whether to re-run the body). The\n // fence-bump check sits AFTER the helper returns so its\n // `Conflict` propagates with the fence-bump message rather than\n // a generic CAS-loss one.\n const success = await this.#singleAttemptCommit(\n inputs,\n session,\n logPrefix,\n \"Writer.commitBatch\",\n /* adoptOwnSessionOnLogConflict */ false,\n );\n await this.#verifyFenceUnchanged(success.expectedEpoch, \"Writer.commitBatch\");\n // Pick the first input's collection as the batch label; in the\n // current `Db.transaction` model every input shares one\n // collection, so this is exact. If future tickets relax that\n // we'll need a per-collection split here.\n this.#emitWriteMetrics(inputs[0]!.collection, success.classAOps);\n return { entries: success.entries, currentEtag: success.currentEtag };\n }\n\n /**\n * One full commit attempt — the shared body of {@link commit} and\n * {@link commitBatch}. Reads `current.json`, walks the log, mints N\n * entries, PUTs content + indexes in parallel, PUTs log entries,\n * CAS-advances `current.json`. Returns the success payload + the\n * pre-commit fence epoch so the caller can run\n * {@link #verifyFenceUnchanged} outside the retry-catch arm.\n *\n * Retryable failures (a peer wrote our seq; a peer won the CAS on\n * `current.json`) throw `BaerlyError{code:\"Conflict\"}`. The caller\n * catches via {@link isPreconditionFailed} and either retries\n * (`commit`) or surfaces (`commitBatch`). Fence-bump and protocol-\n * invariant violations are NOT thrown from this helper — the fence\n * check lives in the caller so its `Conflict` propagates past the\n * retry-catch arm. Other thrown `BaerlyError`s (Internal,\n * InvalidResponse, NetworkError) bypass `isPreconditionFailed` and\n * propagate naturally.\n *\n * Crash safety invariant: content / index PUTs are awaited before\n * log PUTs, which are awaited before the CAS. A crashed mid-attempt\n * writer leaves orphan content / index entries (no log entry\n * references them) — the compactor sweeps the orphans. The\n * inverse — orphan log entry with missing content — is never\n * produced.\n */\n async #singleAttemptCommit(\n inputs: readonly CommitInput[],\n session: string,\n logPrefix: string,\n errorPrefix: string,\n adoptOwnSessionOnLogConflict: boolean,\n ): Promise<SingleAttemptSuccess> {\n // ── Step 1. Read current.json (fresh; carries the ETag). ────────\n // On a fresh bucket / fresh collection the manifest doesn't exist\n // yet. Auto-create it with a zero-state initial so `db.collection(x)\n // .insert(...)` works zero-shot. A peer racing the same create\n // loses cleanly on `If-None-Match: \"*\"`; we re-read to pick up\n // the winner's manifest. Cost: one extra Class A PUT on the very\n // first commit per collection, zero overhead thereafter.\n const read =\n (await readCurrentJson(this.#storage, this.#currentJsonKey)) ??\n (await this.#provisionCurrentJson());\n const current = read.json;\n const baseEtag = read.etag;\n const expectedEpoch = current.writer_fence.epoch;\n\n // ── Step 2. Optional integrity walk (`verifyLogIntegrityOnCommit`,\n // default off). Surfaces missing / malformed entries inside\n // `[log_seq_start, next_seq)` as `Internal` / `InvalidResponse`;\n // entries below `log_seq_start` are folded into the snapshot\n // by `compact()` and possibly swept by `runGc()`, so the walk is\n // bounded to the live tail. The read path catches the same\n // conditions on the next consult — production callers leave the\n // walk off to avoid `O(tail)` Class-B GETs per CAS attempt.\n if (this.#verifyLogIntegrityOnCommit) {\n await this.#walkLog(logPrefix, logSeqStartOf(current), current.next_seq);\n }\n\n // ── Step 3. Mint N LogEntries with contiguous seqs. ─────────────\n // All entries share `session` (one session per logical commit) and\n // a single commit instant: `lsn`'s timestamp and `commit_ts` are\n // derived from ONE clock read so they can't drift apart under skew\n // (a reader validates `commit_ts` against `LAG_WINDOW_MILLIS`, and\n // two independent reads could straddle that band). Intra-batch\n // ordering is by `seq` (the `countKey` lsn suffix), not the shared\n // timestamp, so one instant for the whole batch is correct.\n const commitNowMs = Date.now();\n const commitTs = new Date(commitNowMs).toISOString();\n const lsnTimestamp = timestamp(commitNowMs);\n const entries: LogEntry[] = [];\n for (let i = 0; i < inputs.length; i++) {\n const input = inputs[i]!;\n const seq = current.next_seq + i;\n const lsn = `${lsnTimestamp}_${session}_${countKey(seq)}`;\n const entry: LogEntry = {\n lsn,\n commit_ts: commitTs,\n op: input.op,\n collection: input.collection,\n doc_id: input.docId,\n session,\n seq,\n ...(input.op !== \"D\" && input.body !== undefined ? { after: input.body } : {}),\n ...(input.origin !== undefined ? { origin: input.origin } : {}),\n };\n entries.push(entry);\n }\n\n // ── Step 4. PUT content bodies + index entries in parallel. ─────\n // Content PUT: `ifNoneMatch: \"*\"` makes a same-hash re-write a\n // no-op (412 swallowed). Crash-recovery and same-body replay\n // both rely on this idempotency property.\n //\n // Index PUT: each declared index emits one zero-byte PUT per new\n // key. On `U` / `D` the pre-image is sourced from an earlier\n // same-`docId` input in this batch (if any) before falling back\n // to a log back-walk — preserves correctness when a transaction\n // does `[I, U]` or `[U, D]` on the same doc.\n //\n // Empty `#indexes` short-circuits the index block (including the\n // pre-image GET), preserving zero behaviour change for\n // collections without declared indexes.\n //\n // Filter-aware projection (T4): `allIndexKeysFor` short-circuits\n // on `def.predicate` miss. The writer's diff `oldKeys` vs\n // `newKeys` transparently covers all four U-quadrants without any\n // structural change here:\n //\n // match → match : both non-empty; diff PUTs/DELETEs as today.\n // match → miss : oldKeys non-empty, newKeys empty → DELETE all.\n // miss → match : oldKeys empty, newKeys non-empty → PUT all.\n // miss → miss : both empty → no-op for this def.\n //\n // All four quadrants are pinned by named tests in\n // `writer.test.ts` (\"Writer — filtered index\"). Do\n // not collapse them into one combined case — a regression in one\n // quadrant should fail exactly one named test so the bug is\n // localisable.\n let contentPutCount = 0;\n let indexClassA = 0;\n const parallelPuts: Array<Promise<unknown>> = [];\n // Per-docId in-batch image map: tracks the latest post-image\n // each input lays down so a later input on the same docId reads\n // the in-batch pre-image, not the on-disk one.\n const inBatchImage = new Map<string, DocumentData | undefined>();\n for (const input of inputs) {\n if (input.op !== \"D\" && input.body !== undefined) {\n contentPutCount++;\n const bytes = encodeJsonBytes(input.body);\n const version = await versionFromContent(bytes);\n const contentKey = `${logPrefix}/content/${version}.json`;\n parallelPuts.push(\n this.#storage\n .put(contentKey, bytes, { ifNoneMatch: \"*\", contentType: APPLICATION_JSON })\n .catch((error: unknown) => {\n this.#observe429(error, input.collection);\n if (isPreconditionFailed(error)) {\n return;\n }\n throw error;\n }),\n );\n }\n if (this.#indexes.length > 0) {\n let newKeys: readonly string[] = [];\n let staleKeys: readonly string[] = [];\n if (input.op === \"I\") {\n newKeys = allIndexKeysFor(logPrefix, this.#indexes, input.body, input.docId);\n } else if (input.op === \"U\") {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(logPrefix, input.collection, input.docId, current.next_seq);\n const oldKeys = allIndexKeysFor(logPrefix, this.#indexes, preImage, input.docId);\n newKeys = allIndexKeysFor(logPrefix, this.#indexes, input.body, input.docId);\n const newSet = new Set(newKeys);\n staleKeys = oldKeys.filter((k) => !newSet.has(k));\n } else {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(logPrefix, input.collection, input.docId, current.next_seq);\n staleKeys = allIndexKeysFor(logPrefix, this.#indexes, preImage, input.docId);\n }\n for (const k of newKeys) {\n parallelPuts.push(\n this.#storage\n .put(k, EMPTY_BODY, { ifNoneMatch: \"*\", contentType: APPLICATION_JSON })\n .catch((error: unknown) => {\n this.#observe429(error, input.collection);\n if (isPreconditionFailed(error)) {\n return;\n }\n throw error;\n }),\n );\n }\n for (const k of staleKeys) {\n // Storage.delete is contractually idempotent — no defensive catch.\n parallelPuts.push(this.#storage.delete(k));\n }\n indexClassA += newKeys.length + staleKeys.length;\n if (newKeys.length + staleKeys.length > 0) {\n ctxMetrics().histogram(\n \"db.write.index_ops_per_logical_write\",\n newKeys.length + staleKeys.length,\n { collection: input.collection },\n );\n }\n inBatchImage.set(input.docId, input.op === \"D\" ? undefined : input.body);\n }\n }\n await Promise.all(parallelPuts);\n\n // ── Step 5. PUT log entries. ────────────────────────────────────\n // `ifNoneMatch: \"*\"` per entry. On 412 we bump the counter and\n // record the rejection; the disposition (adopt vs surface) is\n // computed below from the aggregated results.\n //\n // Two cases on 412:\n // (a) a peer wrote a DIFFERENT entry at the same seq — we lost\n // the race; the caller's CAS will also fail.\n // (b) (single-input commit only) our OWN previous attempt\n // landed step 5 but lost step 6, and we're now re-driving\n // the same logical commit. Adopt it and proceed to CAS so\n // the advance gets a chance to commit.\n //\n // We discriminate by `session`: the random per-call id uniquely\n // identifies \"our own previous attempt.\" Adoption is only safe\n // when there's exactly one entry to compare (`commit`'s N=1 case);\n // batch commits surface log-PUT 412s as `Conflict` immediately.\n type LogPutOutcome = { readonly ok: true } | { readonly ok: false };\n const logPutOne = async (entry: LogEntry): Promise<LogPutOutcome> => {\n const logEntryKey = `${logPrefix}/log/${entry.seq}.json`;\n const logBytes = encodeJsonBytes(entry);\n try {\n await this.#storage.put(logEntryKey, logBytes, {\n ifNoneMatch: \"*\",\n contentType: APPLICATION_JSON,\n });\n return { ok: true };\n } catch (error) {\n this.#observe429(error, entry.collection);\n if (!isPreconditionFailed(error)) {\n throw error;\n }\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: entry.collection,\n step: \"log-put\",\n });\n return { ok: false };\n }\n };\n const logPutResults = await Promise.all(entries.map(logPutOne));\n let committedEntries: readonly LogEntry[] = entries;\n const firstConflictIdx = logPutResults.findIndex((r) => !r.ok);\n if (firstConflictIdx !== -1) {\n const conflictedEntry = entries[firstConflictIdx]!;\n const logEntryKey = `${logPrefix}/log/${conflictedEntry.seq}.json`;\n if (adoptOwnSessionOnLogConflict) {\n const existing = await readLogEntry(this.#storage, logEntryKey);\n const decision = tryAdoptOwnSessionLogEntry({\n self: conflictedEntry,\n existing,\n batchSize: inputs.length,\n });\n if (decision.adopt) {\n committedEntries = [decision.entry];\n } else {\n throw new BaerlyError(\n \"Conflict\",\n `${errorPrefix}: log entry already exists at ${logEntryKey}; ${decision.reason}`,\n );\n }\n } else {\n throw new BaerlyError(\n \"Conflict\",\n `${errorPrefix}: log entry already exists at ${logEntryKey}; peer wrote our seq`,\n );\n }\n }\n\n // ── Step 6. CAS-advance current.json with If-Match. ─────────────\n // Bind to `baseEtag` from step 1 — re-reading would risk advancing\n // `next_seq` past a seq we never wrote a log entry for.\n //\n // Accumulate `tail_bytes` EXACTLY. The compactor later subtracts the\n // bytes of the log objects it folds, summed from the fetched object\n // bodies — i.e. exactly what the writer PUT per entry\n // (`encodeJsonBytes(entry)` in `logPutOne`). Counting the writer-add\n // and the compactor-subtract over the identical bytes keeps\n // `tail_bytes` exact under the full-fence CAS. Sum over\n // `committedEntries` (the source of truth for what's actually in the\n // tail — `entries` normally, or the single adopted entry on the\n // own-session-adoption path), NOT `inputs`.\n const batchLogBytes = committedEntries.reduce(\n (sum, e) => sum + encodeJsonBytes(e).byteLength,\n 0,\n );\n const next: CurrentJson = {\n ...current,\n next_seq: current.next_seq + inputs.length,\n tail_bytes: current.tail_bytes + batchLogBytes,\n };\n // Cadence-invariant assert (cheap, load-bearing). The GC write-tick\n // cadence keys off `next_seq` advancing by exactly the number of log\n // entries written. Today one input ⇒ one log entry, so `next_seq`\n // advances by `inputs.length` and `committedEntries.length ===\n // inputs.length` (the adoption path adopts the single in-flight\n // entry of a 1-input commit, preserving the identity). Pin it so a\n // future change that makes one input emit ≠1 entries fails LOUD here\n // instead of silently skewing the GC cadence.\n if (next.next_seq - current.next_seq !== inputs.length) {\n throw new BaerlyError(\n \"Internal\",\n `${errorPrefix}: GC-cadence invariant violated — next_seq advanced by ${\n next.next_seq - current.next_seq\n } but ${inputs.length} input(s) were committed on ${this.#currentJsonKey}`,\n );\n }\n const nextBody = encodeJsonBytes(next);\n const putOpts: StoragePutOptions = {\n ifMatch: baseEtag,\n contentType: APPLICATION_JSON,\n };\n let result: StoragePutResult;\n try {\n result = await this.#storage.put(this.#currentJsonKey, nextBody, putOpts);\n } catch (error) {\n this.#observe429(error, inputs[0]!.collection);\n if (isPreconditionFailed(error)) {\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: inputs[0]!.collection,\n step: \"current-json-cas\",\n });\n throw new BaerlyError(\n \"Conflict\",\n `${errorPrefix}: CAS conflict on ${this.#currentJsonKey}`,\n );\n }\n throw error;\n }\n\n // ── Step 6b. Write-tick maintenance dispatch. ───────────────────\n // Single funnel site reached by BOTH `commit()` and `commitBatch()`\n // exactly once per logical commit (a CAS retry re-enters this helper\n // and dispatches once per successful attempt — but a successful CAS\n // ends the retry loop, so a logical commit dispatches once). Sits\n // BEFORE the caller's `#verifyFenceUnchanged` — a write that then\n // fails its fence check may have paid for one bounded maintenance\n // pass; that's the intended single funnel, bounded and safe.\n //\n // Config rides the per-request observability context\n // (`getCurrentContext()?.maintenance`), set by the adapter — NOT the\n // Writer constructor / `Db.create`. Absent ⇒ inline dispatch +\n // CF-free-safe caps, so a bare `Db.create(...).collection(...)\n // .insert(...)` maintains inline by default once enough writes\n // accrue.\n const prevSeq = current.next_seq; // pre-CAS seq, already in scope\n const maint = getCurrentContext()?.maintenance;\n if (maint?.disabled !== true) {\n const gcInterval = maint?.options?.gcInterval ?? WRITE_TICK_GC_INTERVAL;\n if (shouldFireMaintenance(next, prevSeq, gcInterval)) {\n const dispatch = maint?.dispatch ?? dispatchInlineAwaited;\n // `await dispatch(...)`: `dispatchInlineAwaited` returns the\n // task's promise (awaited inline — deterministic for tests +\n // correct for serverful Node). A `ctx.waitUntil`-style dispatch\n // returns void (fire-and-forget off the ack); `await void` is a\n // no-op. The `.then(() => {}, () => {})` is belt-and-suspenders:\n // `runBoundedMaintenance` already swallows internally, but this\n // guarantees a dispatched task can NEVER reject the commit even\n // if a future change makes it throw.\n await dispatch(() =>\n runBoundedMaintenance(\n {\n storage: this.#storage,\n currentJsonKey: this.#currentJsonKey,\n prevSeq,\n // `disabled` is intentionally NOT forwarded: the outer\n // `maint?.disabled !== true` gate already guarantees we only\n // reach here when maintenance is enabled, so passing it would\n // only ever forward `false` (a no-op) and imply a coupling\n // that doesn't exist.\n ...(maint?.maxFoldBytes !== undefined && { maxFoldBytes: maint.maxFoldBytes }),\n },\n maint?.options,\n ).then(\n () => {},\n () => {},\n ),\n );\n }\n }\n\n // Step 7 — the fence-verify GET — lives in the caller, not here.\n // Both fence-bump and a 412-driven CAS retry use\n // `BaerlyError{code:\"Conflict\"}`; keeping the fence check outside\n // this helper's body lets the caller's retry-catch arm\n // (`isPreconditionFailed`) match ONLY retryable conflicts thrown\n // from inside, while the fence-bump throw propagates.\n\n // Base class-A op count for this attempt: content PUTs (skipping\n // `op:\"D\"`) + log PUTs (= N) + index PUTs + index DELETEs + 1\n // current.json CAS. The fence-verify GET is Class B and excluded.\n // The caller of `commit()` adds `(attempt - 1)` for retry cost.\n const classAOps = contentPutCount + entries.length + indexClassA + 1;\n return {\n entries: committedEntries,\n currentEtag: result.etag,\n classAOps,\n expectedEpoch,\n };\n }\n\n /**\n * Read the pre-image content body for a doc by walking the live\n * log backwards from `currentNextSeq` looking for the\n * most-recent I/U entry on this `(collection, docId)`. Returns\n * `undefined` when:\n *\n * - the doc's most-recent op was `D` (tombstone — no live body);\n * - no entry for this doc lives inside the visible log range\n * `[log_seq_start, currentNextSeq)` (a fresh-insert race or\n * the doc has been folded into the snapshot but is no longer\n * referenced).\n *\n * Used ONLY by the index-emission path on `U` / `D` to compute\n * the stale-key set. Bounded by `log_seq_start`: entries below\n * have been folded into the snapshot and may already be swept\n * off the bucket — a snapshot fold is the rebuild command's job\n * (see `./rebuild-index.ts`), not the writer's.\n *\n * **Cost note:** linear walk, O(snapshot lag). For day-one Phase\n * 8 collections (helpdesk-shape: 100s of docs, <10k log entries)\n * this is fine — the compactor folds the live tail every ~100\n * entries (`packages/server/src/compactor.ts`). A follow-up ticket\n * caches per-doc index head in `current.json` for O(1) lookup.\n * The bound is documented; out of scope here.\n */\n /**\n * Auto-create the per-collection `current.json` at\n * `this.#currentJsonKey` with a zero-state initial manifest. Called\n * by `#singleAttemptCommit` when the read returned `null` (fresh\n * bucket / fresh collection).\n *\n * Concurrency: `createCurrentJson` uses `If-None-Match: \"*\"`. If a\n * peer raced us and won, the storage layer surfaces `Conflict`; we\n * recover by re-reading the now-present manifest. We do NOT retry\n * the create — a single recover-via-read covers every race that\n * could have produced our null read.\n *\n * The seed shape (`snapshot: null`, `next_seq: 0`, `log_seq_start:\n * 0`, `writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" }`)\n * matches `ensureTable` and `baerly deploy`'s pre-warm path, so an\n * operator who pre-provisions and a writer who auto-creates land\n * on byte-identical bytes.\n *\n * @throws BaerlyError code=\"InvalidResponse\" — the post-recover\n * re-read also returned null. Defensive guard; in practice\n * unreachable because the Conflict implies the key now exists.\n */\n async #provisionCurrentJson(): Promise<CurrentJsonRead> {\n const initial: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\n tail_bytes: 0,\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n try {\n return await createCurrentJson(this.#storage, this.#currentJsonKey, initial);\n } catch (error) {\n if (!(error instanceof BaerlyError) || error.code !== \"Conflict\") {\n throw error;\n }\n }\n const recovered = await readCurrentJson(this.#storage, this.#currentJsonKey);\n if (recovered === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `Writer: current.json missing at ${this.#currentJsonKey} after auto-create raced and recover read returned null`,\n );\n }\n return recovered;\n }\n\n async #readPreImage(\n logPrefix: string,\n collection: string,\n docId: string,\n currentNextSeq: number,\n ): Promise<DocumentData | undefined> {\n // Walk newest-to-oldest so we hit the most-recent op first.\n // `s = -1` is the natural empty-bucket sentinel.\n for (let s = currentNextSeq - 1; s >= 0; s--) {\n const logKey = `${logPrefix}/log/${s}.json`;\n const got = await this.#storage.get(logKey);\n if (got === null) {\n // A hole below the visible range — either we walked past\n // `log_seq_start` (the entry was folded + swept) or a peer\n // is mid-CAS on a write we don't see yet. Bail; the\n // rebuild command (`rebuildIndex`) handles holes by\n // re-projecting from the snapshot.\n continue;\n }\n let entry: LogEntry;\n try {\n entry = decodeJsonBytes<LogEntry>(got.body);\n } catch {\n // Malformed entry shouldn't propagate up the index-emission\n // path — let the outer commit's `#walkLog` (step 2) flag it\n // as the protocol violation. Skip.\n continue;\n }\n if (entry.collection !== collection || entry.doc_id !== docId) {\n continue;\n }\n if (entry.op === \"D\") {\n return undefined;\n } // last op was delete\n if ((entry.op === \"I\" || entry.op === \"U\") && entry.after !== undefined) {\n return entry.after;\n }\n }\n return undefined;\n }\n\n /**\n * Walk `log/<logSeqStart>.json` … `log/<nextSeq - 1>.json` with\n * bounded parallelism via `walkLogRange`. Materialised entries are\n * discarded — the walk's only job is to surface a hole or a\n * malformed body inside the visible range as\n * `BaerlyError{code:\"Internal\"}` / `\"InvalidResponse\"`.\n *\n * Gated on `verifyLogIntegrityOnCommit`; default off in production\n * because the per-doc fold already lives in the read path. See the\n * option's docstring for the rationale and the opt-in convention.\n *\n * `logSeqStart` is the boundary set by the compactor on\n * `current.json.log_seq_start`. Entries below it have been folded\n * into the snapshot and may have been swept off the bucket, so the\n * walk MUST NOT GET-require them.\n */\n async #walkLog(logPrefix: string, logSeqStart: number, nextSeq: number): Promise<void> {\n await walkLogRange(this.#storage, logPrefix, logSeqStart, nextSeq);\n }\n\n /**\n * Bump the `db.r2.put.429_total` counter when `err` looks like an\n * R2 prefix-partition rate-limit. Best-effort: detected via\n * `BaerlyError{code:\"NetworkError\"}` with a `429` token in the\n * message. Called from every PUT call site's catch arm; mutually\n * exclusive in practice with `isPreconditionFailed` (412 ≠ 429).\n */\n #observe429(err: unknown, collection: string): void {\n if (is429(err)) {\n ctxMetrics().counter(\"db.r2.put.429_total\", 1, { collection });\n }\n }\n\n /**\n * Emit the per-logical-write `class_a_ops_per_logical_write`\n * histogram shared by `commit` and `commitBatch`. `classAOps`\n * differs between the two paths (retry-budget vs batch shape),\n * so each caller computes it.\n */\n #emitWriteMetrics(collection: string, classAOps: number): void {\n ctxMetrics().histogram(\"db.write.class_a_ops_per_logical_write\", classAOps, { collection });\n }\n\n /**\n * Re-read `current.json` after a successful CAS and assert the\n * writer-fence epoch is still ours. The CAS only mutated `next_seq`\n * (the fence is preserved from `current`), so a post-write epoch\n * mismatch can only mean another writer claimed the fence between\n * our step-1 read and step-6 PUT — the exact split-brain\n * `WriterFence` prevents. Throws `Conflict`; no retry, since the\n * stale writer must defer to the new authority.\n *\n * The fence-verify GET is Class B and intentionally NOT counted in\n * `class_a_ops_per_logical_write`.\n */\n async #verifyFenceUnchanged(expectedEpoch: number, where: string): Promise<void> {\n const postRead = await readCurrentJson(this.#storage, this.#currentJsonKey);\n if (postRead === null) {\n return;\n }\n if (postRead.json.writer_fence.epoch === expectedEpoch) {\n return;\n }\n throw new BaerlyError(\n \"Conflict\",\n `${where}: writer fence bumped from epoch ${expectedEpoch} to ${postRead.json.writer_fence.epoch} during commit on ${this.#currentJsonKey}; stale writer aborting`,\n );\n }\n\n /**\n * Exponential backoff with full jitter. `25 * 2^(attempt-1)` capped\n * at 1500ms; uniform jitter in `[0, base)` keeps colliding peers\n * from re-racing in lockstep. Worst-case total wait across the\n * default 8 attempts is roughly 2.5 s — well under a typical\n * Worker request budget.\n */\n async #backoff(attempt: number): Promise<void> {\n const base = Math.min(this.#initialBackoffMs * 2 ** (attempt - 1), MAX_BACKOFF_MS);\n const sleepMs = base * this.#random();\n if (sleepMs <= 0) {\n return;\n }\n await new Promise<void>((r) => setTimeout(r, sleepMs));\n }\n}\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * `true` when the underlying storage surfaced a `PreconditionFailed`\n * 412 (or its non-S3 equivalents). Every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`.\n */\nconst isPreconditionFailed = (err: unknown): boolean =>\n err instanceof BaerlyError && err.code === \"Conflict\";\n\n/**\n * `true` when the underlying storage surfaced an R2 prefix-partition\n * rate-limit. {@link S3HttpStorage} stamps the upstream HTTP status\n * onto `BaerlyError.cause` as `{ status }`; we discriminate on that\n * structured field rather than regex-matching the message.\n */\nconst is429 = (err: unknown): boolean => {\n if (!(err instanceof BaerlyError) || err.code !== \"NetworkError\") {\n return false;\n }\n const cause = err.cause as { status?: number } | undefined;\n return cause?.status === 429;\n};\n","/**\n * `baerly admin restore` — bulk-import NDJSON into a fresh collection.\n *\n * Reads NDJSON from stdin, reconstructs each row, and calls\n * `Writer.commit({op:\"I\"})` per row into the target bucket.\n * Programmatic callers (today: tests + the export round-trip\n * integration test) can divert the input by passing\n * `{ streams: { stdin } }` to {@link runRestore}. Idempotent on a fresh\n * bucket: re-running on a half-completed restore **refuses** unless\n * `--force` is set (which bumps the writer fence and seeds a fresh\n * `current.json` first).\n *\n * Args:\n * --bucket Required. Target bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Target collection name.\n * --force Truncate the target if it exists (fence-bump + reseed).\n * --json JSON envelope.\n *\n * stdin: NDJSON, one `{_id, ...}` row per line. Empty lines tolerated.\n * EOF terminates.\n *\n * Cost shape: 1 PUT current.json (initial) + N × (1 PUT log + 1 PUT\n * content + 1 PUT current.json CAS) = 3N + 1 Class A ops for N rows.\n *\n * Partial-restore semantics: a mid-stream Network / Internal / parse\n * error leaves the target in a partial state (some rows committed,\n * `current.json` advanced to wherever the last successful commit\n * landed). Re-run with `--force` to truncate, or hand-clean. The\n * malformed-line case (missing `_id`, bad JSON) fails fast on that\n * line; rows committed BEFORE it survive.\n *\n * Exit codes:\n * 0 — every row committed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Network / storage error mid-stream, or a malformed NDJSON\n * line (raised as a plain `Error`, not `BaerlyError`).\n * 3 — Conflict from a pre-existing target without --force, or from a\n * concurrent writer when --force was used.\n */\n\nimport { createInterface } from \"node:readline\";\nimport { type ArgsDef } from \"citty\";\nimport {\n BaerlyError,\n CURRENT_JSON_SCHEMA_VERSION,\n createCurrentJson,\n type CurrentJson,\n type DocumentData,\n encodeJsonBytes,\n readCurrentJson,\n} from \"@baerly/protocol\";\nimport { Writer } from \"@baerly/server/_internal/testing\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst RESTORE_OWNER = \"baerly-restore\";\n\nconst RESTORE_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Target bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Target collection name.\",\n valueHint: \"name\",\n },\n force: {\n type: \"boolean\",\n description: \"Truncate the target if it exists (bump fence + reseed current.json).\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.restore\",\n meta: {\n description: \"Bulk-import canonical NDJSON into a fresh collection.\",\n },\n args: RESTORE_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n\n const head = await readCurrentJson(bucket.storage, currentJsonKey);\n if (head !== null && args.force !== true) {\n throw new BaerlyError(\n \"Conflict\",\n `baerly admin restore: ${currentJsonKey} exists; pass --force to truncate`,\n );\n }\n if (head !== null) {\n // --force: bump the fence on the existing record so any\n // in-flight writer aborts, then overwrite `current.json` with a\n // fresh seed under If-Match. A concurrent writer landing\n // between our read and our CAS PUT surfaces Conflict (exit 3).\n //\n // CRITICAL: stale log entries from the old generation still\n // live on disk under `log/<seq>.json` paths. The writer's\n // `If-None-Match: \"*\"` log PUT will 412 if we restart `next_seq`\n // at 0 and collide with `log/0.json`. We instead advance\n // `next_seq` and `log_seq_start` past the old data so new\n // commits land at fresh sequence numbers and the old log files\n // become unreferenced orphans (the compactor / GC sweep them on\n // the next maintenance pass).\n const truncatedNext = head.json.next_seq;\n const reseeded: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: truncatedNext,\n log_seq_start: truncatedNext,\n writer_fence: {\n epoch: head.json.writer_fence.epoch + 1,\n owner: RESTORE_OWNER,\n claimed_at: \"\",\n },\n tail_bytes: 0,\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n try {\n await bucket.storage.put(currentJsonKey, encodeJsonBytes(reseeded), {\n ifMatch: head.etag,\n contentType: \"application/json\",\n });\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `baerly admin restore: failed to reseed current.json: ${(error as Error).message}`,\n );\n }\n } else {\n // Fresh target: seed `current.json` with `next_seq=0`.\n const seed: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: RESTORE_OWNER, claimed_at: \"\" },\n tail_bytes: 0,\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n await createCurrentJson(bucket.storage, currentJsonKey, seed);\n }\n\n const writer = new Writer({ storage: bucket.storage, currentJsonKey });\n\n const input = ctx.streams?.stdin ?? process.stdin;\n const rl = createInterface({ input, crlfDelay: Infinity });\n let count = 0;\n let lineNo = 0;\n for await (const line of rl) {\n lineNo++;\n if (line.length === 0) {\n continue;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch (error) {\n // Malformed NDJSON mid-stream → exit 2 (the ticket's\n // partial-restore contract: the line that failed wasn't\n // committed, but anything BEFORE it survives). Bare `Error`\n // (not `BaerlyError`) routes through the helper's \"unknown\"\n // arm → exit 2.\n throw new Error(\n `baerly admin restore: line ${lineNo} is not valid JSON: ${(error as Error).message}`,\n { cause: error },\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(`baerly admin restore: line ${lineNo} is not a JSON object`);\n }\n const row = parsed as Record<string, unknown>;\n const id = row[\"_id\"];\n if (typeof id !== \"string\" || id.length === 0) {\n throw new Error(`baerly admin restore: line ${lineNo} missing non-empty string _id`);\n }\n // Pass the full object as the body — `_id` is part of the\n // body in the doc shape, and the writer keys on `docId`\n // separately.\n const body = row as unknown as DocumentData;\n await writer.commit({\n op: \"I\",\n collection: args.collection,\n docId: id,\n body,\n });\n count++;\n }\n emitSuccess({\n command: \"admin.restore\",\n status: \"ok\",\n collection: args.collection,\n restored: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin restore`. */\nexport const restoreCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runRestore = bundle.run;\n"],"mappings":";;;;;;;;;;;;;;;;AAoIA,MAAa,8BAA8B,QAA2C;CAGpF,IAAI,IAAI,cAAc,GACpB,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAQ;CAGzC,IAAI,IAAI,SAAS,YAAY,IAAI,KAAK,SACpC,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAkB;CAKnD,IAAI,IAAI,SAAS,QAAQ,IAAI,KAAK,KAChC,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAY;CAE7C,OAAO;EAAE,OAAO;EAAM,OAAO,IAAI;CAAS;AAC5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC9EA,MAAM,mBAAoC,kBAAkB,GAAG,YAAY;AA0H3E,MAAM,6BAA6B;AACnC,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;;;;;;;;AASzB,MAAM,aAAa,IAAI,WAAW,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CnC,IAAa,SAAb,MAAoB;CAClB;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,MAWT;EACD,KAAKA,WAAW,KAAK;EACrB,KAAKC,kBAAkB,KAAK;EAC5B,KAAKC,cAAc,KAAK,SAAS,cAAA;EACjC,KAAKC,oBA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