@cloudbitmaps/roaring 0.8.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/NOTICE +3 -3
  2. package/PRIVACY.md +198 -72
  3. package/README.md +148 -50
  4. package/dist/bin/export-segments.d.ts +21 -0
  5. package/dist/bin/export-segments.js +1508 -30
  6. package/dist/bin/export-segments.js.map +7 -1
  7. package/dist/codec-bound.d.ts +38 -0
  8. package/dist/index.d.ts +875 -425
  9. package/dist/index.js +997 -306
  10. package/dist/index.js.map +7 -1
  11. package/dist/moved-options.d.ts +14 -0
  12. package/dist/portable/decode.d.ts +54 -0
  13. package/dist/roaring-codec.d.ts +61 -0
  14. package/dist/system-clock.d.ts +40 -0
  15. package/dist/testing/conformance.d.ts +34 -0
  16. package/dist/testing/fuzz-codec.d.ts +9 -0
  17. package/package.json +11 -116
  18. package/dist/azure/index.cjs +0 -14
  19. package/dist/azure/index.cjs.map +0 -1
  20. package/dist/azure/index.d.cts +0 -9
  21. package/dist/azure/index.d.ts +0 -9
  22. package/dist/azure/index.js +0 -3
  23. package/dist/azure/index.js.map +0 -1
  24. package/dist/bin/compact-segments.js +0 -134
  25. package/dist/bin/compact-segments.js.map +0 -1
  26. package/dist/cassandra/index.cjs +0 -14
  27. package/dist/cassandra/index.cjs.map +0 -1
  28. package/dist/cassandra/index.d.cts +0 -1
  29. package/dist/cassandra/index.d.ts +0 -1
  30. package/dist/cassandra/index.js +0 -3
  31. package/dist/cassandra/index.js.map +0 -1
  32. package/dist/chunk-4NVOQJGJ.js +0 -801
  33. package/dist/chunk-4NVOQJGJ.js.map +0 -1
  34. package/dist/dynamodb/index.cjs +0 -14
  35. package/dist/dynamodb/index.cjs.map +0 -1
  36. package/dist/dynamodb/index.d.cts +0 -1
  37. package/dist/dynamodb/index.d.ts +0 -1
  38. package/dist/dynamodb/index.js +0 -3
  39. package/dist/dynamodb/index.js.map +0 -1
  40. package/dist/gcs/index.cjs +0 -14
  41. package/dist/gcs/index.cjs.map +0 -1
  42. package/dist/gcs/index.d.cts +0 -1
  43. package/dist/gcs/index.d.ts +0 -1
  44. package/dist/gcs/index.js +0 -3
  45. package/dist/gcs/index.js.map +0 -1
  46. package/dist/index.cjs +0 -789
  47. package/dist/index.cjs.map +0 -1
  48. package/dist/index.d.cts +0 -642
  49. package/dist/mongodb/index.cjs +0 -14
  50. package/dist/mongodb/index.cjs.map +0 -1
  51. package/dist/mongodb/index.d.cts +0 -1
  52. package/dist/mongodb/index.d.ts +0 -1
  53. package/dist/mongodb/index.js +0 -3
  54. package/dist/mongodb/index.js.map +0 -1
  55. package/dist/mysql/index.cjs +0 -14
  56. package/dist/mysql/index.cjs.map +0 -1
  57. package/dist/mysql/index.d.cts +0 -1
  58. package/dist/mysql/index.d.ts +0 -1
  59. package/dist/mysql/index.js +0 -3
  60. package/dist/mysql/index.js.map +0 -1
  61. package/dist/postgres/index.cjs +0 -14
  62. package/dist/postgres/index.cjs.map +0 -1
  63. package/dist/postgres/index.d.cts +0 -1
  64. package/dist/postgres/index.d.ts +0 -1
  65. package/dist/postgres/index.js +0 -3
  66. package/dist/postgres/index.js.map +0 -1
  67. package/dist/redis/index.cjs +0 -14
  68. package/dist/redis/index.cjs.map +0 -1
  69. package/dist/redis/index.d.cts +0 -1
  70. package/dist/redis/index.d.ts +0 -1
  71. package/dist/redis/index.js +0 -3
  72. package/dist/redis/index.js.map +0 -1
  73. package/dist/s3/index.cjs +0 -14
  74. package/dist/s3/index.cjs.map +0 -1
  75. package/dist/s3/index.d.cts +0 -1
  76. package/dist/s3/index.d.ts +0 -1
  77. package/dist/s3/index.js +0 -3
  78. package/dist/s3/index.js.map +0 -1
