@duraxis/core 0.2.2 → 0.4.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.
package/dist/index.cjs CHANGED
@@ -1,6 +1,345 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let node_crypto = require("node:crypto");
3
3
  let _duraxis_storage = require("@duraxis/storage");
4
+ // src/resources/resource-manager.ts
5
+ var DEFAULT_RESOURCE_LIMITS = Object.freeze({
6
+ maxQueuedOperations: 64,
7
+ maxConcurrentTransactions: 64,
8
+ maxConcurrentQueries: 64,
9
+ maxOpenSnapshots: 128,
10
+ maxOpenIterators: 256,
11
+ maxPendingOperations: 256,
12
+ maxPendingWrites: 1e5,
13
+ maxPendingWriteBytes: 67108864,
14
+ maxResultRows: 1e4,
15
+ maxResultBytes: 16777216,
16
+ maxQueryWorkingBytes: 33554432,
17
+ maxTransactionWorkingBytes: 134217728,
18
+ maxDatabaseWorkingBytes: 536870912,
19
+ maxDocumentBytes: 1048576,
20
+ maxStorageReadBytes: 4194304,
21
+ maxDocumentDepth: 64,
22
+ maxPredicateDepth: 32,
23
+ maxPredicateNodes: 4096,
24
+ maxTransactionDurationMs: 6e4,
25
+ maxQueryDurationMs: 3e4,
26
+ maxSnapshotLifetimeMs: 6e4,
27
+ maxSpillBytes: 268435456
28
+ });
29
+ var ResourceExhaustedError = class extends Error {
30
+ resource;
31
+ limit;
32
+ constructor(resource, limit) {
33
+ super(`Duraxis resource limit exceeded: ${resource} (limit ${limit}); reduce the workload or explicitly configure a larger budget`);
34
+ this.resource = resource;
35
+ this.limit = limit;
36
+ this.name = "ResourceExhaustedError";
37
+ }
38
+ };
39
+ var OperationCancelledError = class extends Error {
40
+ constructor(message = "Duraxis operation cancelled or deadline exceeded") {
41
+ super(message);
42
+ this.name = "OperationCancelledError";
43
+ }
44
+ };
45
+ function resourceLimits(options = {}) {
46
+ const result = {
47
+ ...DEFAULT_RESOURCE_LIMITS,
48
+ ...options
49
+ };
50
+ for (const [name, value] of Object.entries(result)) if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`Invalid resource limit: ${name}`);
51
+ return Object.freeze(result);
52
+ }
53
+ var ResourceScope = class ResourceScope {
54
+ limits;
55
+ parent;
56
+ usage = {};
57
+ high = {};
58
+ children = /* @__PURE__ */ new Set();
59
+ closed = false;
60
+ constructor(limits, parent) {
61
+ this.limits = limits;
62
+ this.parent = parent;
63
+ parent?.children.add(this);
64
+ }
65
+ child(limits) {
66
+ this.assertOpen();
67
+ return new ResourceScope(limits, this);
68
+ }
69
+ assertOpen() {
70
+ if (this.closed) throw new OperationCancelledError("Resource scope is closed");
71
+ }
72
+ change(delta) {
73
+ const chain = [];
74
+ for (let scope = this; scope; scope = scope.parent) {
75
+ scope.assertOpen();
76
+ chain.push(scope);
77
+ for (const [key, value] of Object.entries(delta)) {
78
+ const next = (scope.usage[key] ?? 0) + value;
79
+ if (next < 0) throw new Error("Resource accounting underflow");
80
+ if (next > (scope.limits[key] ?? Number.MAX_SAFE_INTEGER)) throw new ResourceExhaustedError(key, scope.limits[key]);
81
+ }
82
+ }
83
+ for (const scope of chain) for (const [key, value] of Object.entries(delta)) {
84
+ scope.usage[key] = (scope.usage[key] ?? 0) + value;
85
+ scope.high[key] = Math.max(scope.high[key] ?? 0, scope.usage[key]);
86
+ }
87
+ }
88
+ reserve(initial) {
89
+ let held = {};
90
+ let released = false;
91
+ const resize = (amounts) => {
92
+ if (released || this.closed) throw new OperationCancelledError("Reservation is closed");
93
+ const delta = {};
94
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(held), ...Object.keys(amounts)])) {
95
+ const amount = amounts[key] ?? 0;
96
+ if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError("Invalid resource reservation");
97
+ delta[key] = amount - (held[key] ?? 0);
98
+ }
99
+ this.change(delta);
100
+ held = { ...amounts };
101
+ };
102
+ resize(initial);
103
+ return {
104
+ resize,
105
+ release: () => {
106
+ if (released) return;
107
+ released = true;
108
+ if (!this.closed) this.change(Object.fromEntries(Object.entries(held).map(([key, value]) => [key, -value])));
109
+ held = {};
110
+ }
111
+ };
112
+ }
113
+ metrics() {
114
+ return {
115
+ current: { ...this.usage },
116
+ highWater: { ...this.high }
117
+ };
118
+ }
119
+ close() {
120
+ if (this.closed) return;
121
+ for (const child of [...this.children]) child.close();
122
+ this.change(Object.fromEntries(Object.entries(this.usage).map(([key, value]) => [key, -value])));
123
+ this.closed = true;
124
+ this.parent?.children.delete(this);
125
+ }
126
+ };
127
+ function databaseScope(limits) {
128
+ return new ResourceScope({
129
+ workingBytes: limits.maxDatabaseWorkingBytes,
130
+ transactions: limits.maxConcurrentTransactions,
131
+ queries: limits.maxConcurrentQueries,
132
+ snapshots: limits.maxOpenSnapshots,
133
+ iterators: limits.maxOpenIterators,
134
+ pendingOperations: limits.maxPendingOperations,
135
+ queuedOperations: limits.maxQueuedOperations
136
+ });
137
+ }
138
+ function estimateBytes(value, maximum = 134217728, maxDepth = 64) {
139
+ let bytes = 0;
140
+ const ancestors = /* @__PURE__ */ new Set();
141
+ const visit = (item, depth) => {
142
+ if (depth > maxDepth) throw new ResourceExhaustedError("documentDepth", maxDepth);
143
+ if (typeof item == "string") bytes += item.length * 2 + 24;
144
+ else if (item == null || typeof item != "object") bytes += 16;
145
+ else if (item instanceof Uint8Array) bytes += item.byteLength + 64;
146
+ else if (item instanceof Date) bytes += 32;
147
+ else {
148
+ if (ancestors.has(item)) throw new TypeError("Cyclic values are not supported");
149
+ ancestors.add(item);
150
+ bytes += 64;
151
+ for (const key in item) if (Object.hasOwn(item, key)) {
152
+ if (key == "__proto__") throw new TypeError("Unsafe object property");
153
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
154
+ if (!("value" in descriptor)) throw new TypeError("Accessor properties are not supported");
155
+ bytes += key.length * 2 + 32;
156
+ visit(descriptor.value, depth + 1);
157
+ if (bytes > maximum) throw new ResourceExhaustedError("workingBytes", maximum);
158
+ }
159
+ ancestors.delete(item);
160
+ }
161
+ if (bytes > maximum) throw new ResourceExhaustedError("workingBytes", maximum);
162
+ };
163
+ visit(value, 0);
164
+ return bytes;
165
+ }
166
+ function materialize(scope, limits) {
167
+ const reservation = scope.reserve({});
168
+ let rows = 0;
169
+ let bytes = 0;
170
+ let working = 0;
171
+ return {
172
+ add(value) {
173
+ if (rows + 1 > limits.maxResultRows) throw new ResourceExhaustedError("resultRows", limits.maxResultRows);
174
+ const size = estimateBytes(value, limits.maxQueryWorkingBytes, limits.maxDocumentDepth + 4);
175
+ reservation.resize({ workingBytes: working + size * 8 });
176
+ let encoded;
177
+ try {
178
+ encoded = JSON.stringify(value);
179
+ } finally {
180
+ reservation.resize({ workingBytes: working + size });
181
+ }
182
+ if (encoded === void 0) throw new TypeError("Result is not JSON serializable");
183
+ const next = bytes + Buffer.byteLength(encoded);
184
+ if (next > limits.maxResultBytes) throw new ResourceExhaustedError("resultBytes", limits.maxResultBytes);
185
+ working += size;
186
+ bytes = next;
187
+ rows++;
188
+ },
189
+ close: () => reservation.release()
190
+ };
191
+ }
192
+ // src/gc/storage-coordination.ts
193
+ var states = /* @__PURE__ */ new WeakMap();
194
+ function storageCoordination(storage) {
195
+ let state = states.get(storage);
196
+ if (!state) {
197
+ state = {
198
+ active: 0,
199
+ maintenance: false,
200
+ snapshots: /* @__PURE__ */ new Set()
201
+ };
202
+ states.set(storage, state);
203
+ }
204
+ return state;
205
+ }
206
+ var commits = /* @__PURE__ */ new WeakMap();
207
+ async function coordinateCommit(storage, maximum, action) {
208
+ let state = commits.get(storage);
209
+ if (!state) {
210
+ state = {
211
+ tail: Promise.resolve(),
212
+ queued: 0
213
+ };
214
+ commits.set(storage, state);
215
+ }
216
+ if (state.queued >= maximum) throw new ResourceExhaustedError("queuedOperations", maximum);
217
+ state.queued++;
218
+ const previous = state.tail;
219
+ let release;
220
+ state.tail = new Promise((resolve) => {
221
+ release = resolve;
222
+ });
223
+ try {
224
+ await previous;
225
+ return await action();
226
+ } finally {
227
+ state.queued--;
228
+ release();
229
+ }
230
+ }
231
+ // src/resources/operation-owner.ts
232
+ var OperationOwner = class {
233
+ scope;
234
+ onDispose;
235
+ controller = new AbortController();
236
+ storage;
237
+ pending = 0;
238
+ ended = false;
239
+ disposed = false;
240
+ publishing = false;
241
+ timer;
242
+ constructor(scope, storage, durationMs, onDispose, maxReadBytes = 16777216) {
243
+ this.scope = scope;
244
+ this.onDispose = onDispose;
245
+ this.timer = setTimeout(() => this.cancel(new OperationCancelledError("Operation lifetime expired")), durationMs);
246
+ this.timer.unref();
247
+ this.storage = {
248
+ capabilities: storage.capabilities,
249
+ get: (key, options) => this.track(async () => {
250
+ const signal = options?.signal ? AbortSignal.any([this.signal, options.signal]) : this.signal;
251
+ const value = await storage.get(key, {
252
+ signal,
253
+ maxBytes: Math.min(maxReadBytes, options?.maxBytes ?? maxReadBytes)
254
+ });
255
+ if (value && value.data.byteLength > maxReadBytes) throw new Error("Storage read exceeds configured byte limit");
256
+ return value;
257
+ }, maxReadBytes * 3),
258
+ put: (key, data, options) => this.track(() => storage.put(key, data, options), data.byteLength * 2),
259
+ delete: (key, options) => this.track(() => storage.delete(key, options)),
260
+ list: (prefix) => this.track(() => storage.list(prefix))
261
+ };
262
+ }
263
+ get signal() {
264
+ return this.controller.signal;
265
+ }
266
+ get isDisposed() {
267
+ return this.disposed;
268
+ }
269
+ get pendingOperations() {
270
+ return this.pending;
271
+ }
272
+ assertActive() {
273
+ this.signal.throwIfAborted();
274
+ if (this.ended) throw new OperationCancelledError("Operation is closed");
275
+ }
276
+ async track(action, bytes = 0) {
277
+ this.assertActive();
278
+ const lease = this.scope.reserve({
279
+ pendingOperations: 1,
280
+ workingBytes: bytes
281
+ });
282
+ this.pending++;
283
+ try {
284
+ const value = await action();
285
+ if (!this.publishing) this.signal.throwIfAborted();
286
+ return value;
287
+ } finally {
288
+ lease.release();
289
+ this.pending--;
290
+ this.disposeIfReady();
291
+ }
292
+ }
293
+ protectPublication() {
294
+ this.assertActive();
295
+ this.publishing = true;
296
+ clearTimeout(this.timer);
297
+ }
298
+ cancel(reason = new OperationCancelledError()) {
299
+ if (this.publishing) return;
300
+ if (!this.signal.aborted) this.controller.abort(reason);
301
+ this.finish();
302
+ }
303
+ finish() {
304
+ if (this.ended) return;
305
+ this.ended = true;
306
+ clearTimeout(this.timer);
307
+ this.disposeIfReady();
308
+ }
309
+ disposeIfReady() {
310
+ if (!this.ended || this.pending || this.disposed) return;
311
+ this.disposed = true;
312
+ this.scope.close();
313
+ this.onDispose();
314
+ }
315
+ holdCleanup(promise) {
316
+ this.pending++;
317
+ const complete = () => {
318
+ this.pending--;
319
+ this.disposeIfReady();
320
+ };
321
+ promise.then(complete, complete);
322
+ }
323
+ async wait(promise) {
324
+ this.assertActive();
325
+ return new Promise((resolve, reject) => {
326
+ const abort = () => {
327
+ cleanup();
328
+ reject(this.signal.reason);
329
+ };
330
+ const cleanup = () => this.signal.removeEventListener("abort", abort);
331
+ this.signal.addEventListener("abort", abort, { once: true });
332
+ promise.then((value) => {
333
+ cleanup();
334
+ resolve(value);
335
+ }, (error) => {
336
+ cleanup();
337
+ reject(error);
338
+ });
339
+ if (this.signal.aborted) abort();
340
+ });
341
+ }
342
+ };
4
343
  // src/integrity/integrity.ts
