@duraxis/core 0.3.0 → 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,6 +373,7 @@ 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);
@@ -448,6 +788,34 @@ async function readCommitRecord(storage, keys, key) {
448
788
  if (keys.commitKey(record.transactionId, object.data) != key) throw new Error("Commit record identity mismatch");
449
789
  return record;
450
790
  }
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);
817
+ }
818
+ };
451
819
  // src/indexes/bptree/bptree-codec.ts
452
820
  var encoder$3 = new TextEncoder();
453
821
  var decoder$3 = new TextDecoder("utf-8", { fatal: true });
@@ -1097,16 +1465,22 @@ var PrimaryIndex = class {
1097
1465
  }
1098
1466
  };
1099
1467
  // src/indexes/bptree/bptree-node-cache.ts
1100
- /** Query-scoped LRU for already integrity-checked immutable nodes. */
1101
1468
  var BPlusTreeNodeCache = class {
1102
1469
  source;
1103
1470
  capacity;
1471
+ maxBytes;
1104
1472
  entries = /* @__PURE__ */ new Map();
1473
+ sizes = /* @__PURE__ */ new Map();
1474
+ bytes = 0;
1475
+ reservation;
1105
1476
  hits = 0;
1106
1477
  misses = 0;
1107
- constructor(source, capacity = 256) {
1478
+ constructor(source, capacity = 256, maxBytes = 4194304, resources = new ResourceScope({})) {
1108
1479
  this.source = source;
1109
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");
1110
1484
  if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 65536) throw new Error("Invalid B+tree node cache capacity");
1111
1485
  }
1112
1486
  async read(ref) {
@@ -1119,8 +1493,19 @@ var BPlusTreeNodeCache = class {
1119
1493
  }
1120
1494
  this.misses++;
1121
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);
1122
1508
  this.entries.set(ref, node);
1123
- if (this.entries.size > this.capacity) this.entries.delete(this.entries.keys().next().value);
1124
1509
  return node;
1125
1510
  }
1126
1511
  write(node) {
@@ -1128,11 +1513,15 @@ var BPlusTreeNodeCache = class {
1128
1513
  }
1129
1514
  clear() {
1130
1515
  this.entries.clear();
1516
+ this.sizes.clear();
1517
+ this.bytes = 0;
1518
+ this.reservation.resize({});
1131
1519
  }
1132
1520
  getMetrics() {
1133
1521
  return {
1134
1522
  hits: this.hits,
1135
- misses: this.misses
1523
+ misses: this.misses,
1524
+ bytes: this.bytes
1136
1525
  };
1137
1526
  }
1138
1527
  };
@@ -1363,13 +1752,13 @@ var SecondaryIndexManager = class {
1363
1752
  this.nodes = nodes;
1364
1753
  this.primary = new PrimaryIndex(storage, keys, nodes);
1365
1754
  }
