@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.
Files changed (113) hide show
  1. package/README.md +9 -5
  2. package/dist/API.md +161 -10
  3. package/dist/{app-config-Cb5dO2s9.d.ts → app-config-C0Bbw_Z6.d.ts} +18 -9
  4. package/dist/app-config.d.ts +1 -1
  5. package/dist/app-config.js.map +1 -1
  6. package/dist/auth.d.ts +1 -1
  7. package/dist/baerly.js +10 -10
  8. package/dist/baerly.js.map +1 -1
  9. package/dist/bytes-BXdamO3L.js +11 -0
  10. package/dist/bytes-BXdamO3L.js.map +1 -0
  11. package/dist/{client-BLf3Ae5s.d.ts → client-DYZfoZb9.d.ts} +3 -3
  12. package/dist/client-react.d.ts +3 -3
  13. package/dist/client.d.ts +3 -3
  14. package/dist/cloudflare.d.ts +31 -4
  15. package/dist/cloudflare.js +72 -6
  16. package/dist/cloudflare.js.map +1 -1
  17. package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
  18. package/dist/config-DVfDGyw1.js.map +1 -0
  19. package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
  20. package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
  21. package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
  22. package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
  23. package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
  24. package/dist/current-json-C-EyJqs0.js.map +1 -0
  25. package/dist/{db-D62JguBc.d.ts → db-BM3y2JQw.d.ts} +3 -3
  26. package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
  27. package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
  28. package/dist/dev-vite.d.ts +3 -3
  29. package/dist/dev-vite.js +3 -3
  30. package/dist/dev.d.ts +1 -1
  31. package/dist/dev.js +1 -1
  32. package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
  33. package/dist/doctor-Db-hzPmE.js.map +1 -0
  34. package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
  35. package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
  36. package/dist/errors-DOdL95kK.js.map +1 -1
  37. package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
  38. package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
  39. package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
  40. package/dist/fsck-CPPZWt9p.js.map +1 -0
  41. package/dist/{http-CjUO1Bec.js → http-Cw8p6y5b.js} +8 -8
  42. package/dist/{http-CjUO1Bec.js.map → http-Cw8p6y5b.js.map} +1 -1
  43. package/dist/http.d.ts +6 -6
  44. package/dist/http.js +1 -1
  45. package/dist/{index-BYv0hb8M.d.ts → index-C3JAH1Yo.d.ts} +14 -2
  46. package/dist/{index-BGC-ENnj.d.ts → index-DSvwEUeF.d.ts} +63 -54
  47. package/dist/{index-BquQkhJi.d.ts → index-DwDTWPSU.d.ts} +2 -2
  48. package/dist/{index-COsQ-Mlz.d.ts → index-cUY-36AN.d.ts} +3 -3
  49. package/dist/index.d.ts +5 -5
  50. package/dist/index.js +3 -3
  51. package/dist/{indexes-DwOXkn1Y.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
  52. package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
  53. package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
  54. package/dist/maintenance-BRrThz8V.d.ts +449 -0
  55. package/dist/maintenance-BvOv6BMM.js +1295 -0
  56. package/dist/maintenance-BvOv6BMM.js.map +1 -0
  57. package/dist/maintenance-ClzBC1Vv.js +1895 -0
  58. package/dist/maintenance-ClzBC1Vv.js.map +1 -0
  59. package/dist/maintenance.d.ts +2 -323
  60. package/dist/maintenance.js +2 -2
  61. package/dist/node.d.ts +20 -79
  62. package/dist/node.js +2 -2
  63. package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
  64. package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
  65. package/dist/observability.d.ts +2 -2
  66. package/dist/observability.js +2 -2
  67. package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
  68. package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
  69. package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
  70. package/dist/query-BmiQy328.js.map +1 -0
  71. package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
  72. package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
  73. package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
  74. package/dist/restore-C6IcmLeA.js.map +1 -0
  75. package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
  76. package/dist/snapshot-SS8USDUF.js.map +1 -0
  77. package/dist/{src-DyET_VPP.js → src-DU1sCMlr.js} +315 -278
  78. package/dist/src-DU1sCMlr.js.map +1 -0
  79. package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
  80. package/dist/src-QQ7jDeL2.js.map +1 -0
  81. package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
  82. package/dist/src-zhEAmmF7.js.map +1 -0
  83. package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
  84. package/dist/subcommand-DZcHcsYp.js.map +1 -0
  85. package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
  86. package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
  87. package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
  88. package/dist/validate-DCq_0DIn.js.map +1 -0
  89. package/package.json +13 -6
  90. package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
  91. package/dist/config-Bsg8wgwo.js.map +0 -1
  92. package/dist/current-json-BkatBzF7.js.map +0 -1
  93. package/dist/doctor-B8h9GCN9.js.map +0 -1
  94. package/dist/fsck-DEz9lyCy.js.map +0 -1
  95. package/dist/indexes-BXn7a06a.js +0 -297
  96. package/dist/indexes-BXn7a06a.js.map +0 -1
  97. package/dist/log-walk-DIru96UT.js.map +0 -1
  98. package/dist/maintenance-Bn6ul9aV.js +0 -758
  99. package/dist/maintenance-Bn6ul9aV.js.map +0 -1
  100. package/dist/query-DcSbFLJt.js.map +0 -1
  101. package/dist/rebuild-index-C5gTXryd.js +0 -119
  102. package/dist/rebuild-index-C5gTXryd.js.map +0 -1
  103. package/dist/restore-CbKVMMpm.js.map +0 -1
  104. package/dist/snapshot-D7C4_FSl.js +0 -71
  105. package/dist/snapshot-D7C4_FSl.js.map +0 -1
  106. package/dist/snapshot-z_N9hpTe.js +0 -917
  107. package/dist/snapshot-z_N9hpTe.js.map +0 -1
  108. package/dist/src-Chafbw8r.js.map +0 -1
  109. package/dist/src-DyET_VPP.js.map +0 -1
  110. package/dist/src-n0Te1r98.js.map +0 -1
  111. package/dist/subcommand-BWs6K7zb.js +0 -110
  112. package/dist/subcommand-BWs6K7zb.js.map +0 -1
  113. package/dist/validate-DhH1lO8I.js.map +0 -1
@@ -0,0 +1,449 @@
1
+ import { d as IndexDefinition } from "./app-config-C0Bbw_Z6.js";
2
+ import { h as Storage, p as CurrentJson } from "./index-DSvwEUeF.js";
3
+ //#region packages/server/src/compactor.d.ts
4
+ /**
5
+ * Public configuration knobs for {@link compact}. All optional; the
6
+ * engine works unbounded by default. Opt into a per-run cap via the
7
+ * `CLOUDFLARE_FREE_TIER` profile (from `./maintenance.ts`) or by
8
+ * reaching for {@link InternalCompactOptions} via the
9
+ * `@baerly/server/_internal/testing` subpath.
10
+ */
11
+ interface CompactOptions {
12
+ /**
13
+ * Minimum log-tail length to compact. Skips work when there are
14
+ * fewer than this many live entries past the last snapshot.
15
+ * Default 100.
16
+ */
17
+ readonly minEntriesToCompact?: number;
18
+ /** Optional AbortSignal forwarded to every storage call. */
19
+ readonly signal?: AbortSignal;
20
+ }
21
+ /**
22
+ * Internal-only widening of {@link CompactOptions}. Surfaced via the
23
+ * `@baerly/server/_internal/testing` subpath (NOT in the published
24
+ * `publishConfig.exports`); production callers should use
25
+ * {@link CompactOptions}.
26
+ *
27
+ * @internal
28
+ */
29
+ interface InternalCompactOptions extends CompactOptions {
30
+ /**
31
+ * @internal Budget cap for the CF free-tier subrequest budget;
32
+ * `CLOUDFLARE_FREE_TIER` sets it. Tests also set it to exercise
33
+ * the cap path. The compactor's I/O profile is
34
+ * `maxEntriesPerRun + 3` subrequests (N GETs + 1 PUT snapshot +
35
+ * 1 GET current + 1 PUT current). The default is effectively
36
+ * unbounded (`Number.MAX_SAFE_INTEGER`).
37
+ */
38
+ readonly maxEntriesPerRun?: number;
39
+ /**
40
+ * @internal SNAPSHOT-axis byte ceiling. The rebuilt snapshot body
41
+ * (NOT snapshot + tail) must be `<= ceilingBytes` or the fold is
42
+ * DEFERRED before the PUT. `undefined ⇒ no ceiling` (`Infinity`).
43
+ * The write-tick runner threads its pre-fold-projection `C` here as
44
+ * a Node-side belt-and-suspenders; on a CPU-killable CF isolate the
45
+ * kill lands during walk+encode (before this check), so the decisive
46
+ * CF guard is the runner's pre-fold projection, not this.
47
+ */
48
+ readonly ceilingBytes?: number;
49
+ /**
50
+ * @internal SNAPSHOT-axis row ceiling. The rebuilt snapshot row count
51
+ * (`base.size`, NOT including the tail) must be `<= ceilingEntries`
52
+ * or the fold is DEFERRED before the PUT. `undefined ⇒ no ceiling`
53
+ * (`Infinity`). Catches the tiny-doc case where bytes stay small but
54
+ * row count balloons.
55
+ */
56
+ readonly ceilingEntries?: number;
57
+ }
58
+ interface CompactResult {
59
+ /** `true` iff a new snapshot landed and `current.json` was advanced. */
60
+ readonly written: boolean;
61
+ /** Reason `written === false`. */
62
+ readonly skippedReason?: "below-min-threshold" | "current-json-missing" | "cas-lost" | "deferred";
63
+ /** `true` on the over-ceiling rebuild-defer path (`skippedReason === "deferred"`). */
64
+ readonly deferred?: boolean;
65
+ /** Prior snapshot key (`null` if no prior snapshot existed). */
66
+ readonly previousSnapshotKey: string | null;
67
+ /** New snapshot key (`undefined` if `written === false` and no PUT happened). */
68
+ readonly newSnapshotKey?: string;
69
+ /** `log_seq_start` before the run. */
70
+ readonly logSeqStartBefore: number;
71
+ /** `log_seq_start` after the run. */
72
+ readonly logSeqStartAfter: number;
73
+ /** Number of log entries folded into the new snapshot. */
74
+ readonly entriesFolded: number;
75
+ }
76
+ /**
77
+ * Fold a prefix of the live log into a new snapshot and CAS-advance
78
+ * `current.json`. Idempotent: a second run with no new writes is a
79
+ * no-op (below-min-threshold).
80
+ *
81
+ * Single-attempt: on CAS conflict we return
82
+ * `{written: false, skippedReason: "cas-lost", newSnapshotKey}` — the
83
+ * caller (the cron handler invoking `runScheduledMaintenance` from
84
+ * `./maintenance.ts`) decides whether to schedule another run. The
85
+ * orphan snapshot file just written will be swept by `runGc()`.
86
+ *
87
+ * @throws BaerlyError code="InvalidResponse" — `current.json` is
88
+ * present but malformed, or a snapshot body fails its schema /
89
+ * collection cross-check.
90
+ * @throws BaerlyError code="Internal" — protocol-invariant violation:
91
+ * a log entry missing inside `[log_seq_start, foldEnd)`, or the
92
+ * prior-snapshot pointer resolves to no body / a body whose hash
93
+ * doesn't match its filename.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * import { compact } from "@gusto/baerly-storage";
98
+ *
99
+ * const res = await compact(
100
+ * { storage, currentJsonKey: "app/x/tenant/t/manifests/tickets/current.json" },
101
+ * { minEntriesToCompact: 100, maxEntriesPerRun: 40 },
102
+ * );
103
+ * if (res.written) console.log("snapshot landed at", res.newSnapshotKey);
104
+ * ```
105
+ */
106
+ declare const compact: (args: {
107
+ storage: Storage; /** Full bucket-relative key of the CAS pointer. */
108
+ currentJsonKey: string;
109
+ }, options?: CompactOptions) => Promise<CompactResult>;
110
+ //#endregion
111
+ //#region packages/server/src/gc.d.ts
112
+ /**
113
+ * Public tunables for {@link runGc}. All optional; the engine works
114
+ * unbounded by default. Opt into per-run caps via the
115
+ * `CLOUDFLARE_FREE_TIER` profile (from `./maintenance.ts`) or by
116
+ * reaching for {@link InternalRunGcOptions} via the
117
+ * `@baerly/server/_internal/testing` subpath.
118
+ */
119
+ interface RunGcOptions {
120
+ readonly signal?: AbortSignal;
121
+ }
122
+ /**
123
+ * Internal-only widening of {@link RunGcOptions}. Surfaced via the
124
+ * `@baerly/server/_internal/testing` subpath (NOT in the published
125
+ * `publishConfig.exports`); production callers should use
126
+ * {@link RunGcOptions}.
127
+ *
128
+ * @internal
129
+ */
130
+ interface InternalRunGcOptions extends RunGcOptions {
131
+ /**
132
+ * @internal Override grace-period for tests. Defaults to
133
+ * {@link GC_GRACE_PERIOD_MILLIS} (7 days). Tests use `0` to bypass
134
+ * the grace and exercise the sweep path in one pass.
135
+ */
136
+ readonly graceMillis?: number;
137
+ /**
138
+ * @internal Budget cap on candidates marked per category per run.
139
+ * `CLOUDFLARE_FREE_TIER` sets it; bounds LIST + classification
140
+ * cost per pass. The default is effectively unbounded
141
+ * (`Number.MAX_SAFE_INTEGER`).
142
+ */
143
+ readonly maxMarksPerRun?: number;
144
+ /**
145
+ * @internal Budget cap on keys deleted per run.
146
+ * `CLOUDFLARE_FREE_TIER` sets it — CF free-tier safe when paired
147
+ * with `compact()` in the same scheduled handler. The default is
148
+ * effectively unbounded (`Number.MAX_SAFE_INTEGER`).
149
+ */
150
+ readonly maxSweepsPerRun?: number;
151
+ /**
152
+ * @internal Clock injection for tests. Defaults to
153
+ * `() => new Date()`. The function is invoked at mark time (to
154
+ * compute `due_at` when `lastModified` is absent) and at sweep
155
+ * time (to compare against candidate `due_at`).
156
+ */
157
+ readonly now?: () => Date;
158
+ }
159
+ /**
160
+ * Return shape of {@link runGc}.
161
+ */
162
+ interface RunGcResult {
163
+ /** Per-category counts of newly-marked candidates in this pass. */
164
+ readonly marked: {
165
+ readonly stale_log: number;
166
+ readonly orphan_snapshot: number;
167
+ readonly orphan_content: number;
168
+ };
169
+ /** Number of keys deleted in this pass. */
170
+ readonly swept: number;
171
+ /**
172
+ * Depth of `gc/pending.json` after this pass. Drives the
173
+ * `db.orphan.candidate_count` metric. Best-effort on `cas-lost` —
174
+ * see module JSDoc.
175
+ */
176
+ readonly pendingDepth: number;
177
+ }
178
+ /**
179
+ * Single GC pass — mark new orphans, sweep due-elapsed candidates,
180
+ * persist via CAS-update on `gc/pending.json`.
181
+ *
182
+ * Returns immediately if `current.json` is missing — there's nothing
183
+ * to do until a writer has bootstrapped the collection.
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * import { runGc } from "@gusto/baerly-storage";
188
+ *
189
+ * const r = await runGc({ storage, currentJsonKey });
190
+ * console.log(`marked ${r.marked.stale_log} stale logs, swept ${r.swept}`);
191
+ * ```
192
+ */
193
+ declare const runGc: (args: {
194
+ storage: Storage;
195
+ currentJsonKey: string;
196
+ }, options?: RunGcOptions) => Promise<RunGcResult>;
197
+ //#endregion
198
+ //#region packages/server/src/rebuild-index.d.ts
199
+ /**
200
+ * Reconciliation summary.
201
+ *
202
+ * In a normal (mutating) run, the counts describe what was actually
203
+ * PUT / DELETEd. In `dryRun` mode ({@link RebuildIndexOptions.dryRun}),
204
+ * `added` / `removed` report the counts that a real rebuild *would*
205
+ * have produced — storage is unchanged. `kept` counts pre-existing
206
+ * intersection keys (`expected ∩ actual`) at function entry. In a real
207
+ * run, `kept` may also include keys promoted from `added` via the
208
+ * Conflict-race fallback (a PUT with `ifNoneMatch:"*"` returned 412
209
+ * because a peer wrote the same key first, so the key was already
210
+ * in place by the time we observed it); dryRun mode never issues
211
+ * those PUTs and therefore does not observe that race.
212
+ */
213
+ interface RebuildIndexResult {
214
+ /**
215
+ * Keys PUT because they were missing on storage. In `dryRun` mode,
216
+ * the predicted PUT count — no writes were issued.
217
+ */
218
+ readonly added: number;
219
+ /**
220
+ * Keys DELETEd because the doc no longer exists / no longer projects
221
+ * them. In `dryRun` mode, the predicted DELETE count — no deletes
222
+ * were issued.
223
+ */
224
+ readonly removed: number;
225
+ /** Keys already in place. The healthy-index re-run reports this as the full expected count. */
226
+ readonly kept: number;
227
+ }
228
+ /**
229
+ * Optional knobs accepted by {@link rebuildIndex}. Every field is
230
+ * optional; the function behaves identically to the older
231
+ * positional-arg shape when `opts` is omitted.
232
+ *
233
+ * @public — surfaced from `baerly-storage` so admin tooling and the
234
+ * observability layer can opt in.
235
+ */
236
+ interface RebuildIndexOptions {
237
+ /**
238
+ * Cancellation signal. Forwarded to every storage `list` call so
239
+ * long-running rebuilds over large collections can be cut short
240
+ * by admin tooling. Storage `get` / `put` / `delete` calls inside
241
+ * the reconciliation loop do not currently honour the signal
242
+ * (the per-call durations are short enough that cooperative
243
+ * cancellation between calls suffices); future tightening can
244
+ * forward it through without breaking callers.
245
+ */
246
+ readonly signal?: AbortSignal;
247
+ /**
248
+ * When `true`, walk the expected-vs-actual diff and return the
249
+ * counts that a real rebuild would have produced WITHOUT issuing
250
+ * any PUT or DELETE. Used by `baerly admin fsck --indexes`
251
+ * to report drift cheaply. Defaults to `false`.
252
+ *
253
+ * `kept` is reported as the pre-existing intersection
254
+ * (`expected ∩ actual`); a real run can additionally fold
255
+ * Conflict-race-demoted PUTs into `kept`, which dryRun does not
256
+ * observe. See {@link RebuildIndexResult}.
257
+ */
258
+ readonly dryRun?: boolean;
259
+ }
260
+ /**
261
+ * Idempotently reconcile one secondary index for one collection.
262
+ *
263
+ * @param storage Storage handle (any in-tree `Storage`).
264
+ * @param currentJsonKey The collection's `current.json` key.
265
+ * @param def The index to reconcile. Single-field today;
266
+ * composite definitions are accepted by the
267
+ * key encoder but the read path only consults
268
+ * single-field keys.
269
+ * @param opts Optional knobs — see {@link RebuildIndexOptions}.
270
+ * Strictly additive: existing positional-arg
271
+ * callers compile and behave unchanged when
272
+ * omitted.
273
+ *
274
+ * @throws BaerlyError code="InvalidResponse" — `current.json` missing.
275
+ * @throws BaerlyError code="Internal" — protocol-invariant
276
+ * violation (snapshot hash mismatch, missing log entry inside
277
+ * `[log_seq_start, next_seq)`).
278
+ */
279
+ declare const rebuildIndex: (storage: Storage, currentJsonKey: string, def: IndexDefinition, opts?: RebuildIndexOptions) => Promise<RebuildIndexResult>;
280
+ //#endregion
281
+ //#region packages/server/src/maintenance.d.ts
282
+ interface MaintenanceArgs {
283
+ readonly storage: Storage;
284
+ /** Full bucket-relative key of the CAS pointer for the target collection. */
285
+ readonly currentJsonKey: string;
286
+ }
287
+ interface MaintenanceOptions {
288
+ /** Forwarded to `compact()`. */
289
+ readonly compact?: CompactOptions;
290
+ /** Forwarded to `runGc()`. */
291
+ readonly gc?: RunGcOptions;
292
+ /** Forwarded to both primitives. */
293
+ readonly signal?: AbortSignal;
294
+ }
295
+ /**
296
+ * Internal-only widening of {@link MaintenanceOptions}. Surfaced via
297
+ * the `@baerly/server/_internal/testing` subpath (NOT in the
298
+ * published `publishConfig.exports`); production callers should use
299
+ * {@link MaintenanceOptions}.
300
+ *
301
+ * @internal
302
+ */
303
+ interface InternalMaintenanceOptions extends MaintenanceOptions {
304
+ /** @internal Internal compact options (budget caps). */
305
+ readonly compact?: InternalCompactOptions;
306
+ /** @internal Internal GC options (budget caps + clock seam + grace). */
307
+ readonly gc?: InternalRunGcOptions;
308
+ }
309
+ interface MaintenanceResult {
310
+ readonly compact: CompactResult;
311
+ readonly gc: RunGcResult;
312
+ }
313
+ /**
314
+ * Single maintenance pass for one collection. Runs `compact()` then
315
+ * `runGc()` (in that order; the compactor's advance of
316
+ * `log_seq_start` produces the stale-log candidates the GC then
317
+ * marks). Callers wanting a single phase per tick invoke
318
+ * `compact()` or `runGc()` directly instead.
319
+ *
320
+ * Errors propagate — the caller's cron handler is responsible for
321
+ * logging them. The Cloudflare runtime ships uncaught Worker errors
322
+ * to the dashboard; Node operators wrap their `node-cron` callbacks
323
+ * themselves.
324
+ *
325
+ * @example
326
+ * ```ts
327
+ * import { runScheduledMaintenance, CLOUDFLARE_FREE_TIER } from "@gusto/baerly-storage/maintenance";
328
+ *
329
+ * // Node (unbounded — defaults fold the entire live tail):
330
+ * const res = await runScheduledMaintenance(
331
+ * { storage, currentJsonKey: "app/x/tenant/t/manifests/tickets/current.json" },
332
+ * );
333
+ * console.log("compacted:", res.compact.entriesFolded, "swept:", res.gc.swept);
334
+ *
335
+ * // Cloudflare free tier (50-subrequest cap, single phase per tick):
336
+ * await runScheduledMaintenance({ storage, currentJsonKey }, CLOUDFLARE_FREE_TIER);
337
+ * ```
338
+ */
339
+ declare const runScheduledMaintenance: (args: MaintenanceArgs, options?: MaintenanceOptions) => Promise<MaintenanceResult>;
340
+ declare const CLOUDFLARE_FREE_TIER: MaintenanceOptions;
341
+ /**
342
+ * Floor-based GC-cadence boundary crossing. BATCH-SAFE: a
343
+ * `commitBatch` that jumps `next_seq` by its whole batch size can step
344
+ * CLEAN OVER a `next_seq % interval === 0` modulo test; this floor test
345
+ * trips on any interval boundary inside `(prevSeq, nextSeq]`.
346
+ */
347
+ declare const crossesGcBoundary: (prevSeq: number, nextSeq: number, interval: number) => boolean;
348
+ /**
349
+ * The cheap DISPATCH gate the writer calls after a commit — zero
350
+ * storage ops; it reads the post-CAS {@link CurrentJson} already in
351
+ * scope. Ratio-OR-boundary, WITHOUT the entry floor (the floor is part
352
+ * of the fold-trigger Gate 1 checked inside {@link runBoundedMaintenance}).
353
+ * Returning `false` lets the writer skip the dispatch entirely.
354
+ */
355
+ declare const shouldFireMaintenance: (current: CurrentJson, prevSeq: number, gcInterval: number) => boolean;
356
+ /** Per-tier caps for {@link runBoundedMaintenance}, threaded by the adapter. */
357
+ interface BoundedMaintenanceOptions {
358
+ /** Tail slice folded per pass. Default {@link WRITE_TICK_FOLD_ENTRIES_PER_PASS}. */
359
+ readonly maxFoldEntriesPerPass?: number;
360
+ /** Gate-1 minimum live-tail length. Default {@link WRITE_TICK_MIN_ENTRIES_TO_COMPACT}. */
361
+ readonly minEntriesToCompact?: number;
362
+ /** GC marks per pass. Default {@link WRITE_TICK_GC_MAX_MARKS}. */
363
+ readonly gcMaxMarks?: number;
364
+ /** GC sweeps per pass. Default {@link WRITE_TICK_GC_MAX_SWEEPS}. */
365
+ readonly gcMaxSweeps?: number;
366
+ /** GC cadence (boundary-crossing). Default {@link WRITE_TICK_GC_INTERVAL}. */
367
+ readonly gcInterval?: number;
368
+ /**
369
+ * How many phases this tick may run. `"single"` (CF-free-safe
370
+ * default) runs at most one of fold / GC per tick; `"both"` lets a
371
+ * capable host run a fold AND a GC in one tick.
372
+ */
373
+ readonly phasesPerTick?: "single" | "both";
374
+ /**
375
+ * @internal — test seam. Forwarded into the runner's `runGc` call as
376
+ * `graceMillis`. Default `undefined` ⇒ `runGc`'s 7-day
377
+ * {@link GC_GRACE_PERIOD_MILLIS}. The drain-rate test sets `0` so a
378
+ * single pass marks AND sweeps, making the steady-state object-count
379
+ * trajectory observable without an 8-day clock advance. Production
380
+ * never sets this.
381
+ */
382
+ readonly gcGraceMillis?: number;
383
+ /**
384
+ * @internal — test seam. Forwarded into the runner's `runGc` call as
385
+ * the clock `now`. Default `undefined` ⇒ `runGc`'s `() => new Date()`.
386
+ * Production never sets this.
387
+ */
388
+ readonly now?: () => Date;
389
+ readonly signal?: AbortSignal;
390
+ }
391
+ /**
392
+ * The write-tick maintenance runner: a bounded, single-attempt
393
+ * composition of {@link compact} and {@link runGc} for one collection,
394
+ * sized to fit a CPU-killable Cloudflare free-tier isolate by default.
395
+ *
396
+ * Never throws — the write-tick caller must never see a maintenance
397
+ * failure. Expected signals (CAS contention, an over-ceiling deferral)
398
+ * are swallowed quietly; unexpected throws bump
399
+ * `db.maintenance.unexpected_error_total`, log a stack, and are
400
+ * swallowed.
401
+ *
402
+ * Control flow (fold-priority with a stateless GC-starvation guard):
403
+ * 0. `disabled` → return with zero storage ops.
404
+ * 1. Read `current.json` once.
405
+ * 2. Hard-GC starvation boundary (`"single"` only) → GC slice, skip fold.
406
+ * 3. Gate 1 (ratio AND entry floor) trips → fold if viable, else
407
+ * defer (and metric); on `"single"` a successful fold attempt is
408
+ * this tick's one phase.
409
+ * 4. Otherwise (or on `"both"`) → GC iff the cadence boundary crossed.
410
+ */
411
+ declare const runBoundedMaintenance: (args: {
412
+ storage: Storage;
413
+ currentJsonKey: string; /** The writer's PRE-CAS `current.next_seq` — the GC cadence baseline. */
414
+ prevSeq: number; /** `C` override (from `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`). */
415
+ maxFoldBytes?: number; /** From `BAERLY_MAINTENANCE_DISABLE`. */
416
+ disabled?: boolean;
417
+ }, options?: BoundedMaintenanceOptions) => Promise<void>;
418
+ /**
419
+ * Default maintenance dispatcher: run the task inline and await it.
420
+ * Adapters that can keep running after the response (Cloudflare:
421
+ * `ctx.waitUntil`) override this with a fire-and-forget variant that
422
+ * returns `void`.
423
+ */
424
+ declare const dispatchInlineAwaited: (task: () => Promise<void>) => void | Promise<void>;
425
+ /**
426
+ * Per-request maintenance dispatch config, set by the adapter onto the
427
+ * observability context (NOT `Db.create`). It rides the per-request ALS
428
+ * context because `dispatch = ctx.waitUntil` is inherently per-request,
429
+ * and routing it through `Db.create` would widen that surface past its
430
+ * locked four fields. The writer reads it at the post-CAS dispatch
431
+ * point via `getCurrentContext()?.maintenance`.
432
+ *
433
+ * Absent ⇒ inline dispatch + CF-free-safe caps (the defaults inside
434
+ * {@link runBoundedMaintenance}), so a bare `Db.create(...)` maintains
435
+ * out of the box once enough writes accrue.
436
+ */
437
+ interface MaintenanceDispatch {
438
+ /** How to run the maintenance task. Default {@link dispatchInlineAwaited}. CF sets `ctx.waitUntil`. */
439
+ readonly dispatch?: (task: () => Promise<void>) => void | Promise<void>;
440
+ /** From `BAERLY_MAINTENANCE_DISABLE`. */
441
+ readonly disabled?: boolean;
442
+ /** `C` override, from `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`. */
443
+ readonly maxFoldBytes?: number;
444
+ /** Per-tier caps forwarded to {@link runBoundedMaintenance}. */
445
+ readonly options?: BoundedMaintenanceOptions;
446
+ }
447
+ //#endregion
448
+ export { RunGcResult as _, MaintenanceDispatch as a, CompactResult as b, crossesGcBoundary as c, runScheduledMaintenance as d, shouldFireMaintenance as f, RunGcOptions as g, rebuildIndex as h, MaintenanceArgs as i, dispatchInlineAwaited as l, RebuildIndexResult as m, CLOUDFLARE_FREE_TIER as n, MaintenanceOptions as o, RebuildIndexOptions as p, InternalMaintenanceOptions as r, MaintenanceResult as s, BoundedMaintenanceOptions as t, runBoundedMaintenance as u, runGc as v, compact as x, CompactOptions as y };
449
+ //# sourceMappingURL=maintenance-BRrThz8V.d.ts.map