5
344
  function sha256(bytes) {
6
345
  return (0, node_crypto.createHash)("sha256").update(bytes).digest("hex");
@@ -25,7 +364,7 @@ var StorageKeyManager = class {
25
364
  objectPattern;
26
365
  commitPattern;
27
366
  constructor(namespace = "__duraxis/v1") {
28
- if (!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(namespace)) throw new Error("Invalid Duraxis storage namespace");
367
+ if (typeof namespace != "string" || Buffer.byteLength(namespace) > 256 || !/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(namespace)) throw new Error("Invalid Duraxis storage namespace");
29
368
  this.namespace = namespace;
30
369
  this.manifestKey = `${namespace}/manifest`;
31
370
  this.objectPrefix = `${namespace}/objects/`;
@@ -34,11 +373,16 @@ var StorageKeyManager = class {
34
373
  this.indexNodePattern = new RegExp(`^${escapeRegex$1(this.indexNodePrefix)}${UUID$1}-([a-f0-9]{64})$`);
35
374
  this.objectPattern = new RegExp(`^${escapeRegex$1(this.objectPrefix)}(${UUID$1})(?:-([a-f0-9]{64}))?$`);
36
375
  this.commitPattern = new RegExp(`^${escapeRegex$1(this.commitPrefix)}(${UUID$1})-([a-f0-9]{64})$`);
376
+ Object.freeze(this);
37
377
  }
38
378
  validateLogicalKey(key) {
39
379
  (0, _duraxis_storage.assertStorageKey)(key);
40
380
  if (key == "__duraxis" || key.startsWith("__duraxis/")) throw new Error("Reserved Duraxis logical key namespace");
41
381
  }
382
+ validatePrimaryKey(key) {
383
+ if (/^__duraxis\/metadata\/[a-z][a-z0-9-]{0,63}$/.test(key)) return;
384
+ this.validateLogicalKey(key);
385
+ }
42
386
  objectKey(data) {
43
387
  return `${this.objectPrefix}${(0, node_crypto.randomUUID)()}-${sha256(data)}`;
44
388
  }
@@ -444,22 +788,32 @@ async function readCommitRecord(storage, keys, key) {
444
788
  if (keys.commitKey(record.transactionId, object.data) != key) throw new Error("Commit record identity mismatch");
445
789
  return record;
446
790
  }
447
- // src/errors/transaction-conflict.error.ts
448
- var TransactionConflictError = class extends Error {
449
- message;
450
- constructor(message = "Transaction conflict: snapshot is stale") {
451
- super(message);
452
- this.message = message;
453
- this.name = "TransactionConflictError";
454
- }
455
- };
456
- // src/errors/commit-outcome-unknown.error.ts
457
- var CommitOutcomeUnknownError = class extends Error {
458
- transactionId;
459
- constructor(transactionId, cause) {
460
- super(`Commit outcome is unknown for transaction ${transactionId}` + (cause instanceof Error ? `: ${cause.message}` : ""), { cause });
461
- this.name = "CommitOutcomeUnknownError";
462
- this.transactionId = transactionId;
791
+ // src/resources/prepared-writes.ts
792
+ var PreparedWrites = class extends Map {
793
+ limits;
794
+ bytes = 0;
795
+ encodedBytes = 0;
796
+ reservation;
797
+ constructor(scope, limits, source) {
798
+ super();
799
+ this.limits = limits;
800
+ this.reservation = scope.reserve({});
801
+ for (const [key, value] of source) this.set(key, value);
802
+ }
803
+ sizeOf(key, value) {
804
+ return key.length * 2 + 512 + (value.type === "put" ? value.data.byteLength * 8 : 0);
805
+ }
806
+ set(key, value) {
807
+ const previous = this.get(key);
808
+ if (!previous && this.size >= this.limits.maxPendingWrites) throw new ResourceExhaustedError("writes", this.limits.maxPendingWrites);
809
+ if (value.type === "put" && value.data.byteLength > this.limits.maxDocumentBytes) throw new ResourceExhaustedError("documentBytes", this.limits.maxDocumentBytes);
810
+ const next = this.bytes - (previous ? this.sizeOf(key, previous) : 0) + this.sizeOf(key, value);
811
+ const encoded = this.encodedBytes - (previous?.type === "put" ? previous.data.byteLength : 0) + (value.type === "put" ? value.data.byteLength : 0);
812
+ if (encoded > this.limits.maxPendingWriteBytes) throw new ResourceExhaustedError("preparedWriteBytes", this.limits.maxPendingWriteBytes);
813
+ this.reservation.resize({ workingBytes: next });
814
+ this.bytes = next;
815
+ this.encodedBytes = encoded;
816
+ return super.set(key, value);
463
817
  }
464
818
  };
465
819
  // src/indexes/bptree/bptree-codec.ts
@@ -1060,7 +1414,7 @@ var PrimaryIndex = class {
1060
1414
  this.tree = new BPlusTree(nodes);
1061
1415
  }
1062
1416
  async getReference(manifest, logicalKey) {
1063
- this.keys.validateLogicalKey(logicalKey);
1417
+ this.keys.validatePrimaryKey(logicalKey);
1064
1418
  const value = await this.tree.get(manifest.primaryRoot, encoder$2.encode(logicalKey));
1065
1419
  if (value == null) return null;
1066
1420
  const ref = decoder$2.decode(value);
@@ -1070,7 +1424,7 @@ var PrimaryIndex = class {
1070
1424
  async prepare(root, changes) {
1071
1425
  const operations = [];
1072
1426
  for (const [logicalKey, physicalRef] of changes) {
1073
- this.keys.validateLogicalKey(logicalKey);
1427
+ this.keys.validatePrimaryKey(logicalKey);
1074
1428
  if (physicalRef == null) operations.push({
1075
1429
  type: "delete",
1076
1430
  key: encoder$2.encode(logicalKey)
@@ -1101,7 +1455,7 @@ var PrimaryIndex = class {
1101
1455
  for await (const entry of this.tree.scan(root, options)) {
1102
1456
  const key = decoder$2.decode(entry.key);
1103
1457
  const ref = decoder$2.decode(entry.value);
1104
- this.keys.validateLogicalKey(key);
1458
+ this.keys.validatePrimaryKey(key);
1105
1459
  this.keys.validateObjectKey(ref);
1106
1460
  yield {
1107
1461
  key,
@@ -1110,6 +1464,67 @@ var PrimaryIndex = class {
1110
1464
  }
1111
1465
  }
1112
1466
  };
1467
+ // src/indexes/bptree/bptree-node-cache.ts
1468
+ var BPlusTreeNodeCache = class {
1469
+ source;
1470
+ capacity;
1471
+ maxBytes;
1472
+ entries = /* @__PURE__ */ new Map();
1473
+ sizes = /* @__PURE__ */ new Map();
1474
+ bytes = 0;
1475
+ reservation;
1476
+ hits = 0;
1477
+ misses = 0;
1478
+ constructor(source, capacity = 256, maxBytes = 4194304, resources = new ResourceScope({})) {
1479
+ this.source = source;
1480
+ this.capacity = capacity;
1481
+ this.maxBytes = maxBytes;
1482
+ this.reservation = resources.reserve({});
1483
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new RangeError("Invalid cache byte limit");
1484
+ if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 65536) throw new Error("Invalid B+tree node cache capacity");
1485
+ }
1486
+ async read(ref) {
1487
+ const cached = this.entries.get(ref);
1488
+ if (cached) {
1489
+ this.hits++;
1490
+ this.entries.delete(ref);
1491
+ this.entries.set(ref, cached);
1492
+ return cached;
1493
+ }
1494
+ this.misses++;
1495
+ const node = await this.source.read(ref);
1496
+ if (this.entries.has(ref)) return this.entries.get(ref);
1497
+ const size = estimateBytes(node);
1498
+ if (size > this.maxBytes) return node;
1499
+ while (this.entries.size >= this.capacity || this.bytes + size > this.maxBytes) {
1500
+ const oldest = this.entries.keys().next().value;
1501
+ this.bytes -= this.sizes.get(oldest);
1502
+ this.sizes.delete(oldest);
1503
+ this.entries.delete(oldest);
1504
+ }
1505
+ this.reservation.resize({ workingBytes: this.bytes + size });
1506
+ this.bytes += size;
1507
+ this.sizes.set(ref, size);
1508
+ this.entries.set(ref, node);
1509
+ return node;
1510
+ }
1511
+ write(node) {
1512
+ return this.source.write(node);
1513
+ }
1514
+ clear() {
1515
+ this.entries.clear();
1516
+ this.sizes.clear();
1517
+ this.bytes = 0;
1518
+ this.reservation.resize({});
1519
+ }
1520
+ getMetrics() {
1521
+ return {
1522
+ hits: this.hits,
1523
+ misses: this.misses,
1524
+ bytes: this.bytes
1525
+ };
1526
+ }
1527
+ };
1113
1528
  // src/indexes/index-key.ts
1114
1529
  var MASK = 18446744073709551615n;
1115
1530
  var SIGN = 9223372036854775808n;
@@ -1337,18 +1752,18 @@ var SecondaryIndexManager = class {
1337
1752
  this.nodes = nodes;
1338
1753
  this.primary = new PrimaryIndex(storage, keys, nodes);
1339
1754
  }
1340
- async prepare(previousManifest, nextPrimaryRoot, writes, catalog) {
1755
+ async prepare(previousManifest, nextPrimaryRoot, writes, catalog, resources) {
1341
1756
  const roots = new Map(previousManifest.indexRoots);
1342
1757
  const declared = /* @__PURE__ */ new Set();
1343
1758
  const tree = new BPlusTree(this.nodes);
1344
1759
  for (const [collectionName, schema] of catalog) {
1345
1760
  const previousSchema = previousManifest.catalog.get(collectionName);
1346
- const changes = await this.collectChanges(previousManifest, collectionName, writes);
1761
+ const changes = await this.collectChanges(previousManifest, collectionName, writes, resources);
1347
1762
  for (const index of schema.indexes) {
1348
1763
  const id = indexId(collectionName, index.name);
1349
1764
  declared.add(id);
1350
1765
  const oldIndex = previousSchema?.indexes.find((item) => item.name == index.name);
1351
- if (!(oldIndex != null && JSON.stringify(indexFields(oldIndex)) == JSON.stringify(indexFields(index)) && oldIndex.unique == index.unique)) {
1766
+ if (!(oldIndex != null && JSON.stringify(indexFields(oldIndex)) == JSON.stringify(indexFields(index)) && oldIndex.unique == index.unique && indexFields(index).every((part) => JSON.stringify(fieldDefinition(previousSchema, part.field)) == JSON.stringify(fieldDefinition(schema, part.field))))) {
1352
1767
  roots.set(id, await this.rebuild(collectionName, schema, index, nextPrimaryRoot));
1353
1768
  continue;
1354
1769
  }
@@ -1396,15 +1811,20 @@ var SecondaryIndexManager = class {
1396
1811
  for (const id of [...roots.keys()]) if (!declared.has(id)) roots.delete(id);
1397
1812
  return roots;
1398
1813
  }
1399
- async collectChanges(manifest, collection, writes) {
1814
+ async collectChanges(manifest, collection, writes, resources) {
1400
1815
  const changes = [];
1816
+ const memory = resources?.reserve({});
1817
+ let bytes = 0;
1401
1818
  for (const [key, operation] of writes) {
1402
1819
  const parsed = parseRecordKey(key);
1403
1820
  if (parsed == null || parsed.collection != collection) continue;
1404
1821
  const previousRef = await this.primary.getReference(manifest, key);
1822
+ const previousData = previousRef == null ? void 0 : await this.primary.readObject(previousRef);
1823
+ bytes += 512 + (previousData?.byteLength ?? 0) * 8 + (operation.type == "put" ? operation.data.byteLength * 8 : 0);
1824
+ memory?.resize({ workingBytes: bytes });
1405
1825
  changes.push({
1406
1826
  recordId: parsed.id,
1407
- previous: previousRef == null ? void 0 : decodeDocument(await this.primary.readObject(previousRef)),
1827
+ previous: previousRef == null ? void 0 : decodeDocument(previousData),
1408
1828
  next: operation.type == "put" ? decodeDocument(operation.data) : void 0
1409
1829
  });
1410
1830
  }
@@ -1420,7 +1840,12 @@ var SecondaryIndexManager = class {
1420
1840
  operations = [];
1421
1841
  }
1422
1842
  };
1423
- for await (const entry of this.primary.scanReferences(primaryRoot)) {
1843
+ const prefix = encoder.encode(`${RECORD_PREFIX}${collection}/`);
1844
+ const end = prefixSuccessor(prefix);
1845
+ for await (const entry of this.primary.scanReferences(primaryRoot, {
1846
+ gte: prefix,
1847
+ ...end == null ? {} : { lt: end }
1848
+ })) {
1424
1849
  const parsed = parseRecordKey(entry.key);
1425
1850
  if (parsed == null || parsed.collection != collection) continue;
1426
1851
  const values = valuesFor(schema, index, decodeDocument(await this.primary.readObject(entry.ref)));
@@ -1453,7 +1878,6 @@ var SecondaryIndexManager = class {
1453
1878
  root: manifest.indexRoots.get(id)
1454
1879
  };
1455
1880
  }
1456
- /** Ordered, incremental access that never materializes the ID set. */
1457
1881
  async *scanIds(manifest, collection, indexName, options = {}) {
1458
1882
  const { index, root } = this.resolve(manifest, collection, indexName);
1459
1883
  const limit = options.limit ?? Number.MAX_SAFE_INTEGER;
@@ -1481,298 +1905,84 @@ var SecondaryIndexManager = class {
1481
1905
  return ids;
1482
1906
  }
1483
1907
  };
1484
- // src/relations/foreign-key-manager.ts
1485
- var MAX_CASCADE_OPERATIONS = 1e5;
1486
- var ForeignKeyManager = class {
1487
- #primary;
1488
- #secondary;
1489
- constructor(storage, keys = new StorageKeyManager()) {
1490
- this.#primary = new PrimaryIndex(storage, keys);
1491
- this.#secondary = new SecondaryIndexManager(storage, keys);
1908
+ // src/query/context/query-context.ts
1909
+ function cloneWrites(source) {
1910
+ const result = /* @__PURE__ */ new Map();
1911
+ for (const [key, write] of source ?? []) result.set(key, write.type == "delete" ? { type: "delete" } : {
1912
+ type: "put",
1913
+ data: new Uint8Array(write.data)
1914
+ });
1915
+ return result;
1916
+ }
1917
+ var QueryContext = class {
1918
+ options;
1919
+ resources;
1920
+ limits;
1921
+ iteratorReservations = [];
1922
+ primary;
1923
+ secondary;
1924
+ nodeCache;
1925
+ writes;
1926
+ controller = new AbortController();
1927
+ startedAt = performance.now();
1928
+ active = true;
1929
+ iterators = 0;
1930
+ timer;
1931
+ cancellationReturns = /* @__PURE__ */ new Set();
1932
+ metrics = {
1933
+ storageReads: 0,
1934
+ storageWrites: 0,
1935
+ nodesVisited: 0,
1936
+ entriesExamined: 0,
1937
+ recordsExamined: 0,
1938
+ recordsReturned: 0,
1939
+ cacheHits: 0,
1940
+ cacheMisses: 0,
1941
+ durationMs: 0
1942
+ };
1943
+ snapshotValue;
1944
+ get snapshot() {
1945
+ this.assertActive();
1946
+ return this.snapshotValue;
1492
1947
  }
1493
- async prepare(snapshot, sourceWrites, sourceCatalog) {
1494
- const catalog = this.validateCatalog(sourceCatalog);
1495
- const writes = new Map(sourceWrites);
1496
- const incoming = this.incoming(catalog);
1497
- const queue = [];
1498
- const visited = /* @__PURE__ */ new Set();
1499
- for (const [key, operation] of writes) {
1500
- const parsed = parseRecordKey(key);
1501
- if (parsed && operation.type == "delete") queue.push(parsed);
1502
- }
1503
- for (let offset = 0; offset < queue.length; offset++) {
1504
- if (visited.size > MAX_CASCADE_OPERATIONS) throw new Error("Foreign-key cascade operation limit exceeded");
1505
- const parent = queue[offset];
1506
- const parentKey = recordKey(parent.collection, parent.id);
1507
- if (visited.has(parentKey)) continue;
1508
- visited.add(parentKey);
1509
- for (const relation of incoming.get(parent.collection) ?? []) {
1510
- const childIds = await this.childIds(snapshot, writes, relation, parent.id);
1511
- for (const childId of childIds) {
1512
- const childKey = recordKey(relation.collection, childId);
1513
- const document = await this.finalDocument(snapshot, writes, relation.collection, childId);
1514
- if (!document || document[relation.foreignKey.field] !== parent.id) continue;
1515
- switch (relation.foreignKey.onDelete) {
1516
- case "RESTRICT": throw new ReferencedRecordRestrictedError(relation.collection, relation.foreignKey.name, `${parent.collection}/${parent.id}`);
1517
- case "CASCADE":
1518
- writes.set(childKey, { type: "delete" });
1519
- queue.push({
1520
- collection: relation.collection,
1521
- id: childId
1522
- });
1523
- break;
1524
- case "SET_NULL": {
1525
- const next = {
1526
- ...document,
1527
- [relation.foreignKey.field]: null
1528
- };
1529
- writes.set(childKey, {
1530
- type: "put",
1531
- data: encodeDocument(validateDocument(relation.schema, next))
1532
- });
1533
- break;
1534
- }
1535
- }
1536
- }
1537
- }
1538
- }
1539
- for (const [key, operation] of writes) {
1540
- const parsed = parseRecordKey(key);
1541
- if (!parsed || operation.type != "put") continue;
1542
- const schema = catalog.get(parsed.collection);
1543
- if (!schema) throw new InvalidForeignKeyDefinitionError(`Unknown collection: ${parsed.collection}`);
1544
- const document = decodeDocument(operation.data);
1545
- for (const foreignKey of schema.foreignKeys ?? []) {
1546
- const definition = fieldDefinition(schema, foreignKey.field);
1547
- const value = document[foreignKey.field];
1548
- if (value == null) {
1549
- if (value === null && definition.nullable) continue;
1550
- if (value === void 0 && !definition.required) continue;
1551
- throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, String(value));
1552
- }
1553
- if (typeof value != "string" || !await this.finalRecordExists(snapshot, writes, foreignKey.references.collection, value)) throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, `${foreignKey.references.collection}/${String(value)}`);
1554
- }
1555
- }
1556
- return writes;
1948
+ catalogValue = /* @__PURE__ */ new Map();
1949
+ get catalog() {
1950
+ return this.catalogValue;
1557
1951
  }
1558
- validateCatalog(source) {
1559
- const catalog = /* @__PURE__ */ new Map();
1952
+ constructor(storage, snapshot, keys, options = {}) {
1953
+ this.options = options;
1954
+ this.snapshotValue = snapshot;
1955
+ this.limits = options.limits ?? resourceLimits();
1956
+ this.resources = (options.resources ?? new ResourceScope({})).child({
1957
+ workingBytes: this.limits.maxQueryWorkingBytes,
1958
+ spillBytes: this.limits.maxSpillBytes
1959
+ });
1560
1960
  try {
1561
- for (const [name, definition] of source) catalog.set(name, normalizeCollection(definition));
1562
- } catch (cause) {
1563
- throw new InvalidForeignKeyDefinitionError(cause instanceof Error ? cause.message : "Invalid foreign key definition");
1961
+ this.resources.reserve({
1962
+ queries: 1,
1963
+ iterators: 1,
1964
+ workingBytes: estimateBytes([...options.writes ?? []])
1965
+ });
1966
+ } catch (error) {
1967
+ this.resources.close();
1968
+ throw error;
1564
1969
  }
1565
- for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) if (!catalog.has(foreignKey.references.collection)) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} references unknown collection ${foreignKey.references.collection}`);
1566
- return catalog;
1567
- }
1568
- incoming(catalog) {
1569
- const result = /* @__PURE__ */ new Map();
1570
- for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) {
1571
- const index = schema.indexes.find((candidate) => {
1572
- const parts = indexFields(candidate);
1573
- return parts.length == 1 && parts[0].field == foreignKey.field;
1574
- });
1575
- if (!index) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} has no supporting index`);
1576
- const values = result.get(foreignKey.references.collection) ?? [];
1577
- values.push({
1578
- collection,
1579
- schema,
1580
- foreignKey,
1581
- index: index.name
1582
- });
1583
- result.set(foreignKey.references.collection, values);
1584
- }
1585
- for (const values of result.values()) values.sort((left, right) => `${left.collection}/${left.foreignKey.name}`.localeCompare(`${right.collection}/${right.foreignKey.name}`));
1586
- return result;
1587
- }
1588
- async childIds(snapshot, writes, relation, parentId) {
1589
- const result = /* @__PURE__ */ new Set();
1590
- if (snapshot.manifest.catalog.get(relation.collection)?.indexes.some((index) => index.name == relation.index)) for await (const entry of this.#secondary.scanIds(snapshot.manifest, relation.collection, relation.index, { eq: parentId })) result.add(entry.id);
1591
- for (const [key, operation] of writes) {
1592
- const parsed = parseRecordKey(key);
1593
- if (!parsed || parsed.collection != relation.collection) continue;
1594
- if (operation.type == "delete") result.delete(parsed.id);
1595
- else if (decodeDocument(operation.data)[relation.foreignKey.field] === parentId) result.add(parsed.id);
1596
- else result.delete(parsed.id);
1597
- }
1598
- return result;
1599
- }
1600
- async finalRecordExists(snapshot, writes, collection, id) {
1601
- return await this.finalDocument(snapshot, writes, collection, id) != null;
1602
- }
1603
- async finalDocument(snapshot, writes, collection, id) {
1604
- const key = recordKey(collection, id);
1605
- const pending = writes.get(key);
1606
- if (pending) return pending.type == "delete" ? null : decodeDocument(pending.data);
1607
- const stored = await this.#primary.read(snapshot.manifest, key);
1608
- return stored == null ? null : decodeDocument(stored);
1609
- }
1610
- };
1611
- // src/commit/commit-coordinator.ts
1612
- var CommitCoordinator = class {
1613
- storage;
1614
- keys;
1615
- primary;
1616
- secondary;
1617
- foreignKeys;
1618
- constructor(storage, keys = new StorageKeyManager()) {
1619
- this.storage = storage;
1620
- this.keys = keys;
1621
- this.primary = new PrimaryIndex(storage, keys);
1622
- this.secondary = new SecondaryIndexManager(storage, keys);
1623
- this.foreignKeys = new ForeignKeyManager(storage, keys);
1624
- }
1625
- async commit(transaction) {
1626
- const prepared = transaction.prepareForCommit();
1627
- if (prepared.writes.size == 0 && prepared.schemaChanges.size == 0) {
1628
- transaction.markCommitted();
1629
- return;
1630
- }
1631
- const transactionId = (0, node_crypto.randomUUID)();
1632
- const catalog = new Map(prepared.snapshot.manifest.catalog);
1633
- for (const [name, schema] of prepared.schemaChanges) catalog.set(name, schema);
1634
- const writes = await this.foreignKeys.prepare(prepared.snapshot, prepared.writes, catalog);
1635
- const changes = /* @__PURE__ */ new Map();
1636
- for (const [key, operation] of writes) {
1637
- if (operation.type == "delete") {
1638
- changes.set(key, null);
1639
- continue;
1640
- }
1641
- const ref = this.keys.objectKey(operation.data);
1642
- if (!(await this.storage.put(ref, operation.data, { condition: { type: "if-absent" } })).success) throw new Error("Unexpected immutable object key collision");
1643
- changes.set(key, ref);
1644
- }
1645
- const primaryRoot = await this.primary.prepare(prepared.snapshot.manifest.primaryRoot, changes);
1646
- const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog);
1647
- const commitBytes = encodeCommitRecord({
1648
- format: 1,
1649
- transactionId,
1650
- previous: prepared.snapshot.manifest.commitHead
1651
- });
1652
- const commitKey = this.keys.commitKey(transactionId, commitBytes);
1653
- if (!(await this.storage.put(commitKey, commitBytes, { condition: { type: "if-absent" } })).success) throw new Error("Unexpected commit record collision");
1654
- const manifestBytes = encodeManifest({
1655
- format: 1,
1656
- transactionId,
1657
- commitHead: commitKey,
1658
- primaryRoot,
1659
- indexRoots,
1660
- catalog
1661
- }, this.keys);
1662
- transaction.beginPublication();
1663
- let result;
1664
- try {
1665
- result = await this.storage.put(this.keys.manifestKey, manifestBytes, { condition: prepared.snapshot.storageVersion == null ? { type: "if-absent" } : {
1666
- type: "if-version",
1667
- version: prepared.snapshot.storageVersion
1668
- } });
1669
- } catch (cause) {
1670
- transaction.markUnknown();
1671
- throw new CommitOutcomeUnknownError(transactionId, cause);
1672
- }
1673
- if (!result.success) throw new TransactionConflictError();
1674
- transaction.markCommitted();
1675
- }
1676
- };
1677
- // src/snapshots/snapshot-reader.ts
1678
- var ManifestSnapshotReader = class {
1679
- snapshot;
1680
- primary;
1681
- constructor(storage, snapshot, keys) {
1682
- this.snapshot = snapshot;
1683
- this.primary = new PrimaryIndex(storage, keys);
1684
- }
1685
- async get(key) {
1686
- return this.primary.read(this.snapshot.manifest, key);
1687
- }
1688
- };
1689
- // src/errors/transaction-state.error.ts
1690
- var TransactionStateError = class extends Error {
1691
- constructor(message) {
1692
- super(message);
1693
- this.name = "TransactionStateError";
1694
- }
1695
- };
1696
- // src/indexes/bptree/bptree-node-cache.ts
1697
- /** Query-scoped LRU for already integrity-checked immutable nodes. */
1698
- var BPlusTreeNodeCache = class {
1699
- source;
1700
- capacity;
1701
- entries = /* @__PURE__ */ new Map();
1702
- hits = 0;
1703
- misses = 0;
1704
- constructor(source, capacity = 256) {
1705
- this.source = source;
1706
- this.capacity = capacity;
1707
- if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 65536) throw new Error("Invalid B+tree node cache capacity");
1708
- }
1709
- async read(ref) {
1710
- const cached = this.entries.get(ref);
1711
- if (cached) {
1712
- this.hits++;
1713
- this.entries.delete(ref);
1714
- this.entries.set(ref, cached);
1715
- return cached;
1716
- }
1717
- this.misses++;
1718
- const node = await this.source.read(ref);
1719
- this.entries.set(ref, node);
1720
- if (this.entries.size > this.capacity) this.entries.delete(this.entries.keys().next().value);
1721
- return node;
1722
- }
1723
- write(node) {
1724
- return this.source.write(node);
1725
- }
1726
- clear() {
1727
- this.entries.clear();
1728
- }
1729
- getMetrics() {
1730
- return {
1731
- hits: this.hits,
1732
- misses: this.misses
1733
- };
1734
- }
1735
- };
1736
- // src/query/context/query-context.ts
1737
- function cloneWrites(source) {
1738
- const result = /* @__PURE__ */ new Map();
1739
- for (const [key, write] of source ?? []) result.set(key, write.type == "delete" ? { type: "delete" } : {
1740
- type: "put",
1741
- data: new Uint8Array(write.data)
1742
- });
1743
- return result;
1744
- }
1745
- var QueryContext = class {
1746
- snapshot;
1747
- options;
1748
- primary;
1749
- secondary;
1750
- nodeCache;
1751
- writes;
1752
- controller = new AbortController();
1753
- startedAt = performance.now();
1754
- active = true;
1755
- iterators = 0;
1756
- metrics = {
1757
- storageReads: 0,
1758
- storageWrites: 0,
1759
- nodesVisited: 0,
1760
- entriesExamined: 0,
1761
- recordsExamined: 0,
1762
- recordsReturned: 0,
1763
- cacheHits: 0,
1764
- cacheMisses: 0,
1765
- durationMs: 0
1766
- };
1767
- catalog;
1768
- constructor(storage, snapshot, keys, options = {}) {
1769
- this.snapshot = snapshot;
1770
- this.options = options;
1771
- this.nodeCache = new BPlusTreeNodeCache(new BPlusTreeNodeStore(storage, keys));
1772
- this.primary = new PrimaryIndex(storage, keys, this.nodeCache);
1773
- this.secondary = new SecondaryIndexManager(storage, keys, this.nodeCache);
1774
- this.writes = cloneWrites(options.writes);
1775
- this.catalog = new Map(options.catalog ?? snapshot.manifest.catalog);
1970
+ const queryStorage = {
1971
+ put: storage.put.bind(storage),
1972
+ delete: storage.delete.bind(storage),
1973
+ list: storage.list.bind(storage),
1974
+ get: (key, options) => storage.get(key, {
1975
+ ...options,
1976
+ signal: options?.signal ? AbortSignal.any([this.signal, options.signal]) : this.signal
1977
+ })
1978
+ };
1979
+ this.nodeCache = new BPlusTreeNodeCache(new BPlusTreeNodeStore(queryStorage, keys), 256, Math.min(4194304, this.limits.maxQueryWorkingBytes), this.resources);
1980
+ this.primary = new PrimaryIndex(queryStorage, keys, this.nodeCache);
1981
+ this.secondary = new SecondaryIndexManager(queryStorage, keys, this.nodeCache);
1982
+ this.writes = cloneWrites(options.writes);
1983
+ for (const [name, definition] of options.catalog ?? snapshot.manifest.catalog) this.catalogValue.set(name, definition);
1984
+ this.timer = setTimeout(() => this.cancel(new OperationCancelledError("Query lifetime expired")), this.limits.maxQueryDurationMs);
1985
+ this.timer.unref();
1776
1986
  }
1777
1987
  get generation() {
1778
1988
  return this.snapshot.manifest.transactionId || "initial";
@@ -1783,30 +1993,78 @@ var QueryContext = class {
1783
1993
  get isActive() {
1784
1994
  return this.active;
1785
1995
  }
1786
- close(reason = /* @__PURE__ */ new Error("Query context is closed")) {
1996
+ bindCancellation(close) {
1997
+ this.cancellationReturns.add(close);
1998
+ return () => this.cancellationReturns.delete(close);
1999
+ }
2000
+ managed(factory) {
2001
+ const context = this;
2002
+ const iterator = (async function* () {
2003
+ const unbind = context.bindCancellation(() => iterator.return(void 0));
2004
+ try {
2005
+ yield* factory();
2006
+ } finally {
2007
+ unbind();
2008
+ }
2009
+ })();
2010
+ return iterator;
2011
+ }
2012
+ scanCollection(collection, options = {}) {
2013
+ return this.managed(() => this.scanCollectionRows(collection, options));
2014
+ }
2015
+ scanIndex(collection, index, options = {}) {
2016
+ return this.managed(() => this.scanIndexRows(collection, index, options));
2017
+ }
2018
+ close(reason = /* @__PURE__ */ new Error("Query context is closed"), cleanup) {
1787
2019
  if (!this.active) return;
1788
2020
  this.active = false;
2021
+ clearTimeout(this.timer);
2022
+ this.cancellationReturns.clear();
1789
2023
  const cache = this.nodeCache.getMetrics();
1790
2024
  this.metrics.cacheHits = cache.hits;
1791
2025
  this.metrics.cacheMisses = cache.misses;
1792
2026
  this.metrics.durationMs = performance.now() - this.startedAt;
1793
2027
  this.controller.abort(reason);
1794
2028
  this.nodeCache.clear();
1795
- this.options.onClose?.();
2029
+ this.writes.clear();
2030
+ this.catalogValue.clear();
2031
+ this.snapshotValue = void 0;
2032
+ while (this.iterators > 0) this.end();
2033
+ const finish = () => {
2034
+ this.resources.close();
2035
+ this.options.onClose?.();
2036
+ };
2037
+ if (cleanup) {
2038
+ const pending = Promise.resolve().then(cleanup);
2039
+ this.options.onPendingCleanup?.(pending);
2040
+ pending.then(finish, (error) => {
2041
+ this.options.onCleanupFailure?.(error);
2042
+ finish();
2043
+ });
2044
+ } else finish();
1796
2045
  }
1797
2046
  cancel(reason = /* @__PURE__ */ new Error("Query cancelled")) {
1798
- this.close(reason);
2047
+ const callbacks = [...this.cancellationReturns];
2048
+ this.cancellationReturns.clear();
2049
+ this.close(reason, callbacks.length ? async () => {
2050
+ const errors = (await Promise.allSettled(callbacks.map((callback) => Promise.resolve().then(callback)))).filter((result) => result.status == "rejected").map((result) => result.reason);
2051
+ if (errors.length) throw new AggregateError(errors, "Query iterator cleanup failed");
2052
+ } : void 0);
1799
2053
  }
1800
2054
  assertActive() {
2055
+ this.options.assertAccess?.();
1801
2056
  if (!this.active) throw this.controller.signal.reason ?? /* @__PURE__ */ new Error("Query context is closed");
1802
2057
  }
1803
2058
  begin() {
1804
2059
  this.assertActive();
2060
+ this.iteratorReservations.push(this.resources.reserve({ iterators: this.iterators ? 1 : 0 }));
1805
2061
  this.iterators++;
1806
2062
  this.options.onIteratorStart?.();
1807
2063
  }
1808
2064
  end() {
1809
- if (this.iterators > 0) this.iterators--;
2065
+ if (this.iterators == 0) return;
2066
+ this.iterators--;
2067
+ this.iteratorReservations.pop()?.release();
1810
2068
  this.options.onIteratorEnd?.();
1811
2069
  }
1812
2070
  schema(collection) {
@@ -1833,7 +2091,7 @@ var QueryContext = class {
1833
2091
  }
1834
2092
  return result;
1835
2093
  }
1836
- async *scanCollection(collection, options = {}) {
2094
+ async *scanCollectionRows(collection, options = {}) {
1837
2095
  this.begin();
1838
2096
  try {
1839
2097
  this.schema(collection);
@@ -1869,6 +2127,7 @@ var QueryContext = class {
1869
2127
  if (parsed && !pending.has(parsed.id)) break;
1870
2128
  next = await committed.next();
1871
2129
  }
2130
+ if (next.done && pendingIndex >= pendingRows.length) break;
1872
2131
  const staged = pendingRows[pendingIndex];
1873
2132
  const committedKey = next.done ? void 0 : new TextEncoder().encode(next.value.key);
1874
2133
  const usePending = staged != null && (committedKey == null || compareBytes(staged.key, committedKey) * (direction == "ASC" ? 1 : -1) <= 0);
@@ -1910,6 +2169,8 @@ var QueryContext = class {
1910
2169
  const bounds = secondaryIndexBounds(index, options);
1911
2170
  const matches = (key) => (bounds.gt == null || compareBytes(key, bounds.gt) > 0) && (bounds.gte == null || compareBytes(key, bounds.gte) >= 0) && (bounds.lt == null || compareBytes(key, bounds.lt) < 0) && (bounds.lte == null || compareBytes(key, bounds.lte) <= 0);
1912
2171
  const result = [];
2172
+ let bytes = 0;
2173
+ const memory = this.resources.reserve({});
1913
2174
  for (const [id, write] of this.pendingFor(collection)) {
1914
2175
  if (write.type != "put") continue;
1915
2176
  const document = decodeDocument(write.data);
@@ -1925,21 +2186,53 @@ var QueryContext = class {
1925
2186
  }
1926
2187
  if (missing) continue;
1927
2188
  const key = encodeSecondaryKey(values, index.unique ? void 0 : id, orders);
1928
- if (matches(key)) result.push({
1929
- key,
1930
- row: {
1931
- id,
1932
- document
1933
- }
1934
- });
2189
+ if (matches(key)) {
2190
+ bytes += estimateBytes(document) + key.byteLength + id.length * 2;
2191
+ memory.resize({ workingBytes: bytes });
2192
+ result.push({
2193
+ key,
2194
+ row: {
2195
+ id,
2196
+ document
2197
+ }
2198
+ });
2199
+ }
1935
2200
  }
1936
2201
  return result;
1937
2202
  }
1938
- async *scanIndex(collection, indexName, options = {}) {
2203
+ async *scanIndexRows(collection, indexName, options = {}) {
1939
2204
  this.begin();
1940
2205
  try {
1941
- this.schema(collection);
1942
- if (!this.snapshot.manifest.catalog.get(collection)?.indexes.some((index) => index.name == indexName)) throw new Error(`Index is not available in captured snapshot: ${collection}/${indexName}`);
2206
+ const schema = this.schema(collection);
2207
+ if (!schema.indexes.some((index) => index.name == indexName)) throw new Error(`Index is not available in captured snapshot: ${collection}/${indexName}`);
2208
+ const previous = this.snapshot.manifest.catalog.get(collection);
2209
+ if (JSON.stringify(previous) != JSON.stringify(schema)) {
2210
+ const index = schema.indexes.find((item) => item.name == indexName);
2211
+ if (!index) throw new Error(`Unknown index: ${collection}/${indexName}`);
2212
+ const parts = indexFields(index);
2213
+ const bounds = secondaryIndexBounds(index, options);
2214
+ const entries = [];
2215
+ const memory = this.resources.reserve({});
2216
+ let bytes = 0;
2217
+ for await (const row of this.scanCollection(collection, { signal: options.signal })) {
2218
+ const values = parts.map((part) => indexedValue(row.document, part.field, fieldDefinition(schema, part.field)));
2219
+ if (values.some((value) => value === void 0)) continue;
2220
+ const key = encodeSecondaryKey(values, index.unique ? void 0 : row.id, parts.map((part) => part.order));
2221
+ if ((bounds.gt == null || compareBytes(key, bounds.gt) > 0) && (bounds.gte == null || compareBytes(key, bounds.gte) >= 0) && (bounds.lt == null || compareBytes(key, bounds.lt) < 0) && (bounds.lte == null || compareBytes(key, bounds.lte) <= 0)) {
2222
+ bytes += estimateBytes(row) + key.byteLength;
2223
+ memory.resize({ workingBytes: bytes });
2224
+ entries.push({
2225
+ key,
2226
+ row
2227
+ });
2228
+ }
2229
+ }
2230
+ const limit = options.limit ?? Number.MAX_SAFE_INTEGER;
2231
+ if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid query limit");
2232
+ entries.sort((a, b) => compareBytes(a.key, b.key) * (options.direction == "DESC" ? -1 : 1));
2233
+ for (const entry of entries.slice(0, limit)) yield entry.row;
2234
+ return;
2235
+ }
1943
2236
  const limit = options.limit ?? Number.MAX_SAFE_INTEGER;
1944
2237
  if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid query limit");
1945
2238
  if (limit == 0) return;
@@ -1960,6 +2253,7 @@ var QueryContext = class {
1960
2253
  if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
1961
2254
  this.assertActive();
1962
2255
  while (!next.done && pending.has(next.value.id)) next = await committed.next();
2256
+ if (next.done && stagedIndex >= staged.length) break;
1963
2257
  const pendingEntry = staged[stagedIndex];
1964
2258
  const usePending = pendingEntry != null && (next.done || compareBytes(pendingEntry.key, next.value.key) * (direction == "ASC" ? 1 : -1) <= 0);
1965
2259
  let row;
@@ -1988,6 +2282,293 @@ var QueryContext = class {
1988
2282
  }
1989
2283
  }
1990
2284
  };
2285
+ // src/errors/transaction-conflict.error.ts
2286
+ var TransactionConflictError = class extends Error {
2287
+ message;
2288
+ constructor(message = "Transaction conflict: snapshot is stale") {
2289
+ super(message);
2290
+ this.message = message;
2291
+ this.name = "TransactionConflictError";
2292
+ }
2293
+ };
2294
+ // src/errors/commit-outcome-unknown.error.ts
2295
+ var CommitOutcomeUnknownError = class extends Error {
2296
+ transactionId;
2297
+ constructor(transactionId, cause) {
2298
+ super(`Commit outcome is unknown for transaction ${transactionId}; reconcile before retrying`, { cause });
2299
+ this.name = "CommitOutcomeUnknownError";
2300
+ this.transactionId = transactionId;
2301
+ }
2302
+ };
2303
+ // src/relations/foreign-key-manager.ts
2304
+ var MAX_CASCADE_OPERATIONS = 1e5;
2305
+ var ForeignKeyManager = class {
2306
+ #primary;
2307
+ #secondary;
2308
+ constructor(storage, keys = new StorageKeyManager()) {
2309
+ this.#primary = new PrimaryIndex(storage, keys);
2310
+ this.#secondary = new SecondaryIndexManager(storage, keys);
2311
+ }
2312
+ async prepare(snapshot, sourceWrites, sourceCatalog, targetWrites) {
2313
+ const catalog = this.validateCatalog(sourceCatalog);
2314
+ const writes = targetWrites ?? new Map(sourceWrites);
2315
+ const incoming = this.incoming(catalog);
2316
+ const queue = [];
2317
+ const visited = /* @__PURE__ */ new Set();
2318
+ for (const [key, operation] of writes) {
2319
+ const parsed = parseRecordKey(key);
2320
+ if (parsed && operation.type == "delete") queue.push(parsed);
2321
+ }
2322
+ for (let offset = 0; offset < queue.length; offset++) {
2323
+ if (visited.size > MAX_CASCADE_OPERATIONS) throw new Error("Foreign-key cascade operation limit exceeded");
2324
+ const parent = queue[offset];
2325
+ const parentKey = recordKey(parent.collection, parent.id);
2326
+ if (visited.has(parentKey)) continue;
2327
+ visited.add(parentKey);
2328
+ for (const relation of incoming.get(parent.collection) ?? []) {
2329
+ const childIds = await this.childIds(snapshot, writes, relation, parent.id);
2330
+ for (const childId of childIds) {
2331
+ const childKey = recordKey(relation.collection, childId);
2332
+ const document = await this.finalDocument(snapshot, writes, relation.collection, childId);
2333
+ if (!document || document[relation.foreignKey.field] !== parent.id) continue;
2334
+ switch (relation.foreignKey.onDelete) {
2335
+ case "RESTRICT": throw new ReferencedRecordRestrictedError(relation.collection, relation.foreignKey.name, `${parent.collection}/${parent.id}`);
2336
+ case "CASCADE":
2337
+ writes.set(childKey, { type: "delete" });
2338
+ queue.push({
2339
+ collection: relation.collection,
2340
+ id: childId
2341
+ });
2342
+ break;
2343
+ case "SET_NULL": {
2344
+ const next = {
2345
+ ...document,
2346
+ [relation.foreignKey.field]: null
2347
+ };
2348
+ writes.set(childKey, {
2349
+ type: "put",
2350
+ data: encodeDocument(validateDocument(relation.schema, next))
2351
+ });
2352
+ break;
2353
+ }
2354
+ }
2355
+ }
2356
+ }
2357
+ }
2358
+ for (const [key, operation] of writes) {
2359
+ const parsed = parseRecordKey(key);
2360
+ if (!parsed || operation.type != "put") continue;
2361
+ const schema = catalog.get(parsed.collection);
2362
+ if (!schema) throw new InvalidForeignKeyDefinitionError(`Unknown collection: ${parsed.collection}`);
2363
+ const document = decodeDocument(operation.data);
2364
+ for (const foreignKey of schema.foreignKeys ?? []) {
2365
+ const definition = fieldDefinition(schema, foreignKey.field);
2366
+ const value = document[foreignKey.field];
2367
+ if (value == null) {
2368
+ if (value === null && definition.nullable) continue;
2369
+ if (value === void 0 && !definition.required) continue;
2370
+ throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, String(value));
2371
+ }
2372
+ if (typeof value != "string" || !await this.finalRecordExists(snapshot, writes, foreignKey.references.collection, value)) throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, `${foreignKey.references.collection}/${String(value)}`);
2373
+ }
2374
+ }
2375
+ return writes;
2376
+ }
2377
+ validateCatalog(source) {
2378
+ const catalog = /* @__PURE__ */ new Map();
2379
+ try {
2380
+ for (const [name, definition] of source) catalog.set(name, normalizeCollection(definition));
2381
+ } catch (cause) {
2382
+ throw new InvalidForeignKeyDefinitionError(cause instanceof Error ? cause.message : "Invalid foreign key definition");
2383
+ }
2384
+ for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) if (!catalog.has(foreignKey.references.collection)) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} references unknown collection ${foreignKey.references.collection}`);
2385
+ return catalog;
2386
+ }
2387
+ incoming(catalog) {
2388
+ const result = /* @__PURE__ */ new Map();
2389
+ for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) {
2390
+ const index = schema.indexes.find((candidate) => {
2391
+ const parts = indexFields(candidate);
2392
+ return parts.length == 1 && parts[0].field == foreignKey.field;
2393
+ });
2394
+ if (!index) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} has no supporting index`);
2395
+ const values = result.get(foreignKey.references.collection) ?? [];
2396
+ values.push({
2397
+ collection,
2398
+ schema,
2399
+ foreignKey,
2400
+ index: index.name
2401
+ });
2402
+ result.set(foreignKey.references.collection, values);
2403
+ }
2404
+ for (const values of result.values()) values.sort((left, right) => `${left.collection}/${left.foreignKey.name}`.localeCompare(`${right.collection}/${right.foreignKey.name}`));
2405
+ return result;
2406
+ }
2407
+ async childIds(snapshot, writes, relation, parentId) {
2408
+ const result = /* @__PURE__ */ new Set();
2409
+ const previousIndex = snapshot.manifest.catalog.get(relation.collection)?.indexes.find((index) => index.name == relation.index);
2410
+ const compatible = previousIndex && indexFields(previousIndex).length == 1 && indexFields(previousIndex)[0].field == relation.foreignKey.field;
2411
+ if (compatible) for await (const entry of this.#secondary.scanIds(snapshot.manifest, relation.collection, relation.index, { eq: parentId })) result.add(entry.id);
2412
+ if (!compatible) {
2413
+ const prefix = new TextEncoder().encode(`${RECORD_PREFIX}${relation.collection}/`);
2414
+ const end = prefixSuccessor(prefix);
2415
+ for await (const entry of this.#primary.scanReferences(snapshot.manifest.primaryRoot, {
2416
+ gte: prefix,
2417
+ ...end ? { lt: end } : {}
2418
+ })) {
2419
+ const parsed = parseRecordKey(entry.key);
2420
+ if (decodeDocument(await this.#primary.readObject(entry.ref))[relation.foreignKey.field] === parentId) result.add(parsed.id);
2421
+ }
2422
+ }
2423
+ for (const [key, operation] of writes) {
2424
+ const parsed = parseRecordKey(key);
2425
+ if (!parsed || parsed.collection != relation.collection) continue;
2426
+ if (operation.type == "delete") result.delete(parsed.id);
2427
+ else if (decodeDocument(operation.data)[relation.foreignKey.field] === parentId) result.add(parsed.id);
2428
+ else result.delete(parsed.id);
2429
+ }
2430
+ return result;
2431
+ }
2432
+ async finalRecordExists(snapshot, writes, collection, id) {
2433
+ return await this.finalDocument(snapshot, writes, collection, id) != null;
2434
+ }
2435
+ async finalDocument(snapshot, writes, collection, id) {
2436
+ const key = recordKey(collection, id);
2437
+ const pending = writes.get(key);
2438
+ if (pending) return pending.type == "delete" ? null : decodeDocument(pending.data);
2439
+ const stored = await this.#primary.read(snapshot.manifest, key);
2440
+ return stored == null ? null : decodeDocument(stored);
2441
+ }
2442
+ };
2443
+ // src/commit/commit-coordinator.ts
2444
+ var CommitCoordinator = class {
2445
+ storage;
2446
+ keys;
2447
+ coordinationStorage;
2448
+ primary;
2449
+ secondary;
2450
+ foreignKeys;
2451
+ constructor(storage, keys = new StorageKeyManager(), coordinationStorage = storage) {
2452
+ this.storage = storage;
2453
+ this.keys = keys;
2454
+ this.coordinationStorage = coordinationStorage;
2455
+ this.primary = new PrimaryIndex(storage, keys);
2456
+ this.secondary = new SecondaryIndexManager(storage, keys);
2457
+ this.foreignKeys = new ForeignKeyManager(storage, keys);
2458
+ }
2459
+ async commit(transaction) {
2460
+ const admission = transaction.resources.reserve({ queuedOperations: 1 });
2461
+ try {
2462
+ return await coordinateCommit(this.coordinationStorage, transaction.limits.maxQueuedOperations, async () => {
2463
+ if (transaction.hasChanges) {
2464
+ if (((await this.storage.get(this.keys.manifestKey))?.version ?? null) != transaction.expectedStorageVersion) throw new TransactionConflictError();
2465
+ }
2466
+ await this.publish(transaction);
2467
+ });
2468
+ } finally {
2469
+ admission.release();
2470
+ }
2471
+ }
2472
+ async publish(transaction) {
2473
+ const prepared = transaction.prepareForCommit();
2474
+ if (prepared.writes.size == 0 && prepared.schemaChanges.size == 0) {
2475
+ transaction.markCommitted();
2476
+ return;
2477
+ }
2478
+ const transactionId = transaction.id;
2479
+ const catalog = new Map(prepared.snapshot.manifest.catalog);
2480
+ const staged = new PreparedWrites(transaction.resources, transaction.limits, prepared.writes);
2481
+ for (const [name, schema] of prepared.schemaChanges) {
2482
+ if (schema == null) catalog.delete(name);
2483
+ else catalog.set(name, schema);
2484
+ const previous = prepared.snapshot.manifest.catalog.get(name);
2485
+ if (!(schema == null || !previous || JSON.stringify(previous.fields) != JSON.stringify(schema.fields) || previous.allowAdditionalFields != schema.allowAdditionalFields || JSON.stringify(previous.foreignKeys) != JSON.stringify(schema.foreignKeys))) continue;
2486
+ const scanCatalog = new Map(catalog);
2487
+ if (schema == null) scanCatalog.set(name, prepared.snapshot.manifest.catalog.get(name) ?? {
2488
+ name,
2489
+ indexes: []
2490
+ });
2491
+ const context = new QueryContext(this.storage, prepared.snapshot, this.keys, {
2492
+ writes: staged,
2493
+ catalog: scanCatalog,
2494
+ resources: transaction.resources,
2495
+ limits: transaction.limits
2496
+ });
2497
+ try {
2498
+ for await (const row of context.scanCollection(name)) staged.set(recordKey(name, row.id), schema == null ? { type: "delete" } : {
2499
+ type: "put",
2500
+ data: encodeDocument(validateDocument(schema, row.document))
2501
+ });
2502
+ } finally {
2503
+ context.close();
2504
+ }
2505
+ }
2506
+ const writes = await this.foreignKeys.prepare(prepared.snapshot, staged, catalog, staged);
2507
+ for (const [key, value] of writes) if (!staged.has(key)) staged.set(key, value);
2508
+ const changes = /* @__PURE__ */ new Map();
2509
+ for (const [key, operation] of writes) {
2510
+ if (operation.type == "delete") {
2511
+ changes.set(key, null);
2512
+ continue;
2513
+ }
2514
+ const ref = this.keys.objectKey(operation.data);
2515
+ if (!(await this.storage.put(ref, operation.data, { condition: { type: "if-absent" } })).success) throw new Error("Unexpected immutable object key collision");
2516
+ changes.set(key, ref);
2517
+ }
2518
+ const primaryRoot = await this.primary.prepare(prepared.snapshot.manifest.primaryRoot, changes);
2519
+ const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog, transaction.resources);
2520
+ const commitBytes = encodeCommitRecord({
2521
+ format: 1,
2522
+ transactionId,
2523
+ previous: prepared.snapshot.manifest.commitHead
2524
+ });
2525
+ const commitKey = this.keys.commitKey(transactionId, commitBytes);
2526
+ if (!(await this.storage.put(commitKey, commitBytes, { condition: { type: "if-absent" } })).success) throw new Error("Unexpected commit record collision");
2527
+ const manifestBytes = encodeManifest({
2528
+ format: 1,
2529
+ transactionId,
2530
+ commitHead: commitKey,
2531
+ primaryRoot,
2532
+ indexRoots,
2533
+ catalog
2534
+ }, this.keys);
2535
+ transaction.beginPublication();
2536
+ let result;
2537
+ try {
2538
+ result = await this.storage.put(this.keys.manifestKey, manifestBytes, { condition: prepared.snapshot.storageVersion == null ? { type: "if-absent" } : {
2539
+ type: "if-version",
2540
+ version: prepared.snapshot.storageVersion
2541
+ } });
2542
+ } catch (cause) {
2543
+ transaction.markUnknown();
2544
+ throw new CommitOutcomeUnknownError(transactionId, cause);
2545
+ }
2546
+ if (!result.success) {
2547
+ transaction.rejectPublication();
2548
+ throw new TransactionConflictError();
2549
+ }
2550
+ transaction.markCommitted();
2551
+ }
2552
+ };
2553
+ // src/snapshots/snapshot-reader.ts
2554
+ var ManifestSnapshotReader = class {
2555
+ snapshot;
2556
+ primary;
2557
+ constructor(storage, snapshot, keys) {
2558
+ this.snapshot = snapshot;
2559
+ this.primary = new PrimaryIndex(storage, keys);
2560
+ }
2561
+ async get(key) {
2562
+ return this.primary.read(this.snapshot.manifest, key);
2563
+ }
2564
+ };
2565
+ // src/errors/transaction-state.error.ts
2566
+ var TransactionStateError = class extends Error {
2567
+ constructor(message) {
2568
+ super(message);
2569
+ this.name = "TransactionStateError";
2570
+ }
2571
+ };
1991
2572
  // src/query/model/cursor.ts
1992
2573
  function canonical(value) {
1993
2574
  if (value instanceof Date) return JSON.stringify(value.toISOString());
@@ -2016,7 +2597,7 @@ function hmac(key, value) {
2016
2597
  function queryHash(key, query) {
2017
2598
  return hmac(key, canonical(shape(query)));
2018
2599
  }
2019
- function encodeQueryCursor(generation, schema, query, row, signingKey) {
2600
+ function encodeLegacyCursor(generation, schema, query, row, signingKey) {
2020
2601
  if (query.collection != schema.name) throw new Error("Cursor collection mismatch");
2021
2602
  const values = (query.orderBy ?? []).map(({ field }) => {
2022
2603
  if (field == "$id") return row.id;
@@ -2039,7 +2620,7 @@ function encodeQueryCursor(generation, schema, query, row, signingKey) {
2039
2620
  signature: hmac(signingKey, payload)
2040
2621
  })).toString("base64url");
2041
2622
  }
2042
- function decodeQueryCursor(cursor, generation, schema, query, signingKey) {
2623
+ function decodeLegacyCursor(cursor, generation, schema, query, signingKey) {
2043
2624
  let parsed;
2044
2625
  try {
2045
2626
  parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
@@ -2067,6 +2648,108 @@ function decodeQueryCursor(cursor, generation, schema, query, signingKey) {
2067
2648
  })
2068
2649
  };
2069
2650
  }
2651
+ function cursorKeys(value) {
2652
+ if (value instanceof Uint8Array) {
2653
+ if (value.byteLength < 32) throw new Error("Cursor key must contain at least 32 bytes");
2654
+ return {
2655
+ activeKeyId: "default",
2656
+ keys: { default: (0, node_crypto.createHash)("sha256").update(value).digest() },
2657
+ ttlMs: 9e5
2658
+ };
2659
+ }
2660
+ if (!value || !/^[A-Za-z0-9_-]{1,32}$/.test(value.activeKeyId) || !Object.hasOwn(value.keys, value.activeKeyId)) throw new Error("Invalid cursor keyring");
2661
+ for (const [id, key] of Object.entries(value.keys)) if (!/^[A-Za-z0-9_-]{1,32}$/.test(id) || !(key instanceof Uint8Array) || key.byteLength != 32) throw new Error("Cursor encryption keys must contain exactly 32 bytes");
2662
+ if (Object.keys(value.keys).length > 16) throw new Error("Cursor keyring is too large");
2663
+ if (value.ttlMs !== void 0 && (!Number.isSafeInteger(value.ttlMs) || value.ttlMs < 1)) throw new Error("Invalid cursor expiry");
2664
+ return value;
2665
+ }
2666
+ function encodeQueryCursor(generation, schema, query, row, keys, namespace = "") {
2667
+ const ring = cursorKeys(keys);
2668
+ const key = ring.keys[ring.activeKeyId];
2669
+ const legacy = JSON.parse(Buffer.from(encodeLegacyCursor(generation, schema, query, row, key), "base64url").toString());
2670
+ const nonce = (0, node_crypto.randomBytes)(12);
2671
+ const cipher = (0, node_crypto.createCipheriv)("aes-256-gcm", key, nonce);
2672
+ cipher.setAAD(Buffer.from(canonical({
2673
+ version: 3,
2674
+ keyId: ring.activeKeyId,
2675
+ namespace
2676
+ })));
2677
+ const payload = JSON.stringify({
2678
+ ...legacy.payload,
2679
+ version: 3,
2680
+ namespace,
2681
+ expiresAt: Date.now() + (ring.ttlMs ?? 9e5)
2682
+ });
2683
+ const ciphertext = Buffer.concat([cipher.update(payload, "utf8"), cipher.final()]);
2684
+ const cursor = Buffer.from(JSON.stringify({
2685
+ version: 3,
2686
+ keyId: ring.activeKeyId,
2687
+ nonce: nonce.toString("base64url"),
2688
+ ciphertext: ciphertext.toString("base64url"),
2689
+ tag: cipher.getAuthTag().toString("base64url")
2690
+ })).toString("base64url");
2691
+ if (cursor.length > 16384) throw new Error("Query cursor exceeds maximum size");
2692
+ return cursor;
2693
+ }
2694
+ function decodeQueryCursor(cursor, generation, schema, query, keys, namespace = "") {
2695
+ if (typeof cursor != "string" || !cursor.length || cursor.length > 16384 || !/^[A-Za-z0-9_-]+$/.test(cursor)) throw new Error("Invalid query cursor");
2696
+ const ring = cursorKeys(keys);
2697
+ let outer;
2698
+ try {
2699
+ outer = JSON.parse(Buffer.from(cursor, "base64url").toString());
2700
+ } catch {
2701
+ throw new Error("Invalid query cursor");
2702
+ }
2703
+ if (!outer || typeof outer != "object" || Array.isArray(outer)) throw new Error("Invalid query cursor");
2704
+ if (outer.version !== 3) {
2705
+ if (!namespace && ring.allowLegacySigned && ring.legacySigningKey) return decodeLegacyCursor(cursor, generation, schema, query, ring.legacySigningKey);
2706
+ throw new Error("Legacy signed cursors are disabled; restart pagination");
2707
+ }
2708
+ if (Object.keys(outer).sort().join(",") != "ciphertext,keyId,nonce,tag,version" || typeof outer.keyId != "string" || !Object.hasOwn(ring.keys, outer.keyId)) throw new Error("Invalid query cursor");
2709
+ const binary = (value) => {
2710
+ if (typeof value != "string" || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("Invalid query cursor");
2711
+ const result = Buffer.from(value, "base64url");
2712
+ if (result.toString("base64url") != value) throw new Error("Invalid query cursor");
2713
+ return result;
2714
+ };
2715
+ const nonce = binary(outer.nonce);
2716
+ const tag = binary(outer.tag);
2717
+ const ciphertext = binary(outer.ciphertext);
2718
+ if (nonce.length != 12 || tag.length != 16) throw new Error("Invalid query cursor");
2719
+ const key = ring.keys[outer.keyId];
2720
+ let payload;
2721
+ try {
2722
+ const decipher = (0, node_crypto.createDecipheriv)("aes-256-gcm", key, nonce);
2723
+ decipher.setAAD(Buffer.from(canonical({
2724
+ version: 3,
2725
+ keyId: outer.keyId,
2726
+ namespace
2727
+ })));
2728
+ decipher.setAuthTag(tag);
2729
+ payload = JSON.parse(Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString());
2730
+ } catch {
2731
+ throw new Error("Invalid query cursor authentication");
2732
+ }
2733
+ if (!payload || typeof payload != "object" || Array.isArray(payload)) throw new Error("Invalid query cursor payload");
2734
+ if (payload.version != 3 || payload.namespace != namespace || typeof payload.expiresAt != "number" || !Number.isSafeInteger(payload.expiresAt) || payload.expiresAt <= Date.now()) throw new Error("Invalid or expired query cursor");
2735
+ if (payload.generation != generation) throw new Error("Query cursor snapshot generation is unavailable");
2736
+ if (payload.queryHash != queryHash(key, query) || query.collection != schema.name) throw new Error("Query cursor is incompatible with this query");
2737
+ if (typeof payload.id != "string" || !payload.id.length || Buffer.byteLength(payload.id) > 512 || !Array.isArray(payload.values) || payload.values.length != (query.orderBy ?? []).length) throw new Error("Invalid query cursor payload");
2738
+ const values = payload.values.map((value, index) => {
2739
+ if (value && typeof value == "object" && Object.keys(value).join(",") == "missing" && value.missing === true) return void 0;
2740
+ if (value !== null && typeof value != "string" && typeof value != "boolean" && (typeof value != "number" || !Number.isFinite(value))) throw new Error("Invalid cursor scalar");
2741
+ if (fieldDefinition(schema, query.orderBy[index].field)?.type == "date" && typeof value == "string") {
2742
+ const date = new Date(value);
2743
+ if (!Number.isFinite(date.getTime()) || date.toISOString() != value) throw new Error("Invalid cursor date");
2744
+ return date;
2745
+ }
2746
+ return value;
2747
+ });
2748
+ return {
2749
+ id: payload.id,
2750
+ values
2751
+ };
2752
+ }
2070
2753
  // src/query/validation/query-validator.ts
2071
2754
  var MAX_PREDICATE_DEPTH = 64;
2072
2755
  var MAX_IN_VALUES = 1e4;
@@ -2137,10 +2820,36 @@ function predicate(schema, value, depth) {
2137
2820
  default: throw new Error("Unknown query predicate");
2138
2821
  }
2139
2822
  }
2140
- function validateQuery(query, catalog) {
2823
+ function validatePredicateComplexity(query, maxDepth = 32, maxNodes = 4096) {
2824
+ const stack = [{
2825
+ value: query.where,
2826
+ depth: 0
2827
+ }];
2828
+ let count = 0;
2829
+ while (stack.length) {
2830
+ const { value, depth } = stack.pop();
2831
+ if (value == null) continue;
2832
+ if (++count > maxNodes || depth > maxDepth) throw new Error("Query predicate complexity limit exceeded");
2833
+ if (!value || typeof value != "object") throw new Error("Invalid query predicate");
2834
+ const node = value;
2835
+ if (Array.isArray(node.predicates)) {
2836
+ if (node.predicates.length + count + stack.length > maxNodes) throw new Error("Query predicate complexity limit exceeded");
2837
+ for (const child of node.predicates) stack.push({
2838
+ value: child,
2839
+ depth: depth + 1
2840
+ });
2841
+ }
2842
+ if (node.predicate) stack.push({
2843
+ value: node.predicate,
2844
+ depth: depth + 1
2845
+ });
2846
+ }
2847
+ }
2848
+ function validateQuery(query, catalog, limits) {
2141
2849
  if (!query || typeof query != "object" || !isValidSchemaName(query.collection)) throw new Error("Invalid logical query");
2142
2850
  const schema = catalog.get(query.collection);
2143
2851
  if (!schema) throw new Error(`Unknown collection: ${query.collection}`);
2852
+ validatePredicateComplexity(query, limits?.maxPredicateDepth, limits?.maxPredicateNodes);
2144
2853
  if (query.where) predicate(schema, query.where, 0);
2145
2854
  const orders = /* @__PURE__ */ new Set();
2146
2855
  for (const order of query.orderBy ?? []) {
@@ -2355,12 +3064,24 @@ var Sort = class {
2355
3064
  const maximum = this.options.maxRowsInMemory ?? 1e4;
2356
3065
  if (!Number.isSafeInteger(maximum) || maximum < 2) throw new Error("Invalid sort memory limit");
2357
3066
  const compare = (a, b) => compareRows(schema, this.orders, a, b);
3067
+ const memory = context.resources.child({});
3068
+ const chunkMemory = memory.reserve({});
3069
+ let chunkBytes = 0;
3070
+ let spilledBytes = 0;
3071
+ const disk = memory.reserve({});
2358
3072
  const spill = this.options.spill;
2359
3073
  let chunk = [];
2360
3074
  let runs = [];
2361
3075
  const active = /* @__PURE__ */ new Set();
2362
3076
  const write = async (rows) => {
2363
- const handle = await spill.write(rows);
3077
+ const bounded = async function* () {
3078
+ for await (const row of rows) {
3079
+ spilledBytes += estimateBytes(row);
3080
+ disk.resize({ spillBytes: spilledBytes });
3081
+ yield row;
3082
+ }
3083
+ };
3084
+ const handle = await spill.write(bounded());
2364
3085
  active.add(handle);
2365
3086
  return handle;
2366
3087
  };
@@ -2382,12 +3103,24 @@ var Sort = class {
2382
3103
  };
2383
3104
  try {
2384
3105
  for await (const row of this.input.execute(context)) {
3106
+ const size = estimateBytes(row);
3107
+ if (chunkBytes + size > Math.floor(context.limits.maxQueryWorkingBytes / 2) && chunk.length && spill) {
3108
+ chunk.sort(compare);
3109
+ runs.push(await write(chunk));
3110
+ chunk = [];
3111
+ chunkBytes = 0;
3112
+ chunkMemory.resize({});
3113
+ }
3114
+ chunkMemory.resize({ workingBytes: chunkBytes + size });
3115
+ chunkBytes += size;
2385
3116
  chunk.push(row);
2386
3117
  if (chunk.length < maximum) continue;
2387
3118
  if (!this.options.spill) throw new QueryMemoryLimitError();
2388
3119
  chunk.sort(compare);
2389
3120
  runs.push(await write(chunk));
2390
3121
  chunk = [];
3122
+ chunkBytes = 0;
3123
+ chunkMemory.resize({});
2391
3124
  }
2392
3125
  if (runs.length == 0) {
2393
3126
  chunk.sort(compare);
@@ -2414,7 +3147,12 @@ var Sort = class {
2414
3147
  }
2415
3148
  yield* merge(runs);
2416
3149
  } finally {
2417
- await Promise.all([...active].map((handle) => spill.delete(handle)));
3150
+ try {
3151
+ const failures = (await Promise.allSettled([...active].map((handle) => spill.delete(handle)))).filter((r) => r.status == "rejected");
3152
+ if (failures.length) throw new AggregateError(failures.map((r) => r.reason), "Sort spill cleanup failed");
3153
+ } finally {
3154
+ memory.close();
3155
+ }
2418
3156
  }
2419
3157
  }
2420
3158
  };
@@ -2471,9 +3209,15 @@ var SetOperator = class {
2471
3209
  }
2472
3210
  async ids(context, input) {
2473
3211
  const result = /* @__PURE__ */ new Map();
3212
+ const memory = context.resources.reserve({});
3213
+ let bytes = 0;
2474
3214
  for await (const row of input.execute(context)) {
2475
3215
  context.assertActive();
2476
3216
  if (result.size >= this.maxSetEntries && !result.has(row.id)) throw new QueryMemoryLimitError();
3217
+ if (!result.has(row.id)) {
3218
+ bytes += estimateBytes(row);
3219
+ memory.resize({ workingBytes: bytes });
3220
+ }
2477
3221
  result.set(row.id, row);
2478
3222
  }
2479
3223
  return result;
@@ -2483,10 +3227,14 @@ var Union = class extends SetOperator {
2483
3227
  name = "Union";
2484
3228
  async *execute(context) {
2485
3229
  const seen = /* @__PURE__ */ new Set();
3230
+ const memory = context.resources.reserve({});
3231
+ let bytes = 0;
2486
3232
  for (const input of this.inputs) for await (const row of input.execute(context)) {
2487
3233
  context.assertActive();
2488
3234
  if (seen.has(row.id)) continue;
2489
3235
  if (seen.size >= this.maxSetEntries) throw new QueryMemoryLimitError();
3236
+ bytes += row.id.length * 2 + 48;
3237
+ memory.resize({ workingBytes: bytes });
2490
3238
  seen.add(row.id);
2491
3239
  yield row;
2492
3240
  }
@@ -2499,7 +3247,7 @@ var Intersection = class extends SetOperator {
2499
3247
  const candidates = await this.ids(context, first);
2500
3248
  for (const input of rest) {
2501
3249
  const current = await this.ids(context, input);
2502
- for (const id of [...candidates.keys()]) if (!current.has(id)) candidates.delete(id);
3250
+ for (const id of candidates.keys()) if (!current.has(id)) candidates.delete(id);
2503
3251
  }
2504
3252
  for (const row of candidates.values()) {
2505
3253
  context.assertActive();
@@ -2517,7 +3265,15 @@ var Difference = class extends SetOperator {
2517
3265
  this.excluded = excluded;
2518
3266
  }
2519
3267
  async *execute(context) {
2520
- const excluded = await this.ids(context, this.excluded);
3268
+ const excluded = /* @__PURE__ */ new Set();
3269
+ const memory = context.resources.reserve({});
3270
+ let bytes = 0;
3271
+ for await (const row of this.excluded.execute(context)) if (!excluded.has(row.id)) {
3272
+ if (excluded.size >= this.maxSetEntries) throw new QueryMemoryLimitError();
3273
+ bytes += row.id.length * 2 + 48;
3274
+ memory.resize({ workingBytes: bytes });
3275
+ excluded.add(row.id);
3276
+ }
2521
3277
  for await (const row of this.universe.execute(context)) {
2522
3278
  context.assertActive();
2523
3279
  if (!excluded.has(row.id)) yield row;
@@ -2583,7 +3339,7 @@ var QueryExecutor = class {
2583
3339
  }
2584
3340
  }
2585
3341
  semanticPipeline(context, query, source, forceDeterministicSort = false, executionLimit = query.limit) {
2586
- validateQuery(query, context.catalog);
3342
+ validateQuery(query, context.catalog, context.limits);
2587
3343
  let operator = source;
2588
3344
  if (query.where) operator = new Filter(operator, query.where, query.collection);
2589
3345
  const orderBy = query.orderBy ?? [];
@@ -2592,7 +3348,7 @@ var QueryExecutor = class {
2592
3348
  spill: this.options.sortSpill
2593
3349
  });
2594
3350
  if (query.cursor) {
2595
- const cursor = decodeQueryCursor(query.cursor, context.generation, context.catalog.get(query.collection), query, this.signingKey());
3351
+ const cursor = decodeQueryCursor(query.cursor, context.generation, context.catalog.get(query.collection), query, this.signingKey(), this.options.cursorNamespace);
2596
3352
  operator = new CursorAfter(operator, orderBy, cursor.values, cursor.id, query.collection);
2597
3353
  }
2598
3354
  if (executionLimit != null) operator = new Limit(operator, executionLimit);
@@ -2603,6 +3359,7 @@ var QueryExecutor = class {
2603
3359
  return produced?.deterministic == true && produced.fields.length == requested.length && produced.fields.every((field, index) => field.field == requested[index].field && field.direction == requested[index].direction);
2604
3360
  }
2605
3361
  signingKey() {
3362
+ if (this.options.cursorEncryption) return this.options.cursorEncryption;
2606
3363
  const key = this.options.cursorSigningKey;
2607
3364
  if (!(key instanceof Uint8Array) || key.byteLength < 32) throw new Error("Cursor operations require a signing key of at least 32 bytes");
2608
3365
  return key;
@@ -2616,11 +3373,19 @@ var QueryExecutor = class {
2616
3373
  const lookahead = query.limit == null ? void 0 : query.limit + 1;
2617
3374
  const operator = this.semanticPipeline(context, query, source, true, lookahead);
2618
3375
  const raw = [];
2619
- for await (const row of operator.execute(context)) raw.push(row);
3376
+ const results = materialize(context.resources, context.limits);
3377
+ try {
3378
+ for await (const row of operator.execute(context)) {
3379
+ results.add(row);
3380
+ raw.push(row);
3381
+ }
3382
+ } finally {
3383
+ results.close();
3384
+ }
2620
3385
  const schema = context.catalog.get(query.collection);
2621
3386
  const hasMore = query.limit != null && query.limit > 0 && raw.length > query.limit;
2622
3387
  if (hasMore) raw.pop();
2623
- const nextCursor = hasMore && raw.length ? encodeQueryCursor(context.generation, schema, query, raw[raw.length - 1], this.signingKey()) : null;
3388
+ const nextCursor = hasMore && raw.length ? encodeQueryCursor(context.generation, schema, query, raw[raw.length - 1], this.signingKey(), this.options.cursorNamespace) : null;
2624
3389
  return {
2625
3390
  rows: query.projection ? raw.map((row) => ({
2626
3391
  id: row.id,
@@ -2882,8 +3647,8 @@ var RuleBasedPlanner = class {
2882
3647
  constructor(enumerator = new AccessPathEnumerator()) {
2883
3648
  this.enumerator = enumerator;
2884
3649
  }
2885
- plan(query, catalog) {
2886
- const schema = validateQuery(query, catalog);
3650
+ plan(query, catalog, limits) {
3651
+ const schema = validateQuery(query, catalog, limits);
2887
3652
  const selected = this.choose(query, schema, query.where);
2888
3653
  const required = query.orderBy ?? [];
2889
3654
  const requiresSort = required.length > 0 && (!selected.access.deterministicOrdering || selected.access.producedOrdering.length != required.length || selected.access.producedOrdering.some((item, index) => item.field != required[index].field || item.direction != required[index].direction));
@@ -3020,23 +3785,70 @@ var Transaction = class {
3020
3785
  storage;
3021
3786
  keys;
3022
3787
  cursorSigningKey;
3788
+ operationSignal;
3789
+ onPublication;
3790
+ assertAccessScope;
3791
+ runtimeHooks;
3792
+ id = (0, node_crypto.randomUUID)();
3793
+ pendingCleanup = /* @__PURE__ */ new Set();
3794
+ localCancellation = new AbortController();
3795
+ signal;
3796
+ resources;
3797
+ limits;
3798
+ writeReservations = /* @__PURE__ */ new Map();
3799
+ schemaReservations = /* @__PURE__ */ new Map();
3023
3800
  writes = /* @__PURE__ */ new Map();
3024
3801
  schemas = /* @__PURE__ */ new Map();
3025
- capturedSnapshot;
3026
- reader;
3802
+ snapshotValue;
3803
+ get capturedSnapshot() {
3804
+ if (!this.snapshotValue) throw new TransactionStateError("Transaction is closed");
3805
+ return this.snapshotValue;
3806
+ }
3807
+ set capturedSnapshot(value) {
3808
+ this.snapshotValue = value;
3809
+ }
3810
+ readerValue;
3811
+ get reader() {
3812
+ if (!this.readerValue) throw new TransactionStateError("Transaction is closed");
3813
+ return this.readerValue;
3814
+ }
3815
+ set reader(value) {
3816
+ this.readerValue = value;
3817
+ }
3027
3818
  stateValue = "ACTIVE";
3028
3819
  pendingReads = 0;
3029
3820
  readWaiters = [];
3030
3821
  queryContexts = /* @__PURE__ */ new Set();
3031
3822
  planner = new RuleBasedPlanner();
3032
3823
  planCompiler = new PlanCompiler();
3033
- constructor(storage, snapshot, keys = new StorageKeyManager(), cursorSigningKey) {
3824
+ constructor(storage, snapshot, keys = new StorageKeyManager(), cursorSigningKey, parentResources, limits = resourceLimits(), operationSignal, onPublication, assertAccessScope, runtimeHooks = {}) {
3034
3825
  this.storage = storage;
3035
3826
  this.keys = keys;
3036
3827
  this.cursorSigningKey = cursorSigningKey;
3828
+ this.operationSignal = operationSignal;
3829
+ this.onPublication = onPublication;
3830
+ this.assertAccessScope = assertAccessScope;
3831
+ this.runtimeHooks = runtimeHooks;
3832
+ this.signal = operationSignal ? AbortSignal.any([operationSignal, this.localCancellation.signal]) : this.localCancellation.signal;
3833
+ this.limits = limits;
3834
+ this.resources = (parentResources ?? new ResourceScope({})).child({
3835
+ workingBytes: limits.maxTransactionWorkingBytes,
3836
+ writes: limits.maxPendingWrites,
3837
+ writeBytes: limits.maxPendingWriteBytes
3838
+ });
3839
+ this.resources.reserve({ transactions: 1 });
3840
+ this.resources.reserve({ workingBytes: estimateBytes([...snapshot.manifest.catalog]) });
3037
3841
  this.capturedSnapshot = cloneSnapshot(snapshot);
3038
3842
  this.reader = new ManifestSnapshotReader(this.storage, this.capturedSnapshot, keys);
3039
3843
  }
3844
+ get expectedStorageVersion() {
3845
+ this.assertActive();
3846
+ return this.capturedSnapshot.storageVersion;
3847
+ }
3848
+ get hasChanges() {
3849
+ this.assertActive();
3850
+ return this.writes.size + this.schemas.size > 0;
3851
+ }
3040
3852
  get state() {
3041
3853
  return this.stateValue;
3042
3854
  }
@@ -3053,6 +3865,9 @@ var Transaction = class {
3053
3865
  const result = await this.reader.get(key);
3054
3866
  this.assertActive();
3055
3867
  return result;
3868
+ } catch (error) {
3869
+ if (this.stateValue != "ACTIVE" && !this.operationSignal?.aborted && error instanceof OperationCancelledError) throw new TransactionStateError("Transaction is no longer active");
3870
+ throw error;
3056
3871
  } finally {
3057
3872
  this.pendingReads--;
3058
3873
  if (this.pendingReads == 0) for (const resolve of this.readWaiters.splice(0)) resolve();
@@ -3068,23 +3883,71 @@ var Transaction = class {
3068
3883
  this.assertActive();
3069
3884
  this.validateKey(key);
3070
3885
  if (key.startsWith("@duraxis/records/")) throw new Error("Reserved internal collection key");
3071
- this.writes.set(key, { type: "delete" });
3886
+ this.stageDelete(key);
3072
3887
  }
3073
3888
  defineCollection(definition) {
3074
3889
  this.assertActive();
3075
3890
  validateCollection(definition);
3891
+ if (this.schemas.get(definition.name) === null) throw new Error("Cannot recreate a dropped collection in the same transaction");
3076
3892
  if (this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3077
- this.schemas.set(definition.name, cloneSchema(definition));
3893
+ this.stageSchema(definition.name, cloneSchema(definition));
3078
3894
  }
3079
3895
  defineCollections(definitions) {
3080
3896
  this.assertActive();
3081
3897
  const names = /* @__PURE__ */ new Set();
3082
3898
  for (const definition of definitions) {
3083
3899
  validateCollection(definition);
3084
- if (names.has(definition.name) || this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3900
+ if (names.has(definition.name) || this.schemas.has(definition.name) || this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3085
3901
  names.add(definition.name);
3086
3902
  }
3087
- for (const definition of definitions) this.schemas.set(definition.name, cloneSchema(definition));
3903
+ for (const definition of definitions) this.stageSchema(definition.name, cloneSchema(definition));
3904
+ }
3905
+ getCollectionDefinitions() {
3906
+ this.assertActive();
3907
+ const catalog = new Map(this.capturedSnapshot.manifest.catalog);
3908
+ for (const [name, schema] of this.schemas) if (schema == null) catalog.delete(name);
3909
+ else catalog.set(name, schema);
3910
+ return [...catalog.values()].map(cloneSchema);
3911
+ }
3912
+ alterCollection(name, definition) {
3913
+ this.assertActive();
3914
+ this.requireCollection(name);
3915
+ if (name != definition.name) throw new Error("Collection replacement cannot rename a collection");
3916
+ this.stageSchema(name, cloneSchema(definition));
3917
+ }
3918
+ dropCollection(name) {
3919
+ this.assertActive();
3920
+ this.requireCollection(name);
3921
+ this.stageSchema(name, null);
3922
+ }
3923
+ async getMetadata(namespace) {
3924
+ this.assertActive();
3925
+ const key = this.metadataKey(namespace);
3926
+ this.pendingReads++;
3927
+ try {
3928
+ const pending = this.writes.get(key);
3929
+ const value = pending ? pending.type == "delete" ? null : pending.data : await this.reader.get(key);
3930
+ this.assertActive();
3931
+ return value == null ? null : new Uint8Array(value);
3932
+ } finally {
3933
+ this.releaseRead();
3934
+ }
3935
+ }
3936
+ putMetadata(namespace, data) {
3937
+ this.assertActive();
3938
+ this.stagePut(this.metadataKey(namespace), data);
3939
+ }
3940
+ metadataKey(namespace) {
3941
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(namespace)) throw new Error("Invalid metadata namespace");
3942
+ return `__duraxis/metadata/${namespace}`;
3943
+ }
3944
+ async *scanCollection(collection) {
3945
+ const context = this.createQueryContext();
3946
+ try {
3947
+ yield* context.scanCollection(collection);
3948
+ } finally {
3949
+ context.close();
3950
+ }
3088
3951
  }
3089
3952
  addIndex(collection, index) {
3090
3953
  this.assertActive();
@@ -3094,13 +3957,13 @@ var Transaction = class {
3094
3957
  indexes: [...current.indexes, index]
3095
3958
  };
3096
3959
  validateCollection(updated);
3097
- this.schemas.set(collection, cloneSchema(updated));
3960
+ this.stageSchema(collection, cloneSchema(updated));
3098
3961
  }
3099
3962
  removeIndex(collection, indexName) {
3100
3963
  this.assertActive();
3101
3964
  const current = this.requireCollection(collection);
3102
3965
  if (!current.indexes.some((index) => index.name == indexName)) throw new Error(`Unknown index: ${collection}/${indexName}`);
3103
- this.schemas.set(collection, cloneSchema({
3966
+ this.stageSchema(collection, cloneSchema({
3104
3967
  ...current,
3105
3968
  indexes: current.indexes.filter((index) => index.name != indexName)
3106
3969
  }));
@@ -3114,9 +3977,20 @@ var Transaction = class {
3114
3977
  createQueryContext() {
3115
3978
  this.assertActive();
3116
3979
  const catalog = new Map(this.capturedSnapshot.manifest.catalog);
3117
- for (const [name, schema] of this.schemas) catalog.set(name, cloneSchema(schema));
3980
+ for (const [name, schema] of this.schemas) if (schema == null) catalog.delete(name);
3981
+ else catalog.set(name, cloneSchema(schema));
3118
3982
  let context;
3119
3983
  context = new QueryContext(this.storage, cloneSnapshot(this.capturedSnapshot), this.keys, {
3984
+ assertAccess: this.assertAccessScope,
3985
+ onPendingCleanup: (promise) => {
3986
+ this.pendingCleanup.add(promise);
3987
+ this.runtimeHooks.onPendingCleanup?.(promise);
3988
+ const complete = () => this.pendingCleanup.delete(promise);
3989
+ promise.then(complete, complete);
3990
+ },
3991
+ onCleanupFailure: this.runtimeHooks.onCleanupFailure,
3992
+ resources: this.resources,
3993
+ limits: this.limits,
3120
3994
  writes: this.writes,
3121
3995
  catalog,
3122
3996
  onIteratorStart: () => {
@@ -3132,18 +4006,21 @@ var Transaction = class {
3132
4006
  const context = this.createQueryContext();
3133
4007
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3134
4008
  const options = explicit ? explicitOptions : sourceOrOptions;
3135
- const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog), context.catalog);
4009
+ const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog, context.limits), context.catalog);
3136
4010
  const executor = new QueryExecutor(this.queryOptions(options));
3137
4011
  const transaction = this;
3138
- return (async function* () {
3139
- const unbindSignal = transaction.bindSignal(context, options?.signal);
4012
+ const iterator = (async function* () {
4013
+ let unbindSignal = () => {};
3140
4014
  try {
4015
+ unbindSignal = transaction.bindSignal(context, options?.signal);
3141
4016
  yield* executor.execute(context, query, source);
3142
4017
  } finally {
3143
4018
  unbindSignal();
3144
4019
  context.close();
3145
4020
  }
3146
4021
  })();
4022
+ context.bindCancellation(() => iterator.return(void 0));
4023
+ return iterator;
3147
4024
  }
3148
4025
  async queryPage(query, sourceOrOptions, explicitOptions) {
3149
4026
  const context = this.createQueryContext();
@@ -3152,7 +4029,7 @@ var Transaction = class {
3152
4029
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3153
4030
  const options = explicit ? explicitOptions : sourceOrOptions;
3154
4031
  unbindSignal = this.bindSignal(context, options?.signal);
3155
- const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog), context.catalog);
4032
+ const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog, context.limits), context.catalog);
3156
4033
  return await new QueryExecutor(this.queryOptions(options)).page(context, query, source);
3157
4034
  } finally {
3158
4035
  unbindSignal();
@@ -3162,22 +4039,29 @@ var Transaction = class {
3162
4039
  putDocument(collection, id, document) {
3163
4040
  this.assertActive();
3164
4041
  const schema = this.requireCollection(collection);
3165
- const parsed = validateDocument(schema, document);
3166
- const data = encodeDocument(parsed);
3167
- for (const index of schema.indexes) for (const part of index.fields ?? (index.field ? [{
3168
- field: index.field,
3169
- order: "ASC"
3170
- }] : [])) indexedValue(parsed, part.field, fieldDefinition(schema, part.field));
3171
- this.stagePut(recordKey(collection, id), data);
4042
+ const estimate = estimateBytes(document, this.limits.maxDocumentBytes * 4, this.limits.maxDocumentDepth);
4043
+ const encoding = this.resources.reserve({ workingBytes: estimate * 4 });
4044
+ try {
4045
+ const parsed = validateDocument(schema, document);
4046
+ const data = encodeDocument(parsed);
4047
+ for (const index of schema.indexes) for (const part of index.fields ?? (index.field ? [{
4048
+ field: index.field,
4049
+ order: "ASC"
4050
+ }] : [])) indexedValue(parsed, part.field, fieldDefinition(schema, part.field));
4051
+ this.stagePut(recordKey(collection, id), data);
4052
+ } finally {
4053
+ encoding.release();
4054
+ }
3172
4055
  }
3173
4056
  deleteDocument(collection, id) {
3174
4057
  this.assertActive();
3175
4058
  this.requireCollection(collection);
3176
- this.writes.set(recordKey(collection, id), { type: "delete" });
4059
+ this.stageDelete(recordKey(collection, id));
3177
4060
  }
3178
4061
  prepareForCommit() {
3179
4062
  this.assertActive();
3180
4063
  if (this.pendingReads != 0) throw new TransactionStateError("Transaction has pending reads; await all tx.get() calls");
4064
+ this.resources.reserve({ workingBytes: [...this.writes].reduce((n, [key, op]) => n + key.length * 2 + 96 + (op.type == "put" ? op.data.byteLength : 0), 0) });
3181
4065
  this.stateValue = "PREPARING";
3182
4066
  const writes = /* @__PURE__ */ new Map();
3183
4067
  for (const [key, operation] of this.writes) writes.set(key, operation.type == "delete" ? { type: "delete" } : {
@@ -3187,7 +4071,7 @@ var Transaction = class {
3187
4071
  return {
3188
4072
  snapshot: cloneSnapshot(this.capturedSnapshot),
3189
4073
  writes,
3190
- schemaChanges: new Map([...this.schemas].map(([name, schema]) => [name, cloneSchema(schema)]))
4074
+ schemaChanges: new Map([...this.schemas].map(([name, schema]) => [name, schema == null ? null : cloneSchema(schema)]))
3191
4075
  };
3192
4076
  }
3193
4077
  async waitForReads() {
@@ -3197,7 +4081,9 @@ var Transaction = class {
3197
4081
  });
3198
4082
  }
3199
4083
  beginPublication() {
4084
+ this.assertAccessScope?.();
3200
4085
  if (this.stateValue != "PREPARING") throw new TransactionStateError("Transaction is not preparing");
4086
+ this.onPublication?.();
3201
4087
  this.stateValue = "COMMITTING";
3202
4088
  }
3203
4089
  markCommitted() {
@@ -3208,17 +4094,56 @@ var Transaction = class {
3208
4094
  this.stateValue = "UNKNOWN";
3209
4095
  }
3210
4096
  abort() {
4097
+ if (this.stateValue == "COMMITTING") return;
3211
4098
  if (this.stateValue != "COMMITTED" && this.stateValue != "UNKNOWN") this.stateValue = "ABORTED";
3212
4099
  }
4100
+ rejectPublication() {
4101
+ if (this.stateValue != "COMMITTING") throw new TransactionStateError("No publication in progress");
4102
+ this.stateValue = "ABORTED";
4103
+ }
3213
4104
  close() {
4105
+ if (this.stateValue == "COMMITTING") return;
4106
+ this.localCancellation.abort(new TransactionStateError("Transaction is closed"));
3214
4107
  if (this.stateValue == "ACTIVE" || this.stateValue == "PREPARING") this.abort();
3215
- for (const context of [...this.queryContexts]) context.close();
4108
+ for (const context of [...this.queryContexts]) context.cancel(new TransactionStateError("Transaction is closed"));
3216
4109
  this.queryContexts.clear();
3217
4110
  this.writes.clear();
3218
4111
  this.schemas.clear();
4112
+ this.writeReservations.clear();
4113
+ this.schemaReservations.clear();
4114
+ if (this.pendingCleanup.size) Promise.allSettled([...this.pendingCleanup]).then(() => this.resources.close());
4115
+ else this.resources.close();
4116
+ this.snapshotValue = void 0;
4117
+ this.readerValue = void 0;
4118
+ }
4119
+ createMaterializationBudget() {
4120
+ return materialize(this.resources, this.limits);
4121
+ }
4122
+ reserveWrite(key, bytes) {
4123
+ if (bytes > this.limits.maxDocumentBytes) throw new ResourceExhaustedError("documentBytes", this.limits.maxDocumentBytes);
4124
+ const amounts = {
4125
+ writes: 1,
4126
+ writeBytes: bytes,
4127
+ workingBytes: bytes + key.length * 2 + 128
4128
+ };
4129
+ const current = this.writeReservations.get(key);
4130
+ if (current) current.resize(amounts);
4131
+ else this.writeReservations.set(key, this.resources.reserve(amounts));
4132
+ }
4133
+ stageDelete(key) {
4134
+ this.reserveWrite(key, 0);
4135
+ this.writes.set(key, { type: "delete" });
4136
+ }
4137
+ stageSchema(name, schema) {
4138
+ const amounts = { workingBytes: estimateBytes(schema) + 128 };
4139
+ const current = this.schemaReservations.get(name);
4140
+ if (current) current.resize(amounts);
4141
+ else this.schemaReservations.set(name, this.resources.reserve(amounts));
4142
+ this.schemas.set(name, schema);
3219
4143
  }
3220
4144
  stagePut(key, data) {
3221
4145
  if (!(data instanceof Uint8Array)) throw new TypeError("Storage value must be Uint8Array");
4146
+ this.reserveWrite(key, data.byteLength);
3222
4147
  this.writes.set(key, {
3223
4148
  type: "put",
3224
4149
  data: new Uint8Array(data)
@@ -3231,13 +4156,15 @@ var Transaction = class {
3231
4156
  queryOptions(options) {
3232
4157
  return {
3233
4158
  ...options,
3234
- cursorSigningKey: options?.cursorSigningKey ?? this.cursorSigningKey
4159
+ cursorSigningKey: this.cursorSigningKey,
4160
+ cursorEncryption: this.runtimeHooks.cursorEncryption,
4161
+ cursorNamespace: this.keys.namespace
3235
4162
  };
3236
4163
  }
3237
4164
  bindSignal(context, signal) {
3238
4165
  if (!signal) return () => {};
3239
4166
  const cancel = () => context.cancel(signal.reason ?? /* @__PURE__ */ new Error("Query cancelled"));
3240
- if (signal.aborted) cancel();
4167
+ if (signal.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
3241
4168
  else signal.addEventListener("abort", cancel, { once: true });
3242
4169
  return () => signal.removeEventListener("abort", cancel);
3243
4170
  }
@@ -3245,7 +4172,7 @@ var Transaction = class {
3245
4172
  return value != null && typeof value.execute == "function";
3246
4173
  }
3247
4174
  collection(name) {
3248
- return this.schemas.get(name) ?? this.capturedSnapshot.manifest.catalog.get(name);
4175
+ return this.schemas.has(name) ? this.schemas.get(name) ?? void 0 : this.capturedSnapshot.manifest.catalog.get(name);
3249
4176
  }
3250
4177
  requireCollection(name) {
3251
4178
  const schema = this.collection(name);
@@ -3253,9 +4180,12 @@ var Transaction = class {
3253
4180
  return schema;
3254
4181
  }
3255
4182
  assertActive() {
4183
+ this.assertAccessScope?.();
4184
+ this.operationSignal?.throwIfAborted();
3256
4185
  if (this.stateValue != "ACTIVE") throw new TransactionStateError("Transaction is no longer active");
3257
4186
  }
3258
4187
  validateKey(key) {
4188
+ if (Buffer.byteLength(key) > 1024) throw new ResourceExhaustedError("keyBytes", 1024);
3259
4189
  this.keys.validateLogicalKey(key);
3260
4190
  encodeIndexKey(new TextEncoder().encode(key));
3261
4191
  }
@@ -3305,6 +4235,196 @@ var RecoveryManager = class {
3305
4235
  return count;
3306
4236
  }
3307
4237
  };
4238
+ // src/gc/reachability-scanner.ts
4239
+ var MAX_REFERENCES = 1e5;
4240
+ var MAX_BYTES = 33554432;
4241
+ var ManifestReachabilityScanner = class {
4242
+ keys;
4243
+ nodes;
4244
+ primary;
4245
+ constructor(keys, storage) {
4246
+ this.keys = keys;
4247
+ this.nodes = new BPlusTreeNodeStore(storage, keys);
4248
+ this.primary = new PrimaryIndex(storage, keys);
4249
+ }
4250
+ async scan(snapshot, options = {}) {
4251
+ const maximum = options.maxReferences ?? MAX_REFERENCES;
4252
+ const maxBytes = options.maxBytes ?? MAX_BYTES;
4253
+ const reachable = /* @__PURE__ */ new Set();
4254
+ let bytes = 0;
4255
+ const add = (ref) => {
4256
+ if (reachable.has(ref)) return;
4257
+ const size = ref.length * 2 + 64;
4258
+ if (reachable.size >= maximum || bytes + size > maxBytes) throw new ResourceExhaustedError("gcReachability", maxBytes);
4259
+ bytes += size;
4260
+ reachable.add(ref);
4261
+ };
4262
+ const path = /* @__PURE__ */ new Set();
4263
+ const visit = async (ref, depth) => {
4264
+ options.signal?.throwIfAborted();
4265
+ if (path.has(ref) || depth >= 128) throw new Error("Invalid B+tree cycle or depth during reachability scan");
4266
+ if (reachable.has(ref)) return;
4267
+ this.keys.validateIndexNodeKey(ref);
4268
+ add(ref);
4269
+ path.add(ref);
4270
+ try {
4271
+ const node = await this.nodes.read(ref);
4272
+ if (node.type == "internal") for (const child of node.children) await visit(child, depth + 1);
4273
+ } finally {
4274
+ path.delete(ref);
4275
+ }
4276
+ };
4277
+ if (snapshot.manifest.primaryRoot) await visit(snapshot.manifest.primaryRoot, 0);
4278
+ for (const root of snapshot.manifest.indexRoots.values()) if (root) await visit(root, 0);
4279
+ for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot)) {
4280
+ options.signal?.throwIfAborted();
4281
+ add(entry.ref);
4282
+ }
4283
+ return reachable;
4284
+ }
4285
+ };
4286
+ // src/gc/garbage-collector.ts
4287
+ var DEFAULT_GRACE_PERIOD_MS = 864e5;
4288
+ var GarbageCollector = class {
4289
+ storage;
4290
+ keys;
4291
+ activeSnapshots;
4292
+ scanner;
4293
+ resourceParent;
4294
+ constructor(storage, keys, activeSnapshots, scanner = new ManifestReachabilityScanner(keys, storage), resourceParent = new ResourceScope({ workingBytes: 67108864 })) {
4295
+ this.storage = storage;
4296
+ this.keys = keys;
4297
+ this.activeSnapshots = activeSnapshots;
4298
+ this.scanner = scanner;
4299
+ this.resourceParent = resourceParent;
4300
+ }
4301
+ async collect(options = {}) {
4302
+ const started = performance.now();
4303
+ const dryRun = options.dryRun != false;
4304
+ if (!dryRun && options.exclusiveMaintenance != true) throw new Error("Deletion requires explicit exclusive maintenance intent and verified driver ownership");
4305
+ const coordination = storageCoordination(this.storage);
4306
+ if (coordination.maintenance) throw new Error("Maintenance is already active");
4307
+ if (!dryRun && (coordination.active || this.activeSnapshots().length)) throw new Error("Cannot delete objects with active snapshots or operations");
4308
+ if (!dryRun && !this.storage.verifyExclusiveOwnership) throw new Error("Destructive GC is unsupported without verified single-owner storage; shared/distributed storage must use dry-run");
4309
+ if (!this.storage.iterate) throw new Error("GC requires incremental storage listing support");
4310
+ coordination.maintenance = true;
4311
+ const maxMarkBytes = options.maxMarkBytes ?? 33554432;
4312
+ const maxReferences = options.maxReferences ?? 1e5;
4313
+ if (!Number.isSafeInteger(maxMarkBytes) || maxMarkBytes < 1 || !Number.isSafeInteger(maxReferences) || maxReferences < 1) {
4314
+ coordination.maintenance = false;
4315
+ throw new RangeError("Invalid GC mark budget");
4316
+ }
4317
+ const resources = this.resourceParent.child({ workingBytes: maxMarkBytes * 2 });
4318
+ const reservation = resources.reserve({});
4319
+ let markBytes = 0;
4320
+ try {
4321
+ if (!dryRun) await this.storage.verifyExclusiveOwnership();
4322
+ const olderThanMs = options.olderThanMs ?? DEFAULT_GRACE_PERIOD_MS;
4323
+ if (!Number.isSafeInteger(olderThanMs) || olderThanMs < 0) throw new Error("Invalid GC grace period");
4324
+ const batchSize = options.batchSize ?? 256;
4325
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1e5) throw new Error("Invalid GC batch size");
4326
+ if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
4327
+ const current = await this.storage.get(this.keys.manifestKey);
4328
+ const snapshot = {
4329
+ manifest: current ? decodeManifest(current.data, this.keys) : emptyManifest(),
4330
+ storageVersion: current?.version ?? null
4331
+ };
4332
+ const reachable = /* @__PURE__ */ new Set();
4333
+ if (coordination.snapshots.size > maxReferences) throw new ResourceExhaustedError("gcSnapshots", maxReferences);
4334
+ const retainedSnapshots = [snapshot, .../* @__PURE__ */ new Set([...this.activeSnapshots(), ...coordination.snapshots])];
4335
+ const mark = (ref) => {
4336
+ if (reachable.has(ref)) return;
4337
+ if (reachable.size >= maxReferences) throw new ResourceExhaustedError("gcReferences", maxReferences);
4338
+ const size = ref.length * 2 + 64;
4339
+ if (markBytes + size > maxMarkBytes) throw new ResourceExhaustedError("gcMarkBytes", maxMarkBytes);
4340
+ reservation.resize({ workingBytes: markBytes + size });
4341
+ markBytes += size;
4342
+ reachable.add(ref);
4343
+ };
4344
+ for (const item of retainedSnapshots) {
4345
+ const scanLease = resources.reserve({ workingBytes: maxMarkBytes });
4346
+ try {
4347
+ const refs = await this.scanner.scan(item, {
4348
+ maxReferences,
4349
+ maxBytes: maxMarkBytes,
4350
+ signal: options.signal
4351
+ });
4352
+ for (const ref of refs) mark(ref);
4353
+ } finally {
4354
+ scanLease.release();
4355
+ }
4356
+ }
4357
+ for (const retained of retainedSnapshots) {
4358
+ let cursor = retained.manifest.commitHead;
4359
+ let count = 0;
4360
+ while (cursor) {
4361
+ if (reachable.has(cursor)) break;
4362
+ if (++count > 1e6) throw new Error("Commit history scan limit exceeded during GC");
4363
+ mark(cursor);
4364
+ cursor = (await readCommitRecord(this.storage, this.keys, cursor)).previous;
4365
+ }
4366
+ }
4367
+ const cutoff = Date.now() - olderThanMs;
4368
+ let candidates = 0;
4369
+ let deleted = 0;
4370
+ let failed = 0;
4371
+ let scanned = 0;
4372
+ let nodesScanned = 0;
4373
+ let commitsScanned = 0;
4374
+ let position = 0;
4375
+ for (const prefix of [
4376
+ this.keys.objectPrefix,
4377
+ this.keys.indexNodePrefix,
4378
+ this.keys.commitPrefix
4379
+ ]) for await (const object of this.storage.iterate(prefix, {
4380
+ pageSize: Math.min(batchSize, 1e3),
4381
+ signal: options.signal
4382
+ })) {
4383
+ if (prefix == this.keys.objectPrefix) scanned++;
4384
+ else if (prefix == this.keys.indexNodePrefix) nodesScanned++;
4385
+ else commitsScanned++;
4386
+ position++;
4387
+ if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
4388
+ if (object.key.startsWith(this.keys.objectPrefix)) this.keys.validateObjectKey(object.key);
4389
+ else if (object.key.startsWith(this.keys.indexNodePrefix)) this.keys.validateIndexNodeKey(object.key);
4390
+ else this.keys.validateCommitKey(object.key);
4391
+ if (!Number.isSafeInteger(object.createdAt)) throw new Error(`Invalid object timestamp: ${object.key}`);
4392
+ if (reachable.has(object.key) || object.createdAt > cutoff) continue;
4393
+ candidates++;
4394
+ if (dryRun) {
4395
+ if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
4396
+ continue;
4397
+ }
4398
+ try {
4399
+ await this.storage.verifyExclusiveOwnership();
4400
+ if ((await this.storage.delete(object.key, { condition: {
4401
+ type: "if-version",
4402
+ version: object.version
4403
+ } })).success) deleted++;
4404
+ else failed++;
4405
+ } catch (error) {
4406
+ failed++;
4407
+ if (!options.continueOnError) throw error;
4408
+ }
4409
+ if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
4410
+ }
4411
+ return {
4412
+ scanned,
4413
+ nodesScanned,
4414
+ reachable: reachable.size,
4415
+ candidates,
4416
+ deleted,
4417
+ failed,
4418
+ commitsScanned,
4419
+ durationMs: performance.now() - started,
4420
+ dryRun
4421
+ };
4422
+ } finally {
4423
+ resources.close();
4424
+ coordination.maintenance = false;
4425
+ }
4426
+ }
4427
+ };
3308
4428
  // src/indexes/bptree/bptree-validator.ts
3309
4429
  var BPlusTreeValidator = class {
3310
4430
  nodes;
@@ -3406,125 +4526,6 @@ var BPlusTreeValidator = class {
3406
4526
  return found;
3407
4527
  }
3408
4528
  };
3409
- // src/gc/reachability-scanner.ts
3410
- var ManifestReachabilityScanner = class {
3411
- keys;
3412
- nodes;
3413
- primary;
3414
- constructor(keys, storage) {
3415
- this.keys = keys;
3416
- this.nodes = new BPlusTreeNodeStore(storage, keys);
3417
- this.primary = new PrimaryIndex(storage, keys);
3418
- }
3419
- async scan(snapshot) {
3420
- const reachable = /* @__PURE__ */ new Set();
3421
- const roots = /* @__PURE__ */ new Set();
3422
- if (snapshot.manifest.primaryRoot != null) roots.add(snapshot.manifest.primaryRoot);
3423
- for (const root of snapshot.manifest.indexRoots.values()) if (root != null) roots.add(root);
3424
- const validator = new BPlusTreeValidator(this.nodes);
3425
- for (const root of roots) {
3426
- this.keys.validateIndexNodeKey(root);
3427
- const references = await validator.reachableNodes(root);
3428
- for (const ref of references) reachable.add(ref);
3429
- }
3430
- for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot)) reachable.add(entry.ref);
3431
- return reachable;
3432
- }
3433
- };
3434
- // src/gc/garbage-collector.ts
3435
- var DEFAULT_GRACE_PERIOD_MS = 864e5;
3436
- var GarbageCollector = class {
3437
- storage;
3438
- keys;
3439
- activeSnapshots;
3440
- scanner;
3441
- constructor(storage, keys, activeSnapshots, scanner = new ManifestReachabilityScanner(keys, storage)) {
3442
- this.storage = storage;
3443
- this.keys = keys;
3444
- this.activeSnapshots = activeSnapshots;
3445
- this.scanner = scanner;
3446
- }
3447
- async collect(options = {}) {
3448
- const started = performance.now();
3449
- const dryRun = options.dryRun != false;
3450
- if (!dryRun && options.exclusiveMaintenance != true) throw new Error("Deletion requires externally guaranteed exclusive maintenance");
3451
- if (!dryRun && this.activeSnapshots().length != 0) throw new Error("Cannot delete objects with active snapshots");
3452
- const olderThanMs = options.olderThanMs ?? DEFAULT_GRACE_PERIOD_MS;
3453
- if (!Number.isSafeInteger(olderThanMs) || olderThanMs < 0) throw new Error("Invalid GC grace period");
3454
- const batchSize = options.batchSize ?? 256;
3455
- if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1e5) throw new Error("Invalid GC batch size");
3456
- if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
3457
- const current = await this.storage.get(this.keys.manifestKey);
3458
- const snapshot = {
3459
- manifest: current ? decodeManifest(current.data, this.keys) : emptyManifest(),
3460
- storageVersion: current?.version ?? null
3461
- };
3462
- const reachable = /* @__PURE__ */ new Set();
3463
- const retainedSnapshots = [snapshot, ...this.activeSnapshots()];
3464
- for (const item of retainedSnapshots) {
3465
- const refs = await this.scanner.scan(item);
3466
- for (const ref of refs) reachable.add(ref);
3467
- }
3468
- const objects = await this.storage.list(this.keys.objectPrefix);
3469
- const nodes = await this.storage.list(this.keys.indexNodePrefix);
3470
- const commits = await this.storage.list(this.keys.commitPrefix);
3471
- const reachableCommits = /* @__PURE__ */ new Set();
3472
- for (const retained of retainedSnapshots) {
3473
- let cursor = retained.manifest.commitHead;
3474
- let count = 0;
3475
- while (cursor) {
3476
- if (reachableCommits.has(cursor)) break;
3477
- if (++count > 1e6) throw new Error("Commit history scan limit exceeded during GC");
3478
- reachableCommits.add(cursor);
3479
- cursor = (await readCommitRecord(this.storage, this.keys, cursor)).previous;
3480
- }
3481
- }
3482
- const cutoff = Date.now() - olderThanMs;
3483
- let candidates = 0;
3484
- let deleted = 0;
3485
- let failed = 0;
3486
- const candidatesForScan = [
3487
- ...objects,
3488
- ...nodes,
3489
- ...commits
3490
- ];
3491
- for (let position = 0; position < candidatesForScan.length; position++) {
3492
- if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
3493
- const object = candidatesForScan[position];
3494
- if (object.key.startsWith(this.keys.objectPrefix)) this.keys.validateObjectKey(object.key);
3495
- else if (object.key.startsWith(this.keys.indexNodePrefix)) this.keys.validateIndexNodeKey(object.key);
3496
- else this.keys.validateCommitKey(object.key);
3497
- if (!Number.isSafeInteger(object.createdAt)) throw new Error(`Invalid object timestamp: ${object.key}`);
3498
- if (reachable.has(object.key) || reachableCommits.has(object.key) || object.createdAt > cutoff) continue;
3499
- candidates++;
3500
- if (dryRun) {
3501
- if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
3502
- continue;
3503
- }
3504
- try {
3505
- if ((await this.storage.delete(object.key, { condition: {
3506
- type: "if-version",
3507
- version: object.version
3508
- } })).success) deleted++;
3509
- } catch (error) {
3510
- failed++;
3511
- if (!options.continueOnError) throw error;
3512
- }
3513
- if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
3514
- }
3515
- return {
3516
- scanned: objects.length,
3517
- nodesScanned: nodes.length,
3518
- reachable: reachable.size,
3519
- candidates,
3520
- deleted,
3521
- failed,
3522
- commitsScanned: commits.length,
3523
- durationMs: performance.now() - started,
3524
- dryRun
3525
- };
3526
- }
3527
- };
3528
4529
  // src/indexes/index-consistency-checker.ts
3529
4530
  var decoder = new TextDecoder();
3530
4531
  var IndexConsistencyChecker = class {
@@ -3617,13 +4618,13 @@ function immutableCollection(definition) {
3617
4618
  ...foreignKeys.length == 0 ? {} : { foreignKeys }
3618
4619
  });
3619
4620
  }
3620
- var DuraxisDatabase = class {
4621
+ var DuraxisDatabase = class DuraxisDatabase {
4622
+ resourceLimits;
4623
+ resources;
4624
+ cursorEncryption;
4625
+ accessScope;
3621
4626
  storage;
3622
4627
  keys;
3623
- coordinator;
3624
- recovery;
3625
- primary;
3626
- secondary;
3627
4628
  cursorSigningKey;
3628
4629
  planner = new RuleBasedPlanner();
3629
4630
  planCompiler = new PlanCompiler();
@@ -3639,48 +4640,173 @@ var DuraxisDatabase = class {
3639
4640
  garbageCollectionDurationMs: 0
3640
4641
  };
3641
4642
  active = /* @__PURE__ */ new Set();
4643
+ owners = /* @__PURE__ */ new Map();
4644
+ operations = /* @__PURE__ */ new Set();
4645
+ closePromise;
4646
+ cleanupFailures = [];
4647
+ outcomes = /* @__PURE__ */ new Map();
4648
+ drainWaiters = /* @__PURE__ */ new Set();
3642
4649
  maintenance = false;
3643
4650
  pendingSnapshotAcquisitions = 0;
3644
4651
  closed = false;
3645
4652
  constructor(options) {
4653
+ if (options.storage.capabilities?.boundedReads !== true) throw new Error("Core requires a storage driver with verified bounded-read support; update the driver contract");
4654
+ this.resourceLimits = resourceLimits(options.resources);
4655
+ this.resources = databaseScope(this.resourceLimits);
4656
+ this.accessScope = options.accessScope ? Object.freeze({ ...options.accessScope }) : void 0;
4657
+ if (this.accessScope && (!options.namespace || !/^[A-Za-z0-9_-]{1,64}$/.test(this.accessScope.tenant) || typeof this.accessScope.currentTenant != "function")) throw new Error("Tenant scope requires an explicit namespace and trusted tenant resolver");
4658
+ this.cursorEncryption = options.cursorEncryption ? {
4659
+ ...options.cursorEncryption,
4660
+ keys: Object.fromEntries(Object.entries(options.cursorEncryption.keys).map(([id, key]) => [id, new Uint8Array(key)]))
4661
+ } : void 0;
3646
4662
  this.storage = options.storage;
3647
4663
  this.keys = new StorageKeyManager(options.namespace);
3648
- this.coordinator = new CommitCoordinator(this.storage, this.keys);
3649
- this.recovery = new RecoveryManager(this.storage, this.keys);
3650
- this.primary = new PrimaryIndex(this.storage, this.keys);
3651
- this.secondary = new SecondaryIndexManager(this.storage, this.keys);
3652
4664
  this.cursorSigningKey = options.cursorSigningKey == null ? (0, node_crypto.randomBytes)(32) : new Uint8Array(options.cursorSigningKey);
3653
4665
  if (this.cursorSigningKey.byteLength < 32) throw new Error("Cursor signing key must contain at least 32 bytes");
3654
4666
  }
4667
+ get namespace() {
4668
+ return this.keys.namespace;
4669
+ }
4670
+ static forTenant(options) {
4671
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(options.tenant)) throw new Error("Invalid tenant identifier");
4672
+ return new DuraxisDatabase({
4673
+ ...options,
4674
+ namespace: `tenants/${options.tenant}/v1`,
4675
+ accessScope: {
4676
+ tenant: options.tenant,
4677
+ currentTenant: options.currentTenant
4678
+ }
4679
+ });
4680
+ }
4681
+ assertAccess() {
4682
+ if (this.accessScope && this.accessScope.currentTenant() !== this.accessScope.tenant) throw new Error("Missing or incorrect tenant access scope");
4683
+ }
3655
4684
  async transaction(callback) {
4685
+ this.assertAccess();
3656
4686
  this.metrics.transactionsStarted++;
3657
- const snapshot = await this.acquireSnapshot();
3658
- const tx = new Transaction(this.storage, snapshot, this.keys, this.cursorSigningKey);
4687
+ const snapshot = await this.acquireSnapshot("transaction");
4688
+ const owner = this.owners.get(snapshot);
4689
+ let tx;
4690
+ try {
4691
+ tx = new Transaction(owner.storage, snapshot, this.keys, this.cursorSigningKey, owner.scope, this.resourceLimits, owner.signal, () => owner.protectPublication(), () => this.assertAccess(), {
4692
+ cursorEncryption: this.cursorEncryption,
4693
+ onPendingCleanup: (promise) => owner.holdCleanup(promise),
4694
+ onCleanupFailure: (error) => {
4695
+ if (this.cleanupFailures.length < 16) this.cleanupFailures.push(/* @__PURE__ */ new Error("Deferred query cleanup failed; inspect storage health"));
4696
+ }
4697
+ });
4698
+ } catch (error) {
4699
+ owner.finish();
4700
+ throw error;
4701
+ }
4702
+ const abort = () => tx.close();
4703
+ owner.signal.addEventListener("abort", abort, { once: true });
3659
4704
  try {
3660
- const result = await callback(tx);
4705
+ const result = await owner.wait(Promise.resolve().then(() => callback(tx)));
3661
4706
  const started = performance.now();
3662
4707
  try {
3663
- await this.coordinator.commit(tx);
4708
+ await new CommitCoordinator(owner.storage, this.keys, this.storage).commit(tx);
3664
4709
  } finally {
3665
4710
  this.metrics.commitDurationMs += performance.now() - started;
3666
4711
  }
4712
+ this.rememberOutcome(tx.id, "COMMITTED");
3667
4713
  this.metrics.transactionsCommitted++;
3668
4714
  return result;
3669
4715
  } catch (error) {
3670
4716
  if (error instanceof TransactionConflictError) this.metrics.transactionConflicts++;
3671
4717
  if (error instanceof CommitOutcomeUnknownError) this.metrics.commitOutcomesUnknown++;
4718
+ if (!(error instanceof CommitOutcomeUnknownError)) this.rememberOutcome(tx.id, "NOT_COMMITTED");
3672
4719
  tx.abort();
3673
4720
  throw error;
3674
4721
  } finally {
4722
+ owner.signal.removeEventListener("abort", abort);
3675
4723
  this.releaseSnapshot(snapshot, tx);
3676
4724
  }
3677
4725
  }
4726
+ rememberOutcome(id, status) {
4727
+ if (this.outcomes.size >= 1024) this.outcomes.delete(this.outcomes.keys().next().value);
4728
+ this.outcomes.set(id, {
4729
+ status,
4730
+ expires: Date.now() + 864e5
4731
+ });
4732
+ }
4733
+ async resolveCommitOutcome(id) {
4734
+ this.assertAccess();
4735
+ const retained = this.outcomes.get(id);
4736
+ if (retained && retained.expires > Date.now()) return retained.status;
4737
+ if (await this.transaction(async (tx) => {
4738
+ const bytes = await tx.getMetadata("idempotency");
4739
+ if (!bytes) return false;
4740
+ const entries = JSON.parse(new TextDecoder().decode(bytes));
4741
+ return Object.values(entries).some((entry) => entry.id == id && entry.expires > Date.now());
4742
+ })) return "COMMITTED";
4743
+ return await this.getCommitStatus(id) == "committed" ? "COMMITTED" : "UNKNOWN";
4744
+ }
4745
+ async transactionOnce(operationId, callback) {
4746
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(operationId)) throw new Error("Invalid idempotency identifier");
4747
+ try {
4748
+ return await this.transaction(async (tx) => {
4749
+ const bytes = await tx.getMetadata("idempotency");
4750
+ const ledger = bytes ? JSON.parse(new TextDecoder().decode(bytes)) : {};
4751
+ const existing = Object.hasOwn(ledger, operationId) ? ledger[operationId] : void 0;
4752
+ if (existing && existing.expires > Date.now()) return {
4753
+ applied: false,
4754
+ transactionId: existing.id
4755
+ };
4756
+ const live = Object.fromEntries(Object.entries(ledger).filter(([, entry]) => entry.expires > Date.now()));
4757
+ if (Object.keys(live).length >= 1024) throw new Error("Idempotency retention capacity exceeded; wait for expiration or use a separate namespace");
4758
+ const result = await callback(tx);
4759
+ Object.defineProperty(live, operationId, {
4760
+ value: {
4761
+ id: tx.id,
4762
+ expires: Date.now() + 864e5
4763
+ },
4764
+ enumerable: true
4765
+ });
4766
+ tx.putMetadata("idempotency", new TextEncoder().encode(JSON.stringify(live)));
4767
+ return {
4768
+ applied: true,
4769
+ transactionId: tx.id,
4770
+ result
4771
+ };
4772
+ });
4773
+ } catch (error) {
4774
+ if (!(error instanceof TransactionConflictError) && !(error instanceof CommitOutcomeUnknownError)) throw error;
4775
+ const receipt = await this.transaction(async (tx) => {
4776
+ const bytes = await tx.getMetadata("idempotency");
4777
+ if (!bytes) return void 0;
4778
+ const ledger = JSON.parse(new TextDecoder().decode(bytes));
4779
+ return Object.hasOwn(ledger, operationId) && ledger[operationId].expires > Date.now() ? ledger[operationId] : void 0;
4780
+ });
4781
+ if (receipt) return {
4782
+ applied: false,
4783
+ transactionId: receipt.id
4784
+ };
4785
+ throw error;
4786
+ }
4787
+ }
3678
4788
  async snapshot(callback) {
3679
4789
  const snapshot = await this.acquireSnapshot();
3680
- const tx = new Transaction(this.storage, snapshot, this.keys, this.cursorSigningKey);
4790
+ const owner = this.owners.get(snapshot);
4791
+ let tx;
4792
+ try {
4793
+ tx = new Transaction(owner.storage, snapshot, this.keys, this.cursorSigningKey, owner.scope, this.resourceLimits, owner.signal, () => owner.protectPublication(), () => this.assertAccess(), {
4794
+ cursorEncryption: this.cursorEncryption,
4795
+ onPendingCleanup: (promise) => owner.holdCleanup(promise),
4796
+ onCleanupFailure: (error) => {
4797
+ if (this.cleanupFailures.length < 16) this.cleanupFailures.push(/* @__PURE__ */ new Error("Deferred query cleanup failed; inspect storage health"));
4798
+ }
4799
+ });
4800
+ } catch (error) {
4801
+ owner.finish();
4802
+ throw error;
4803
+ }
4804
+ const abort = () => tx.close();
4805
+ owner.signal.addEventListener("abort", abort, { once: true });
3681
4806
  try {
3682
- return await callback({ get: (key) => tx.get(key) });
4807
+ return await owner.wait(Promise.resolve().then(() => callback({ get: (key) => tx.get(key) })));
3683
4808
  } finally {
4809
+ owner.signal.removeEventListener("abort", abort);
3684
4810
  this.releaseSnapshot(snapshot, tx);
3685
4811
  }
3686
4812
  }
@@ -3697,7 +4823,7 @@ var DuraxisDatabase = class {
3697
4823
  try {
3698
4824
  return Object.freeze([...snapshot.manifest.catalog.values()].map((definition) => immutableCollection(definition)).sort((left, right) => left.name.localeCompare(right.name)));
3699
4825
  } finally {
3700
- this.active.delete(snapshot);
4826
+ this.finishSnapshot(snapshot);
3701
4827
  }
3702
4828
  }
3703
4829
  async addIndex(collection, index) {
@@ -3710,65 +4836,79 @@ var DuraxisDatabase = class {
3710
4836
  }
3711
4837
  query(query, sourceOrOptions, explicitOptions) {
3712
4838
  const database = this;
3713
- return (async function* () {
4839
+ const iterator = (async function* () {
3714
4840
  const started = performance.now();
3715
4841
  database.metrics.queries++;
3716
- const snapshot = await database.acquireSnapshot();
3717
- const context = new QueryContext(database.storage, snapshot, database.keys);
4842
+ const snapshot = await database.acquireSnapshot("query");
4843
+ const context = database.queryContext(snapshot);
4844
+ context.bindCancellation(() => iterator.return(void 0));
3718
4845
  let unbindSignal = () => {};
3719
4846
  try {
3720
4847
  const explicit = database.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3721
4848
  const options = explicit ? explicitOptions : sourceOrOptions;
3722
4849
  unbindSignal = database.bindSignal(context, options?.signal);
3723
- const source = explicit ?? database.planCompiler.compile(database.planner.plan(query, context.catalog), context.catalog);
4850
+ const source = explicit ?? database.planCompiler.compile(database.planner.plan(query, context.catalog, context.limits), context.catalog);
3724
4851
  yield* new QueryExecutor(database.queryOptions(options)).execute(context, query, source);
3725
4852
  } finally {
3726
4853
  unbindSignal();
3727
4854
  database.metrics.queryDurationMs += performance.now() - started;
3728
4855
  context.close();
3729
- database.active.delete(snapshot);
4856
+ database.finishSnapshot(snapshot);
3730
4857
  }
3731
4858
  })();
4859
+ return iterator;
3732
4860
  }
3733
4861
  async queryPage(query, sourceOrOptions, explicitOptions) {
3734
4862
  const started = performance.now();
3735
4863
  this.metrics.queries++;
3736
4864
  const snapshot = await this.acquireSnapshot();
3737
- const context = new QueryContext(this.storage, snapshot, this.keys);
4865
+ const context = this.queryContext(snapshot);
3738
4866
  let unbindSignal = () => {};
3739
4867
  try {
3740
4868
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3741
4869
  const options = explicit ? explicitOptions : sourceOrOptions;
3742
4870
  unbindSignal = this.bindSignal(context, options?.signal);
3743
- const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog), context.catalog);
4871
+ const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog, context.limits), context.catalog);
3744
4872
  return await new QueryExecutor(this.queryOptions(options)).page(context, query, source);
3745
4873
  } finally {
3746
4874
  unbindSignal();
3747
4875
  this.metrics.queryDurationMs += performance.now() - started;
3748
4876
  context.close();
3749
- this.active.delete(snapshot);
4877
+ this.finishSnapshot(snapshot);
3750
4878
  }
3751
4879
  }
3752
4880
  async queryAll(query, options) {
3753
4881
  const rows = [];
3754
- for await (const row of this.query(query, options)) rows.push(row);
3755
- return rows;
4882
+ const results = materialize(this.resources, this.resourceLimits);
4883
+ try {
4884
+ for await (const row of this.query(query, options)) {
4885
+ results.add(row);
4886
+ rows.push(row);
4887
+ }
4888
+ return rows;
4889
+ } finally {
4890
+ results.close();
4891
+ }
4892
+ }
4893
+ createMaterializationBudget() {
4894
+ return materialize(this.resources, this.resourceLimits);
3756
4895
  }
3757
4896
  async explain(query) {
3758
4897
  const snapshot = await this.acquireSnapshot();
3759
4898
  try {
3760
- return explainPhysicalPlan(this.planner.plan(query, snapshot.manifest.catalog));
4899
+ return explainPhysicalPlan(this.planner.plan(query, snapshot.manifest.catalog, this.resourceLimits));
3761
4900
  } finally {
3762
- this.active.delete(snapshot);
4901
+ this.finishSnapshot(snapshot);
3763
4902
  }
3764
4903
  }
3765
4904
  executePlan(query, plan, options) {
3766
4905
  if (plan.collection != query.collection) throw new Error("Plan and query collections differ");
3767
4906
  if (plan.limit != query.limit || JSON.stringify(plan.projection ?? null) != JSON.stringify(query.projection ?? null) || JSON.stringify(plan.requiredOrdering) != JSON.stringify(query.orderBy ?? [])) throw new Error("Physical plan is incompatible with the logical query");
3768
4907
  const database = this;
3769
- return (async function* () {
3770
- const snapshot = await database.acquireSnapshot();
3771
- const context = new QueryContext(database.storage, snapshot, database.keys);
4908
+ const iterator = (async function* () {
4909
+ const snapshot = await database.acquireSnapshot("query");
4910
+ const context = database.queryContext(snapshot);
4911
+ context.bindCancellation(() => iterator.return(void 0));
3772
4912
  const unbindSignal = database.bindSignal(context, options?.signal);
3773
4913
  try {
3774
4914
  const source = database.planCompiler.compile(plan, context.catalog);
@@ -3776,67 +4916,74 @@ var DuraxisDatabase = class {
3776
4916
  } finally {
3777
4917
  unbindSignal();
3778
4918
  context.close();
3779
- database.active.delete(snapshot);
4919
+ database.finishSnapshot(snapshot);
3780
4920
  }
3781
4921
  })();
4922
+ return iterator;
3782
4923
  }
3783
4924
  async getDocument(collection, id) {
3784
4925
  return this.transaction((tx) => tx.getDocument(collection, id));
3785
4926
  }
3786
4927
  async findByIndex(collection, indexName, value, limit = 100) {
3787
4928
  const snapshot = await this.acquireSnapshot();
4929
+ const context = this.queryContext(snapshot);
4930
+ const memory = this.createMaterializationBudget();
4931
+ const rows = [];
3788
4932
  try {
3789
- const ids = await this.secondary.lookupIds(snapshot.manifest, collection, indexName, value, limit);
3790
- const rows = [];
3791
- for (const id of ids) {
3792
- const bytes = await this.primary.read(snapshot.manifest, recordKey(collection, id));
3793
- if (bytes == null) throw new Error(`Index references missing record: ${collection}/${id}`);
3794
- rows.push({
3795
- id,
3796
- document: decodeDocument(bytes)
3797
- });
4933
+ for await (const row of context.scanIndex(collection, indexName, {
4934
+ eq: value,
4935
+ limit
4936
+ })) {
4937
+ memory.add(row);
4938
+ rows.push(row);
3798
4939
  }
3799
4940
  return rows;
3800
4941
  } finally {
3801
- this.active.delete(snapshot);
4942
+ memory.close();
4943
+ context.close();
4944
+ this.finishSnapshot(snapshot);
3802
4945
  }
3803
4946
  }
3804
4947
  async scanCollection(collection, limit = 100) {
3805
- if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid scan limit");
3806
4948
  const snapshot = await this.acquireSnapshot();
4949
+ const context = this.queryContext(snapshot);
4950
+ const memory = this.createMaterializationBudget();
4951
+ const rows = [];
3807
4952
  try {
3808
- if (!snapshot.manifest.catalog.has(collection)) throw new Error(`Unknown collection: ${collection}`);
3809
- const rows = [];
3810
- if (limit == 0) return rows;
3811
- const prefix = new TextEncoder().encode(`${RECORD_PREFIX}${collection}/`);
3812
- const end = prefixSuccessor(prefix);
3813
- for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot, {
3814
- gte: prefix,
3815
- ...end == null ? {} : { lt: end }
3816
- })) {
3817
- const parsed = parseRecordKey(entry.key);
3818
- if (!parsed || parsed.collection != collection) continue;
3819
- rows.push({
3820
- id: parsed.id,
3821
- document: decodeDocument(await this.primary.readObject(entry.ref))
3822
- });
3823
- if (rows.length >= limit) break;
4953
+ for await (const row of context.scanCollection(collection, { limit })) {
4954
+ memory.add(row);
4955
+ rows.push(row);
3824
4956
  }
3825
4957
  return rows;
3826
4958
  } finally {
3827
- this.active.delete(snapshot);
4959
+ memory.close();
4960
+ context.close();
4961
+ this.finishSnapshot(snapshot);
3828
4962
  }
3829
4963
  }
3830
4964
  async getCommitStatus(transactionId) {
3831
- return this.recovery.getCommitStatus(transactionId);
4965
+ const snapshot = await this.acquireSnapshot();
4966
+ try {
4967
+ return await new RecoveryManager(this.owners.get(snapshot).storage, this.keys).getCommitStatus(transactionId);
4968
+ } finally {
4969
+ this.finishSnapshot(snapshot);
4970
+ }
3832
4971
  }
3833
4972
  async verifyHistory() {
3834
- return this.recovery.verifyHistory();
4973
+ const snapshot = await this.acquireSnapshot();
4974
+ try {
4975
+ return await new RecoveryManager(this.owners.get(snapshot).storage, this.keys).verifyHistory();
4976
+ } finally {
4977
+ this.finishSnapshot(snapshot);
4978
+ }
3835
4979
  }
3836
- /** Starts a new verifiable commit-history chain without changing data roots. */
3837
4980
  async checkpointHistory() {
4981
+ this.assertAccess();
3838
4982
  if (this.closed) throw new Error("Database is closed");
3839
4983
  if (this.maintenance || this.active.size || this.pendingSnapshotAcquisitions) throw new Error("History checkpoint requires exclusive database maintenance");
4984
+ const shared = storageCoordination(this.storage);
4985
+ if (shared.maintenance || shared.active) throw new Error("History checkpoint requires exclusive database maintenance");
4986
+ shared.maintenance = true;
3840
4987
  this.maintenance = true;
3841
4988
  const transactionId = (0, node_crypto.randomUUID)();
3842
4989
  try {
@@ -3866,26 +5013,29 @@ var DuraxisDatabase = class {
3866
5013
  return transactionId;
3867
5014
  } finally {
3868
5015
  this.maintenance = false;
5016
+ shared.maintenance = false;
3869
5017
  }
3870
5018
  }
3871
5019
  async verifyIntegrity() {
3872
5020
  const snapshot = await this.acquireSnapshot();
5021
+ const storage = this.owners.get(snapshot).storage;
5022
+ const primary = new PrimaryIndex(storage, this.keys);
3873
5023
  try {
3874
- const scanner = new ManifestReachabilityScanner(this.keys, this.storage);
3875
- const nodes = new BPlusTreeNodeStore(this.storage, this.keys);
5024
+ const scanner = new ManifestReachabilityScanner(this.keys, storage);
5025
+ const nodes = new BPlusTreeNodeStore(storage, this.keys);
3876
5026
  const reachable = await scanner.scan(snapshot);
3877
5027
  let objectsCount = 0;
3878
5028
  let nodesCount = 0;
3879
5029
  for (const ref of reachable) if (ref.startsWith(this.keys.objectPrefix)) {
3880
- await this.primary.readObject(ref);
5030
+ await primary.readObject(ref);
3881
5031
  objectsCount++;
3882
5032
  } else {
3883
5033
  this.keys.validateIndexNodeKey(ref);
3884
5034
  await nodes.read(ref);
3885
5035
  nodesCount++;
3886
5036
  }
3887
- const indexes = await new IndexConsistencyChecker(this.storage, this.keys).verify(snapshot.manifest);
3888
- const commits = await this.recovery.verifyHistory();
5037
+ const indexes = await new IndexConsistencyChecker(storage, this.keys).verify(snapshot.manifest);
5038
+ const commits = await new RecoveryManager(storage, this.keys).verifyHistory();
3889
5039
  return {
3890
5040
  objects: objectsCount,
3891
5041
  nodes: nodesCount,
@@ -3893,10 +5043,11 @@ var DuraxisDatabase = class {
3893
5043
  commits
3894
5044
  };
3895
5045
  } finally {
3896
- this.active.delete(snapshot);
5046
+ this.finishSnapshot(snapshot);
3897
5047
  }
3898
5048
  }
3899
5049
  async collectGarbage(storage, options = {}) {
5050
+ this.assertAccess();
3900
5051
  const started = performance.now();
3901
5052
  this.metrics.garbageCollections++;
3902
5053
  if (storage != this.storage) throw new Error("GC driver must match database storage");
@@ -3904,47 +5055,107 @@ var DuraxisDatabase = class {
3904
5055
  this.maintenance = true;
3905
5056
  try {
3906
5057
  if (options.dryRun == false && (this.active.size > 0 || this.pendingSnapshotAcquisitions > 0)) throw new Error("Active transactions or pending snapshots prevent GC");
3907
- return await new GarbageCollector(this.storage, this.keys, () => [...this.active]).collect(options);
5058
+ return await new GarbageCollector(this.storage, this.keys, () => [...this.active], new ManifestReachabilityScanner(this.keys, this.storage), this.resources).collect(options);
3908
5059
  } finally {
3909
5060
  this.metrics.garbageCollectionDurationMs += performance.now() - started;
3910
5061
  this.maintenance = false;
3911
5062
  }
3912
5063
  }
5064
+ finishSnapshot(snapshot) {
5065
+ this.owners.get(snapshot)?.finish();
5066
+ }
5067
+ queryContext(snapshot) {
5068
+ const owner = this.owners.get(snapshot);
5069
+ let context;
5070
+ const abort = () => context.cancel(owner.signal.reason);
5071
+ try {
5072
+ context = new QueryContext(owner.storage, snapshot, this.keys, {
5073
+ resources: owner.scope,
5074
+ limits: this.resourceLimits,
5075
+ assertAccess: () => this.assertAccess(),
5076
+ onPendingCleanup: (promise) => owner.holdCleanup(promise),
5077
+ onCleanupFailure: (error) => {
5078
+ if (this.cleanupFailures.length < 16) this.cleanupFailures.push(/* @__PURE__ */ new Error("Deferred query cleanup failed; inspect storage health"));
5079
+ },
5080
+ onClose: () => {
5081
+ owner.signal.removeEventListener("abort", abort);
5082
+ owner.finish();
5083
+ }
5084
+ });
5085
+ } catch (error) {
5086
+ owner.finish();
5087
+ throw error;
5088
+ }
5089
+ owner.signal.addEventListener("abort", abort, { once: true });
5090
+ if (owner.signal.aborted) abort();
5091
+ return context;
5092
+ }
3913
5093
  releaseSnapshot(snapshot, tx) {
3914
5094
  tx.close();
3915
- if (!tx.hasPendingReads) {
3916
- this.active.delete(snapshot);
3917
- return;
3918
- }
3919
- tx.waitForReads().then(() => {
3920
- this.active.delete(snapshot);
3921
- });
5095
+ this.finishSnapshot(snapshot);
3922
5096
  }
3923
5097
  queryOptions(options) {
3924
5098
  return {
3925
5099
  ...options,
3926
- cursorSigningKey: options?.cursorSigningKey ?? this.cursorSigningKey
5100
+ cursorSigningKey: this.cursorSigningKey,
5101
+ cursorEncryption: this.cursorEncryption,
5102
+ cursorNamespace: this.keys.namespace
3927
5103
  };
3928
5104
  }
3929
5105
  bindSignal(context, signal) {
3930
5106
  if (!signal) return () => {};
3931
5107
  const cancel = () => context.cancel(signal.reason ?? /* @__PURE__ */ new Error("Query cancelled"));
3932
- if (signal.aborted) cancel();
5108
+ if (signal.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
3933
5109
  else signal.addEventListener("abort", cancel, { once: true });
3934
5110
  return () => signal.removeEventListener("abort", cancel);
3935
5111
  }
3936
5112
  isOperator(value) {
3937
5113
  return value != null && typeof value.execute == "function";
3938
5114
  }
3939
- async acquireSnapshot() {
5115
+ async acquireSnapshot(kind = "snapshot") {
5116
+ this.assertAccess();
3940
5117
  if (this.closed) throw new Error("Database is closed");
3941
- if (this.maintenance) throw new Error("Database is in exclusive maintenance mode");
5118
+ if (this.maintenance || storageCoordination(this.storage).maintenance) throw new Error("Database is in exclusive maintenance mode");
5119
+ const scope = this.resources.child({ workingBytes: kind == "query" ? this.resourceLimits.maxQueryWorkingBytes : this.resourceLimits.maxTransactionWorkingBytes });
5120
+ try {
5121
+ scope.reserve({ snapshots: 1 });
5122
+ } catch (error) {
5123
+ scope.close();
5124
+ throw error;
5125
+ }
5126
+ const shared = storageCoordination(this.storage);
5127
+ shared.active++;
5128
+ let snapshot;
5129
+ const owner = new OperationOwner(scope, this.storage, Math.min(this.resourceLimits.maxSnapshotLifetimeMs, kind == "transaction" ? this.resourceLimits.maxTransactionDurationMs : kind == "query" ? this.resourceLimits.maxQueryDurationMs : this.resourceLimits.maxSnapshotLifetimeMs), () => {
5130
+ if (snapshot) {
5131
+ this.active.delete(snapshot);
5132
+ this.owners.delete(snapshot);
5133
+ shared.snapshots.delete(snapshot);
5134
+ }
5135
+ shared.active--;
5136
+ this.operations.delete(owner);
5137
+ if (!this.operations.size) for (const resolve of [...this.drainWaiters]) resolve();
5138
+ }, this.resourceLimits.maxStorageReadBytes);
5139
+ this.operations.add(owner);
3942
5140
  this.pendingSnapshotAcquisitions++;
3943
5141
  try {
3944
- const snapshot = await this.createSnapshot();
3945
- if (this.maintenance) throw new Error("Database is in exclusive maintenance mode");
5142
+ const stored = await owner.wait(owner.storage.get(this.keys.manifestKey));
5143
+ if (this.maintenance || this.closed) throw new Error("Database is not accepting snapshots");
5144
+ snapshot = stored == null ? {
5145
+ manifest: emptyManifest(),
5146
+ storageVersion: null
5147
+ } : {
5148
+ manifest: decodeManifest(stored.data, this.keys),
5149
+ storageVersion: stored.version
5150
+ };
5151
+ scope.reserve({ workingBytes: estimateBytes([...snapshot.manifest.catalog]) + estimateBytes([...snapshot.manifest.indexRoots]) });
3946
5152
  this.active.add(snapshot);
5153
+ shared.snapshots.add(snapshot);
5154
+ this.owners.set(snapshot, owner);
3947
5155
  return snapshot;
5156
+ } catch (error) {
5157
+ owner.finish();
5158
+ throw error;
3948
5159
  } finally {
3949
5160
  this.pendingSnapshotAcquisitions--;
3950
5161
  }
@@ -3952,14 +5163,37 @@ var DuraxisDatabase = class {
3952
5163
  getMetrics() {
3953
5164
  return {
3954
5165
  ...this.metrics,
5166
+ resources: this.resources.metrics(),
3955
5167
  ...this.storage.getMetrics ? { storage: this.storage.getMetrics() } : {}
3956
5168
  };
3957
5169
  }
3958
- async close(options = {}) {
3959
- if (this.closed) return;
3960
- if (this.active.size || this.pendingSnapshotAcquisitions) throw new Error("Cannot close database with active transactions or queries");
5170
+ close(options = {}) {
5171
+ if (this.closePromise) return this.closePromise;
3961
5172
  this.closed = true;
3962
- if (options.closeStorage) await this.storage.close?.();
5173
+ const timeout = options.timeoutMs ?? 3e4;
5174
+ if (!Number.isSafeInteger(timeout) || timeout < 1) return Promise.reject(/* @__PURE__ */ new RangeError("Invalid shutdown deadline"));
5175
+ this.closePromise = (async () => {
5176
+ for (const owner of this.operations) owner.cancel(new OperationCancelledError("Database is shutting down"));
5177
+ if (this.operations.size) await new Promise((resolve, reject) => {
5178
+ const complete = () => {
5179
+ clearTimeout(timer);
5180
+ this.drainWaiters.delete(complete);
5181
+ resolve();
5182
+ };
5183
+ const timer = setTimeout(() => {
5184
+ this.drainWaiters.delete(complete);
5185
+ reject(new OperationCancelledError(`Shutdown deadline exceeded; ${this.operations.size} operations still protect storage. Storage was not closed`));
5186
+ }, timeout);
5187
+ this.drainWaiters.add(complete);
5188
+ if (!this.operations.size) complete();
5189
+ });
5190
+ if (options.closeStorage) await this.storage.close?.();
5191
+ if (this.cleanupFailures.length) throw new AggregateError(this.cleanupFailures.splice(0), "Deferred query cleanup failed");
5192
+ })();
5193
+ this.closePromise.catch(() => {
5194
+ this.closePromise = void 0;
5195
+ });
5196
+ return this.closePromise;
3963
5197
  }
3964
5198
  async createSnapshot() {
3965
5199
  const stored = await this.storage.get(this.keys.manifestKey);
@@ -3992,6 +5226,7 @@ exports.BPlusTreeNodeStore = BPlusTreeNodeStore;
3992
5226
  exports.BPlusTreeValidator = BPlusTreeValidator;
3993
5227
  exports.CollectionScan = CollectionScan;
3994
5228
  exports.CommitOutcomeUnknownError = CommitOutcomeUnknownError;
5229
+ exports.DEFAULT_RESOURCE_LIMITS = DEFAULT_RESOURCE_LIMITS;
3995
5230
  exports.Difference = Difference;
3996
5231
  exports.DuraxisDatabase = DuraxisDatabase;
3997
5232
  exports.Filter = Filter;
@@ -4003,6 +5238,7 @@ exports.InvalidForeignKeyDefinitionError = InvalidForeignKeyDefinitionError;
4003
5238
  exports.Limit = Limit;
4004
5239
  exports.ManifestReachabilityScanner = ManifestReachabilityScanner;
4005
5240
  exports.ManifestSnapshotReader = ManifestSnapshotReader;
5241
+ exports.OperationCancelledError = OperationCancelledError;
4006
5242
  exports.PlanCompiler = PlanCompiler;
4007
5243
  exports.PredicateAnalyzer = PredicateAnalyzer;
4008
5244
  exports.PrimaryIndex = PrimaryIndex;
@@ -4015,6 +5251,8 @@ exports.RecoveryManager = RecoveryManager;
4015
5251
  exports.ReferenceQueryExecutor = ReferenceQueryExecutor;
4016
5252
  exports.ReferencedRecordNotFoundError = ReferencedRecordNotFoundError;
4017
5253
  exports.ReferencedRecordRestrictedError = ReferencedRecordRestrictedError;
5254
+ exports.ResourceExhaustedError = ResourceExhaustedError;
5255
+ exports.ResourceScope = ResourceScope;
4018
5256
  exports.RuleBasedPlanner = RuleBasedPlanner;
4019
5257
  exports.SecondaryIndexManager = SecondaryIndexManager;
4020
5258
  exports.SecondaryIndexRangeScan = SecondaryIndexRangeScan;
@@ -4038,6 +5276,7 @@ exports.encodeIdentifier = encodeIdentifier;
4038
5276
  exports.encodeQueryCursor = encodeQueryCursor;
4039
5277
  exports.encodeScalar = encodeScalar;
4040
5278
  exports.encodeSecondaryKey = encodeSecondaryKey;
5279
+ exports.estimateBytes = estimateBytes;
4041
5280
  exports.evaluatePredicate = evaluatePredicate;
4042
5281
  exports.explainPhysicalPlan = explainPhysicalPlan;
4043
5282
  exports.fieldDefinition = fieldDefinition;
@@ -4045,11 +5284,13 @@ exports.indexFields = indexFields;
4045
5284
  exports.indexId = indexId;
4046
5285
  exports.indexRangeBounds = indexRangeBounds;
4047
5286
  exports.indexedValue = indexedValue;
5287
+ exports.materialize = materialize;
4048
5288
  exports.normalizeCollection = normalizeCollection;
4049
5289
  exports.parseRecordKey = parseRecordKey;
4050
5290
  exports.prefixBounds = prefixBounds;
4051
5291
  exports.prefixSuccessor = prefixSuccessor;
4052
5292
  exports.recordKey = recordKey;
5293
+ exports.resourceLimits = resourceLimits;
4053
5294
  exports.secondaryIndexBounds = secondaryIndexBounds;
4054
5295
  exports.validateCollection = validateCollection;
4055
5296
  exports.validateDocument = validateDocument;