@cloudbitmaps/core 0.1.0-rc.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 (76) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +12 -0
  3. package/README.md +22 -0
  4. package/dist/azure/index.cjs +368 -0
  5. package/dist/azure/index.cjs.map +1 -0
  6. package/dist/azure/index.d.cts +48 -0
  7. package/dist/azure/index.d.ts +48 -0
  8. package/dist/azure/index.js +304 -0
  9. package/dist/azure/index.js.map +1 -0
  10. package/dist/cassandra/index.cjs +265 -0
  11. package/dist/cassandra/index.cjs.map +1 -0
  12. package/dist/cassandra/index.d.cts +52 -0
  13. package/dist/cassandra/index.d.ts +52 -0
  14. package/dist/cassandra/index.js +204 -0
  15. package/dist/cassandra/index.js.map +1 -0
  16. package/dist/chunk-2YDULGXS.js +203 -0
  17. package/dist/chunk-2YDULGXS.js.map +1 -0
  18. package/dist/chunk-7LMLYSVJ.js +43 -0
  19. package/dist/chunk-7LMLYSVJ.js.map +1 -0
  20. package/dist/chunk-AS6ODRLT.js +6 -0
  21. package/dist/chunk-AS6ODRLT.js.map +1 -0
  22. package/dist/chunk-NUIDEEFZ.js +91 -0
  23. package/dist/chunk-NUIDEEFZ.js.map +1 -0
  24. package/dist/chunk-SNJVZ227.js +35 -0
  25. package/dist/chunk-SNJVZ227.js.map +1 -0
  26. package/dist/dynamodb/index.cjs +731 -0
  27. package/dist/dynamodb/index.cjs.map +1 -0
  28. package/dist/dynamodb/index.d.cts +106 -0
  29. package/dist/dynamodb/index.d.ts +106 -0
  30. package/dist/dynamodb/index.js +460 -0
  31. package/dist/dynamodb/index.js.map +1 -0
  32. package/dist/gcs/index.cjs +343 -0
  33. package/dist/gcs/index.cjs.map +1 -0
  34. package/dist/gcs/index.d.cts +46 -0
  35. package/dist/gcs/index.d.ts +46 -0
  36. package/dist/gcs/index.js +279 -0
  37. package/dist/gcs/index.js.map +1 -0
  38. package/dist/index.cjs +4031 -0
  39. package/dist/index.cjs.map +1 -0
  40. package/dist/index.d.cts +1945 -0
  41. package/dist/index.d.ts +1945 -0
  42. package/dist/index.js +3642 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/mongodb/index.cjs +260 -0
  45. package/dist/mongodb/index.cjs.map +1 -0
  46. package/dist/mongodb/index.d.cts +45 -0
  47. package/dist/mongodb/index.d.ts +45 -0
  48. package/dist/mongodb/index.js +199 -0
  49. package/dist/mongodb/index.js.map +1 -0
  50. package/dist/mysql/index.cjs +281 -0
  51. package/dist/mysql/index.cjs.map +1 -0
  52. package/dist/mysql/index.d.cts +56 -0
  53. package/dist/mysql/index.d.ts +56 -0
  54. package/dist/mysql/index.js +211 -0
  55. package/dist/mysql/index.js.map +1 -0
  56. package/dist/ports-D3BrJ6ax.d.cts +357 -0
  57. package/dist/ports-D3BrJ6ax.d.ts +357 -0
  58. package/dist/postgres/index.cjs +273 -0
  59. package/dist/postgres/index.cjs.map +1 -0
  60. package/dist/postgres/index.d.cts +54 -0
  61. package/dist/postgres/index.d.ts +54 -0
  62. package/dist/postgres/index.js +203 -0
  63. package/dist/postgres/index.js.map +1 -0
  64. package/dist/redis/index.cjs +257 -0
  65. package/dist/redis/index.cjs.map +1 -0
  66. package/dist/redis/index.d.cts +42 -0
  67. package/dist/redis/index.d.ts +42 -0
  68. package/dist/redis/index.js +197 -0
  69. package/dist/redis/index.js.map +1 -0
  70. package/dist/s3/index.cjs +891 -0
  71. package/dist/s3/index.cjs.map +1 -0
  72. package/dist/s3/index.d.cts +112 -0
  73. package/dist/s3/index.d.ts +112 -0
  74. package/dist/s3/index.js +555 -0
  75. package/dist/s3/index.js.map +1 -0
  76. package/package.json +172 -0