package/dist/index.cjs DELETED
@@ -1,789 +0,0 @@
1
- 'use strict';
2
-
3
- var core = require('@cloudbitmaps/core');
4
- var roaring = require('roaring');
5
-
6
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
-
8
- var roaring__default = /*#__PURE__*/_interopDefault(roaring);
9
-
10
- // src/index.ts
11
- var { RoaringBitmap32, SerializationFormat, DeserializationFormat } = roaring__default.default;
12
- var SafeBitmap = class _SafeBitmap {
13
- bitmap;
14
- constructor(bitmap) {
15
- this.bitmap = bitmap;
16
- }
17
- static empty() {
18
- return new _SafeBitmap(new RoaringBitmap32());
19
- }
20
- static fromValues(values) {
21
- return new _SafeBitmap(new RoaringBitmap32(values));
22
- }
23
- /**
24
- * S1: validate size, then deserialize with the **portable** (validated) format.
25
- * Throws `IntegrityError` if the input exceeds `maxBytes` or fails to decode — the
26
- * native addon is never handed unbounded or unsafe-format input.
27
- */
28
- static safeDeserialize(bytes, maxBytes) {
29
- if (bytes.length > maxBytes) {
30
- throw new core.IntegrityError(`serialized bitmap is ${bytes.length}B, exceeds cap ${maxBytes}B`);
31
- }
32
- try {
33
- return new _SafeBitmap(RoaringBitmap32.deserialize(bytes, DeserializationFormat.portable));
34
- } catch (err) {
35
- throw new core.IntegrityError(`failed to deserialize bitmap: ${err.message}`);
36
- }
37
- }
38
- serialize() {
39
- return this.bitmap.serialize(SerializationFormat.portable);
40
- }
41
- /**
42
- * Convert containers to run-encoding where that is smaller. Representation only — membership is untouched, and
43
- * the portable format still round-trips through {@link RoaringCodec.safeDeserialize}.
44
- *
45
- * Roaring's third container type is a RUN, and no implementation selects it on its own: it takes an explicit
46
- * `runOptimize()` pass. Nothing here made that call, so run-shaped ids paid array or bitset prices — measured
47
- * at **570×** for a contiguous 1M-id range (128.1 KiB → 0.2 KiB) and **63×** for a 2,000-run shape
48
- * (536.5 KiB → 8.5 KiB). Sparse ids come out byte-identical, so this is never a losing trade; roaring keeps
49
- * whichever encoding is smaller per container.
50
- *
51
- * Those two factors are THIS CALL's own before/after on the same ids. They are not the ones the site quotes
52
- * (543× and 63×) — those compare the optimized encoding against the best *fixed* representation at its floor,
53
- * a different baseline that happens to land near 63× on the run shape too. `pnpm bench:encoding` prints both
54
- * columns; don't carry a figure between them without checking which denominator it had.
55
- *
56
- * Called by the engine only when writing an immutable cold generation — see {@link CodecBitmap.optimize} for
57
- * why the per-operation warm path deliberately does not.
58
- */
59
- optimize() {
60
- this.bitmap.runOptimize();
61
- }
62
- /**
63
- * Largest value, or `undefined` when empty. O(1) — roaring reads it off the container index, so the engine's
64
- * per-chunk range assertion costs one call per chunk rather than a walk per id.
65
- */
66
- maximum() {
67
- return this.bitmap.isEmpty ? void 0 : this.bitmap.maximum();
68
- }
69
- add(value) {
70
- this.bitmap.add(value);
71
- }
72
- addMany(values) {
73
- this.bitmap.addMany(values);
74
- }
75
- remove(value) {
76
- this.bitmap.remove(value);
77
- }
78
- removeMany(values) {
79
- this.bitmap.removeMany(values);
80
- }
81
- has(value) {
82
- return this.bitmap.has(value);
83
- }
84
- get size() {
85
- return this.bitmap.size;
86
- }
87
- get isEmpty() {
88
- return this.bitmap.isEmpty;
89
- }
90
- clone() {
91
- return new _SafeBitmap(this.bitmap.clone());
92
- }
93
- // The binary set ops take the `CodecBitmap` interface type (per the seam), but a single store is
94
- // single-codec (homogeneity contract), so `other` is always a `SafeBitmap` here — reach its private
95
- // `bitmap` (accessible on same-class instances) for the native op.
96
- /** In-place union: `this = this ∪ other`. */
97
- orInPlace(other) {
98
- this.bitmap.orInPlace(other.bitmap);
99
- }
100
- /** In-place difference: `this = this \ other`. */
101
- andNotInPlace(other) {
102
- this.bitmap.andNotInPlace(other.bitmap);
103
- }
104
- /** In-place intersection: `this = this ∩ other`. */
105
- andInPlace(other) {
106
- this.bitmap.andInPlace(other.bitmap);
107
- }
108
- /** Ascending iterator over the set values. */
109
- [Symbol.iterator]() {
110
- return this.bitmap[Symbol.iterator]();
111
- }
112
- toArray() {
113
- return this.bitmap.toArray();
114
- }
115
- };
116
- var roaringCodec = {
117
- empty: () => SafeBitmap.empty(),
118
- fromValues: (values) => SafeBitmap.fromValues(values),
119
- safeDeserialize: (bytes, maxBytes) => SafeBitmap.safeDeserialize(bytes, maxBytes)
120
- };
121
-
122
- // src/system-clock.ts
123
- var SystemClock = class {
124
- now() {
125
- return Date.now();
126
- }
127
- sleep(ms) {
128
- if (ms <= 0) return Promise.resolve();
129
- return new Promise((resolve) => {
130
- setTimeout(resolve, ms);
131
- });
132
- }
133
- /**
134
- * `setImmediate`, and it has to be — this is the one place where the choice of primitive is the whole feature.
135
- *
136
- * A long CPU-bound loop in `core/` (bulk-load is the one that matters) periodically hands the loop back so a
137
- * co-resident HTTP server keeps answering. Measured on the **synthetic yield-primitive benchmark** — a
138
- * 61,035-iteration loop yielding every 1,024, isolating the primitive rather than timing a real load (the
139
- * end-to-end figures are 450 ms → 19 ms; see `cooperative.ts`, which lists all three experiments):
140
- *
141
- * ```text
142
- * no yield 568 ms wall 568.0 ms worst event-loop gap
143
- * sleep(0) 555 ms wall 555.2 ms ← a microtask. Yields NOTHING.
144
- * setImmediate 569 ms wall 13.8 ms ← free, and 41x less starvation
145
- * setTimeout(1) 625 ms wall 15.0 ms ← +10% wall for no extra relief
146
- * ```
147
- *
148
- * `sleep(0)` resolving on a microtask is correct for its own contract and useless for this: microtasks drain
149
- * before the loop ever advances a phase, so `await sleep(0)` in a tight loop never lets a single pending I/O
150
- * callback run. `setImmediate` fires in the check phase *after* pending I/O, which is exactly the ordering a
151
- * server wants — inbound requests are serviced before the loop resumes chewing.
152
- *
153
- * A timer is not ref'd here (unlike {@link sleep}): a yield expresses "someone else may go first", never
154
- * "there is outstanding work" — and `setImmediate` cannot outlive the turn that scheduled it anyway.
155
- */
156
- yieldNow() {
157
- return new Promise((resolve) => {
158
- setImmediate(resolve);
159
- });
160
- }
161
- };
162
- var bulkLoadCrbmGeneration = (driver, key, ids, options = {}) => core.bulkLoadCrbmGeneration(driver, key, ids, {
163
- ...options,
164
- codec: options.codec ?? roaringCodec,
165
- clock: options.clock ?? new SystemClock()
166
- });
167
- var compactSegment = (ref, deps, options) => core.compactSegment(ref, { ...deps, codec: deps.codec ?? roaringCodec }, options);
168
- var runCompactionCycle = (deps, options) => core.runCompactionCycle({ ...deps, codec: deps.codec ?? roaringCodec }, options);
169
- var runExport = (reader, registry, sink, options = {}) => core.runExport(reader, registry, sink, { ...options, codec: options.codec ?? roaringCodec });
170
-
171
- // src/index.ts
172
- var SystemRng = class {
173
- next() {
174
- return Math.random();
175
- }
176
- };
177
- var DEFAULT_CACHE_MAX_CHUNKS = 1024;
178
- var DEFAULT_ADMIN_CONCURRENCY = 8;
179
- function validateConcurrency(concurrency) {
180
- if (concurrency !== void 0 && (!Number.isInteger(concurrency) || concurrency < 1)) {
181
- throw new core.ValidationError(`concurrency must be a positive integer; got ${concurrency}`);
182
- }
183
- }
184
- function requireScope(options, op) {
185
- if (options.namespace === void 0 && options.allNamespaces !== true) {
186
- throw new core.ValidationError(
187
- `${op} scans the global id space across all namespaces \u2014 pass an explicit \`namespace\`, or \`{ allNamespaces: true }\` to intentionally sweep the whole fleet`
188
- );
189
- }
190
- }
191
- function resolveColdSource(options, clock) {
192
- const cold = options.cold;
193
- if (cold === null || typeof cold !== "object") {
194
- throw new core.ValidationError("`cold` must be an IColdDriver or a ColdChunkSource");
195
- }
196
- const hasGetChunk = typeof cold.getChunk === "function";
197
- const hasPutImmutable = typeof cold.putImmutable === "function";
198
- if (hasGetChunk && hasPutImmutable) {
199
- throw new core.ValidationError(
200
- "`cold` exposes both `getChunk` and `putImmutable` \u2014 ambiguous; pass an IColdDriver or a ColdChunkSource, not a hybrid"
201
- );
202
- }
203
- if (!hasGetChunk && !hasPutImmutable) {
204
- throw new core.ValidationError("`cold` must be an IColdDriver or a ColdChunkSource");
205
- }
206
- if (hasGetChunk) {
207
- if (options.registry !== void 0 || options.keystore !== void 0 || options.requireEncryption === true) {
208
- throw new core.ValidationError(
209
- "registry/keystore/requireEncryption apply only when `cold` is a raw IColdDriver; configure them on the ColdChunkSource you passed instead"
210
- );
211
- }
212
- return { source: cold, driver: void 0 };
213
- }
214
- const driver = cold;
215
- return {
216
- source: new core.CrbmColdChunkSource(driver, {
217
- registry: options.registry,
218
- keystore: options.keystore,
219
- requireEncryption: options.requireEncryption,
220
- clock,
221
- currentGenTtlMs: options.coldGenTtlMs,
222
- maxOpenSegments: options.coldReaderCacheMax,
223
- maxOpenIndexBytes: options.coldReaderCacheMaxBytes
224
- }),
225
- driver
226
- };
227
- }
228
- var CloudRoaring = class {
229
- engine;
230
- clock;
231
- metrics;
232
- // The store's own drivers, kept so the in-process lifecycle helpers (`compact`/`eraseSubject`/`subjectReport`)
233
- // reuse them instead of making you re-pass a CompactionDeps. `coldDriver` is set only when `cold` was a raw
234
- // IColdDriver (a pre-built ColdChunkSource has no underlying driver to compact through).
235
- coldDriver;
236
- warmDriver;
237
- registry;
238
- keystore;
239
- requireEncryption;
240
- /** Resolved store-level per-op budget (null = disabled); the admin scans use it, with a per-op override. */
241
- budget;
242
- constructor(options) {
243
- const clock = options.clock ?? new SystemClock();
244
- const rng = options.rng ?? new SystemRng();
245
- const metrics = core.safeMetrics(options.metrics ?? core.NOOP_METRICS);
246
- const cache = new core.BoundedLru({
247
- maxEntries: options.cacheMaxChunks ?? DEFAULT_CACHE_MAX_CHUNKS,
248
- ttlMs: options.cacheTtlMs,
249
- clock
250
- });
251
- const resolved = resolveColdSource(options, clock);
252
- let cold = resolved.source;
253
- let warm = options.warm;
254
- if (options.retry !== false) {
255
- const retryOpts = {
256
- clock,
257
- rng,
258
- policy: options.retry,
259
- // Bridge transient-fault retries into the metrics stream, then call the user's own hook.
260
- onRetry: (info) => {
261
- metrics.onEvent({
262
- kind: "retry",
263
- reason: "transient",
264
- attempt: info.attempt,
265
- delayMs: info.delayMs
266
- });
267
- options.onRetry?.(info);
268
- }
269
- };
270
- warm = new core.RetryingWarmDriver(options.warm, retryOpts);
271
- cold = new core.RetryingColdChunkSource(cold, retryOpts);
272
- }
273
- if (options.writeConcurrency !== void 0 && (!Number.isInteger(options.writeConcurrency) || options.writeConcurrency < 1)) {
274
- throw new core.ValidationError(
275
- `writeConcurrency must be a positive integer; got ${options.writeConcurrency}`
276
- );
277
- }
278
- this.budget = core.resolveBudget(options.budget, core.DEFAULT_BUDGET);
279
- const deps = {
280
- warm,
281
- cold,
282
- cache,
283
- codec: roaringCodec,
284
- // the facade injects the flagship codec; core stays codec-agnostic
285
- clock,
286
- rng,
287
- occBackoff: options.occBackoff,
288
- metrics,
289
- warmReadConsistency: options.warmReadConsistency,
290
- writeConcurrency: options.writeConcurrency,
291
- maxWarmScanBytes: options.maxWarmScanBytes,
292
- budget: this.budget
293
- };
294
- this.engine = new core.SegmentEngine(deps);
295
- this.clock = clock;
296
- this.metrics = metrics;
297
- this.coldDriver = resolved.driver;
298
- this.warmDriver = options.warm;
299
- this.registry = options.registry;
300
- this.keystore = options.keystore;
301
- this.requireEncryption = options.requireEncryption ?? false;
302
- }
303
- /**
304
- * Build {@link CompactionDeps} from the store's own drivers, for the in-process lifecycle helpers
305
- * ({@link compact} / {@link eraseSubject}). Requires the store to have been constructed with a **raw cold
306
- * driver** (a pre-built `ColdChunkSource` has no underlying `IColdDriver` to compact through) and a `registry`
307
- * (the authoritative `currentGen` pointer compaction swaps). Out-of-process callers use the `compactSegment`
308
- * free function with explicit deps.
309
- */
310
- compactionDeps() {
311
- if (this.coldDriver === void 0) {
312
- throw new core.UnsupportedError(
313
- "compact/dropSegment/eraseSubject/checkConsistency need the store built with a raw cold driver (IColdDriver), not a pre-built ColdChunkSource \u2014 or call the compactSegment/runConsistencyCheck free functions with explicit deps"
314
- );
315
- }
316
- if (this.registry === void 0) {
317
- throw new core.UnsupportedError(
318
- "compact/eraseSubject/checkConsistency need a `registry` in the store config"
319
- );
320
- }
321
- return {
322
- cold: this.coldDriver,
323
- warm: this.warmDriver,
324
- registry: this.registry,
325
- clock: this.clock,
326
- codec: roaringCodec,
327
- // facade injects the flagship codec
328
- keystore: this.keystore,
329
- requireEncryption: this.requireEncryption,
330
- metrics: this.metrics
331
- // safe-wrapped sink → store.compact/eraseSubject emit `compaction` events (gap #2)
332
- };
333
- }
334
- /** Get a handle to a segment. Validates the name/namespace grammar (finding S2). */
335
- segment(name, options) {
336
- const ref = { segment: name, namespace: options?.namespace };
337
- core.validateSegmentRef(ref);
338
- return new Segment(this.engine, ref, this.clock, this.metrics);
339
- }
340
- /**
341
- * **Subject access (GDPR Art. 15 / CCPA right-to-know): which segments is this id a member of?** (Phase 6b.)
342
- *
343
- * Enumerates the **registered** segments (via the store's own `registry`) and does a tier-merging `has(id)` on
344
- * each — no drivers to re-pass. Complete only over registered segments (register your segments if you claim
345
- * SAR support). There is deliberately **no `id → segments` reverse index** — that would tax every write for a
346
- * rare request; this admin scan is `O(registered segments)` and touches no hot path.
347
- * Requires a `registry` in the store config
348
- * (throws {@link UnsupportedError} otherwise).
349
- */
350
- async subjectReport(id, options = {}) {
351
- if (this.registry === void 0) {
352
- throw new core.UnsupportedError("subjectReport needs a `registry` in the store config");
353
- }
354
- const registry = this.registry;
355
- requireScope(options, "subjectReport");
356
- validateConcurrency(options.concurrency);
357
- const budget = core.resolvePerOpBudget(options.budget, this.budget);
358
- core.splitId(id);
359
- const recs = await core.collectWithinBudget(
360
- registry.list(options.namespace),
361
- budget,
362
- "subjectReport"
363
- );
364
- const membership = await core.mapWithConcurrency(
365
- recs,
366
- options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,
367
- async (rec) => {
368
- if (rec.status === "destroyed") return null;
369
- const ref = { segment: rec.segment, namespace: rec.namespace };
370
- return await this.engine.has(ref, id, { consistent: true }) ? { segment: rec.segment, namespace: rec.namespace } : null;
371
- }
372
- );
373
- const segments = membership.filter((m) => m !== null);
374
- return { id, segments, scannedSegments: recs.length };
375
- }
376
- /**
377
- * **Subject erasure (GDPR Art. 17): remove an id from every segment it's in, with a physical-deletion
378
- * guarantee.** (Phase 6b.)
379
- *
380
- * For each **registered** segment the id is a member of: writes a logical `remove` tombstone (immediate) and
381
- * then **force-compacts that segment now** — folding the tombstone into a fresh immutable generation so the
382
- * bit is *physically* gone from Cold on return, even for an otherwise-idle/archival segment that organic
383
- * compaction would never touch (the P13 fix). The returned per-segment record is your **erasure ledger** —
384
- * persist it / route it to your audit sink as the proof of deletion; the physical-purge proof is
385
- * compaction's own VERIFY step (a re-`has()` here would be unsound — a pinned cold source can still read the
386
- * old generation; take a fresh generation view after erasing, exactly as with the compaction daemon).
387
- *
388
- * Uses the store's **own** drivers (raw cold + warm + registry), so the old integrator obligation to wire a
389
- * matching `CompactionDeps` is gone — the `remove()` and the force-compaction provably run over the same tiers.
390
- * Requires the store built with a **raw cold driver + registry** (throws {@link UnsupportedError} otherwise;
391
- * a pre-built `ColdChunkSource` store has no `IColdDriver` to compact through — use the `compactSegment` free
392
- * function there). **One contract remains** (an integrator obligation the library cannot check): **do not
393
- * concurrently re-add the same id while erasing it.** A normal `add(id)` landing between the `remove` and the
394
- * compaction clears the tombstone and folds the id back into the new generation
395
- * (`effective = (cold ∪ adds) \ removes`); `physicallyPurged` attests only that compaction committed a
396
- * generation with the tombstones applied at pin time — quiesce writes for the subject during erasure.
397
- *
398
- * **A `physicallyPurged:false` entry means the logical removal holds but the physical purge didn't run this
399
- * call** — either a daemon held a live lease (`note:'leased-by-other'`; the daemon finishes it), or the
400
- * force-compaction hit an isolated fault (`note:'error: …'`; per-segment faults are caught so one segment
401
- * can't discard the whole ledger). `physicallyPurged:false` is **conservative** (a concurrent daemon may
402
- * already have purged the bit — `'clean'`). **Recovery:** follow up any `physicallyPurged:false` entry with
403
- * `store.compact(ref)` (or let the daemon do it) — **re-running `eraseSubject` will NOT re-purge it**, because
404
- * `has()` now reads false (the tombstone) so the segment is skipped as a non-member. The physical-purge proof
405
- * is compaction's own VERIFY step (a re-`has()` here would be unsound: a pinned cold source can still read the
406
- * old generation — take a fresh generation view after erasing, as with the daemon). Admin-only path;
407
- * `O(registered segments)`, no hot-path cost. Per-subject crypto-shred is infeasible (a subject's bit is
408
- * co-mingled in a shared container), so this is the single-subject erasure route; whole-segment/tenant erasure
409
- * is the `destroySegment`/`eraseNamespace` free functions.
410
- */
411
- async eraseSubject(id, options) {
412
- const compaction = this.compactionDeps();
413
- core.validateCompactionOptions({ owner: options.owner });
414
- requireScope(options, "eraseSubject");
415
- validateConcurrency(options.concurrency);
416
- const budget = core.resolvePerOpBudget(options.budget, this.budget);
417
- core.splitId(id);
418
- const recs = await core.collectWithinBudget(
419
- compaction.registry.list(options.namespace),
420
- budget,
421
- "eraseSubject"
422
- );
423
- const entries = await core.mapWithConcurrency(
424
- recs,
425
- options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,
426
- async (rec) => {
427
- if (rec.status === "destroyed") return null;
428
- const ref = { segment: rec.segment, namespace: rec.namespace };
429
- let removed = false;
430
- try {
431
- if (!await this.engine.has(ref, id, { consistent: true })) return null;
432
- await this.engine.remove(ref, id);
433
- removed = true;
434
- const result = await core.compactSegment(ref, compaction, {
435
- owner: options.owner,
436
- audit: options.audit
437
- });
438
- return {
439
- segment: rec.segment,
440
- namespace: rec.namespace,
441
- removed: true,
442
- physicallyPurged: result.compacted,
443
- toGen: result.toGen,
444
- note: result.compacted ? void 0 : result.reason
445
- };
446
- } catch (err) {
447
- return {
448
- segment: rec.segment,
449
- namespace: rec.namespace,
450
- removed,
451
- physicallyPurged: false,
452
- note: `error: ${err instanceof Error ? err.message : String(err)}`
453
- };
454
- }
455
- }
456
- );
457
- const erasedFrom = entries.filter((e) => e !== null);
458
- return { id, erasedFrom, scannedSegments: recs.length };
459
- }
460
- /**
461
- * **Compact one segment now**, in-process, using the store's own drivers — a convenience over the
462
- * {@link compactSegment} free function. Merges `(cold ∪ adds) \ removes` into a fresh immutable generation,
463
- * swaps `currentGen`, then version-fenced-purges the archived Warm rows. A no-op (`compacted:false`) when the
464
- * segment has no dirty rows or a daemon holds a live lease — never throws on the normal contention/lease paths.
465
- * Requires the store built with a **raw cold driver + registry** (throws {@link UnsupportedError} otherwise);
466
- * like the daemon, it uses the raw drivers directly (a transient fault surfaces to you rather than retrying
467
- * under the hood). **Not for the request/hot path** — it reads and rewrites a whole Cold generation (streaming,
468
- * constant-memory, but full-segment I/O). Use the `compact-segments` daemon (`runCompactionCycle`) for routine
469
- * background compaction; reach for `store.compact()` for occasional/manual one-shots — a maintenance endpoint,
470
- * a small daemon-less deployment, or right after a targeted `remove`.
471
- */
472
- async compact(ref, options) {
473
- core.validateSegmentRef(ref);
474
- const deps = this.compactionDeps();
475
- const result = await core.compactSegment(ref, deps, options);
476
- if (result.compacted) {
477
- await core.gcOrphanGenerations(ref, { cold: deps.cold, registry: deps.registry }).catch(
478
- () => void 0
479
- );
480
- }
481
- return result;
482
- }
483
- /**
484
- * **Dispose of a segment — tombstone it, delete its Warm rows, delete its Cold objects.** Irreversible.
485
- *
486
- * The operation a rolling window needs: `destroySegment` crypto-shreds (bytes unreadable everywhere including
487
- * backups, but still sitting in your bucket and still billed, and it requires encryption), while this one
488
- * removes the storage and works on a cleartext segment. On an encrypted segment it does both.
489
- *
490
- * Pass `{ dryRun: true }` first — it reports the generations it *would* delete and changes nothing. That
491
- * matters more than the `confirmSegment` guard for anything automated, because in a loop the guard is the same
492
- * variable twice.
493
- *
494
- * ```ts
495
- * for (const day of expiredDays) {
496
- * // A colon is NOT legal in a name — the family goes in the namespace, the date in the segment.
497
- * const ref = { namespace: 'active-daily', segment: day };
498
- * await store.dropSegment(ref, { confirmSegment: ref.segment });
499
- * }
500
- * ```
501
- *
502
- * **Omitting the namespace addresses a different segment and is a silent no-op** — you get
503
- * `{ dropped: false, reason: 'absent' }`, not a throw, so a retention loop with that mistake deletes nothing
504
- * forever and quietly. Branch on `dropped`, and treat `reason: 'absent'` as the alert.
505
- *
506
- * **Works on an accumulator too.** A segment you created by writing to it — never bulk-loaded, never compacted,
507
- * so it has no registry row and no Cold objects — is retired by deleting its Warm rows alone. That reports
508
- * `{ dropped: true, reason: 'warm-only' }`: there is no tombstone to write, and deliberately none is written,
509
- * because a `destroyed` row per retired daily bucket would be registry litter. The data really is gone.
510
- *
511
- * **Inspect `generationsRemaining`.** Empty is the normal outcome; non-empty means the storage was NOT fully
512
- * reclaimed and the drop should be re-run. A compaction that was already in flight when the tombstone landed
513
- * still finishes staging one more object, so a single sweep can miss it — this call re-sweeps and then reports
514
- * whatever it still could not remove rather than returning a result that looks like a clean drop.
515
- *
516
- * Reads become empty within `coldGenTtlMs` (default 2 s), not instantly: a store that had already read this
517
- * segment may answer from its cached generation + hot chunks until that window lapses. A reader that never
518
- * touched it sees empty at once. **That bound needs a clock and `coldGenTtlMs > 0`** — a store built without a
519
- * clock, or with `coldGenTtlMs: 0` ("pin forever"), holds its resolved snapshot for its own lifetime and can
520
- * keep answering `true` for a dropped segment indefinitely; restart it.
521
- *
522
- * Needs the store built with a **raw cold driver + a registry** (throws {@link UnsupportedError} otherwise),
523
- * because it has to enumerate and delete generations — a pre-built `ColdChunkSource` only reads.
524
- */
525
- async dropSegment(ref, options) {
526
- core.validateSegmentRef(ref);
527
- const deps = this.compactionDeps();
528
- return core.dropSegment(ref, { registry: deps.registry, warm: deps.warm, cold: deps.cold }, options);
529
- }
530
- /**
531
- * **Cross-tier DR consistency check (audit gap #11).** After a restore/failover, verify every registered
532
- * segment's `currentGen` actually has its `.crbm` present in Cold — catching a **torn restore** where the
533
- * registry (`currentGen`) came back ahead of the object store, so a pointer references a generation that
534
- * isn't there (reads would then throw). Read-only, bounded fan-out; run it at startup after a restore.
535
- * Returns `{ checked, inconsistent }` — `inconsistent` empty ⇒ coherent; otherwise it names the segments to
536
- * recover (restore the object store, or roll the registry back to a coherent point). Needs the store built
537
- * with a **raw cold driver + a registry** (throws {@link UnsupportedError} otherwise). `destroyed`
538
- * (crypto-shredded) segments are skipped. Pair it with the DR runbook (docs/guide/disaster-recovery.md).
539
- */
540
- async checkConsistency(options = {}) {
541
- const deps = this.compactionDeps();
542
- return core.runConsistencyCheck({ cold: deps.cold, registry: deps.registry }, options);
543
- }
544
- /**
545
- * **Export ("eject") every registered segment's current effective set** through the injected `sink`, using
546
- * only public read APIs — so your data is readable **without CloudRoaring** (the exit path; see the README's
547
- * "Your data stays yours"). `format: 'roaring'` (default) writes one **portable RoaringBitmap32** per segment
548
- * (loadable by any roaring library); `'ndjson'` writes newline-delimited ids (zero-dependency, streaming).
549
- * Enumerates via the store's **own** registry (needs one — throws {@link UnsupportedError} otherwise) so the
550
- * enumeration and the read path provably share one registry; an all-warm segment not yet in the registry can be
551
- * named via `options.candidates`. Encrypted segments are decrypted transparently **iff** this store was wired
552
- * with their keystore — the export is therefore **cleartext**; protect it. Crypto-shredded segments are skipped.
553
- * A segment that can't be read is isolated into the manifest's `failed[]` (the run continues), so "a manifest
554
- * exists" means the run finished — check `failed`. The `export-segments` CLI wraps this with a filesystem sink.
555
- */
556
- async exportSegments(sink, options = {}) {
557
- if (this.registry === void 0) {
558
- throw new core.UnsupportedError("exportSegments needs a `registry` in the store config");
559
- }
560
- return core.runExport(this, this.registry, sink, {
561
- ...options,
562
- codec: options.codec ?? roaringCodec
563
- });
564
- }
565
- /**
566
- * Planning cost estimate (Phase 5b) — pure, no instance/data needed: sizing, sales, what-if. For a real,
567
- * grounded report from live segment sizes, use `store.segment(name).costReport()`. See {@link CostReport}.
568
- */
569
- static estimateCost(input) {
570
- return core.estimateCost(input);
571
- }
572
- };
573
- var Segment = class {
574
- constructor(engine, ref, clock, metrics) {
575
- this.engine = engine;
576
- this.ref = ref;
577
- this.clock = clock;
578
- this.metrics = metrics;
579
- this.metricsOn = metrics !== core.NOOP_METRICS;
580
- }
581
- engine;
582
- ref;
583
- clock;
584
- metrics;
585
- metricsOn;
586
- /**
587
- * Time an op with the injected clock and emit an `op` metric on completion (success or throw). Skipped
588
- * entirely when no sink is wired, so the default path pays nothing.
589
- */
590
- async timed(name, fn) {
591
- if (!this.metricsOn) return fn();
592
- const startedAt = this.clock.now();
593
- try {
594
- return await fn();
595
- } finally {
596
- this.metrics.onEvent({ kind: "op", name, ms: Math.max(0, this.clock.now() - startedAt) });
597
- }
598
- }
599
- /** Add an id (integer in `[0, 2^32)`). Throws {@link ValidationError} on a bad id. */
600
- add(id) {
601
- return this.timed("add", () => this.engine.add(this.ref, id));
602
- }
603
- /**
604
- * Add many ids, from a **sync or async** iterable. Not atomic across chunks — see the class note.
605
- *
606
- * An async source means a database cursor streams straight in — `addMany(athenaCursor())` rather than
607
- * hand-batching `page → addMany(page)`. Ids are grouped by chunk and each chunk is written **exactly once**,
608
- * however long the stream: pending ids are held compressed, not buffered-and-flushed, so a long stream costs
609
- * no more backend writes than a short one. Peak memory is the roaring representation of the ids you pass.
610
- *
611
- * **For a very large set, reach for `bulkLoadCrbmGeneration` instead.** `addMany` expresses a *delta* and
612
- * writes one warm row per touched chunk — around 61,000 of them for a set spread across the whole id space.
613
- * Bulk-load *replaces* the segment with one immutable Cold object. See the guide's cost comparison; picking
614
- * the wrong one of these is the most expensive mistake available in this library.
615
- */
616
- addMany(ids) {
617
- return this.timed("addMany", () => this.engine.addMany(this.ref, ids));
618
- }
619
- /** Remove an id (integer in `[0, 2^32)`). Throws {@link ValidationError} on a bad id. */
620
- remove(id) {
621
- return this.timed("remove", () => this.engine.remove(this.ref, id));
622
- }
623
- /** Remove many ids, from a **sync or async** iterable. Not atomic across chunks — see {@link addMany}. */
624
- removeMany(ids) {
625
- return this.timed("removeMany", () => this.engine.removeMany(this.ref, ids));
626
- }
627
- /**
628
- * **Claim ids atomically — add them, and get back only the ones that were not already there.**
629
- *
630
- * The durable analogue of Redis `SETBIT` returning the prior bit, which is what an exactly-once *"have I
631
- * already sent to / already processed this id?"* check needs. `has()` then `add()` cannot give you this: two
632
- * workers can both read absent and both proceed.
633
- *
634
- * ```ts
635
- * const sent = store.segment(day, { namespace: 'sent-daily' });
636
- * const toSend = await sent.claimMany(candidateIds); // only the ids this worker won
637
- * for (const id of toSend) enqueue(id); // ...so nobody else will send them
638
- * ```
639
- *
640
- * **Pass a batch, not one id.** A Warm write rewrites a whole 64K-id chunk bitmap, so claiming ids one at a
641
- * time is the single most expensive way to use this library — measured at ~5,000 writes and ~23 MB for 5,000
642
- * ids, against 1 write and ~8 KB for the same ids in one call. This method does one OCC read-modify-write per
643
- * distinct chunk, giving you Redis's *semantics* without Redis's per-id *cost shape*.
644
- *
645
- * **Exactly-once holds per id**, which is the guarantee that matters: each id lives in one chunk, a chunk is
646
- * one OCC row, so exactly one concurrent claimer sees any given id as new. Like `addMany` it is **not** atomic
647
- * across chunks — a mid-flight failure can leave some chunks claimed — but re-running is safe, because
648
- * already-claimed ids simply come back as not-new.
649
- *
650
- * Order of the returned ids is unspecified.
651
- */
652
- claimMany(ids) {
653
- return this.timed("claimMany", () => this.engine.claimMany(this.ref, ids));
654
- }
655
- has(id) {
656
- return this.timed("has", () => this.engine.has(this.ref, id));
657
- }
658
- count() {
659
- return this.timed("count", () => this.engine.count(this.ref));
660
- }
661
- iterate() {
662
- return this.engine.iterate(this.ref);
663
- }
664
- /**
665
- * Chunk-skipping intersection: stream the ids in **this** segment AND every segment in `others`, ascending.
666
- * Fetches only the Cold chunks present in *all* operands (a key absent from any operand contributes nothing
667
- * and is never downloaded), streaming under a bounded in-flight window — so the Cold footprint stays small
668
- * (Lambda-friendly) regardless of segment size. Pass `concurrency` to tune that window (a positive integer).
669
- * AND is commutative, so `a.intersect([b])` and `b.intersect([a])` yield the same ids. (Warm state is read
670
- * up front, so total memory also carries each operand's Warm size — negligible under Topology-A.) Pass
671
- * `budget` to override the store's per-op denial-of-wallet budget for this call (or `false` to lift it).
672
- */
673
- /**
674
- * Map the facade's `Segment` handles in `exclude` down to the plain refs `core` takes. A method rather than
675
- * a module function because `ref` is class-private — the encapsulation is worth more than the free function.
676
- */
677
- refsIn(options) {
678
- if (options === void 0) return void 0;
679
- const { exclude, ...rest } = options;
680
- return exclude === void 0 ? rest : { ...rest, exclude: exclude.map((o) => o.ref) };
681
- }
682
- intersect(others, options) {
683
- return this.engine.intersect([this.ref, ...others.map((o) => o.ref)], this.refsIn(options));
684
- }
685
- /**
686
- * Materialize `this ∩ others…` (minus `exclude`) **into** `dest` (added, not replaced). Streaming +
687
- * bounded-memory, but **not atomic** across chunks — see {@link addMany}.
688
- */
689
- intersectInto(dest, others, options) {
690
- return this.timed(
691
- "intersectInto",
692
- () => this.engine.intersectInto(
693
- dest.ref,
694
- [this.ref, ...others.map((o) => o.ref)],
695
- this.refsIn(options)
696
- )
697
- );
698
- }
699
- /**
700
- * `this ∪ others…`, minus `options.exclude` — streamed ascending.
701
- *
702
- * **The one composite read with no chunk-skipping,** and that is inherent to union rather than a limitation
703
- * here: an id in *any* operand belongs to the result, so every chunk of every operand must be read.
704
- * `intersect` prunes any key missing from any operand; union has nothing to prune. It is charged against the
705
- * same per-op budget, so a wide union is refused rather than quietly billed — pass `budget` to raise it
706
- * deliberately. If you find yourself unioning the same segments on every read, materializing the combined
707
- * segment once (`unionInto`, or a bulk-load rebuild) is the cheaper shape.
708
- */
709
- union(others, options) {
710
- return this.engine.union([this.ref, ...others.map((o) => o.ref)], this.refsIn(options));
711
- }
712
- /** Materialize `this ∪ others…` (minus `exclude`) **into** `dest`. **Not atomic** — see {@link addMany}. */
713
- unionInto(dest, others, options) {
714
- return this.timed(
715
- "unionInto",
716
- () => this.engine.unionInto(
717
- dest.ref,
718
- [this.ref, ...others.map((o) => o.ref)],
719
- this.refsIn(options)
720
- )
721
- );
722
- }
723
- /**
724
- * `this \ (excludes…)` — streamed ascending. Suppression on its own.
725
- *
726
- * Reads every chunk of `this` (any of them may survive the subtraction) but each exclude **only where it
727
- * overlaps this segment**, so the cost tracks the segment being filtered rather than the size of the
728
- * suppression list: at most one read per surviving key of `this`, so subtracting a 61,000-chunk global
729
- * opt-out list from a 40-chunk audience costs at most 40 reads, not 61,000.
730
- *
731
- * To filter the *result of an intersection*, do not chain — pass `exclude` to {@link intersect} instead, so
732
- * the suppression folds into the same pass rather than materializing an intermediate segment first.
733
- */
734
- andNot(excludes, options) {
735
- return this.engine.andNot(
736
- this.ref,
737
- excludes.map((o) => o.ref),
738
- options
739
- );
740
- }
741
- /** Materialize `this \ (excludes…)` **into** `dest`. **Not atomic** — see {@link addMany}. */
742
- andNotInto(dest, excludes, options) {
743
- return this.timed(
744
- "andNotInto",
745
- () => this.engine.andNotInto(
746
- dest.ref,
747
- this.ref,
748
- excludes.map((o) => o.ref),
749
- options
750
- )
751
- );
752
- }
753
- /**
754
- * Grounded cost report for this segment (Phase 5b): storage cost from its **real** `.crbm` size (exact,
755
- * no payload reads); request cost from the supplied `workload` rates. A segment with no Cold generation
756
- * reports zero storage. See {@link CostReport} — it always includes a verdict (incl. the lose-zone).
757
- */
758
- async costReport(options) {
759
- const canMeasure = this.engine.supportsColdSize;
760
- const size = canMeasure ? await this.engine.segmentSize(this.ref) : null;
761
- return core.groundedReport({
762
- coldBytes: size?.sizeBytes ?? 0,
763
- grounded: canMeasure,
764
- workload: options?.workload,
765
- topology: options?.topology,
766
- pricing: options?.pricing,
767
- extraNotes: canMeasure ? void 0 : ["cold source has no sizeOf() \u2014 storage not measured, reported as $0."]
768
- });
769
- }
770
- };
771
- var VERSION = "0.8.2";
772
-
773
- exports.CloudRoaring = CloudRoaring;
774
- exports.SafeBitmap = SafeBitmap;
775
- exports.Segment = Segment;
776
- exports.VERSION = VERSION;
777
- exports.bulkLoadCrbmGeneration = bulkLoadCrbmGeneration;
778
- exports.compactSegment = compactSegment;
779
- exports.roaringCodec = roaringCodec;
780
- exports.runCompactionCycle = runCompactionCycle;
781
- exports.runExport = runExport;
782
- Object.keys(core).forEach(function (k) {
783
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
784
- enumerable: true,
785
- get: function () { return core[k]; }
786
- });
787
- });
788
- //# sourceMappingURL=index.cjs.map
789
- //# sourceMappingURL=index.cjs.map