1366
- async prepare(previousManifest, nextPrimaryRoot, writes, catalog) {
1755
+ async prepare(previousManifest, nextPrimaryRoot, writes, catalog, resources) {
1367
1756
  const roots = new Map(previousManifest.indexRoots);
1368
1757
  const declared = /* @__PURE__ */ new Set();
1369
1758
  const tree = new BPlusTree(this.nodes);
1370
1759
  for (const [collectionName, schema] of catalog) {
1371
1760
  const previousSchema = previousManifest.catalog.get(collectionName);
1372
- const changes = await this.collectChanges(previousManifest, collectionName, writes);
1761
+ const changes = await this.collectChanges(previousManifest, collectionName, writes, resources);
1373
1762
  for (const index of schema.indexes) {
1374
1763
  const id = indexId(collectionName, index.name);
1375
1764
  declared.add(id);
@@ -1422,15 +1811,20 @@ var SecondaryIndexManager = class {
1422
1811
  for (const id of [...roots.keys()]) if (!declared.has(id)) roots.delete(id);
1423
1812
  return roots;
1424
1813
  }
1425
- async collectChanges(manifest, collection, writes) {
1814
+ async collectChanges(manifest, collection, writes, resources) {
1426
1815
  const changes = [];
1816
+ const memory = resources?.reserve({});
1817
+ let bytes = 0;
1427
1818
  for (const [key, operation] of writes) {
1428
1819
  const parsed = parseRecordKey(key);
1429
1820
  if (parsed == null || parsed.collection != collection) continue;
1430
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 });
1431
1825
  changes.push({
1432
1826
  recordId: parsed.id,
1433
- previous: previousRef == null ? void 0 : decodeDocument(await this.primary.readObject(previousRef)),
1827
+ previous: previousRef == null ? void 0 : decodeDocument(previousData),
1434
1828
  next: operation.type == "put" ? decodeDocument(operation.data) : void 0
1435
1829
  });
1436
1830
  }
@@ -1521,8 +1915,10 @@ function cloneWrites(source) {
1521
1915
  return result;
1522
1916
  }
1523
1917
  var QueryContext = class {
1524
- snapshot;
1525
1918
  options;
1919
+ resources;
1920
+ limits;
1921
+ iteratorReservations = [];
1526
1922
  primary;
1527
1923
  secondary;
1528
1924
  nodeCache;
@@ -1531,6 +1927,8 @@ var QueryContext = class {
1531
1927
  startedAt = performance.now();
1532
1928
  active = true;
1533
1929
  iterators = 0;
1930
+ timer;
1931
+ cancellationReturns = /* @__PURE__ */ new Set();
1534
1932
  metrics = {
1535
1933
  storageReads: 0,
1536
1934
  storageWrites: 0,
@@ -1542,15 +1940,49 @@ var QueryContext = class {
1542
1940
  cacheMisses: 0,
1543
1941
  durationMs: 0
1544
1942
  };
1545
- catalog;
1943
+ snapshotValue;
1944
+ get snapshot() {
1945
+ this.assertActive();
1946
+ return this.snapshotValue;
1947
+ }
1948
+ catalogValue = /* @__PURE__ */ new Map();
1949
+ get catalog() {
1950
+ return this.catalogValue;
1951
+ }
1546
1952
  constructor(storage, snapshot, keys, options = {}) {
1547
- this.snapshot = snapshot;
1548
1953
  this.options = options;
1549
- this.nodeCache = new BPlusTreeNodeCache(new BPlusTreeNodeStore(storage, keys));
1550
- this.primary = new PrimaryIndex(storage, keys, this.nodeCache);
1551
- this.secondary = new SecondaryIndexManager(storage, keys, this.nodeCache);
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
+ });
1960
+ try {
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;
1969
+ }
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);
1552
1982
  this.writes = cloneWrites(options.writes);
1553
- this.catalog = new Map(options.catalog ?? snapshot.manifest.catalog);
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();
1554
1986
  }
1555
1987
  get generation() {
1556
1988
  return this.snapshot.manifest.transactionId || "initial";
@@ -1561,30 +1993,78 @@ var QueryContext = class {
1561
1993
  get isActive() {
1562
1994
  return this.active;
1563
1995
  }
1564
- 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) {
1565
2019
  if (!this.active) return;
1566
2020
  this.active = false;
2021
+ clearTimeout(this.timer);
2022
+ this.cancellationReturns.clear();
1567
2023
  const cache = this.nodeCache.getMetrics();
1568
2024
  this.metrics.cacheHits = cache.hits;
1569
2025
  this.metrics.cacheMisses = cache.misses;
1570
2026
  this.metrics.durationMs = performance.now() - this.startedAt;
1571
2027
  this.controller.abort(reason);
1572
2028
  this.nodeCache.clear();
1573
- 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();
1574
2045
  }
1575
2046
  cancel(reason = /* @__PURE__ */ new Error("Query cancelled")) {
1576
- 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);
1577
2053
  }
1578
2054
  assertActive() {
2055
+ this.options.assertAccess?.();
1579
2056
  if (!this.active) throw this.controller.signal.reason ?? /* @__PURE__ */ new Error("Query context is closed");
1580
2057
  }
1581
2058
  begin() {
1582
2059
  this.assertActive();
2060
+ this.iteratorReservations.push(this.resources.reserve({ iterators: this.iterators ? 1 : 0 }));
1583
2061
  this.iterators++;
1584
2062
  this.options.onIteratorStart?.();
1585
2063
  }
1586
2064
  end() {
1587
- if (this.iterators > 0) this.iterators--;
2065
+ if (this.iterators == 0) return;
2066
+ this.iterators--;
2067
+ this.iteratorReservations.pop()?.release();
1588
2068
  this.options.onIteratorEnd?.();
1589
2069
  }
1590
2070
  schema(collection) {
@@ -1611,7 +2091,7 @@ var QueryContext = class {
1611
2091
  }
1612
2092
  return result;
1613
2093
  }
1614
- async *scanCollection(collection, options = {}) {
2094
+ async *scanCollectionRows(collection, options = {}) {
1615
2095
  this.begin();
1616
2096
  try {
1617
2097
  this.schema(collection);
@@ -1689,6 +2169,8 @@ var QueryContext = class {
1689
2169
  const bounds = secondaryIndexBounds(index, options);
1690
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);
1691
2171
  const result = [];
2172
+ let bytes = 0;
2173
+ const memory = this.resources.reserve({});
1692
2174
  for (const [id, write] of this.pendingFor(collection)) {
1693
2175
  if (write.type != "put") continue;
1694
2176
  const document = decodeDocument(write.data);
@@ -1704,17 +2186,21 @@ var QueryContext = class {
1704
2186
  }
1705
2187
  if (missing) continue;
1706
2188
  const key = encodeSecondaryKey(values, index.unique ? void 0 : id, orders);
1707
- if (matches(key)) result.push({
1708
- key,
1709
- row: {
1710
- id,
1711
- document
1712
- }
1713
- });
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
+ }
1714
2200
  }
1715
2201
  return result;
1716
2202
  }
1717
- async *scanIndex(collection, indexName, options = {}) {
2203
+ async *scanIndexRows(collection, indexName, options = {}) {
1718
2204
  this.begin();
1719
2205
  try {
1720
2206
  const schema = this.schema(collection);
@@ -1726,14 +2212,20 @@ var QueryContext = class {
1726
2212
  const parts = indexFields(index);
1727
2213
  const bounds = secondaryIndexBounds(index, options);
1728
2214
  const entries = [];
2215
+ const memory = this.resources.reserve({});
2216
+ let bytes = 0;
1729
2217
  for await (const row of this.scanCollection(collection, { signal: options.signal })) {
1730
2218
  const values = parts.map((part) => indexedValue(row.document, part.field, fieldDefinition(schema, part.field)));
1731
2219
  if (values.some((value) => value === void 0)) continue;
1732
2220
  const key = encodeSecondaryKey(values, index.unique ? void 0 : row.id, parts.map((part) => part.order));
1733
- 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)) entries.push({
1734
- key,
1735
- row
1736
- });
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
+ }
1737
2229
  }
1738
2230
  const limit = options.limit ?? Number.MAX_SAFE_INTEGER;
1739
2231
  if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid query limit");
@@ -1803,7 +2295,7 @@ var TransactionConflictError = class extends Error {
1803
2295
  var CommitOutcomeUnknownError = class extends Error {
1804
2296
  transactionId;
1805
2297
  constructor(transactionId, cause) {
1806
- super(`Commit outcome is unknown for transaction ${transactionId}` + (cause instanceof Error ? `: ${cause.message}` : ""), { cause });
2298
+ super(`Commit outcome is unknown for transaction ${transactionId}; reconcile before retrying`, { cause });
1807
2299
  this.name = "CommitOutcomeUnknownError";
1808
2300
  this.transactionId = transactionId;
1809
2301
  }
@@ -1817,9 +2309,9 @@ var ForeignKeyManager = class {
1817
2309
  this.#primary = new PrimaryIndex(storage, keys);
1818
2310
  this.#secondary = new SecondaryIndexManager(storage, keys);
1819
2311
  }
1820
- async prepare(snapshot, sourceWrites, sourceCatalog) {
2312
+ async prepare(snapshot, sourceWrites, sourceCatalog, targetWrites) {
1821
2313
  const catalog = this.validateCatalog(sourceCatalog);
1822
- const writes = new Map(sourceWrites);
2314
+ const writes = targetWrites ?? new Map(sourceWrites);
1823
2315
  const incoming = this.incoming(catalog);
1824
2316
  const queue = [];
1825
2317
  const visited = /* @__PURE__ */ new Set();
@@ -1952,25 +2444,40 @@ var ForeignKeyManager = class {
1952
2444
  var CommitCoordinator = class {
1953
2445
  storage;
1954
2446
  keys;
2447
+ coordinationStorage;
1955
2448
  primary;
1956
2449
  secondary;
1957
2450
  foreignKeys;
1958
- constructor(storage, keys = new StorageKeyManager()) {
2451
+ constructor(storage, keys = new StorageKeyManager(), coordinationStorage = storage) {
1959
2452
  this.storage = storage;
1960
2453
  this.keys = keys;
2454
+ this.coordinationStorage = coordinationStorage;
1961
2455
  this.primary = new PrimaryIndex(storage, keys);
1962
2456
  this.secondary = new SecondaryIndexManager(storage, keys);
1963
2457
  this.foreignKeys = new ForeignKeyManager(storage, keys);
1964
2458
  }
1965
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) {
1966
2473
  const prepared = transaction.prepareForCommit();
1967
2474
  if (prepared.writes.size == 0 && prepared.schemaChanges.size == 0) {
1968
2475
  transaction.markCommitted();
1969
2476
  return;
1970
2477
  }
1971
- const transactionId = (0, node_crypto.randomUUID)();
2478
+ const transactionId = transaction.id;
1972
2479
  const catalog = new Map(prepared.snapshot.manifest.catalog);
1973
- const staged = new Map(prepared.writes);
2480
+ const staged = new PreparedWrites(transaction.resources, transaction.limits, prepared.writes);
1974
2481
  for (const [name, schema] of prepared.schemaChanges) {
1975
2482
  if (schema == null) catalog.delete(name);
1976
2483
  else catalog.set(name, schema);
@@ -1983,7 +2490,9 @@ var CommitCoordinator = class {
1983
2490
  });
1984
2491
  const context = new QueryContext(this.storage, prepared.snapshot, this.keys, {
1985
2492
  writes: staged,
1986
- catalog: scanCatalog
2493
+ catalog: scanCatalog,
2494
+ resources: transaction.resources,
2495
+ limits: transaction.limits
1987
2496
  });
1988
2497
  try {
1989
2498
  for await (const row of context.scanCollection(name)) staged.set(recordKey(name, row.id), schema == null ? { type: "delete" } : {
@@ -1994,7 +2503,8 @@ var CommitCoordinator = class {
1994
2503
  context.close();
1995
2504
  }
1996
2505
  }
1997
- const writes = await this.foreignKeys.prepare(prepared.snapshot, staged, catalog);
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);
1998
2508
  const changes = /* @__PURE__ */ new Map();
1999
2509
  for (const [key, operation] of writes) {
2000
2510
  if (operation.type == "delete") {
@@ -2006,7 +2516,7 @@ var CommitCoordinator = class {
2006
2516
  changes.set(key, ref);
2007
2517
  }
2008
2518
  const primaryRoot = await this.primary.prepare(prepared.snapshot.manifest.primaryRoot, changes);
2009
- const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog);
2519
+ const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog, transaction.resources);
2010
2520
  const commitBytes = encodeCommitRecord({
2011
2521
  format: 1,
2012
2522
  transactionId,
@@ -2033,7 +2543,10 @@ var CommitCoordinator = class {
2033
2543
  transaction.markUnknown();
2034
2544
  throw new CommitOutcomeUnknownError(transactionId, cause);
2035
2545
  }
2036
- if (!result.success) throw new TransactionConflictError();
2546
+ if (!result.success) {
2547
+ transaction.rejectPublication();
2548
+ throw new TransactionConflictError();
2549
+ }
2037
2550
  transaction.markCommitted();
2038
2551
  }
2039
2552
  };
@@ -2084,7 +2597,7 @@ function hmac(key, value) {
2084
2597
  function queryHash(key, query) {
2085
2598
  return hmac(key, canonical(shape(query)));
2086
2599
  }
2087
- function encodeQueryCursor(generation, schema, query, row, signingKey) {
2600
+ function encodeLegacyCursor(generation, schema, query, row, signingKey) {
2088
2601
  if (query.collection != schema.name) throw new Error("Cursor collection mismatch");
2089
2602
  const values = (query.orderBy ?? []).map(({ field }) => {
2090
2603
  if (field == "$id") return row.id;
@@ -2107,7 +2620,7 @@ function encodeQueryCursor(generation, schema, query, row, signingKey) {
2107
2620
  signature: hmac(signingKey, payload)
2108
2621
  })).toString("base64url");
2109
2622
  }
2110
- function decodeQueryCursor(cursor, generation, schema, query, signingKey) {
2623
+ function decodeLegacyCursor(cursor, generation, schema, query, signingKey) {
2111
2624
  let parsed;
2112
2625
  try {
2113
2626
  parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
@@ -2135,6 +2648,108 @@ function decodeQueryCursor(cursor, generation, schema, query, signingKey) {
2135
2648
  })
2136
2649
  };
2137
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
+ }
2138
2753
  // src/query/validation/query-validator.ts
2139
2754
  var MAX_PREDICATE_DEPTH = 64;
2140
2755
  var MAX_IN_VALUES = 1e4;
@@ -2205,10 +2820,36 @@ function predicate(schema, value, depth) {
2205
2820
  default: throw new Error("Unknown query predicate");
2206
2821
  }
2207
2822
  }
2208
- 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) {
2209
2849
  if (!query || typeof query != "object" || !isValidSchemaName(query.collection)) throw new Error("Invalid logical query");
2210
2850
  const schema = catalog.get(query.collection);
2211
2851
  if (!schema) throw new Error(`Unknown collection: ${query.collection}`);
2852
+ validatePredicateComplexity(query, limits?.maxPredicateDepth, limits?.maxPredicateNodes);
2212
2853
  if (query.where) predicate(schema, query.where, 0);
2213
2854
  const orders = /* @__PURE__ */ new Set();
2214
2855
  for (const order of query.orderBy ?? []) {
@@ -2423,12 +3064,24 @@ var Sort = class {
2423
3064
  const maximum = this.options.maxRowsInMemory ?? 1e4;
2424
3065
  if (!Number.isSafeInteger(maximum) || maximum < 2) throw new Error("Invalid sort memory limit");
2425
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({});
2426
3072
  const spill = this.options.spill;
2427
3073
  let chunk = [];
2428
3074
  let runs = [];
2429
3075
  const active = /* @__PURE__ */ new Set();
2430
3076
  const write = async (rows) => {
2431
- 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());
2432
3085
  active.add(handle);
2433
3086
  return handle;
2434
3087
  };
@@ -2450,12 +3103,24 @@ var Sort = class {
2450
3103
  };
2451
3104
  try {
2452
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;
2453
3116
  chunk.push(row);
2454
3117
  if (chunk.length < maximum) continue;
2455
3118
  if (!this.options.spill) throw new QueryMemoryLimitError();
2456
3119
  chunk.sort(compare);
2457
3120
  runs.push(await write(chunk));
2458
3121
  chunk = [];
3122
+ chunkBytes = 0;
3123
+ chunkMemory.resize({});
2459
3124
  }
2460
3125
  if (runs.length == 0) {
2461
3126
  chunk.sort(compare);
@@ -2482,7 +3147,12 @@ var Sort = class {
2482
3147
  }
2483
3148
  yield* merge(runs);
2484
3149
  } finally {
2485
- 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
+ }
2486
3156
  }
2487
3157
  }
2488
3158
  };
@@ -2539,9 +3209,15 @@ var SetOperator = class {
2539
3209
  }
2540
3210
  async ids(context, input) {
2541
3211
  const result = /* @__PURE__ */ new Map();
3212
+ const memory = context.resources.reserve({});
3213
+ let bytes = 0;
2542
3214
  for await (const row of input.execute(context)) {
2543
3215
  context.assertActive();
2544
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
+ }
2545
3221
  result.set(row.id, row);
2546
3222
  }
2547
3223
  return result;
@@ -2551,10 +3227,14 @@ var Union = class extends SetOperator {
2551
3227
  name = "Union";
2552
3228
  async *execute(context) {
2553
3229
  const seen = /* @__PURE__ */ new Set();
3230
+ const memory = context.resources.reserve({});
3231
+ let bytes = 0;
2554
3232
  for (const input of this.inputs) for await (const row of input.execute(context)) {
2555
3233
  context.assertActive();
2556
3234
  if (seen.has(row.id)) continue;
2557
3235
  if (seen.size >= this.maxSetEntries) throw new QueryMemoryLimitError();
3236
+ bytes += row.id.length * 2 + 48;
3237
+ memory.resize({ workingBytes: bytes });
2558
3238
  seen.add(row.id);
2559
3239
  yield row;
2560
3240
  }
@@ -2567,7 +3247,7 @@ var Intersection = class extends SetOperator {
2567
3247
  const candidates = await this.ids(context, first);
2568
3248
  for (const input of rest) {
2569
3249
  const current = await this.ids(context, input);
2570
- 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);
2571
3251
  }
2572
3252
  for (const row of candidates.values()) {
2573
3253
  context.assertActive();
@@ -2585,7 +3265,15 @@ var Difference = class extends SetOperator {
2585
3265
  this.excluded = excluded;
2586
3266
  }
2587
3267
  async *execute(context) {
2588
- 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
+ }
2589
3277
  for await (const row of this.universe.execute(context)) {
2590
3278
  context.assertActive();
2591
3279
  if (!excluded.has(row.id)) yield row;
@@ -2651,7 +3339,7 @@ var QueryExecutor = class {
2651
3339
  }
2652
3340
  }
2653
3341
  semanticPipeline(context, query, source, forceDeterministicSort = false, executionLimit = query.limit) {
2654
- validateQuery(query, context.catalog);
3342
+ validateQuery(query, context.catalog, context.limits);
2655
3343
  let operator = source;
2656
3344
  if (query.where) operator = new Filter(operator, query.where, query.collection);
2657
3345
  const orderBy = query.orderBy ?? [];
@@ -2660,7 +3348,7 @@ var QueryExecutor = class {
2660
3348
  spill: this.options.sortSpill
2661
3349
  });
2662
3350
  if (query.cursor) {
2663
- 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);
2664
3352
  operator = new CursorAfter(operator, orderBy, cursor.values, cursor.id, query.collection);
2665
3353
  }
2666
3354
  if (executionLimit != null) operator = new Limit(operator, executionLimit);
@@ -2671,6 +3359,7 @@ var QueryExecutor = class {
2671
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);
2672
3360
  }
2673
3361
  signingKey() {
3362
+ if (this.options.cursorEncryption) return this.options.cursorEncryption;
2674
3363
  const key = this.options.cursorSigningKey;
2675
3364
  if (!(key instanceof Uint8Array) || key.byteLength < 32) throw new Error("Cursor operations require a signing key of at least 32 bytes");
2676
3365
  return key;
@@ -2684,11 +3373,19 @@ var QueryExecutor = class {
2684
3373
  const lookahead = query.limit == null ? void 0 : query.limit + 1;
2685
3374
  const operator = this.semanticPipeline(context, query, source, true, lookahead);
2686
3375
  const raw = [];
2687
- 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
+ }
2688
3385
  const schema = context.catalog.get(query.collection);
2689
3386
  const hasMore = query.limit != null && query.limit > 0 && raw.length > query.limit;
2690
3387
  if (hasMore) raw.pop();
2691
- 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;
2692
3389
  return {
2693
3390
  rows: query.projection ? raw.map((row) => ({
2694
3391
  id: row.id,
@@ -2950,8 +3647,8 @@ var RuleBasedPlanner = class {
2950
3647
  constructor(enumerator = new AccessPathEnumerator()) {
2951
3648
  this.enumerator = enumerator;
2952
3649
  }
2953
- plan(query, catalog) {
2954
- const schema = validateQuery(query, catalog);
3650
+ plan(query, catalog, limits) {
3651
+ const schema = validateQuery(query, catalog, limits);
2955
3652
  const selected = this.choose(query, schema, query.where);
2956
3653
  const required = query.orderBy ?? [];
2957
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));
@@ -3088,23 +3785,70 @@ var Transaction = class {
3088
3785
  storage;
3089
3786
  keys;
3090
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();
3091
3800
  writes = /* @__PURE__ */ new Map();
3092
3801
  schemas = /* @__PURE__ */ new Map();
3093
- capturedSnapshot;
3094
- 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
+ }
3095
3818
  stateValue = "ACTIVE";
3096
3819
  pendingReads = 0;
3097
3820
  readWaiters = [];
3098
3821
  queryContexts = /* @__PURE__ */ new Set();
3099
3822
  planner = new RuleBasedPlanner();
3100
3823
  planCompiler = new PlanCompiler();
3101
- constructor(storage, snapshot, keys = new StorageKeyManager(), cursorSigningKey) {
3824
+ constructor(storage, snapshot, keys = new StorageKeyManager(), cursorSigningKey, parentResources, limits = resourceLimits(), operationSignal, onPublication, assertAccessScope, runtimeHooks = {}) {
3102
3825
  this.storage = storage;
3103
3826
  this.keys = keys;
3104
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]) });
3105
3841
  this.capturedSnapshot = cloneSnapshot(snapshot);
3106
3842
  this.reader = new ManifestSnapshotReader(this.storage, this.capturedSnapshot, keys);
3107
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
+ }
3108
3852
  get state() {
3109
3853
  return this.stateValue;
3110
3854
  }
@@ -3121,6 +3865,9 @@ var Transaction = class {
3121
3865
  const result = await this.reader.get(key);
3122
3866
  this.assertActive();
3123
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;
3124
3871
  } finally {
3125
3872
  this.pendingReads--;
3126
3873
  if (this.pendingReads == 0) for (const resolve of this.readWaiters.splice(0)) resolve();
@@ -3136,14 +3883,14 @@ var Transaction = class {
3136
3883
  this.assertActive();
3137
3884
  this.validateKey(key);
3138
3885
  if (key.startsWith("@duraxis/records/")) throw new Error("Reserved internal collection key");
3139
- this.writes.set(key, { type: "delete" });
3886
+ this.stageDelete(key);
3140
3887
  }
3141
3888
  defineCollection(definition) {
3142
3889
  this.assertActive();
3143
3890
  validateCollection(definition);
3144
3891
  if (this.schemas.get(definition.name) === null) throw new Error("Cannot recreate a dropped collection in the same transaction");
3145
3892
  if (this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3146
- this.schemas.set(definition.name, cloneSchema(definition));
3893
+ this.stageSchema(definition.name, cloneSchema(definition));
3147
3894
  }
3148
3895
  defineCollections(definitions) {
3149
3896
  this.assertActive();
@@ -3153,7 +3900,7 @@ var Transaction = class {
3153
3900
  if (names.has(definition.name) || this.schemas.has(definition.name) || this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3154
3901
  names.add(definition.name);
3155
3902
  }
3156
- for (const definition of definitions) this.schemas.set(definition.name, cloneSchema(definition));
3903
+ for (const definition of definitions) this.stageSchema(definition.name, cloneSchema(definition));
3157
3904
  }
3158
3905
  getCollectionDefinitions() {
3159
3906
  this.assertActive();
@@ -3166,12 +3913,12 @@ var Transaction = class {
3166
3913
  this.assertActive();
3167
3914
  this.requireCollection(name);
3168
3915
  if (name != definition.name) throw new Error("Collection replacement cannot rename a collection");
3169
- this.schemas.set(name, cloneSchema(definition));
3916
+ this.stageSchema(name, cloneSchema(definition));
3170
3917
  }
3171
3918
  dropCollection(name) {
3172
3919
  this.assertActive();
3173
3920
  this.requireCollection(name);
3174
- this.schemas.set(name, null);
3921
+ this.stageSchema(name, null);
3175
3922
  }
3176
3923
  async getMetadata(namespace) {
3177
3924
  this.assertActive();
@@ -3210,13 +3957,13 @@ var Transaction = class {
3210
3957
  indexes: [...current.indexes, index]
3211
3958
  };
3212
3959
  validateCollection(updated);
3213
- this.schemas.set(collection, cloneSchema(updated));
3960
+ this.stageSchema(collection, cloneSchema(updated));
3214
3961
  }
3215
3962
  removeIndex(collection, indexName) {
3216
3963
  this.assertActive();
3217
3964
  const current = this.requireCollection(collection);
3218
3965
  if (!current.indexes.some((index) => index.name == indexName)) throw new Error(`Unknown index: ${collection}/${indexName}`);
3219
- this.schemas.set(collection, cloneSchema({
3966
+ this.stageSchema(collection, cloneSchema({
3220
3967
  ...current,
3221
3968
  indexes: current.indexes.filter((index) => index.name != indexName)
3222
3969
  }));
@@ -3234,6 +3981,16 @@ var Transaction = class {
3234
3981
  else catalog.set(name, cloneSchema(schema));
3235
3982
  let context;
3236
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,
3237
3994
  writes: this.writes,
3238
3995
  catalog,
3239
3996
  onIteratorStart: () => {
@@ -3249,18 +4006,21 @@ var Transaction = class {
3249
4006
  const context = this.createQueryContext();
3250
4007
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3251
4008
  const options = explicit ? explicitOptions : sourceOrOptions;
3252
- 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);
3253
4010
  const executor = new QueryExecutor(this.queryOptions(options));
3254
4011
  const transaction = this;
3255
- return (async function* () {
3256
- const unbindSignal = transaction.bindSignal(context, options?.signal);
4012
+ const iterator = (async function* () {
4013
+ let unbindSignal = () => {};
3257
4014
  try {
4015
+ unbindSignal = transaction.bindSignal(context, options?.signal);
3258
4016
  yield* executor.execute(context, query, source);
3259
4017
  } finally {
3260
4018
  unbindSignal();
3261
4019
  context.close();
3262
4020
  }
3263
4021
  })();
4022
+ context.bindCancellation(() => iterator.return(void 0));
4023
+ return iterator;
3264
4024
  }
3265
4025
  async queryPage(query, sourceOrOptions, explicitOptions) {
3266
4026
  const context = this.createQueryContext();
@@ -3269,7 +4029,7 @@ var Transaction = class {
3269
4029
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3270
4030
  const options = explicit ? explicitOptions : sourceOrOptions;
3271
4031
  unbindSignal = this.bindSignal(context, options?.signal);
3272
- 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);
3273
4033
  return await new QueryExecutor(this.queryOptions(options)).page(context, query, source);
3274
4034
  } finally {
3275
4035
  unbindSignal();
@@ -3279,22 +4039,29 @@ var Transaction = class {
3279
4039
  putDocument(collection, id, document) {
3280
4040
  this.assertActive();
3281
4041
  const schema = this.requireCollection(collection);
3282
- const parsed = validateDocument(schema, document);
3283
- const data = encodeDocument(parsed);
3284
- for (const index of schema.indexes) for (const part of index.fields ?? (index.field ? [{
3285
- field: index.field,
3286
- order: "ASC"
3287
- }] : [])) indexedValue(parsed, part.field, fieldDefinition(schema, part.field));
3288
- 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
+ }
3289
4055
  }
3290
4056
  deleteDocument(collection, id) {
3291
4057
  this.assertActive();
3292
4058
  this.requireCollection(collection);
3293
- this.writes.set(recordKey(collection, id), { type: "delete" });
4059
+ this.stageDelete(recordKey(collection, id));
3294
4060
  }
3295
4061
  prepareForCommit() {
3296
4062
  this.assertActive();
3297
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) });
3298
4065
  this.stateValue = "PREPARING";
3299
4066
  const writes = /* @__PURE__ */ new Map();
3300
4067
  for (const [key, operation] of this.writes) writes.set(key, operation.type == "delete" ? { type: "delete" } : {
@@ -3314,7 +4081,9 @@ var Transaction = class {
3314
4081
  });
3315
4082
  }
3316
4083
  beginPublication() {
4084
+ this.assertAccessScope?.();
3317
4085
  if (this.stateValue != "PREPARING") throw new TransactionStateError("Transaction is not preparing");
4086
+ this.onPublication?.();
3318
4087
  this.stateValue = "COMMITTING";
3319
4088
  }
3320
4089
  markCommitted() {
@@ -3325,17 +4094,56 @@ var Transaction = class {
3325
4094
  this.stateValue = "UNKNOWN";
3326
4095
  }
3327
4096
  abort() {
4097
+ if (this.stateValue == "COMMITTING") return;
3328
4098
  if (this.stateValue != "COMMITTED" && this.stateValue != "UNKNOWN") this.stateValue = "ABORTED";
3329
4099
  }
4100
+ rejectPublication() {
4101
+ if (this.stateValue != "COMMITTING") throw new TransactionStateError("No publication in progress");
4102
+ this.stateValue = "ABORTED";
4103
+ }
3330
4104
  close() {
4105
+ if (this.stateValue == "COMMITTING") return;
4106
+ this.localCancellation.abort(new TransactionStateError("Transaction is closed"));
3331
4107
  if (this.stateValue == "ACTIVE" || this.stateValue == "PREPARING") this.abort();
3332
- for (const context of [...this.queryContexts]) context.close();
4108
+ for (const context of [...this.queryContexts]) context.cancel(new TransactionStateError("Transaction is closed"));
3333
4109
  this.queryContexts.clear();
3334
4110
  this.writes.clear();
3335
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);
3336
4143
  }
3337
4144
  stagePut(key, data) {
3338
4145
  if (!(data instanceof Uint8Array)) throw new TypeError("Storage value must be Uint8Array");
4146
+ this.reserveWrite(key, data.byteLength);
3339
4147
  this.writes.set(key, {
3340
4148
  type: "put",
3341
4149
  data: new Uint8Array(data)
@@ -3348,13 +4156,15 @@ var Transaction = class {
3348
4156
  queryOptions(options) {
3349
4157
  return {
3350
4158
  ...options,
3351
- cursorSigningKey: options?.cursorSigningKey ?? this.cursorSigningKey
4159
+ cursorSigningKey: this.cursorSigningKey,
4160
+ cursorEncryption: this.runtimeHooks.cursorEncryption,
4161
+ cursorNamespace: this.keys.namespace
3352
4162
  };
3353
4163
  }
3354
4164
  bindSignal(context, signal) {
3355
4165
  if (!signal) return () => {};
3356
4166
  const cancel = () => context.cancel(signal.reason ?? /* @__PURE__ */ new Error("Query cancelled"));
3357
- if (signal.aborted) cancel();
4167
+ if (signal.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
3358
4168
  else signal.addEventListener("abort", cancel, { once: true });
3359
4169
  return () => signal.removeEventListener("abort", cancel);
3360
4170
  }
@@ -3370,9 +4180,12 @@ var Transaction = class {
3370
4180
  return schema;
3371
4181
  }
3372
4182
  assertActive() {
4183
+ this.assertAccessScope?.();
4184
+ this.operationSignal?.throwIfAborted();
3373
4185
  if (this.stateValue != "ACTIVE") throw new TransactionStateError("Transaction is no longer active");
3374
4186
  }
3375
4187
  validateKey(key) {
4188
+ if (Buffer.byteLength(key) > 1024) throw new ResourceExhaustedError("keyBytes", 1024);
3376
4189
  this.keys.validateLogicalKey(key);
3377
4190
  encodeIndexKey(new TextEncoder().encode(key));
3378
4191
  }
@@ -3422,6 +4235,196 @@ var RecoveryManager = class {
3422
4235
  return count;
3423
4236
  }
3424
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
+ };
3425
4428
  // src/indexes/bptree/bptree-validator.ts
3426
4429
  var BPlusTreeValidator = class {
3427
4430
  nodes;
@@ -3523,125 +4526,6 @@ var BPlusTreeValidator = class {
3523
4526
  return found;
3524
4527
  }
3525
4528
  };
3526
- // src/gc/reachability-scanner.ts
3527
- var ManifestReachabilityScanner = class {
3528
- keys;
3529
- nodes;
3530
- primary;
3531
- constructor(keys, storage) {
3532
- this.keys = keys;
3533
- this.nodes = new BPlusTreeNodeStore(storage, keys);
3534
- this.primary = new PrimaryIndex(storage, keys);
3535
- }
3536
- async scan(snapshot) {
3537
- const reachable = /* @__PURE__ */ new Set();
3538
- const roots = /* @__PURE__ */ new Set();
3539
- if (snapshot.manifest.primaryRoot != null) roots.add(snapshot.manifest.primaryRoot);
3540
- for (const root of snapshot.manifest.indexRoots.values()) if (root != null) roots.add(root);
3541
- const validator = new BPlusTreeValidator(this.nodes);
3542
- for (const root of roots) {
3543
- this.keys.validateIndexNodeKey(root);
3544
- const references = await validator.reachableNodes(root);
3545
- for (const ref of references) reachable.add(ref);
3546
- }
3547
- for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot)) reachable.add(entry.ref);
3548
- return reachable;
3549
- }
3550
- };
3551
- // src/gc/garbage-collector.ts
3552
- var DEFAULT_GRACE_PERIOD_MS = 864e5;
3553
- var GarbageCollector = class {
3554
- storage;
3555
- keys;
3556
- activeSnapshots;
3557
- scanner;
3558
- constructor(storage, keys, activeSnapshots, scanner = new ManifestReachabilityScanner(keys, storage)) {
3559
- this.storage = storage;
3560
- this.keys = keys;
3561
- this.activeSnapshots = activeSnapshots;
3562
- this.scanner = scanner;
3563
- }
3564
- async collect(options = {}) {
3565
- const started = performance.now();
3566
- const dryRun = options.dryRun != false;
3567
- if (!dryRun && options.exclusiveMaintenance != true) throw new Error("Deletion requires externally guaranteed exclusive maintenance");
3568
- if (!dryRun && this.activeSnapshots().length != 0) throw new Error("Cannot delete objects with active snapshots");
3569
- const olderThanMs = options.olderThanMs ?? DEFAULT_GRACE_PERIOD_MS;
3570
- if (!Number.isSafeInteger(olderThanMs) || olderThanMs < 0) throw new Error("Invalid GC grace period");
3571
- const batchSize = options.batchSize ?? 256;
3572
- if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1e5) throw new Error("Invalid GC batch size");
3573
- if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
3574
- const current = await this.storage.get(this.keys.manifestKey);
3575
- const snapshot = {
3576
- manifest: current ? decodeManifest(current.data, this.keys) : emptyManifest(),
3577
- storageVersion: current?.version ?? null
3578
- };
3579
- const reachable = /* @__PURE__ */ new Set();
3580
- const retainedSnapshots = [snapshot, ...this.activeSnapshots()];
3581
- for (const item of retainedSnapshots) {
3582
- const refs = await this.scanner.scan(item);
3583
- for (const ref of refs) reachable.add(ref);
3584
- }
3585
- const objects = await this.storage.list(this.keys.objectPrefix);
3586
- const nodes = await this.storage.list(this.keys.indexNodePrefix);
3587
- const commits = await this.storage.list(this.keys.commitPrefix);
3588
- const reachableCommits = /* @__PURE__ */ new Set();
3589
- for (const retained of retainedSnapshots) {
3590
- let cursor = retained.manifest.commitHead;
3591
- let count = 0;
3592
- while (cursor) {
3593
- if (reachableCommits.has(cursor)) break;
3594
- if (++count > 1e6) throw new Error("Commit history scan limit exceeded during GC");
3595
- reachableCommits.add(cursor);
3596
- cursor = (await readCommitRecord(this.storage, this.keys, cursor)).previous;
3597
- }
3598
- }
3599
- const cutoff = Date.now() - olderThanMs;
3600
- let candidates = 0;
3601
- let deleted = 0;
3602
- let failed = 0;
3603
- const candidatesForScan = [
3604
- ...objects,
3605
- ...nodes,
3606
- ...commits
3607
- ];
3608
- for (let position = 0; position < candidatesForScan.length; position++) {
3609
- if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
3610
- const object = candidatesForScan[position];
3611
- if (object.key.startsWith(this.keys.objectPrefix)) this.keys.validateObjectKey(object.key);
3612
- else if (object.key.startsWith(this.keys.indexNodePrefix)) this.keys.validateIndexNodeKey(object.key);
3613
- else this.keys.validateCommitKey(object.key);
3614
- if (!Number.isSafeInteger(object.createdAt)) throw new Error(`Invalid object timestamp: ${object.key}`);
3615
- if (reachable.has(object.key) || reachableCommits.has(object.key) || object.createdAt > cutoff) continue;
3616
- candidates++;
3617
- if (dryRun) {
3618
- if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
3619
- continue;
3620
- }
3621
- try {
3622
- if ((await this.storage.delete(object.key, { condition: {
3623
- type: "if-version",
3624
- version: object.version
3625
- } })).success) deleted++;
3626
- } catch (error) {
3627
- failed++;
3628
- if (!options.continueOnError) throw error;
3629
- }
3630
- if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
3631
- }
3632
- return {
3633
- scanned: objects.length,
3634
- nodesScanned: nodes.length,
3635
- reachable: reachable.size,
3636
- candidates,
3637
- deleted,
3638
- failed,
3639
- commitsScanned: commits.length,
3640
- durationMs: performance.now() - started,
3641
- dryRun
3642
- };
3643
- }
3644
- };
3645
4529
  // src/indexes/index-consistency-checker.ts
3646
4530
  var decoder = new TextDecoder();
3647
4531
  var IndexConsistencyChecker = class {
@@ -3734,13 +4618,13 @@ function immutableCollection(definition) {
3734
4618
  ...foreignKeys.length == 0 ? {} : { foreignKeys }
3735
4619
  });
3736
4620
  }
3737
- var DuraxisDatabase = class {
4621
+ var DuraxisDatabase = class DuraxisDatabase {
4622
+ resourceLimits;
4623
+ resources;
4624
+ cursorEncryption;
4625
+ accessScope;
3738
4626
  storage;
3739
4627
  keys;
3740
- coordinator;
3741
- recovery;
3742
- primary;
3743
- secondary;
3744
4628
  cursorSigningKey;
3745
4629
  planner = new RuleBasedPlanner();
3746
4630
  planCompiler = new PlanCompiler();
@@ -3756,48 +4640,173 @@ var DuraxisDatabase = class {
3756
4640
  garbageCollectionDurationMs: 0
3757
4641
  };
3758
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();
3759
4649
  maintenance = false;
3760
4650
  pendingSnapshotAcquisitions = 0;
3761
4651
  closed = false;
3762
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;
3763
4662
  this.storage = options.storage;
3764
4663
  this.keys = new StorageKeyManager(options.namespace);
3765
- this.coordinator = new CommitCoordinator(this.storage, this.keys);
3766
- this.recovery = new RecoveryManager(this.storage, this.keys);
3767
- this.primary = new PrimaryIndex(this.storage, this.keys);
3768
- this.secondary = new SecondaryIndexManager(this.storage, this.keys);
3769
4664
  this.cursorSigningKey = options.cursorSigningKey == null ? (0, node_crypto.randomBytes)(32) : new Uint8Array(options.cursorSigningKey);
3770
4665
  if (this.cursorSigningKey.byteLength < 32) throw new Error("Cursor signing key must contain at least 32 bytes");
3771
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
+ }
3772
4684
  async transaction(callback) {
4685
+ this.assertAccess();
3773
4686
  this.metrics.transactionsStarted++;
3774
- const snapshot = await this.acquireSnapshot();
3775
- 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 });
3776
4704
  try {
3777
- const result = await callback(tx);
4705
+ const result = await owner.wait(Promise.resolve().then(() => callback(tx)));
3778
4706
  const started = performance.now();
3779
4707
  try {
3780
- await this.coordinator.commit(tx);
4708
+ await new CommitCoordinator(owner.storage, this.keys, this.storage).commit(tx);
3781
4709
  } finally {
3782
4710
  this.metrics.commitDurationMs += performance.now() - started;
3783
4711
  }
4712
+ this.rememberOutcome(tx.id, "COMMITTED");
3784
4713
  this.metrics.transactionsCommitted++;
3785
4714
  return result;
3786
4715
  } catch (error) {
3787
4716
  if (error instanceof TransactionConflictError) this.metrics.transactionConflicts++;
3788
4717
  if (error instanceof CommitOutcomeUnknownError) this.metrics.commitOutcomesUnknown++;
4718
+ if (!(error instanceof CommitOutcomeUnknownError)) this.rememberOutcome(tx.id, "NOT_COMMITTED");
3789
4719
  tx.abort();
3790
4720
  throw error;
3791
4721
  } finally {
4722
+ owner.signal.removeEventListener("abort", abort);
3792
4723
  this.releaseSnapshot(snapshot, tx);
3793
4724
  }
3794
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
+ }
3795
4788
  async snapshot(callback) {
3796
4789
  const snapshot = await this.acquireSnapshot();
3797
- 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 });
3798
4806
  try {
3799
- return await callback({ get: (key) => tx.get(key) });
4807
+ return await owner.wait(Promise.resolve().then(() => callback({ get: (key) => tx.get(key) })));
3800
4808
  } finally {
4809
+ owner.signal.removeEventListener("abort", abort);
3801
4810
  this.releaseSnapshot(snapshot, tx);
3802
4811
  }
3803
4812
  }
@@ -3814,7 +4823,7 @@ var DuraxisDatabase = class {
3814
4823
  try {
3815
4824
  return Object.freeze([...snapshot.manifest.catalog.values()].map((definition) => immutableCollection(definition)).sort((left, right) => left.name.localeCompare(right.name)));
3816
4825
  } finally {
3817
- this.active.delete(snapshot);
4826
+ this.finishSnapshot(snapshot);
3818
4827
  }
3819
4828
  }
3820
4829
  async addIndex(collection, index) {
@@ -3827,65 +4836,79 @@ var DuraxisDatabase = class {
3827
4836
  }
3828
4837
  query(query, sourceOrOptions, explicitOptions) {
3829
4838
  const database = this;
3830
- return (async function* () {
4839
+ const iterator = (async function* () {
3831
4840
  const started = performance.now();
3832
4841
  database.metrics.queries++;
3833
- const snapshot = await database.acquireSnapshot();
3834
- 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));
3835
4845
  let unbindSignal = () => {};
3836
4846
  try {
3837
4847
  const explicit = database.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3838
4848
  const options = explicit ? explicitOptions : sourceOrOptions;
3839
4849
  unbindSignal = database.bindSignal(context, options?.signal);
3840
- 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);
3841
4851
  yield* new QueryExecutor(database.queryOptions(options)).execute(context, query, source);
3842
4852
  } finally {
3843
4853
  unbindSignal();
3844
4854
  database.metrics.queryDurationMs += performance.now() - started;
3845
4855
  context.close();
3846
- database.active.delete(snapshot);
4856
+ database.finishSnapshot(snapshot);
3847
4857
  }
3848
4858
  })();
4859
+ return iterator;
3849
4860
  }
3850
4861
  async queryPage(query, sourceOrOptions, explicitOptions) {
3851
4862
  const started = performance.now();
3852
4863
  this.metrics.queries++;
3853
4864
  const snapshot = await this.acquireSnapshot();
3854
- const context = new QueryContext(this.storage, snapshot, this.keys);
4865
+ const context = this.queryContext(snapshot);
3855
4866
  let unbindSignal = () => {};
3856
4867
  try {
3857
4868
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3858
4869
  const options = explicit ? explicitOptions : sourceOrOptions;
3859
4870
  unbindSignal = this.bindSignal(context, options?.signal);
3860
- 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);
3861
4872
  return await new QueryExecutor(this.queryOptions(options)).page(context, query, source);
3862
4873
  } finally {
3863
4874
  unbindSignal();
3864
4875
  this.metrics.queryDurationMs += performance.now() - started;
3865
4876
  context.close();
3866
- this.active.delete(snapshot);
4877
+ this.finishSnapshot(snapshot);
3867
4878
  }
3868
4879
  }
3869
4880
  async queryAll(query, options) {
3870
4881
  const rows = [];
3871
- for await (const row of this.query(query, options)) rows.push(row);
3872
- 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);
3873
4895
  }
3874
4896
  async explain(query) {
3875
4897
  const snapshot = await this.acquireSnapshot();
3876
4898
  try {
3877
- return explainPhysicalPlan(this.planner.plan(query, snapshot.manifest.catalog));
4899
+ return explainPhysicalPlan(this.planner.plan(query, snapshot.manifest.catalog, this.resourceLimits));
3878
4900
  } finally {
3879
- this.active.delete(snapshot);
4901
+ this.finishSnapshot(snapshot);
3880
4902
  }
3881
4903
  }
3882
4904
  executePlan(query, plan, options) {
3883
4905
  if (plan.collection != query.collection) throw new Error("Plan and query collections differ");
3884
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");
3885
4907
  const database = this;
3886
- return (async function* () {
3887
- const snapshot = await database.acquireSnapshot();
3888
- 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));
3889
4912
  const unbindSignal = database.bindSignal(context, options?.signal);
3890
4913
  try {
3891
4914
  const source = database.planCompiler.compile(plan, context.catalog);
@@ -3893,67 +4916,74 @@ var DuraxisDatabase = class {
3893
4916
  } finally {
3894
4917
  unbindSignal();
3895
4918
  context.close();
3896
- database.active.delete(snapshot);
4919
+ database.finishSnapshot(snapshot);
3897
4920
  }
3898
4921
  })();
4922
+ return iterator;
3899
4923
  }
3900
4924
  async getDocument(collection, id) {
3901
4925
  return this.transaction((tx) => tx.getDocument(collection, id));
3902
4926
  }
3903
4927
  async findByIndex(collection, indexName, value, limit = 100) {
3904
4928
  const snapshot = await this.acquireSnapshot();
4929
+ const context = this.queryContext(snapshot);
4930
+ const memory = this.createMaterializationBudget();
4931
+ const rows = [];
3905
4932
  try {
3906
- const ids = await this.secondary.lookupIds(snapshot.manifest, collection, indexName, value, limit);
3907
- const rows = [];
3908
- for (const id of ids) {
3909
- const bytes = await this.primary.read(snapshot.manifest, recordKey(collection, id));
3910
- if (bytes == null) throw new Error(`Index references missing record: ${collection}/${id}`);
3911
- rows.push({
3912
- id,
3913
- document: decodeDocument(bytes)
3914
- });
4933
+ for await (const row of context.scanIndex(collection, indexName, {
4934
+ eq: value,
4935
+ limit
4936
+ })) {
4937
+ memory.add(row);
4938
+ rows.push(row);
3915
4939
  }
3916
4940
  return rows;
3917
4941
  } finally {
3918
- this.active.delete(snapshot);
4942
+ memory.close();
4943
+ context.close();
4944
+ this.finishSnapshot(snapshot);
3919
4945
  }
3920
4946
  }
3921
4947
  async scanCollection(collection, limit = 100) {
3922
- if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid scan limit");
3923
4948
  const snapshot = await this.acquireSnapshot();
4949
+ const context = this.queryContext(snapshot);
4950
+ const memory = this.createMaterializationBudget();
4951
+ const rows = [];
3924
4952
  try {
3925
- if (!snapshot.manifest.catalog.has(collection)) throw new Error(`Unknown collection: ${collection}`);
3926
- const rows = [];
3927
- if (limit == 0) return rows;
3928
- const prefix = new TextEncoder().encode(`${RECORD_PREFIX}${collection}/`);
3929
- const end = prefixSuccessor(prefix);
3930
- for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot, {
3931
- gte: prefix,
3932
- ...end == null ? {} : { lt: end }
3933
- })) {
3934
- const parsed = parseRecordKey(entry.key);
3935
- if (!parsed || parsed.collection != collection) continue;
3936
- rows.push({
3937
- id: parsed.id,
3938
- document: decodeDocument(await this.primary.readObject(entry.ref))
3939
- });
3940
- if (rows.length >= limit) break;
4953
+ for await (const row of context.scanCollection(collection, { limit })) {
4954
+ memory.add(row);
4955
+ rows.push(row);
3941
4956
  }
3942
4957
  return rows;
3943
4958
  } finally {
3944
- this.active.delete(snapshot);
4959
+ memory.close();
4960
+ context.close();
4961
+ this.finishSnapshot(snapshot);
3945
4962
  }
3946
4963
  }
3947
4964
  async getCommitStatus(transactionId) {
3948
- 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
+ }
3949
4971
  }
3950
4972
  async verifyHistory() {
3951
- 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
+ }
3952
4979
  }
3953
- /** Starts a new verifiable commit-history chain without changing data roots. */
3954
4980
  async checkpointHistory() {
4981
+ this.assertAccess();
3955
4982
  if (this.closed) throw new Error("Database is closed");
3956
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;
3957
4987
  this.maintenance = true;
3958
4988
  const transactionId = (0, node_crypto.randomUUID)();
3959
4989
  try {
@@ -3983,26 +5013,29 @@ var DuraxisDatabase = class {
3983
5013
  return transactionId;
3984
5014
  } finally {
3985
5015
  this.maintenance = false;
5016
+ shared.maintenance = false;
3986
5017
  }
3987
5018
  }
3988
5019
  async verifyIntegrity() {
3989
5020
  const snapshot = await this.acquireSnapshot();
5021
+ const storage = this.owners.get(snapshot).storage;
5022
+ const primary = new PrimaryIndex(storage, this.keys);
3990
5023
  try {
3991
- const scanner = new ManifestReachabilityScanner(this.keys, this.storage);
3992
- const nodes = new BPlusTreeNodeStore(this.storage, this.keys);
5024
+ const scanner = new ManifestReachabilityScanner(this.keys, storage);
5025
+ const nodes = new BPlusTreeNodeStore(storage, this.keys);
3993
5026
  const reachable = await scanner.scan(snapshot);
3994
5027
  let objectsCount = 0;
3995
5028
  let nodesCount = 0;
3996
5029
  for (const ref of reachable) if (ref.startsWith(this.keys.objectPrefix)) {
3997
- await this.primary.readObject(ref);
5030
+ await primary.readObject(ref);
3998
5031
  objectsCount++;
3999
5032
  } else {
4000
5033
  this.keys.validateIndexNodeKey(ref);
4001
5034
  await nodes.read(ref);
4002
5035
  nodesCount++;
4003
5036
  }
4004
- const indexes = await new IndexConsistencyChecker(this.storage, this.keys).verify(snapshot.manifest);
4005
- 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();
4006
5039
  return {
4007
5040
  objects: objectsCount,
4008
5041
  nodes: nodesCount,
@@ -4010,10 +5043,11 @@ var DuraxisDatabase = class {
4010
5043
  commits
4011
5044
  };
4012
5045
  } finally {
4013
- this.active.delete(snapshot);
5046
+ this.finishSnapshot(snapshot);
4014
5047
  }
4015
5048
  }
4016
5049
  async collectGarbage(storage, options = {}) {
5050
+ this.assertAccess();
4017
5051
  const started = performance.now();
4018
5052
  this.metrics.garbageCollections++;
4019
5053
  if (storage != this.storage) throw new Error("GC driver must match database storage");
@@ -4021,47 +5055,107 @@ var DuraxisDatabase = class {
4021
5055
  this.maintenance = true;
4022
5056
  try {
4023
5057
  if (options.dryRun == false && (this.active.size > 0 || this.pendingSnapshotAcquisitions > 0)) throw new Error("Active transactions or pending snapshots prevent GC");
4024
- 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);
4025
5059
  } finally {
4026
5060
  this.metrics.garbageCollectionDurationMs += performance.now() - started;
4027
5061
  this.maintenance = false;
4028
5062
  }
4029
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
+ }
4030
5093
  releaseSnapshot(snapshot, tx) {
4031
5094
  tx.close();
4032
- if (!tx.hasPendingReads) {
4033
- this.active.delete(snapshot);
4034
- return;
4035
- }
4036
- tx.waitForReads().then(() => {
4037
- this.active.delete(snapshot);
4038
- });
5095
+ this.finishSnapshot(snapshot);
4039
5096
  }
4040
5097
  queryOptions(options) {
4041
5098
  return {
4042
5099
  ...options,
4043
- cursorSigningKey: options?.cursorSigningKey ?? this.cursorSigningKey
5100
+ cursorSigningKey: this.cursorSigningKey,
5101
+ cursorEncryption: this.cursorEncryption,
5102
+ cursorNamespace: this.keys.namespace
4044
5103
  };
4045
5104
  }
4046
5105
  bindSignal(context, signal) {
4047
5106
  if (!signal) return () => {};
4048
5107
  const cancel = () => context.cancel(signal.reason ?? /* @__PURE__ */ new Error("Query cancelled"));
4049
- if (signal.aborted) cancel();
5108
+ if (signal.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
4050
5109
  else signal.addEventListener("abort", cancel, { once: true });
4051
5110
  return () => signal.removeEventListener("abort", cancel);
4052
5111
  }
4053
5112
  isOperator(value) {
4054
5113
  return value != null && typeof value.execute == "function";
4055
5114
  }
4056
- async acquireSnapshot() {
5115
+ async acquireSnapshot(kind = "snapshot") {
5116
+ this.assertAccess();
4057
5117
  if (this.closed) throw new Error("Database is closed");
4058
- 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);
4059
5140
  this.pendingSnapshotAcquisitions++;
4060
5141
  try {
4061
- const snapshot = await this.createSnapshot();
4062
- 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]) });
4063
5152
  this.active.add(snapshot);
5153
+ shared.snapshots.add(snapshot);
5154
+ this.owners.set(snapshot, owner);
4064
5155
  return snapshot;
5156
+ } catch (error) {
5157
+ owner.finish();
5158
+ throw error;
4065
5159
  } finally {
4066
5160
  this.pendingSnapshotAcquisitions--;
4067
5161
  }
@@ -4069,14 +5163,37 @@ var DuraxisDatabase = class {
4069
5163
  getMetrics() {
4070
5164
  return {
4071
5165
  ...this.metrics,
5166
+ resources: this.resources.metrics(),
4072
5167
  ...this.storage.getMetrics ? { storage: this.storage.getMetrics() } : {}
4073
5168
  };
4074
5169
  }
4075
- async close(options = {}) {
4076
- if (this.closed) return;
4077
- 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;
4078
5172
  this.closed = true;
4079
- 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;
4080
5197
  }
4081
5198
  async createSnapshot() {
4082
5199
  const stored = await this.storage.get(this.keys.manifestKey);
@@ -4109,6 +5226,7 @@ exports.BPlusTreeNodeStore = BPlusTreeNodeStore;
4109
5226
  exports.BPlusTreeValidator = BPlusTreeValidator;
4110
5227
  exports.CollectionScan = CollectionScan;
4111
5228
  exports.CommitOutcomeUnknownError = CommitOutcomeUnknownError;
5229
+ exports.DEFAULT_RESOURCE_LIMITS = DEFAULT_RESOURCE_LIMITS;
4112
5230
  exports.Difference = Difference;
4113
5231
  exports.DuraxisDatabase = DuraxisDatabase;
4114
5232
  exports.Filter = Filter;
@@ -4120,6 +5238,7 @@ exports.InvalidForeignKeyDefinitionError = InvalidForeignKeyDefinitionError;
4120
5238
  exports.Limit = Limit;
4121
5239
  exports.ManifestReachabilityScanner = ManifestReachabilityScanner;
4122
5240
  exports.ManifestSnapshotReader = ManifestSnapshotReader;
5241
+ exports.OperationCancelledError = OperationCancelledError;
4123
5242
  exports.PlanCompiler = PlanCompiler;
4124
5243
  exports.PredicateAnalyzer = PredicateAnalyzer;
4125
5244
  exports.PrimaryIndex = PrimaryIndex;
@@ -4132,6 +5251,8 @@ exports.RecoveryManager = RecoveryManager;
4132
5251
  exports.ReferenceQueryExecutor = ReferenceQueryExecutor;
4133
5252
  exports.ReferencedRecordNotFoundError = ReferencedRecordNotFoundError;
4134
5253
  exports.ReferencedRecordRestrictedError = ReferencedRecordRestrictedError;
5254
+ exports.ResourceExhaustedError = ResourceExhaustedError;
5255
+ exports.ResourceScope = ResourceScope;
4135
5256
  exports.RuleBasedPlanner = RuleBasedPlanner;
4136
5257
  exports.SecondaryIndexManager = SecondaryIndexManager;
4137
5258
  exports.SecondaryIndexRangeScan = SecondaryIndexRangeScan;
@@ -4155,6 +5276,7 @@ exports.encodeIdentifier = encodeIdentifier;
4155
5276
  exports.encodeQueryCursor = encodeQueryCursor;
4156
5277
  exports.encodeScalar = encodeScalar;
4157
5278
  exports.encodeSecondaryKey = encodeSecondaryKey;
5279
+ exports.estimateBytes = estimateBytes;
4158
5280
  exports.evaluatePredicate = evaluatePredicate;
4159
5281
  exports.explainPhysicalPlan = explainPhysicalPlan;
4160
5282
  exports.fieldDefinition = fieldDefinition;
@@ -4162,11 +5284,13 @@ exports.indexFields = indexFields;
4162
5284
  exports.indexId = indexId;
4163
5285
  exports.indexRangeBounds = indexRangeBounds;
4164
5286
  exports.indexedValue = indexedValue;
5287
+ exports.materialize = materialize;
4165
5288
  exports.normalizeCollection = normalizeCollection;
4166
5289
  exports.parseRecordKey = parseRecordKey;
4167
5290
  exports.prefixBounds = prefixBounds;
4168
5291
  exports.prefixSuccessor = prefixSuccessor;
4169
5292
  exports.recordKey = recordKey;
5293
+ exports.resourceLimits = resourceLimits;
4170
5294
  exports.secondaryIndexBounds = secondaryIndexBounds;
4171
5295
  exports.validateCollection = validateCollection;
4172
5296
  exports.validateDocument = validateDocument;