@@ -0,0 +1,265 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+
5
+ // src/drivers/cassandra/warm.ts
6
+
7
+ // src/core/errors.ts
8
+ var ERROR_BRAND = /* @__PURE__ */ Symbol.for("cloud-roaring.error");
9
+ var TRANSIENT_BRAND = /* @__PURE__ */ Symbol.for("cloud-roaring.error.transient");
10
+ var CloudRoaringError = class extends Error {
11
+ /** Cross-bundle brand — see the predicates ({@link isCloudRoaringError}, …). Non-enumerable-ish (symbol key ⇒ not in JSON). */
12
+ [ERROR_BRAND] = true;
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = new.target.name;
16
+ }
17
+ };
18
+ var ValidationError = class extends CloudRoaringError {
19
+ };
20
+ var WriteConflictError = class extends CloudRoaringError {
21
+ };
22
+ var IntegrityError = class extends CloudRoaringError {
23
+ };
24
+ var TransientError = class extends CloudRoaringError {
25
+ /** A second brand so the whole transient subtree (incl. {@link TimeoutError}) is classifiable cross-bundle. */
26
+ [TRANSIENT_BRAND] = true;
27
+ constructor(message, options) {
28
+ super(message);
29
+ if (options && "cause" in options) this.cause = options.cause;
30
+ }
31
+ };
32
+
33
+ // src/core/ports.ts
34
+ var NO_ROW = /* @__PURE__ */ Symbol.for("cloud-roaring.no-row");
35
+
36
+ // src/core/validate.ts
37
+ var CHUNK_KEY_MAX = 65535;
38
+ var NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;
39
+ function validatePart(value, field) {
40
+ if (typeof value !== "string" || !NAME.test(value) || value.includes("..")) {
41
+ throw new ValidationError(
42
+ `${field} must match ${String(NAME)} and contain no "..": got ${JSON.stringify(value)}`
43
+ );
44
+ }
45
+ }
46
+ function validateSegmentRef(ref) {
47
+ validatePart(ref.segment, "segment");
48
+ if (ref.namespace !== void 0) validatePart(ref.namespace, "namespace");
49
+ }
50
+ function validateChunkRef(ref) {
51
+ validateSegmentRef(ref);
52
+ if (!Number.isInteger(ref.chunkKey) || ref.chunkKey < 0 || ref.chunkKey > CHUNK_KEY_MAX) {
53
+ throw new ValidationError(
54
+ `chunkKey must be an integer in [0, ${CHUNK_KEY_MAX}]; got ${ref.chunkKey}`
55
+ );
56
+ }
57
+ }
58
+
59
+ // src/drivers/_shared/keys.ts
60
+ var DEFAULT_NAMESPACE = "_default";
61
+ function namespacePart(namespace) {
62
+ return namespace ?? DEFAULT_NAMESPACE;
63
+ }
64
+
65
+ // src/drivers/cassandra/keys.ts
66
+ var IDENT = /^[A-Za-z_][A-Za-z0-9_]{0,47}$/;
67
+ function quoteIdent(id, what) {
68
+ if (!IDENT.test(id)) {
69
+ throw new ValidationError(
70
+ `invalid ${what} ${JSON.stringify(id)} \u2014 expected a CQL identifier (letters, digits, underscore; \u226448 chars; leading letter/underscore)`
71
+ );
72
+ }
73
+ return `"${id}"`;
74
+ }
75
+ function validateAndQuoteTable(keyspace, table) {
76
+ return `${quoteIdent(keyspace, "keyspace")}.${quoteIdent(table, "table")}`;
77
+ }
78
+ function normalizeKeyPrefix(prefix) {
79
+ if (prefix === void 0 || prefix === "") return "";
80
+ for (const ch of prefix) {
81
+ if (ch.charCodeAt(0) < 32) {
82
+ throw new ValidationError("keyPrefix must not contain control characters");
83
+ }
84
+ }
85
+ return prefix;
86
+ }
87
+
88
+ // src/drivers/cassandra/cassandra-errors.ts
89
+ function networkCode(err) {
90
+ const code = err?.code;
91
+ return typeof code === "string" && /^E[A-Z_]+$/.test(code) ? code : void 0;
92
+ }
93
+ var TRANSIENT_NAMES = /* @__PURE__ */ new Set([
94
+ "NoHostAvailableError",
95
+ "OperationTimedOutError",
96
+ "BusyConnectionError",
97
+ // connection-pool exhaustion — a transient back-pressure fault
98
+ "DriverError"
99
+ // generic connection-level driver fault (e.g. socket closed mid-request)
100
+ ]);
101
+ var RETRYABLE_RESPONSE_CODES = /* @__PURE__ */ new Set([
102
+ 4096,
103
+ // Unavailable
104
+ 4097,
105
+ // Overloaded
106
+ 4098,
107
+ // IsBootstrapping
108
+ 4099,
109
+ // TruncateError
110
+ 4352,
111
+ // WriteTimeout
112
+ 4608
113
+ // ReadTimeout
114
+ ]);
115
+ function isTransient(err) {
116
+ const name = err?.name;
117
+ if (typeof name === "string" && TRANSIENT_NAMES.has(name)) return true;
118
+ if (name === "ResponseError") {
119
+ const code = err.code;
120
+ if (typeof code === "number" && RETRYABLE_RESPONSE_CODES.has(code)) return true;
121
+ return false;
122
+ }
123
+ const net = networkCode(err);
124
+ return net === "ECONNRESET" || net === "ECONNABORTED" || net === "ETIMEDOUT" || net === "ESOCKETTIMEDOUT" || net === "ECONNREFUSED" || net === "EHOSTUNREACH" || net === "ENETUNREACH" || net === "EPIPE" || net === "EAI_AGAIN" || net === "ENOTFOUND";
125
+ }
126
+
127
+ // src/drivers/cassandra/warm.ts
128
+ var DEFAULT_TABLE = "cloud_roaring_warm";
129
+ var DEFAULT_FETCH_SIZE = 500;
130
+ var CONSISTENCY_LOCAL_SERIAL = 9;
131
+ var CONSISTENCY_LOCAL_ONE = 10;
132
+ function cassandraWarmTableDDL(keyspace, table = DEFAULT_TABLE) {
133
+ const t = validateAndQuoteTable(keyspace, table);
134
+ return `CREATE TABLE IF NOT EXISTS ${t} (
135
+ kp text,
136
+ ns text,
137
+ seg text,
138
+ ck int,
139
+ tok text,
140
+ payload blob,
141
+ PRIMARY KEY ((kp, ns, seg), ck)
142
+ );`;
143
+ }
144
+ var CassandraWarmDriver = class {
145
+ client;
146
+ table;
147
+ // validated + quoted "keyspace"."table"
148
+ keyPrefix;
149
+ fetchSize;
150
+ constructor(options) {
151
+ this.client = options.client;
152
+ this.table = validateAndQuoteTable(options.keyspace, options.table ?? DEFAULT_TABLE);
153
+ this.keyPrefix = normalizeKeyPrefix(options.keyPrefix);
154
+ const fetch = options.listPageSize ?? DEFAULT_FETCH_SIZE;
155
+ if (!Number.isSafeInteger(fetch) || fetch < 1) {
156
+ throw new ValidationError(`listPageSize must be a positive safe integer; got ${fetch}`);
157
+ }
158
+ this.fetchSize = fetch;
159
+ }
160
+ /** Read consistency: `LOCAL_SERIAL` (linearizable, read-your-writes) unless the caller opts into eventual. */
161
+ readConsistency(opts) {
162
+ return opts?.consistent === false ? CONSISTENCY_LOCAL_ONE : CONSISTENCY_LOCAL_SERIAL;
163
+ }
164
+ async get(ref, opts) {
165
+ validateChunkRef(ref);
166
+ try {
167
+ const res = await this.client.execute(
168
+ `SELECT tok, payload FROM ${this.table} WHERE kp = ? AND ns = ? AND seg = ? AND ck = ?`,
169
+ [this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey],
170
+ { prepare: true, consistency: this.readConsistency(opts) }
171
+ );
172
+ const row = res.rows[0];
173
+ return row === void 0 ? null : this.rowFrom(row, ref.chunkKey);
174
+ } catch (err) {
175
+ throw this.mapError(err);
176
+ }
177
+ }
178
+ async putConditional(ref, bytes, expected) {
179
+ validateChunkRef(ref);
180
+ const token = crypto.randomUUID();
181
+ const payload = Buffer.from(bytes);
182
+ const ns = namespacePart(ref.namespace);
183
+ let applied;
184
+ try {
185
+ const res = expected === NO_ROW ? await this.client.execute(
186
+ `INSERT INTO ${this.table} (kp, ns, seg, ck, tok, payload) VALUES (?, ?, ?, ?, ?, ?) IF NOT EXISTS`,
187
+ [this.keyPrefix, ns, ref.segment, ref.chunkKey, token, payload],
188
+ { prepare: true }
189
+ ) : await this.client.execute(
190
+ `UPDATE ${this.table} SET tok = ?, payload = ? WHERE kp = ? AND ns = ? AND seg = ? AND ck = ? IF tok = ?`,
191
+ [token, payload, this.keyPrefix, ns, ref.segment, ref.chunkKey, expected],
192
+ { prepare: true }
193
+ );
194
+ applied = res.wasApplied();
195
+ } catch (err) {
196
+ throw this.mapError(err);
197
+ }
198
+ if (!applied) {
199
+ throw new WriteConflictError(
200
+ expected === NO_ROW ? `chunk ${ref.chunkKey} already exists (create-if-absent)` : `OCC conflict on chunk ${ref.chunkKey}`
201
+ );
202
+ }
203
+ return { token };
204
+ }
205
+ async deleteConditional(ref, expected) {
206
+ validateChunkRef(ref);
207
+ let applied;
208
+ try {
209
+ const res = await this.client.execute(
210
+ `DELETE FROM ${this.table} WHERE kp = ? AND ns = ? AND seg = ? AND ck = ? IF tok = ?`,
211
+ [this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey, expected],
212
+ { prepare: true }
213
+ );
214
+ applied = res.wasApplied();
215
+ } catch (err) {
216
+ throw this.mapError(err);
217
+ }
218
+ if (!applied) {
219
+ throw new WriteConflictError(`fenced-delete conflict on chunk ${ref.chunkKey}`);
220
+ }
221
+ }
222
+ async *listChunks(ref, opts) {
223
+ validateSegmentRef(ref);
224
+ const stream = this.client.stream(
225
+ `SELECT ck, tok, payload FROM ${this.table} WHERE kp = ? AND ns = ? AND seg = ?`,
226
+ [this.keyPrefix, namespacePart(ref.namespace), ref.segment],
227
+ { prepare: true, fetchSize: this.fetchSize, consistency: this.readConsistency(opts) }
228
+ );
229
+ try {
230
+ for await (const raw of stream) {
231
+ if (typeof raw.ck !== "number") {
232
+ throw new IntegrityError("warm row is missing its numeric chunk key (ck)");
233
+ }
234
+ yield { chunkKey: raw.ck, ...this.rowFrom(raw, raw.ck) };
235
+ }
236
+ } catch (err) {
237
+ throw this.mapError(err);
238
+ }
239
+ }
240
+ /** Build a {@link WarmRow} from a raw row; reject one missing/mistyped fields (corrupt/foreign). */
241
+ rowFrom(row, chunkKey) {
242
+ if (typeof row.tok !== "string" || row.tok === "") {
243
+ throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its token`);
244
+ }
245
+ if (!(row.payload instanceof Uint8Array)) {
246
+ throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its payload`);
247
+ }
248
+ return { token: row.tok, bytes: new Uint8Array(row.payload) };
249
+ }
250
+ /** Reclassify a transient Cassandra fault as a retryable {@link TransientError}; else propagate unchanged. */
251
+ mapError(err) {
252
+ if (isTransient(err)) {
253
+ return new TransientError(
254
+ `transient Cassandra fault: ${err?.name ?? "unknown"}`,
255
+ { cause: err }
256
+ );
257
+ }
258
+ return err;
259
+ }
260
+ };
261
+
262
+ exports.CassandraWarmDriver = CassandraWarmDriver;
263
+ exports.cassandraWarmTableDDL = cassandraWarmTableDDL;
264
+ //# sourceMappingURL=index.cjs.map
265
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/errors.ts","../../src/core/ports.ts","../../src/core/validate.ts","../../src/drivers/_shared/keys.ts","../../src/drivers/cassandra/keys.ts","../../src/drivers/cassandra/cassandra-errors.ts","../../src/drivers/cassandra/warm.ts"],"names":["randomUUID"],"mappings":";;;;;;;AAcA,IAAM,WAAA,mBAA6B,MAAA,CAAO,GAAA,CAAI,qBAAqB,CAAA;AACnE,IAAM,eAAA,mBAAiC,MAAA,CAAO,GAAA,CAAI,+BAA+B,CAAA;AAG1E,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA;AAAA,EAE3C,CAAU,WAAW,IAAI,IAAA;AAAA,EACzB,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AAGb,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AAAA,EACzB;AACF,CAAA;AAGO,IAAM,eAAA,GAAN,cAA8B,iBAAA,CAAkB;AAAC,CAAA;AAGjD,IAAM,kBAAA,GAAN,cAAiC,iBAAA,CAAkB;AAAC,CAAA;AAGpD,IAAM,cAAA,GAAN,cAA6B,iBAAA,CAAkB;AAAC,CAAA;AAwDhD,IAAM,cAAA,GAAN,cAA6B,iBAAA,CAAkB;AAAA;AAAA,EAEpD,CAAU,eAAe,IAAI,IAAA;AAAA,EAC7B,WAAA,CAAY,SAAiB,OAAA,EAA+B;AAC1D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAI,OAAA,IAAW,OAAA,IAAW,OAAA,EAAS,IAAA,CAAK,QAAQ,OAAA,CAAQ,KAAA;AAAA,EAC1D;AACF,CAAA;;;AC9EO,IAAM,MAAA,mBAAwB,MAAA,CAAO,GAAA,CAAI,sBAAsB,CAAA;;;ACbtE,IAAM,aAAA,GAAgB,KAAA;AAGtB,IAAM,IAAA,GAAO,oCAAA;AAEb,SAAS,YAAA,CAAa,OAAe,KAAA,EAAqB;AACxD,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,I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strings. Retry is the driver\n * decorators' job, not the engine's: a driver classifies its backend's failures into this vocabulary, and\n * `withRetry` decides what is transient.\n */\n\n/**\n * Registry-symbol brands. The package ships as multiple bundles — the core entry and the `./s3` / `./dynamodb`\n * subpaths — and the builder inlines `core/errors` into each. A driver in a subpath bundle therefore throws a\n * *different* class object than the one the core engine/retry code would `instanceof`-check, so `instanceof`\n * silently returns false across that boundary in the published CJS package (defeating OCC/transient retry and\n * compaction race-handling). These `Symbol.for` brands are identity-stable across bundles/realms; classify\n * errors with the exported predicates below (never `instanceof`) anywhere an error may cross the boundary.\n */\nconst ERROR_BRAND: unique symbol = Symbol.for('cloud-roaring.error');\nconst TRANSIENT_BRAND: unique symbol = Symbol.for('cloud-roaring.error.transient');\n\n/** Base class for every error CloudRoaring throws. */\nexport class CloudRoaringError extends Error {\n /** Cross-bundle brand — see the predicates ({@link isCloudRoaringError}, …). Non-enumerable-ish (symbol key ⇒ not in JSON). */\n readonly [ERROR_BRAND] = true as const;\n constructor(message: string) {\n super(message);\n // Subclass name (works under transpilation since we set it explicitly). Also the discriminator the\n // predicates match on — a runtime string, so it survives bundling where the class identity does not.\n this.name = new.target.name;\n }\n}\n\n/** Invalid caller input (bad id, segment name, options). Raised before any storage call. */\nexport class ValidationError extends CloudRoaringError {}\n\n/** An OCC conditional write/delete lost the race — the row changed since it was read. */\nexport class WriteConflictError extends CloudRoaringError {}\n\n/** Bytes from a tier are corrupt, oversized, or fail a checksum/format check. */\nexport class IntegrityError extends CloudRoaringError {}\n\n/**\n * A requested object/row does not exist. Part of the driver error vocabulary; thrown by\n * persistent drivers from Phase 2 — the Phase-1 engine + in-memory drivers return `null` instead.\n */\nexport class NotFoundError extends CloudRoaringError {}\n\n/**\n * This build/configuration cannot perform the requested operation, though nothing is malformed. Two uses:\n * (1) **format** — the bytes are well-formed but unreadable here (an unknown `.crbm` major version, an\n * encrypted file before the crypto path exists) — distinct from `IntegrityError` (corruption); and (2)\n * **store configuration** — an operation this store's wiring doesn't support (e.g. a lifecycle helper like\n * `compact`/`eraseSubject` called on a store built without a raw cold driver + registry). Raised at\n * operation time, before any mutation.\n */\nexport class UnsupportedError extends CloudRoaringError {}\n\n/**\n * A driver cannot meet a capability the chosen topology requires (e.g. a Cold driver without range\n * reads). Raised fail-fast at wiring time, never mid-operation.\n */\nexport class CapabilityError extends CloudRoaringError {}\n\n/**\n * An operation would exceed its per-op **denial-of-wallet budget** — too many backend requests for a single\n * `count`/`iterate`/`intersect`/`subjectReport`/`eraseSubject` call — so it is refused **before** fanning out\n * (Decision #3 / invariant T3). Default-on but generous (normal ops never hit it); tune it\n * per store (`budget`) or per op, or disable with `budget: false`. Deterministic (never retried): the op is too\n * big by policy, not by luck. Each request's bytes are separately capped (the safe-deserialize ceiling), so\n * bounding the request count transitively bounds bytes. Carries the projected count + the limit, never data.\n */\nexport class BudgetExceededError extends CloudRoaringError {}\n\n/**\n * An encrypted segment's data key (DEK) cannot be unwrapped because the keystore holds none of the\n * key-encryption-keys (KEKs) its wrappings reference — the KEK was never configured, rotated away without\n * keeping the old key, or lost. Deterministic (never retried): without a KEK the ciphertext is unreadable by\n * design. The flip side of crypto-shred — when this is *intended* (a destroyed segment) the registry row is\n * already a `destroyed` tombstone; when it's *not*, restore the missing KEK (or its recovery KEK). Carries no\n * key material.\n */\nexport class KeyUnavailableError extends CloudRoaringError {}\n\n/**\n * A **transient** infrastructure fault that is safe to retry — throttling, a 5xx, a dropped connection,\n * a client-side request timeout. Drivers classify their backend's retryable faults and raise this (the\n * SDK-specific knowledge stays in the SDK-specific driver); the retry layer (`core/retry`) retries **only**\n * this class, never a deterministic error like {@link ValidationError}, {@link IntegrityError},\n * {@link NotFoundError}, or {@link WriteConflictError} (retrying those is pointless or wrong). The original\n * error is preserved in `cause` so callers can still inspect it.\n *\n * Note for logging hygiene (threat-model S12): `cause` is the **raw SDK error**, which may carry operational\n * metadata (endpoint host, request IDs, `$metadata`). The library's own `message` is identifier-only and safe\n * to log; if you serialize the whole error *chain*, be aware you're including that metadata.\n */\nexport class TransientError extends CloudRoaringError {\n /** A second brand so the whole transient subtree (incl. {@link TimeoutError}) is classifiable cross-bundle. */\n readonly [TRANSIENT_BRAND] = true as const;\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n if (options && 'cause' in options) this.cause = options.cause;\n }\n}\n\n/**\n * A single attempt exceeded its time budget. Subclass of {@link TransientError} so the retry layer treats a\n * timeout as retryable by default — a stalled request often succeeds on a fresh connection. Raised by a\n * driver whose injected client reports a request timeout — setting one on your injected client is the\n * recommended way to bound a hang.\n */\nexport class TimeoutError extends TransientError {}\n\n/**\n * Bundle-safe error predicates — use these, not `instanceof`, wherever an error may cross the core↔driver\n * (`./s3` / `./dynamodb`) boundary (and prefer them in consumer `catch` blocks too, for the same reason). They\n * match the {@link ERROR_BRAND} registry brand + the runtime `name`, both of which survive separate bundling.\n */\nfunction hasBrand(err: unknown, brand: symbol): boolean {\n return (\n typeof err === 'object' && err !== null && (err as Record<symbol, unknown>)[brand] === true\n );\n}\n\n/** Any error thrown by CloudRoaring (any tier, any bundle). */\nexport function isCloudRoaringError(err: unknown): err is CloudRoaringError {\n return hasBrand(err, ERROR_BRAND);\n}\n\n/** An OCC conditional write/delete lost the race — retry the read-modify-write, don't fail. */\nexport function isWriteConflictError(err: unknown): err is WriteConflictError {\n return isCloudRoaringError(err) && err.name === 'WriteConflictError';\n}\n\n/** A retryable transient infrastructure fault (incl. {@link TimeoutError}). The retry layer keys on this. */\nexport function isTransientError(err: unknown): err is TransientError {\n return hasBrand(err, TRANSIENT_BRAND);\n}\n\n/** A requested object/row does not exist. */\nexport function isNotFoundError(err: unknown): err is NotFoundError {\n return isCloudRoaringError(err) && err.name === 'NotFoundError';\n}\n\n/** Corrupt/oversized/failed-checksum bytes from a tier. */\nexport function isIntegrityError(err: unknown): err is IntegrityError {\n return isCloudRoaringError(err) && err.name === 'IntegrityError';\n}\n\n/** Invalid caller input. */\nexport function isValidationError(err: unknown): err is ValidationError {\n return isCloudRoaringError(err) && err.name === 'ValidationError';\n}\n","/**\n * Storage-driver contracts the engine depends on.\n *\n * Phase 1 uses the subset needed by the in-memory engine: the per-chunk Warm store (under OCC) and a\n * per-chunk read view of Cold. Drivers move opaque bytes + an OCC token; they never understand roaring,\n * `adds`/`removes`, or the `.crbm` layout. The full `IColdDriver` (blob/range) + `IRegistryDriver` arrive\n * with generations in Phase 2/3 — the `.crbm` reader will implement `ColdChunkSource`.\n */\n\nimport type { BlobSink } from './blob';\nimport type { WrappedDek } from './crypto';\n\n/** Opaque optimistic-concurrency token — unique per write, compared by equality only. */\nexport type Token = string;\n\n/** Sentinel for `putConditional` meaning \"the row must not exist yet\" (create). */\n// `Symbol.for` (the global registry), NOT `Symbol()`: the package ships multiple bundles (the core entry and\n// the `./dynamodb` / `./s3` subpaths), and tsup inlines `core/ports` into each. A plain `Symbol('no-row')`\n// would be a DISTINCT instance per bundle, so the engine's `NO_ROW` wouldn't `===` the one the DynamoDb warm\n// driver compares against — every create would misroute to the token-fenced path and fail. A registry symbol\n// is identity-stable across bundles/realms. (Invisible in tests, which share one source module graph.)\nexport const NO_ROW: unique symbol = Symbol.for('cloud-roaring.no-row');\nexport type NoRow = typeof NO_ROW;\n\nexport interface SegmentRef {\n readonly namespace?: string;\n readonly segment: string;\n}\n\nexport interface ChunkRef extends SegmentRef {\n readonly chunkKey: number;\n}\n\n/** Identifies one immutable `.crbm` object — a single generation of a segment. */\nexport interface GenKey extends SegmentRef {\n readonly generation: number;\n}\n\nexport interface WarmRow {\n readonly token: Token;\n /** Read-only: owned by the driver. Callers must NOT mutate the buffer (re-encode to write). */\n readonly bytes: Uint8Array;\n}\n\n/**\n * Read consistency for a Warm fetch (gap #9). `consistent: true` (the default — omitted ⇒ true) is a\n * strong, read-your-writes read, as the OCC read-modify-write path requires. `consistent: false` requests an\n * **eventually-consistent** read — on DynamoDB that is ~½ the RCU cost; a driver that is always strongly\n * consistent (in-memory, LocalFs) ignores it. The engine uses it only on read paths (`has`/`count`/`iterate`/\n * `intersect`) when the store opts into `warmReadConsistency: 'eventual'`, trading read-after-write for cost.\n */\nexport interface WarmReadOptions {\n readonly consistent?: boolean;\n}\n\n/** Per-chunk Warm store under optimistic concurrency. Returned byte buffers are read-only. */\nexport interface IWarmDriver {\n get(ref: ChunkRef, opts?: WarmReadOptions): Promise<WarmRow | null>;\n /** OCC write. `expected` = `NO_ROW` to create, else the token previously read. Throws `WriteConflictError` on mismatch. */\n putConditional(\n ref: ChunkRef,\n bytes: Uint8Array,\n expected: Token | NoRow,\n ): Promise<{ token: Token }>;\n /**\n * Fenced delete — only if the stored token still equals `expected`; throws `WriteConflictError`\n * otherwise. **Used by compaction (Phase 4); the Phase-1 engine never calls it** — drivers still\n * implement it to satisfy the conformance suite.\n */\n deleteConditional(ref: ChunkRef, expected: Token): Promise<void>;\n /** All dirty chunks of a segment, ascending `chunkKey`. Yielded `bytes` are read-only. */\n listChunks(\n ref: SegmentRef,\n opts?: WarmReadOptions,\n ): AsyncIterable<{ chunkKey: number } & WarmRow>;\n}\n\n/**\n * A segment's grounded on-disk footprint (Phase 5b) — the current generation's Cold object bytes, read\n * cheaply from the `.crbm` footer/index (no payload reads). Powers the grounded `costReport()`.\n */\nexport interface SegmentSize {\n readonly sizeBytes: number;\n}\n\n/** Per-chunk read view of the immutable Cold tier (implemented by the `.crbm` reader from Phase 2). */\nexport interface ColdChunkSource {\n /** Read-only bytes for the chunk, or `null` if absent. Callers must not mutate the buffer. */\n getChunk(ref: ChunkRef): Promise<Uint8Array | null>;\n listChunkKeys(ref: SegmentRef): Promise<number[]>;\n /**\n * Optional (Phase 5b): the current generation's grounded size, cheaply (from the already-parsed\n * `.crbm` index — no payload reads), or `null` if the segment has no Cold generation. Powers the\n * grounded `costReport()`.\n */\n sizeOf?(ref: SegmentRef): Promise<SegmentSize | null>;\n /**\n * Optional (Phase 5c): the current generation's **per-chunk cardinality** (`chunkKey → count`), read\n * from the already-parsed `.crbm` index with **no payload reads**, or `null` if the segment has no Cold\n * generation. Powers the cheap `count()` — a warm-delta-free chunk is counted straight from the index\n * instead of fetching + deserializing it. A source with no index (e.g. the in-memory source) omits this,\n * and `count()` falls back to fetching + merging every chunk.\n */\n cardinalities?(ref: SegmentRef): Promise<ReadonlyMap<number, number> | null>;\n /**\n * Optional (Phase B, gap #4): the segment's **current generation number** as this source resolves it right now\n * (registry `currentGen`, or the highest cold generation), or `null` if the segment has no Cold generation. The\n * engine keys its HOT chunk cache by this so a generation bump (a compaction commit) is observed — a new\n * generation misses the cache instead of serving a stale decoded chunk, and an erased id can't resurrect from a\n * cached pre-compaction chunk. Cheap: served from the source's own (short-TTL-refreshed) snapshot, **not** a\n * fresh backend read per call. A source that pins one immutable generation for its whole lifetime and never\n * refreshes may omit this — the engine then keys the cache without a generation, exactly as before.\n */\n currentGeneration?(ref: SegmentRef): Promise<number | null>;\n}\n\n/** Capabilities a Cold driver advertises; validated at wiring time, fail-fast. */\nexport interface ColdCaps {\n /** REQUIRED — the format relies on byte-range reads. */\n readonly rangeRead: true;\n /** Largest single object the backend accepts (informs single-object-vs-shard, B7 — future). */\n readonly maxObjectBytes: number;\n /** Optional: enables the pure-object `LATEST`-pointer registry variant (S3 conditional put). */\n readonly conditionalPut?: boolean;\n}\n\n/**\n * Immutable object storage for `.crbm` generations. A \"dumb byte mover\": it\n * understands neither roaring nor the `.crbm` layout, only opaque bytes addressed by a {@link GenKey}.\n * The core never reuses a key, so puts are write-once.\n */\nexport interface IColdDriver {\n capabilities(): ColdCaps;\n /**\n * Stream a new immutable generation. The driver opens a destination, hands `write` a {@link BlobSink},\n * then atomically commits (and computes the content hash). Throws if the key already exists (write-once).\n */\n putImmutable(\n key: GenKey,\n write: (sink: BlobSink) => Promise<void>,\n ): Promise<{ size: number; sha256: string }>;\n /** Range read; the caller bounds-checks. Out-of-range is rejected, never a short/adjacent read. */\n getRange(key: GenKey, offset: number, length: number): Promise<Uint8Array>;\n /** Speculative tail read: the last `min(maxBytes, size)` bytes + the total object size. */\n getTail(key: GenKey, maxBytes: number): Promise<{ bytes: Uint8Array; size: number }>;\n delete(key: GenKey): Promise<void>;\n /** Enumerate the generations present for a segment (orphan sweep / latest-gen resolution). */\n list(ref: SegmentRef): AsyncIterable<GenKey>;\n}\n\n/**\n * Lifecycle status of a segment. `active` is the steady state;\n * `compacting`/`erasing` are transient flags a daemon sets while it works (Phase 4d/4e); `destroyed` is the\n * post-crypto-shred tombstone (the row is kept for audit but the segment is logically gone). The 4c registry\n * stores and round-trips the field; the *transitions* are driven by their owning features.\n */\nexport type RegistryStatus = 'active' | 'compacting' | 'erasing' | 'destroyed';\n\n/** Free-form, JSON-serializable governance metadata (retention/residency policy); shape lands in Phase 6. */\nexport type GovernanceMeta = Record<string, unknown>;\n\n/**\n * One registry row — the authoritative per-segment record. Exactly one per segment.\n */\nexport interface RegistryRecord extends SegmentRef {\n /** **The** authoritative LATEST pointer: which immutable Cold generation is current. */\n readonly currentGen: number;\n /**\n * Per-segment data-key (DEK) wrappings for encryption-at-rest (Phase 4e): the DEK envelope-wrapped under one\n * or more KEKs (active + optional recovery). Reading unwraps with any held KEK; **crypto-shred deletes this\n * whole list**, making the segment's at-rest bytes permanently unrecoverable. Absent ⇒ the segment is\n * cleartext. See [DECISIONS #19].\n */\n readonly wrappedDeks?: readonly WrappedDek[];\n /**\n * Optional **external** key reference (reserved) — e.g. a KMS key ARN for a future KMS keystore adapter that\n * keeps wrapped material in the KMS rather than in-band {@link wrappedDeks}. Unused by the in-process BYOK\n * keystore. Clearable on crypto-shred.\n */\n readonly keyId?: string;\n /**\n * Dirty-row hint written by `findCompactable`. Discovery still recomputes the live dirty count by scanning\n * Warm each cycle (the count that decides candidacy), but it now **reads** this hint to gate a change-guarded\n * CAS — the hint is only rewritten when the count actually moved, so an all-idle fleet issues no per-segment\n * registry writes. It does not yet drive candidacy — turning the Warm scan itself into O(dirty) is a\n * deferred cheap-enumeration fix.\n */\n readonly dirtyChunkCount: number;\n readonly status: RegistryStatus;\n /**\n * Daemon health (Phase D, gap #2): epoch-ms of the last **successfully committed** compaction, and the\n * count of **consecutive** compaction failures (reset to 0 by a successful commit). `lastCompactedAt`\n * powers a dead-man's-switch / staleness alarm; `consecutiveFailures` drives **poison-segment quarantine** —\n * discovery skips a segment past a failure threshold so one corrupt Warm row can't freeze the compaction of a\n * segment **that has a committed generation** forever (with no alarm) while its Warm backlog grows unbounded.\n * (A segment whose *very first* compaction keeps failing has no registry row to count against yet —\n * bootstrap faults are surfaced as `error` results but not yet quarantined; gap #2.) Both\n * **optional** (absent on rows written before Phase D, and on a segment never compacted) — read them as\n * `lastCompactedAt ?? undefined`, `consecutiveFailures ?? 0`.\n */\n readonly lastCompactedAt?: number;\n readonly consecutiveFailures?: number;\n /**\n * Compaction lease (Phase 4d): the opaque id of the worker currently compacting this segment, and the\n * epoch-ms at which its lease expires. `status === 'compacting'` with `leaseExpiresAt` in the future means\n * a live daemon owns it; once `leaseExpiresAt` is past, another worker may **steal** the lease (the prior\n * holder crashed). Both absent in the steady (`active`) state. The lease is an efficiency guard only — the\n * 2-phase commit is correct without it (OCC-fenced swap + write-once generations + version-fenced purge).\n */\n readonly leaseOwner?: string;\n readonly leaseExpiresAt?: number;\n /** Governance policy (Phase 6); stored + round-tripped now, semantics later. */\n readonly retention?: GovernanceMeta;\n readonly residency?: GovernanceMeta;\n /** Epoch-ms of creation / last mutation (from the driver's injected clock). */\n readonly createdAt: number;\n readonly updatedAt: number;\n /** Opaque OCC token — compare-by-equality, never reused (ABA-safe), exactly like {@link WarmRow.token}. */\n readonly token: Token;\n}\n\n/** The caller-settable fields at {@link IRegistryDriver.create} (audit + token are driver-managed). */\nexport interface NewRegistryRecord {\n readonly currentGen: number;\n readonly wrappedDeks?: readonly WrappedDek[];\n readonly keyId?: string;\n /** Defaults to 0. */\n readonly dirtyChunkCount?: number;\n /** Defaults to `'active'`. */\n readonly status?: RegistryStatus;\n readonly retention?: GovernanceMeta;\n readonly residency?: GovernanceMeta;\n}\n\n/** Fields a {@link IRegistryDriver.compareAndSwap} may mutate (identity + audit + token are off-limits). */\nexport type RegistryPatch = Partial<\n Pick<\n RegistryRecord,\n | 'currentGen'\n | 'wrappedDeks'\n | 'keyId'\n | 'dirtyChunkCount'\n | 'status'\n | 'leaseOwner'\n | 'leaseExpiresAt'\n | 'lastCompactedAt'\n | 'consecutiveFailures'\n | 'retention'\n | 'residency'\n >\n>;\n\n/** Capabilities a registry driver advertises; validated fail-fast at wiring time. */\nexport interface RegCaps {\n /** REQUIRED — `currentGen` feeds read correctness + compaction CAS, so reads must be strongly consistent. */\n readonly strongRead: true;\n}\n\n/**\n * Per-segment registry — the authoritative source of `currentGen`, the discovery index, and (Phase 4e) the\n * wrapped-DEK holder. One row per segment under OCC: a\n * never-reused, equality-compared {@link Token} (ABA-safe across delete→recreate, like the Warm tier).\n */\nexport interface IRegistryDriver {\n capabilities(): RegCaps;\n /** The segment's record, or `null` if it doesn't exist (or was deleted). */\n get(ref: SegmentRef): Promise<RegistryRecord | null>;\n /** Create the row; throws {@link WriteConflictError} if it already exists (use CAS to mutate). */\n create(ref: SegmentRef, record: NewRegistryRecord): Promise<{ token: Token }>;\n /** Server-side compare-and-set: apply `patch` iff the stored token equals `expected`, else `WriteConflictError`. */\n compareAndSwap(ref: SegmentRef, expected: Token, patch: RegistryPatch): Promise<{ token: Token }>;\n /** Discovery: every live record, optionally scoped to one namespace. Order is unspecified. */\n list(namespace?: string): AsyncIterable<RegistryRecord>;\n /** Remove the row (tombstoned for ABA-safety — a later `create` still gets a fresh, greater token). */\n delete(ref: SegmentRef): Promise<void>;\n}\n","/**\n * Boundary validation for segment / namespace names (finding S2).\n * Names become object keys, partition keys, and file paths — so they're validated before they\n * ever reach storage: strict charset, bounded length, no path traversal.\n */\nimport { ValidationError } from './errors';\nimport type { ChunkRef, SegmentRef } from './ports';\n\nconst CHUNK_KEY_MAX = 0xffff;\n\n// The locked name grammar: 1 leading alphanumeric + up to 255 more (max 256 chars).\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;\n\nfunction validatePart(value: string, field: string): void {\n if (typeof value !== 'string' || !NAME.test(value) || value.includes('..')) {\n throw new ValidationError(\n `${field} must match ${String(NAME)} and contain no \"..\": got ${JSON.stringify(value)}`,\n );\n }\n}\n\nexport function validateSegmentRef(ref: SegmentRef): void {\n validatePart(ref.segment, 'segment');\n if (ref.namespace !== undefined) validatePart(ref.namespace, 'namespace');\n}\n\n/** Validate a chunk ref: the segment/namespace grammar plus `chunkKey` ∈ `[0, 65535]` (a u16). */\nexport function validateChunkRef(ref: ChunkRef): void {\n validateSegmentRef(ref);\n if (!Number.isInteger(ref.chunkKey) || ref.chunkKey < 0 || ref.chunkKey > CHUNK_KEY_MAX) {\n throw new ValidationError(\n `chunkKey must be an integer in [0, ${CHUNK_KEY_MAX}]; got ${ref.chunkKey}`,\n );\n }\n}\n","/**\n * Shared key-grammar fragments used by every driver's logical-ref → physical-key mapping (Phase 4c).\n *\n * Extracted once the registry drivers became the 4th/5th consumer of the same `_default` namespace sentinel\n * (it lived copy-pasted in `s3/keys`, `dynamodb/keys`, `localfs/paths`). Pure string logic, no SDK, no I/O —\n * lives in the SDK-free `_shared` bundle so any driver may import it.\n */\n\n/**\n * The physical stand-in for an **absent** namespace. The name grammar forbids a leading underscore\n * so `_default` can never collide with a real\n * namespace — `segment(\"s\")` and `segment(\"s\", { namespace: \"_default\" })` would be a grammar error, not an\n * aliasing hazard.\n */\nexport const DEFAULT_NAMESPACE = '_default';\n\n/** Map an optional namespace to its physical part: the namespace itself, or {@link DEFAULT_NAMESPACE}. */\nexport function namespacePart(namespace: string | undefined): string {\n return namespace ?? DEFAULT_NAMESPACE;\n}\n","/**\n * Identifier + key validation for {@link CassandraWarmDriver} (Phase 7).\n *\n * Pure, SDK-free string logic — unit-testable without a live Cassandra. The logical ref is stored across\n * **bound (`?`) columns** (`kp`/`ns`/`seg`/`ck`), so ref/prefix values are never concatenated into CQL. The\n * only values that CANNOT be bind parameters are the **keyspace + table identifiers**, so they are validated\n * against a strict grammar and quoted before interpolation — the sole CQL-injection vector, closed.\n */\nimport { ValidationError } from '@/core/errors';\n\n/** A CQL identifier: leading letter/underscore, then letters/digits/underscores (≤48 = Cassandra max). */\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]{0,47}$/;\n\nfunction quoteIdent(id: string, what: string): string {\n if (!IDENT.test(id)) {\n throw new ValidationError(\n `invalid ${what} ${JSON.stringify(id)} — expected a CQL identifier ` +\n `(letters, digits, underscore; ≤48 chars; leading letter/underscore)`,\n );\n }\n return `\"${id}\"`;\n}\n\n/** Validate + quote `keyspace` and `table` into a fully-qualified `\"keyspace\".\"table\"` for interpolation. */\nexport function validateAndQuoteTable(keyspace: string, table: string): string {\n return `${quoteIdent(keyspace, 'keyspace')}.${quoteIdent(table, 'table')}`;\n}\n\n/**\n * Validate a caller-supplied key prefix (bound as a `?` value, so this is a sanity guard, not an\n * anti-injection boundary): no control characters. Empty/undefined ⇒ no prefix (stored as `''`).\n */\nexport function normalizeKeyPrefix(prefix: string | undefined): string {\n if (prefix === undefined || prefix === '') return '';\n for (const ch of prefix) {\n if (ch.charCodeAt(0) < 0x20) {\n throw new ValidationError('keyPrefix must not contain control characters');\n }\n }\n return prefix;\n}\n","/**\n * Pure helpers for classifying Cassandra / ScyllaDB (`cassandra-driver`) errors (Phase 7; transient class\n * mirrors the other drivers).\n *\n * SDK-free + side-effect-free — they read only structural shapes off the thrown value (`err.name`, `err.code`).\n * The driver signals an OCC conflict itself (an LWT that returns `wasApplied() === false`), so there's no\n * \"conflict\" classifier here — only transient-vs-not. Everything not transient propagates unchanged so a real\n * bug is never blind-retried.\n */\n\n/** A network-level error `code` string (starts with `E`, uppercase letters + underscore, no digits). */\nfunction networkCode(err: unknown): string | undefined {\n const code = (err as { code?: unknown } | null)?.code;\n return typeof code === 'string' && /^E[A-Z_]+$/.test(code) ? code : undefined;\n}\n\n/**\n * Transient `cassandra-driver` error classes: no coordinator reachable, a client-side operation timeout, or a\n * server response for a timeout / overload / unavailable / bootstrapping node. All safe to retry (the\n * resilience layer rides them out). A deterministic server error (syntax, invalid query, unauthorized) is a\n * `ResponseError` with a non-retryable code and is NOT matched here, so it surfaces.\n */\nconst TRANSIENT_NAMES = new Set<string>([\n 'NoHostAvailableError',\n 'OperationTimedOutError',\n 'BusyConnectionError', // connection-pool exhaustion — a transient back-pressure fault\n 'DriverError', // generic connection-level driver fault (e.g. socket closed mid-request)\n]);\n\n// ResponseError `code` values (CQL binary protocol) that are retryable: server overloaded / bootstrapping,\n// truncate, and read/write TIMEOUTS + unavailable. NOTE: an LWT write-timeout retry is ambiguous — the write\n// may have committed, so a retry can surface a spurious WriteConflictError (the caller's OCC re-read converges;\n// no data loss). ReadFailure/WriteFailure (0x1300/0x1500) are deliberately EXCLUDED — they signal a replica-\n// side *failure* (e.g. a tombstone-threshold breach), not a timeout, so a blind retry wouldn't help. Other\n// deterministic codes (SyntaxError 0x2000, Invalid 0x2200, Unauthorized 0x2100, AlreadyExists 0x2400) are\n// likewise excluded so a real bug surfaces.\nconst RETRYABLE_RESPONSE_CODES = new Set<number>([\n 0x1000, // Unavailable\n 0x1001, // Overloaded\n 0x1002, // IsBootstrapping\n 0x1003, // TruncateError\n 0x1100, // WriteTimeout\n 0x1200, // ReadTimeout\n]);\n\nexport function isTransient(err: unknown): boolean {\n const name = (err as { name?: unknown } | null)?.name;\n if (typeof name === 'string' && TRANSIENT_NAMES.has(name)) return true;\n if (name === 'ResponseError') {\n const code = (err as { code?: unknown }).code;\n if (typeof code === 'number' && RETRYABLE_RESPONSE_CODES.has(code)) return true;\n return false; // a ResponseError with any other code is deterministic → must surface\n }\n const net = networkCode(err);\n return (\n net === 'ECONNRESET' ||\n net === 'ECONNABORTED' ||\n net === 'ETIMEDOUT' ||\n net === 'ESOCKETTIMEDOUT' ||\n net === 'ECONNREFUSED' ||\n net === 'EHOSTUNREACH' ||\n net === 'ENETUNREACH' ||\n net === 'EPIPE' ||\n net === 'EAI_AGAIN' ||\n net === 'ENOTFOUND'\n );\n}\n","/**\n * `CassandraWarmDriver` — an {@link IWarmDriver} over Cassandra / ScyllaDB (Phase 7).\n *\n * Uses the official `cassandra-driver`, an **optional peer dependency** — only consumers of\n * `cloud-roaring/cassandra` install it. A `Client` is **injected** (dependency injection): the driver owns no\n * connection/credential logic, so it's thin and reuses the caller's client.\n *\n * Each chunk is one row in a table partitioned by `(kp, ns, seg)` and clustered by `ck` — so all of a\n * segment's chunks share one partition and `listChunks` is a single partition read already ordered by\n * `ck` ascending. The opaque OCC **token** (a random UUID per write) lives in a `tok` column (`token` is a CQL\n * reserved word), and OCC is a **lightweight transaction** (LWT — Paxos-linearizable compare-and-set):\n * - **create-if-absent** = `INSERT … IF NOT EXISTS`; not applied ⇒ {@link WriteConflictError}.\n * - **token-fenced update / delete** = `UPDATE … / DELETE … IF tok = ?`; not applied (token moved or row\n * absent) ⇒ {@link WriteConflictError}.\n *\n * The LWT's `IF` is evaluated under Paxos against the latest committed value, so the compare-and-set is\n * correct even if a prior `get` read a slightly stale value (a doomed write is simply not applied → retry).\n * **Reads observe the latest committed LWT value:** `get`/`listChunks` run at `LOCAL_SERIAL` by default (a\n * linearizable read that completes any in-flight Paxos round — the read-your-writes the OCC path needs on a\n * multi-node RF>1 cluster), downgrading to `LOCAL_ONE` only when the caller passes `{ consistent: false }`.\n * Tokens are not reused across delete→recreate (ABA-safe, D3 — probabilistic random UUID). Drivers may use\n * `node:crypto`.\n */\nimport { randomUUID } from 'node:crypto';\nimport type { Client } from 'cassandra-driver';\nimport { IntegrityError, TransientError, ValidationError, WriteConflictError } from '@/core/errors';\nimport { NO_ROW } from '@/core/ports';\nimport type {\n ChunkRef,\n IWarmDriver,\n NoRow,\n SegmentRef,\n Token,\n WarmReadOptions,\n WarmRow,\n} from '@/core/ports';\nimport { validateChunkRef, validateSegmentRef } from '@/core/validate';\nimport { namespacePart } from '../_shared/keys';\nimport { normalizeKeyPrefix, validateAndQuoteTable } from './keys';\nimport { isTransient } from './cassandra-errors';\n\nconst DEFAULT_TABLE = 'cloud_roaring_warm';\n/** listChunks page size (CQL `fetchSize`) — the stream auto-pages, bounding resident rows on a wide segment. */\nconst DEFAULT_FETCH_SIZE = 500;\n// `cassandra-driver` `types.consistencies` values — stable CQL binary-protocol constants, inlined so the built\n// subpath keeps NO runtime `cassandra-driver` import (the SDK stays a pure type + optional peer, as with the\n// other drivers). LOCAL_SERIAL = a linearizable read (observes the latest committed LWT value / read-your-\n// writes); LOCAL_ONE = a fast, possibly-stale read used only when the caller opts into eventual consistency.\nconst CONSISTENCY_LOCAL_SERIAL = 9;\nconst CONSISTENCY_LOCAL_ONE = 10;\n\nexport interface CassandraWarmDriverOptions {\n /**\n * A connected `cassandra-driver` `Client`. The driver never connects/shuts it down — the caller owns it.\n * Notes: identifiers (keyspace/table) are **case-sensitive** here (quoted), so pass them exactly as stored\n * (lowercase unless created quoted). OCC reads use `LOCAL_SERIAL` — linearizable **within one datacenter**;\n * a **multi-DC** deployment that needs cross-DC linearizable OCC must run at `SERIAL` (configure it on the\n * client and note this driver defaults to the local variant). An LWT that times out is ambiguous: the retry\n * layer may re-issue it and surface a spurious `WriteConflictError` for a write that actually committed —\n * the caller's OCC re-read converges and no data is lost.\n */\n readonly client: Client;\n /** Keyspace holding the warm table (must already exist — replication is a deployment decision). */\n readonly keyspace: string;\n /** Warm table name (default `cloud_roaring_warm`). Must already exist (see `cassandraWarmTableDDL`). */\n readonly table?: string;\n /** Optional key-prefix column value so several logical stores can share one table (bound as data). */\n readonly keyPrefix?: string;\n /** Advanced: `listChunks` fetch (page) size (default 500). Tunes peak memory on wide segments. */\n readonly listPageSize?: number;\n}\n\n/** One raw warm row as selected (cassandra-driver decodes `blob`→Buffer, `int`→number, `text`→string).\n * NB: the token column is named `tok`, not `token` — `token` is a reserved word in CQL (`token()` function). */\ninterface RawRow {\n ck?: unknown;\n tok?: unknown;\n payload?: unknown;\n}\n\n/**\n * The idempotent CQL DDL for the warm table (identifier-validated + quoted). The driver does **not** create\n * schema at runtime (it stays thin); run this once at deploy time against an existing keyspace, e.g.\n * `await client.execute(cassandraWarmTableDDL('my_ks'))`.\n */\nexport function cassandraWarmTableDDL(keyspace: string, table: string = DEFAULT_TABLE): string {\n const t = validateAndQuoteTable(keyspace, table);\n return (\n `CREATE TABLE IF NOT EXISTS ${t} (\\n` +\n // `tok`, not `token` — `token` is a reserved word in CQL.\n ` kp text,\\n ns text,\\n seg text,\\n ck int,\\n tok text,\\n payload blob,\\n` +\n ` PRIMARY KEY ((kp, ns, seg), ck)\\n` +\n `);`\n );\n}\n\nexport class CassandraWarmDriver implements IWarmDriver {\n private readonly client: Client;\n private readonly table: string; // validated + quoted \"keyspace\".\"table\"\n private readonly keyPrefix: string;\n private readonly fetchSize: number;\n\n constructor(options: CassandraWarmDriverOptions) {\n this.client = options.client;\n this.table = validateAndQuoteTable(options.keyspace, options.table ?? DEFAULT_TABLE);\n this.keyPrefix = normalizeKeyPrefix(options.keyPrefix);\n const fetch = options.listPageSize ?? DEFAULT_FETCH_SIZE;\n if (!Number.isSafeInteger(fetch) || fetch < 1) {\n throw new ValidationError(`listPageSize must be a positive safe integer; got ${fetch}`);\n }\n this.fetchSize = fetch;\n }\n\n /** Read consistency: `LOCAL_SERIAL` (linearizable, read-your-writes) unless the caller opts into eventual. */\n private readConsistency(opts?: WarmReadOptions): number {\n return opts?.consistent === false ? CONSISTENCY_LOCAL_ONE : CONSISTENCY_LOCAL_SERIAL;\n }\n\n async get(ref: ChunkRef, opts?: WarmReadOptions): Promise<WarmRow | null> {\n validateChunkRef(ref);\n try {\n const res = await this.client.execute(\n `SELECT tok, payload FROM ${this.table} WHERE kp = ? AND ns = ? AND seg = ? AND ck = ?`,\n [this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey],\n { prepare: true, consistency: this.readConsistency(opts) },\n );\n const row = res.rows[0] as RawRow | undefined;\n return row === undefined ? null : this.rowFrom(row, ref.chunkKey);\n } catch (err) {\n throw this.mapError(err);\n }\n }\n\n async putConditional(\n ref: ChunkRef,\n bytes: Uint8Array,\n expected: Token | NoRow,\n ): Promise<{ token: Token }> {\n validateChunkRef(ref);\n const token = randomUUID();\n const payload = Buffer.from(bytes); // copy: severs any caller-owned/reused input buffer\n const ns = namespacePart(ref.namespace);\n let applied: boolean;\n try {\n const res =\n expected === NO_ROW\n ? await this.client.execute(\n `INSERT INTO ${this.table} (kp, ns, seg, ck, tok, payload) ` +\n `VALUES (?, ?, ?, ?, ?, ?) IF NOT EXISTS`,\n [this.keyPrefix, ns, ref.segment, ref.chunkKey, token, payload],\n { prepare: true },\n )\n : await this.client.execute(\n `UPDATE ${this.table} SET tok = ?, payload = ? ` +\n `WHERE kp = ? AND ns = ? AND seg = ? AND ck = ? IF tok = ?`,\n [token, payload, this.keyPrefix, ns, ref.segment, ref.chunkKey, expected],\n { prepare: true },\n );\n applied = res.wasApplied();\n } catch (err) {\n throw this.mapError(err);\n }\n if (!applied) {\n throw new WriteConflictError(\n expected === NO_ROW\n ? `chunk ${ref.chunkKey} already exists (create-if-absent)`\n : `OCC conflict on chunk ${ref.chunkKey}`,\n );\n }\n return { token };\n }\n\n async deleteConditional(ref: ChunkRef, expected: Token): Promise<void> {\n validateChunkRef(ref);\n let applied: boolean;\n try {\n const res = await this.client.execute(\n `DELETE FROM ${this.table} WHERE kp = ? AND ns = ? AND seg = ? AND ck = ? IF tok = ?`,\n [this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey, expected],\n { prepare: true },\n );\n applied = res.wasApplied();\n } catch (err) {\n throw this.mapError(err);\n }\n if (!applied) {\n throw new WriteConflictError(`fenced-delete conflict on chunk ${ref.chunkKey}`);\n }\n }\n\n async *listChunks(\n ref: SegmentRef,\n opts?: WarmReadOptions,\n ): AsyncIterable<{ chunkKey: number } & WarmRow> {\n validateSegmentRef(ref);\n // A single-partition read, already ordered by the `ck` clustering key (ascending). `client.stream` is an\n // object-mode Readable that auto-pages at `fetchSize`, so peak memory is bounded on a wide segment.\n const stream = this.client.stream(\n `SELECT ck, tok, payload FROM ${this.table} WHERE kp = ? AND ns = ? AND seg = ?`,\n [this.keyPrefix, namespacePart(ref.namespace), ref.segment],\n { prepare: true, fetchSize: this.fetchSize, consistency: this.readConsistency(opts) },\n );\n try {\n // `client.stream` returns an object-mode Readable (async-iterable at runtime); its type defs expose only\n // the EventEmitter surface, so cast via `unknown`.\n for await (const raw of stream as unknown as AsyncIterable<RawRow>) {\n // Untrusted-data posture (like the sibling drivers): a corrupt row with a non-numeric `ck` must not\n // surface as `{ chunkKey: undefined }`.\n if (typeof raw.ck !== 'number') {\n throw new IntegrityError('warm row is missing its numeric chunk key (ck)');\n }\n yield { chunkKey: raw.ck, ...this.rowFrom(raw, raw.ck) };\n }\n } catch (err) {\n throw this.mapError(err);\n }\n }\n\n /** Build a {@link WarmRow} from a raw row; reject one missing/mistyped fields (corrupt/foreign). */\n private rowFrom(row: RawRow, chunkKey: number): WarmRow {\n if (typeof row.tok !== 'string' || row.tok === '') {\n throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its token`);\n }\n if (!(row.payload instanceof Uint8Array)) {\n throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its payload`);\n }\n return { token: row.tok, bytes: new Uint8Array(row.payload) };\n }\n\n /** Reclassify a transient Cassandra fault as a retryable {@link TransientError}; else propagate unchanged. */\n private mapError(err: unknown): unknown {\n if (isTransient(err)) {\n return new TransientError(\n `transient Cassandra fault: ${(err as { name?: unknown } | null)?.name ?? 'unknown'}`,\n { cause: err },\n );\n }\n return err;\n }\n}\n"]}
@@ -0,0 +1,52 @@
1
+ import { Client } from 'cassandra-driver';
2
+ import { a as IWarmDriver, b as ChunkRef, W as WarmReadOptions, c as WarmRow, T as Token, N as NoRow, S as SegmentRef } from '../ports-D3BrJ6ax.cjs';
3
+
4
+ interface CassandraWarmDriverOptions {
5
+ /**
6
+ * A connected `cassandra-driver` `Client`. The driver never connects/shuts it down — the caller owns it.
7
+ * Notes: identifiers (keyspace/table) are **case-sensitive** here (quoted), so pass them exactly as stored
8
+ * (lowercase unless created quoted). OCC reads use `LOCAL_SERIAL` — linearizable **within one datacenter**;
9
+ * a **multi-DC** deployment that needs cross-DC linearizable OCC must run at `SERIAL` (configure it on the
10
+ * client and note this driver defaults to the local variant). An LWT that times out is ambiguous: the retry
11
+ * layer may re-issue it and surface a spurious `WriteConflictError` for a write that actually committed —
12
+ * the caller's OCC re-read converges and no data is lost.
13
+ */
14
+ readonly client: Client;
15
+ /** Keyspace holding the warm table (must already exist — replication is a deployment decision). */
16
+ readonly keyspace: string;
17
+ /** Warm table name (default `cloud_roaring_warm`). Must already exist (see `cassandraWarmTableDDL`). */
18
+ readonly table?: string;
19
+ /** Optional key-prefix column value so several logical stores can share one table (bound as data). */
20
+ readonly keyPrefix?: string;
21
+ /** Advanced: `listChunks` fetch (page) size (default 500). Tunes peak memory on wide segments. */
22
+ readonly listPageSize?: number;
23
+ }
24
+ /**
25
+ * The idempotent CQL DDL for the warm table (identifier-validated + quoted). The driver does **not** create
26
+ * schema at runtime (it stays thin); run this once at deploy time against an existing keyspace, e.g.
27
+ * `await client.execute(cassandraWarmTableDDL('my_ks'))`.
28
+ */
29
+ declare function cassandraWarmTableDDL(keyspace: string, table?: string): string;
30
+ declare class CassandraWarmDriver implements IWarmDriver {
31
+ private readonly client;
32
+ private readonly table;
33
+ private readonly keyPrefix;
34
+ private readonly fetchSize;
35
+ constructor(options: CassandraWarmDriverOptions);
36
+ /** Read consistency: `LOCAL_SERIAL` (linearizable, read-your-writes) unless the caller opts into eventual. */
37
+ private readConsistency;
38
+ get(ref: ChunkRef, opts?: WarmReadOptions): Promise<WarmRow | null>;
39
+ putConditional(ref: ChunkRef, bytes: Uint8Array, expected: Token | NoRow): Promise<{
40
+ token: Token;
41
+ }>;
42
+ deleteConditional(ref: ChunkRef, expected: Token): Promise<void>;
43
+ listChunks(ref: SegmentRef, opts?: WarmReadOptions): AsyncIterable<{
44
+ chunkKey: number;
45
+ } & WarmRow>;
46
+ /** Build a {@link WarmRow} from a raw row; reject one missing/mistyped fields (corrupt/foreign). */
47
+ private rowFrom;
48
+ /** Reclassify a transient Cassandra fault as a retryable {@link TransientError}; else propagate unchanged. */
49
+ private mapError;
50
+ }
51
+
52
+ export { CassandraWarmDriver, type CassandraWarmDriverOptions, cassandraWarmTableDDL };
@@ -0,0 +1,52 @@
1
+ import { Client } from 'cassandra-driver';
2
+ import { a as IWarmDriver, b as ChunkRef, W as WarmReadOptions, c as WarmRow, T as Token, N as NoRow, S as SegmentRef } from '../ports-D3BrJ6ax.js';
3
+
4
+ interface CassandraWarmDriverOptions {
5
+ /**
6
+ * A connected `cassandra-driver` `Client`. The driver never connects/shuts it down — the caller owns it.
7
+ * Notes: identifiers (keyspace/table) are **case-sensitive** here (quoted), so pass them exactly as stored
8
+ * (lowercase unless created quoted). OCC reads use `LOCAL_SERIAL` — linearizable **within one datacenter**;
9
+ * a **multi-DC** deployment that needs cross-DC linearizable OCC must run at `SERIAL` (configure it on the
10
+ * client and note this driver defaults to the local variant). An LWT that times out is ambiguous: the retry
11
+ * layer may re-issue it and surface a spurious `WriteConflictError` for a write that actually committed —
12
+ * the caller's OCC re-read converges and no data is lost.
13
+ */
14
+ readonly client: Client;
15
+ /** Keyspace holding the warm table (must already exist — replication is a deployment decision). */
16
+ readonly keyspace: string;
17
+ /** Warm table name (default `cloud_roaring_warm`). Must already exist (see `cassandraWarmTableDDL`). */
18
+ readonly table?: string;
19
+ /** Optional key-prefix column value so several logical stores can share one table (bound as data). */
20
+ readonly keyPrefix?: string;
21
+ /** Advanced: `listChunks` fetch (page) size (default 500). Tunes peak memory on wide segments. */
22
+ readonly listPageSize?: number;
23
+ }
24
+ /**
25
+ * The idempotent CQL DDL for the warm table (identifier-validated + quoted). The driver does **not** create
26
+ * schema at runtime (it stays thin); run this once at deploy time against an existing keyspace, e.g.
27
+ * `await client.execute(cassandraWarmTableDDL('my_ks'))`.
28
+ */
29
+ declare function cassandraWarmTableDDL(keyspace: string, table?: string): string;
30
+ declare class CassandraWarmDriver implements IWarmDriver {
31
+ private readonly client;
32
+ private readonly table;
33
+ private readonly keyPrefix;
34
+ private readonly fetchSize;
35
+ constructor(options: CassandraWarmDriverOptions);
36
+ /** Read consistency: `LOCAL_SERIAL` (linearizable, read-your-writes) unless the caller opts into eventual. */
37
+ private readConsistency;
38
+ get(ref: ChunkRef, opts?: WarmReadOptions): Promise<WarmRow | null>;
39
+ putConditional(ref: ChunkRef, bytes: Uint8Array, expected: Token | NoRow): Promise<{
40
+ token: Token;
41
+ }>;
42
+ deleteConditional(ref: ChunkRef, expected: Token): Promise<void>;
43
+ listChunks(ref: SegmentRef, opts?: WarmReadOptions): AsyncIterable<{
44
+ chunkKey: number;
45
+ } & WarmRow>;
46
+ /** Build a {@link WarmRow} from a raw row; reject one missing/mistyped fields (corrupt/foreign). */
47
+ private rowFrom;
48
+ /** Reclassify a transient Cassandra fault as a retryable {@link TransientError}; else propagate unchanged. */
49
+ private mapError;
50
+ }
51
+
52
+ export { CassandraWarmDriver, type CassandraWarmDriverOptions, cassandraWarmTableDDL };