@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.js CHANGED
@@ -1,5 +1,344 @@
1
- import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
2
  import { assertStorageKey } from "@duraxis/storage";
3
+ // src/resources/resource-manager.ts
4
+ var DEFAULT_RESOURCE_LIMITS = Object.freeze({
5
+ maxQueuedOperations: 64,
6
+ maxConcurrentTransactions: 64,
7
+ maxConcurrentQueries: 64,
8
+ maxOpenSnapshots: 128,
9
+ maxOpenIterators: 256,
10
+ maxPendingOperations: 256,
11
+ maxPendingWrites: 1e5,
12
+ maxPendingWriteBytes: 67108864,
13
+ maxResultRows: 1e4,
14
+ maxResultBytes: 16777216,
15
+ maxQueryWorkingBytes: 33554432,
16
+ maxTransactionWorkingBytes: 134217728,
17
+ maxDatabaseWorkingBytes: 536870912,
18
+ maxDocumentBytes: 1048576,
19
+ maxStorageReadBytes: 4194304,
20
+ maxDocumentDepth: 64,
21
+ maxPredicateDepth: 32,
22
+ maxPredicateNodes: 4096,
23
+ maxTransactionDurationMs: 6e4,
24
+ maxQueryDurationMs: 3e4,
25
+ maxSnapshotLifetimeMs: 6e4,
26
+ maxSpillBytes: 268435456
27
+ });
28
+ var ResourceExhaustedError = class extends Error {
29
+ resource;
30
+ limit;
31
+ constructor(resource, limit) {
32
+ super(`Duraxis resource limit exceeded: ${resource} (limit ${limit}); reduce the workload or explicitly configure a larger budget`);
33
+ this.resource = resource;
34
+ this.limit = limit;
35
+ this.name = "ResourceExhaustedError";
36
+ }
37
+ };
38
+ var OperationCancelledError = class extends Error {
39
+ constructor(message = "Duraxis operation cancelled or deadline exceeded") {
40
+ super(message);
41
+ this.name = "OperationCancelledError";
42
+ }
43
+ };
44
+ function resourceLimits(options = {}) {
45
+ const result = {
46
+ ...DEFAULT_RESOURCE_LIMITS,
47
+ ...options
48
+ };
49
+ for (const [name, value] of Object.entries(result)) if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`Invalid resource limit: ${name}`);
50
+ return Object.freeze(result);
51
+ }
52
+ var ResourceScope = class ResourceScope {
53
+ limits;
54
+ parent;
55
+ usage = {};
56
+ high = {};
57
+ children = /* @__PURE__ */ new Set();
58
+ closed = false;
59
+ constructor(limits, parent) {
60
+ this.limits = limits;
61
+ this.parent = parent;
62
+ parent?.children.add(this);
63
+ }
64
+ child(limits) {
65
+ this.assertOpen();
66
+ return new ResourceScope(limits, this);
67
+ }
68
+ assertOpen() {
69
+ if (this.closed) throw new OperationCancelledError("Resource scope is closed");
70
+ }
71
+ change(delta) {
72
+ const chain = [];
73
+ for (let scope = this; scope; scope = scope.parent) {
74
+ scope.assertOpen();
75
+ chain.push(scope);
76
+ for (const [key, value] of Object.entries(delta)) {
77
+ const next = (scope.usage[key] ?? 0) + value;
78
+ if (next < 0) throw new Error("Resource accounting underflow");
79
+ if (next > (scope.limits[key] ?? Number.MAX_SAFE_INTEGER)) throw new ResourceExhaustedError(key, scope.limits[key]);
80
+ }
81
+ }
82
+ for (const scope of chain) for (const [key, value] of Object.entries(delta)) {
83
+ scope.usage[key] = (scope.usage[key] ?? 0) + value;
84
+ scope.high[key] = Math.max(scope.high[key] ?? 0, scope.usage[key]);
85
+ }
86
+ }
87
+ reserve(initial) {
88
+ let held = {};
89
+ let released = false;
90
+ const resize = (amounts) => {
91
+ if (released || this.closed) throw new OperationCancelledError("Reservation is closed");
92
+ const delta = {};
93
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(held), ...Object.keys(amounts)])) {
94
+ const amount = amounts[key] ?? 0;
95
+ if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError("Invalid resource reservation");
96
+ delta[key] = amount - (held[key] ?? 0);
97
+ }
98
+ this.change(delta);
99
+ held = { ...amounts };
100
+ };
101
+ resize(initial);
102
+ return {
103
+ resize,
104
+ release: () => {
105
+ if (released) return;
106
+ released = true;
107
+ if (!this.closed) this.change(Object.fromEntries(Object.entries(held).map(([key, value]) => [key, -value])));
108
+ held = {};
109
+ }
110
+ };
111
+ }
112
+ metrics() {
113
+ return {
114
+ current: { ...this.usage },
115
+ highWater: { ...this.high }
116
+ };
117
+ }
118
+ close() {
119
+ if (this.closed) return;
120
+ for (const child of [...this.children]) child.close();
121
+ this.change(Object.fromEntries(Object.entries(this.usage).map(([key, value]) => [key, -value])));
122
+ this.closed = true;
123
+ this.parent?.children.delete(this);
124
+ }
125
+ };
126
+ function databaseScope(limits) {
127
+ return new ResourceScope({
128
+ workingBytes: limits.maxDatabaseWorkingBytes,
129
+ transactions: limits.maxConcurrentTransactions,
130
+ queries: limits.maxConcurrentQueries,
131
+ snapshots: limits.maxOpenSnapshots,
132
+ iterators: limits.maxOpenIterators,
133
+ pendingOperations: limits.maxPendingOperations,
134
+ queuedOperations: limits.maxQueuedOperations
135
+ });
136
+ }
137
+ function estimateBytes(value, maximum = 134217728, maxDepth = 64) {
138
+ let bytes = 0;
139
+ const ancestors = /* @__PURE__ */ new Set();
140
+ const visit = (item, depth) => {
141
+ if (depth > maxDepth) throw new ResourceExhaustedError("documentDepth", maxDepth);
142
+ if (typeof item == "string") bytes += item.length * 2 + 24;
143
+ else if (item == null || typeof item != "object") bytes += 16;
144
+ else if (item instanceof Uint8Array) bytes += item.byteLength + 64;
145
+ else if (item instanceof Date) bytes += 32;
146
+ else {
147
+ if (ancestors.has(item)) throw new TypeError("Cyclic values are not supported");
148
+ ancestors.add(item);
149
+ bytes += 64;
150
+ for (const key in item) if (Object.hasOwn(item, key)) {
151
+ if (key == "__proto__") throw new TypeError("Unsafe object property");
152
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
153
+ if (!("value" in descriptor)) throw new TypeError("Accessor properties are not supported");
154
+ bytes += key.length * 2 + 32;
155
+ visit(descriptor.value, depth + 1);
156
+ if (bytes > maximum) throw new ResourceExhaustedError("workingBytes", maximum);
157
+ }
158
+ ancestors.delete(item);
159
+ }
160
+ if (bytes > maximum) throw new ResourceExhaustedError("workingBytes", maximum);
161
+ };
162
+ visit(value, 0);
163
+ return bytes;
164
+ }
165
+ function materialize(scope, limits) {
166
+ const reservation = scope.reserve({});
167
+ let rows = 0;
168
+ let bytes = 0;
169
+ let working = 0;
170
+ return {
171
+ add(value) {
172
+ if (rows + 1 > limits.maxResultRows) throw new ResourceExhaustedError("resultRows", limits.maxResultRows);
173
+ const size = estimateBytes(value, limits.maxQueryWorkingBytes, limits.maxDocumentDepth + 4);
174
+ reservation.resize({ workingBytes: working + size * 8 });
175
+ let encoded;
176
+ try {
177
+ encoded = JSON.stringify(value);
178
+ } finally {
179
+ reservation.resize({ workingBytes: working + size });
180
+ }
181
+ if (encoded === void 0) throw new TypeError("Result is not JSON serializable");
182
+ const next = bytes + Buffer.byteLength(encoded);
183
+ if (next > limits.maxResultBytes) throw new ResourceExhaustedError("resultBytes", limits.maxResultBytes);
184
+ working += size;
185
+ bytes = next;
186
+ rows++;
187
+ },
188
+ close: () => reservation.release()
189
+ };
190
+ }
191
+ // src/gc/storage-coordination.ts
192
+ var states = /* @__PURE__ */ new WeakMap();
193
+ function storageCoordination(storage) {
194
+ let state = states.get(storage);
195
+ if (!state) {
196
+ state = {
197
+ active: 0,
198
+ maintenance: false,
199
+ snapshots: /* @__PURE__ */ new Set()
200
+ };
201
+ states.set(storage, state);
202
+ }
203
+ return state;
204
+ }
205
+ var commits = /* @__PURE__ */ new WeakMap();
206
+ async function coordinateCommit(storage, maximum, action) {
207
+ let state = commits.get(storage);
208
+ if (!state) {
209
+ state = {
210
+ tail: Promise.resolve(),
211
+ queued: 0
212
+ };
213
+ commits.set(storage, state);
214
+ }
215
+ if (state.queued >= maximum) throw new ResourceExhaustedError("queuedOperations", maximum);
216
+ state.queued++;
217
+ const previous = state.tail;
218
+ let release;
219
+ state.tail = new Promise((resolve) => {
220
+ release = resolve;
221
+ });
222
+ try {
223
+ await previous;
224
+ return await action();
225
+ } finally {
226
+ state.queued--;
227
+ release();
228
+ }
229
+ }
230
+ // src/resources/operation-owner.ts
231
+ var OperationOwner = class {
232
+ scope;
233
+ onDispose;
234
+ controller = new AbortController();
235
+ storage;
236
+ pending = 0;
237
+ ended = false;
238
+ disposed = false;
239
+ publishing = false;
240
+ timer;
241
+ constructor(scope, storage, durationMs, onDispose, maxReadBytes = 16777216) {
242
+ this.scope = scope;
243
+ this.onDispose = onDispose;
244
+ this.timer = setTimeout(() => this.cancel(new OperationCancelledError("Operation lifetime expired")), durationMs);
245
+ this.timer.unref();
246
+ this.storage = {
247
+ capabilities: storage.capabilities,
248
+ get: (key, options) => this.track(async () => {
249
+ const signal = options?.signal ? AbortSignal.any([this.signal, options.signal]) : this.signal;
250
+ const value = await storage.get(key, {
251
+ signal,
252
+ maxBytes: Math.min(maxReadBytes, options?.maxBytes ?? maxReadBytes)
253
+ });
254
+ if (value && value.data.byteLength > maxReadBytes) throw new Error("Storage read exceeds configured byte limit");
255
+ return value;
256
+ }, maxReadBytes * 3),
257
+ put: (key, data, options) => this.track(() => storage.put(key, data, options), data.byteLength * 2),
258
+ delete: (key, options) => this.track(() => storage.delete(key, options)),
259
+ list: (prefix) => this.track(() => storage.list(prefix))
260
+ };
261
+ }
262
+ get signal() {
263
+ return this.controller.signal;
264
+ }
265
+ get isDisposed() {
266
+ return this.disposed;
267
+ }
268
+ get pendingOperations() {
269
+ return this.pending;
270
+ }
271
+ assertActive() {
272
+ this.signal.throwIfAborted();
273
+ if (this.ended) throw new OperationCancelledError("Operation is closed");
274
+ }
275
+ async track(action, bytes = 0) {
276
+ this.assertActive();
277
+ const lease = this.scope.reserve({
278
+ pendingOperations: 1,
279
+ workingBytes: bytes
280
+ });
281
+ this.pending++;
282
+ try {
283
+ const value = await action();
284
+ if (!this.publishing) this.signal.throwIfAborted();
285
+ return value;
286
+ } finally {
287
+ lease.release();
288
+ this.pending--;
289
+ this.disposeIfReady();
290
+ }
291
+ }
292
+ protectPublication() {
293
+ this.assertActive();
294
+ this.publishing = true;
295
+ clearTimeout(this.timer);
296
+ }
297
+ cancel(reason = new OperationCancelledError()) {
298
+ if (this.publishing) return;
299
+ if (!this.signal.aborted) this.controller.abort(reason);
300
+ this.finish();
301
+ }
302
+ finish() {
303
+ if (this.ended) return;
304
+ this.ended = true;
305
+ clearTimeout(this.timer);
306
+ this.disposeIfReady();
307
+ }
308
+ disposeIfReady() {
309
+ if (!this.ended || this.pending || this.disposed) return;
310
+ this.disposed = true;
311
+ this.scope.close();
312
+ this.onDispose();
313
+ }
314
+ holdCleanup(promise) {
315
+ this.pending++;
316
+ const complete = () => {
317
+ this.pending--;
318
+ this.disposeIfReady();
319
+ };
320
+ promise.then(complete, complete);
321
+ }
322
+ async wait(promise) {
323
+ this.assertActive();
324
+ return new Promise((resolve, reject) => {
325
+ const abort = () => {
326
+ cleanup();
327
+ reject(this.signal.reason);
328
+ };
329
+ const cleanup = () => this.signal.removeEventListener("abort", abort);
330
+ this.signal.addEventListener("abort", abort, { once: true });
331
+ promise.then((value) => {
332
+ cleanup();
333
+ resolve(value);
334
+ }, (error) => {
335
+ cleanup();
336
+ reject(error);
337
+ });
338
+ if (this.signal.aborted) abort();
339
+ });
340
+ }
341
+ };
3
342
  // src/integrity/integrity.ts
4
343
  function sha256(bytes) {
5
344
  return createHash("sha256").update(bytes).digest("hex");
@@ -24,7 +363,7 @@ var StorageKeyManager = class {
24
363
  objectPattern;
25
364
  commitPattern;
26
365
  constructor(namespace = "__duraxis/v1") {
27
- if (!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(namespace)) throw new Error("Invalid Duraxis storage namespace");
366
+ 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");
28
367
  this.namespace = namespace;
29
368
  this.manifestKey = `${namespace}/manifest`;
30
369
  this.objectPrefix = `${namespace}/objects/`;
@@ -33,6 +372,7 @@ var StorageKeyManager = class {
33
372
  this.indexNodePattern = new RegExp(`^${escapeRegex$1(this.indexNodePrefix)}${UUID$1}-([a-f0-9]{64})$`);
34
373
  this.objectPattern = new RegExp(`^${escapeRegex$1(this.objectPrefix)}(${UUID$1})(?:-([a-f0-9]{64}))?$`);
35
374
  this.commitPattern = new RegExp(`^${escapeRegex$1(this.commitPrefix)}(${UUID$1})-([a-f0-9]{64})$`);
375
+ Object.freeze(this);
36
376
  }
37
377
  validateLogicalKey(key) {
38
378
  assertStorageKey(key);
@@ -447,6 +787,34 @@ async function readCommitRecord(storage, keys, key) {
447
787
  if (keys.commitKey(record.transactionId, object.data) != key) throw new Error("Commit record identity mismatch");
448
788
  return record;
449
789
  }
790
+ // src/resources/prepared-writes.ts
791
+ var PreparedWrites = class extends Map {
792
+ limits;
793
+ bytes = 0;
794
+ encodedBytes = 0;
795
+ reservation;
796
+ constructor(scope, limits, source) {
797
+ super();
798
+ this.limits = limits;
799
+ this.reservation = scope.reserve({});
800
+ for (const [key, value] of source) this.set(key, value);
801
+ }
802
+ sizeOf(key, value) {
803
+ return key.length * 2 + 512 + (value.type === "put" ? value.data.byteLength * 8 : 0);
804
+ }
805
+ set(key, value) {
806
+ const previous = this.get(key);
807
+ if (!previous && this.size >= this.limits.maxPendingWrites) throw new ResourceExhaustedError("writes", this.limits.maxPendingWrites);
808
+ if (value.type === "put" && value.data.byteLength > this.limits.maxDocumentBytes) throw new ResourceExhaustedError("documentBytes", this.limits.maxDocumentBytes);
809
+ const next = this.bytes - (previous ? this.sizeOf(key, previous) : 0) + this.sizeOf(key, value);
810
+ const encoded = this.encodedBytes - (previous?.type === "put" ? previous.data.byteLength : 0) + (value.type === "put" ? value.data.byteLength : 0);
811
+ if (encoded > this.limits.maxPendingWriteBytes) throw new ResourceExhaustedError("preparedWriteBytes", this.limits.maxPendingWriteBytes);
812
+ this.reservation.resize({ workingBytes: next });
813
+ this.bytes = next;
814
+ this.encodedBytes = encoded;
815
+ return super.set(key, value);
816
+ }
817
+ };
450
818
  // src/indexes/bptree/bptree-codec.ts
451
819
  var encoder$3 = new TextEncoder();
452
820
  var decoder$3 = new TextDecoder("utf-8", { fatal: true });
@@ -1096,16 +1464,22 @@ var PrimaryIndex = class {
1096
1464
  }
1097
1465
  };
1098
1466
  // src/indexes/bptree/bptree-node-cache.ts
1099
- /** Query-scoped LRU for already integrity-checked immutable nodes. */
1100
1467
  var BPlusTreeNodeCache = class {
1101
1468
  source;
1102
1469
  capacity;
1470
+ maxBytes;
1103
1471
  entries = /* @__PURE__ */ new Map();
1472
+ sizes = /* @__PURE__ */ new Map();
1473
+ bytes = 0;
1474
+ reservation;
1104
1475
  hits = 0;
1105
1476
  misses = 0;
1106
- constructor(source, capacity = 256) {
1477
+ constructor(source, capacity = 256, maxBytes = 4194304, resources = new ResourceScope({})) {
1107
1478
  this.source = source;
1108
1479
  this.capacity = capacity;
1480
+ this.maxBytes = maxBytes;
1481
+ this.reservation = resources.reserve({});
1482
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new RangeError("Invalid cache byte limit");
1109
1483
  if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 65536) throw new Error("Invalid B+tree node cache capacity");
1110
1484
  }
1111
1485
  async read(ref) {
@@ -1118,8 +1492,19 @@ var BPlusTreeNodeCache = class {
1118
1492
  }
1119
1493
  this.misses++;
1120
1494
  const node = await this.source.read(ref);
1495
+ if (this.entries.has(ref)) return this.entries.get(ref);
1496
+ const size = estimateBytes(node);
1497
+ if (size > this.maxBytes) return node;
1498
+ while (this.entries.size >= this.capacity || this.bytes + size > this.maxBytes) {
1499
+ const oldest = this.entries.keys().next().value;
1500
+ this.bytes -= this.sizes.get(oldest);
1501
+ this.sizes.delete(oldest);
1502
+ this.entries.delete(oldest);
1503
+ }
1504
+ this.reservation.resize({ workingBytes: this.bytes + size });
1505
+ this.bytes += size;
1506
+ this.sizes.set(ref, size);
1121
1507
  this.entries.set(ref, node);
1122
- if (this.entries.size > this.capacity) this.entries.delete(this.entries.keys().next().value);
1123
1508
  return node;
1124
1509
  }
1125
1510
  write(node) {
@@ -1127,11 +1512,15 @@ var BPlusTreeNodeCache = class {
1127
1512
  }
1128
1513
  clear() {
1129
1514
  this.entries.clear();
1515
+ this.sizes.clear();
1516
+ this.bytes = 0;
1517
+ this.reservation.resize({});
1130
1518
  }
1131
1519
  getMetrics() {
1132
1520
  return {
1133
1521
  hits: this.hits,
1134
- misses: this.misses
1522
+ misses: this.misses,
1523
+ bytes: this.bytes
1135
1524
  };
1136
1525
  }
1137
1526
  };
@@ -1362,13 +1751,13 @@ var SecondaryIndexManager = class {
1362
1751
  this.nodes = nodes;
1363
1752
  this.primary = new PrimaryIndex(storage, keys, nodes);
1364
1753
  }
1365
- async prepare(previousManifest, nextPrimaryRoot, writes, catalog) {
1754
+ async prepare(previousManifest, nextPrimaryRoot, writes, catalog, resources) {
1366
1755
  const roots = new Map(previousManifest.indexRoots);
1367
1756
  const declared = /* @__PURE__ */ new Set();
1368
1757
  const tree = new BPlusTree(this.nodes);
1369
1758
  for (const [collectionName, schema] of catalog) {
1370
1759
  const previousSchema = previousManifest.catalog.get(collectionName);
1371
- const changes = await this.collectChanges(previousManifest, collectionName, writes);
1760
+ const changes = await this.collectChanges(previousManifest, collectionName, writes, resources);
1372
1761
  for (const index of schema.indexes) {
1373
1762
  const id = indexId(collectionName, index.name);
1374
1763
  declared.add(id);
@@ -1421,15 +1810,20 @@ var SecondaryIndexManager = class {
1421
1810
  for (const id of [...roots.keys()]) if (!declared.has(id)) roots.delete(id);
1422
1811
  return roots;
1423
1812
  }
1424
- async collectChanges(manifest, collection, writes) {
1813
+ async collectChanges(manifest, collection, writes, resources) {
1425
1814
  const changes = [];
1815
+ const memory = resources?.reserve({});
1816
+ let bytes = 0;
1426
1817
  for (const [key, operation] of writes) {
1427
1818
  const parsed = parseRecordKey(key);
1428
1819
  if (parsed == null || parsed.collection != collection) continue;
1429
1820
  const previousRef = await this.primary.getReference(manifest, key);
1821
+ const previousData = previousRef == null ? void 0 : await this.primary.readObject(previousRef);
1822
+ bytes += 512 + (previousData?.byteLength ?? 0) * 8 + (operation.type == "put" ? operation.data.byteLength * 8 : 0);
1823
+ memory?.resize({ workingBytes: bytes });
1430
1824
  changes.push({
1431
1825
  recordId: parsed.id,
1432
- previous: previousRef == null ? void 0 : decodeDocument(await this.primary.readObject(previousRef)),
1826
+ previous: previousRef == null ? void 0 : decodeDocument(previousData),
1433
1827
  next: operation.type == "put" ? decodeDocument(operation.data) : void 0
1434
1828
  });
1435
1829
  }
@@ -1520,8 +1914,10 @@ function cloneWrites(source) {
1520
1914
  return result;
1521
1915
  }
1522
1916
  var QueryContext = class {
1523
- snapshot;
1524
1917
  options;
1918
+ resources;
1919
+ limits;
1920
+ iteratorReservations = [];
1525
1921
  primary;
1526
1922
  secondary;
1527
1923
  nodeCache;
@@ -1530,6 +1926,8 @@ var QueryContext = class {
1530
1926
  startedAt = performance.now();
1531
1927
  active = true;
1532
1928
  iterators = 0;
1929
+ timer;
1930
+ cancellationReturns = /* @__PURE__ */ new Set();
1533
1931
  metrics = {
1534
1932
  storageReads: 0,
1535
1933
  storageWrites: 0,
@@ -1541,15 +1939,49 @@ var QueryContext = class {
1541
1939
  cacheMisses: 0,
1542
1940
  durationMs: 0
1543
1941
  };
1544
- catalog;
1942
+ snapshotValue;
1943
+ get snapshot() {
1944
+ this.assertActive();
1945
+ return this.snapshotValue;
1946
+ }
1947
+ catalogValue = /* @__PURE__ */ new Map();
1948
+ get catalog() {
1949
+ return this.catalogValue;
1950
+ }
1545
1951
  constructor(storage, snapshot, keys, options = {}) {
1546
- this.snapshot = snapshot;
1547
1952
  this.options = options;
1548
- this.nodeCache = new BPlusTreeNodeCache(new BPlusTreeNodeStore(storage, keys));
1549
- this.primary = new PrimaryIndex(storage, keys, this.nodeCache);
1550
- this.secondary = new SecondaryIndexManager(storage, keys, this.nodeCache);
1953
+ this.snapshotValue = snapshot;
1954
+ this.limits = options.limits ?? resourceLimits();
1955
+ this.resources = (options.resources ?? new ResourceScope({})).child({
1956
+ workingBytes: this.limits.maxQueryWorkingBytes,
1957
+ spillBytes: this.limits.maxSpillBytes
1958
+ });
1959
+ try {
1960
+ this.resources.reserve({
1961
+ queries: 1,
1962
+ iterators: 1,
1963
+ workingBytes: estimateBytes([...options.writes ?? []])
1964
+ });
1965
+ } catch (error) {
1966
+ this.resources.close();
1967
+ throw error;
1968
+ }
1969
+ const queryStorage = {
1970
+ put: storage.put.bind(storage),
1971
+ delete: storage.delete.bind(storage),
1972
+ list: storage.list.bind(storage),
1973
+ get: (key, options) => storage.get(key, {
1974
+ ...options,
1975
+ signal: options?.signal ? AbortSignal.any([this.signal, options.signal]) : this.signal
1976
+ })
1977
+ };
1978
+ this.nodeCache = new BPlusTreeNodeCache(new BPlusTreeNodeStore(queryStorage, keys), 256, Math.min(4194304, this.limits.maxQueryWorkingBytes), this.resources);
1979
+ this.primary = new PrimaryIndex(queryStorage, keys, this.nodeCache);
1980
+ this.secondary = new SecondaryIndexManager(queryStorage, keys, this.nodeCache);
1551
1981
  this.writes = cloneWrites(options.writes);
1552
- this.catalog = new Map(options.catalog ?? snapshot.manifest.catalog);
1982
+ for (const [name, definition] of options.catalog ?? snapshot.manifest.catalog) this.catalogValue.set(name, definition);
1983
+ this.timer = setTimeout(() => this.cancel(new OperationCancelledError("Query lifetime expired")), this.limits.maxQueryDurationMs);
1984
+ this.timer.unref();
1553
1985
  }
1554
1986
  get generation() {
1555
1987
  return this.snapshot.manifest.transactionId || "initial";
@@ -1560,30 +1992,78 @@ var QueryContext = class {
1560
1992
  get isActive() {
1561
1993
  return this.active;
1562
1994
  }
1563
- close(reason = /* @__PURE__ */ new Error("Query context is closed")) {
1995
+ bindCancellation(close) {
1996
+ this.cancellationReturns.add(close);
1997
+ return () => this.cancellationReturns.delete(close);
1998
+ }
1999
+ managed(factory) {
2000
+ const context = this;
2001
+ const iterator = (async function* () {
2002
+ const unbind = context.bindCancellation(() => iterator.return(void 0));
2003
+ try {
2004
+ yield* factory();
2005
+ } finally {
2006
+ unbind();
2007
+ }
2008
+ })();
2009
+ return iterator;
2010
+ }
2011
+ scanCollection(collection, options = {}) {
2012
+ return this.managed(() => this.scanCollectionRows(collection, options));
2013
+ }
2014
+ scanIndex(collection, index, options = {}) {
2015
+ return this.managed(() => this.scanIndexRows(collection, index, options));
2016
+ }
2017
+ close(reason = /* @__PURE__ */ new Error("Query context is closed"), cleanup) {
1564
2018
  if (!this.active) return;
1565
2019
  this.active = false;
2020
+ clearTimeout(this.timer);
2021
+ this.cancellationReturns.clear();
1566
2022
  const cache = this.nodeCache.getMetrics();
1567
2023
  this.metrics.cacheHits = cache.hits;
1568
2024
  this.metrics.cacheMisses = cache.misses;
1569
2025
  this.metrics.durationMs = performance.now() - this.startedAt;
1570
2026
  this.controller.abort(reason);
1571
2027
  this.nodeCache.clear();
1572
- this.options.onClose?.();
2028
+ this.writes.clear();
2029
+ this.catalogValue.clear();
2030
+ this.snapshotValue = void 0;
2031
+ while (this.iterators > 0) this.end();
2032
+ const finish = () => {
2033
+ this.resources.close();
2034
+ this.options.onClose?.();
2035
+ };
2036
+ if (cleanup) {
2037
+ const pending = Promise.resolve().then(cleanup);
2038
+ this.options.onPendingCleanup?.(pending);
2039
+ pending.then(finish, (error) => {
2040
+ this.options.onCleanupFailure?.(error);
2041
+ finish();
2042
+ });
2043
+ } else finish();
1573
2044
  }
1574
2045
  cancel(reason = /* @__PURE__ */ new Error("Query cancelled")) {
1575
- this.close(reason);
2046
+ const callbacks = [...this.cancellationReturns];
2047
+ this.cancellationReturns.clear();
2048
+ this.close(reason, callbacks.length ? async () => {
2049
+ const errors = (await Promise.allSettled(callbacks.map((callback) => Promise.resolve().then(callback)))).filter((result) => result.status == "rejected").map((result) => result.reason);
2050
+ if (errors.length) throw new AggregateError(errors, "Query iterator cleanup failed");
2051
+ } : void 0);
1576
2052
  }
1577
2053
  assertActive() {
2054
+ this.options.assertAccess?.();
1578
2055
  if (!this.active) throw this.controller.signal.reason ?? /* @__PURE__ */ new Error("Query context is closed");
1579
2056
  }
1580
2057
  begin() {
1581
2058
  this.assertActive();
2059
+ this.iteratorReservations.push(this.resources.reserve({ iterators: this.iterators ? 1 : 0 }));
1582
2060
  this.iterators++;
1583
2061
  this.options.onIteratorStart?.();
1584
2062
  }
1585
2063
  end() {
1586
- if (this.iterators > 0) this.iterators--;
2064
+ if (this.iterators == 0) return;
2065
+ this.iterators--;
2066
+ this.iteratorReservations.pop()?.release();
1587
2067
  this.options.onIteratorEnd?.();
1588
2068
  }
1589
2069
  schema(collection) {
@@ -1610,7 +2090,7 @@ var QueryContext = class {
1610
2090
  }
1611
2091
  return result;
1612
2092
  }
1613
- async *scanCollection(collection, options = {}) {
2093
+ async *scanCollectionRows(collection, options = {}) {
1614
2094
  this.begin();
1615
2095
  try {
1616
2096
  this.schema(collection);
@@ -1688,6 +2168,8 @@ var QueryContext = class {
1688
2168
  const bounds = secondaryIndexBounds(index, options);
1689
2169
  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);
1690
2170
  const result = [];
2171
+ let bytes = 0;
2172
+ const memory = this.resources.reserve({});
1691
2173
  for (const [id, write] of this.pendingFor(collection)) {
1692
2174
  if (write.type != "put") continue;
1693
2175
  const document = decodeDocument(write.data);
@@ -1703,17 +2185,21 @@ var QueryContext = class {
1703
2185
  }
1704
2186
  if (missing) continue;
1705
2187
  const key = encodeSecondaryKey(values, index.unique ? void 0 : id, orders);
1706
- if (matches(key)) result.push({
1707
- key,
1708
- row: {
1709
- id,
1710
- document
1711
- }
1712
- });
2188
+ if (matches(key)) {
2189
+ bytes += estimateBytes(document) + key.byteLength + id.length * 2;
2190
+ memory.resize({ workingBytes: bytes });
2191
+ result.push({
2192
+ key,
2193
+ row: {
2194
+ id,
2195
+ document
2196
+ }
2197
+ });
2198
+ }
1713
2199
  }
1714
2200
  return result;
1715
2201
  }
1716
- async *scanIndex(collection, indexName, options = {}) {
2202
+ async *scanIndexRows(collection, indexName, options = {}) {
1717
2203
  this.begin();
1718
2204
  try {
1719
2205
  const schema = this.schema(collection);
@@ -1725,14 +2211,20 @@ var QueryContext = class {
1725
2211
  const parts = indexFields(index);
1726
2212
  const bounds = secondaryIndexBounds(index, options);
1727
2213
  const entries = [];
2214
+ const memory = this.resources.reserve({});
2215
+ let bytes = 0;
1728
2216
  for await (const row of this.scanCollection(collection, { signal: options.signal })) {
1729
2217
  const values = parts.map((part) => indexedValue(row.document, part.field, fieldDefinition(schema, part.field)));
1730
2218
  if (values.some((value) => value === void 0)) continue;
1731
2219
  const key = encodeSecondaryKey(values, index.unique ? void 0 : row.id, parts.map((part) => part.order));
1732
- 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({
1733
- key,
1734
- row
1735
- });
2220
+ 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)) {
2221
+ bytes += estimateBytes(row) + key.byteLength;
2222
+ memory.resize({ workingBytes: bytes });
2223
+ entries.push({
2224
+ key,
2225
+ row
2226
+ });
2227
+ }
1736
2228
  }
1737
2229
  const limit = options.limit ?? Number.MAX_SAFE_INTEGER;
1738
2230
  if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid query limit");
@@ -1802,7 +2294,7 @@ var TransactionConflictError = class extends Error {
1802
2294
  var CommitOutcomeUnknownError = class extends Error {
1803
2295
  transactionId;
1804
2296
  constructor(transactionId, cause) {
1805
- super(`Commit outcome is unknown for transaction ${transactionId}` + (cause instanceof Error ? `: ${cause.message}` : ""), { cause });
2297
+ super(`Commit outcome is unknown for transaction ${transactionId}; reconcile before retrying`, { cause });
1806
2298
  this.name = "CommitOutcomeUnknownError";
1807
2299
  this.transactionId = transactionId;
1808
2300
  }
@@ -1816,9 +2308,9 @@ var ForeignKeyManager = class {
1816
2308
  this.#primary = new PrimaryIndex(storage, keys);
1817
2309
  this.#secondary = new SecondaryIndexManager(storage, keys);
1818
2310
  }
1819
- async prepare(snapshot, sourceWrites, sourceCatalog) {
2311
+ async prepare(snapshot, sourceWrites, sourceCatalog, targetWrites) {
1820
2312
  const catalog = this.validateCatalog(sourceCatalog);
1821
- const writes = new Map(sourceWrites);
2313
+ const writes = targetWrites ?? new Map(sourceWrites);
1822
2314
  const incoming = this.incoming(catalog);
1823
2315
  const queue = [];
1824
2316
  const visited = /* @__PURE__ */ new Set();
@@ -1951,25 +2443,40 @@ var ForeignKeyManager = class {
1951
2443
  var CommitCoordinator = class {
1952
2444
  storage;
1953
2445
  keys;
2446
+ coordinationStorage;
1954
2447
  primary;
1955
2448
  secondary;
1956
2449
  foreignKeys;
1957
- constructor(storage, keys = new StorageKeyManager()) {
2450
+ constructor(storage, keys = new StorageKeyManager(), coordinationStorage = storage) {
1958
2451
  this.storage = storage;
1959
2452
  this.keys = keys;
2453
+ this.coordinationStorage = coordinationStorage;
1960
2454
  this.primary = new PrimaryIndex(storage, keys);
1961
2455
  this.secondary = new SecondaryIndexManager(storage, keys);
1962
2456
  this.foreignKeys = new ForeignKeyManager(storage, keys);
1963
2457
  }
1964
2458
  async commit(transaction) {
2459
+ const admission = transaction.resources.reserve({ queuedOperations: 1 });
2460
+ try {
2461
+ return await coordinateCommit(this.coordinationStorage, transaction.limits.maxQueuedOperations, async () => {
2462
+ if (transaction.hasChanges) {
2463
+ if (((await this.storage.get(this.keys.manifestKey))?.version ?? null) != transaction.expectedStorageVersion) throw new TransactionConflictError();
2464
+ }
2465
+ await this.publish(transaction);
2466
+ });
2467
+ } finally {
2468
+ admission.release();
2469
+ }
2470
+ }
2471
+ async publish(transaction) {
1965
2472
  const prepared = transaction.prepareForCommit();
1966
2473
  if (prepared.writes.size == 0 && prepared.schemaChanges.size == 0) {
1967
2474
  transaction.markCommitted();
1968
2475
  return;
1969
2476
  }
1970
- const transactionId = randomUUID();
2477
+ const transactionId = transaction.id;
1971
2478
  const catalog = new Map(prepared.snapshot.manifest.catalog);
1972
- const staged = new Map(prepared.writes);
2479
+ const staged = new PreparedWrites(transaction.resources, transaction.limits, prepared.writes);
1973
2480
  for (const [name, schema] of prepared.schemaChanges) {
1974
2481
  if (schema == null) catalog.delete(name);
1975
2482
  else catalog.set(name, schema);
@@ -1982,7 +2489,9 @@ var CommitCoordinator = class {
1982
2489
  });
1983
2490
  const context = new QueryContext(this.storage, prepared.snapshot, this.keys, {
1984
2491
  writes: staged,
1985
- catalog: scanCatalog
2492
+ catalog: scanCatalog,
2493
+ resources: transaction.resources,
2494
+ limits: transaction.limits
1986
2495
  });
1987
2496
  try {
1988
2497
  for await (const row of context.scanCollection(name)) staged.set(recordKey(name, row.id), schema == null ? { type: "delete" } : {
@@ -1993,7 +2502,8 @@ var CommitCoordinator = class {
1993
2502
  context.close();
1994
2503
  }
1995
2504
  }
1996
- const writes = await this.foreignKeys.prepare(prepared.snapshot, staged, catalog);
2505
+ const writes = await this.foreignKeys.prepare(prepared.snapshot, staged, catalog, staged);
2506
+ for (const [key, value] of writes) if (!staged.has(key)) staged.set(key, value);
1997
2507
  const changes = /* @__PURE__ */ new Map();
1998
2508
  for (const [key, operation] of writes) {
1999
2509
  if (operation.type == "delete") {
@@ -2005,7 +2515,7 @@ var CommitCoordinator = class {
2005
2515
  changes.set(key, ref);
2006
2516
  }
2007
2517
  const primaryRoot = await this.primary.prepare(prepared.snapshot.manifest.primaryRoot, changes);
2008
- const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog);
2518
+ const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog, transaction.resources);
2009
2519
  const commitBytes = encodeCommitRecord({
2010
2520
  format: 1,
2011
2521
  transactionId,
@@ -2032,7 +2542,10 @@ var CommitCoordinator = class {
2032
2542
  transaction.markUnknown();
2033
2543
  throw new CommitOutcomeUnknownError(transactionId, cause);
2034
2544
  }
2035
- if (!result.success) throw new TransactionConflictError();
2545
+ if (!result.success) {
2546
+ transaction.rejectPublication();
2547
+ throw new TransactionConflictError();
2548
+ }
2036
2549
  transaction.markCommitted();
2037
2550
  }
2038
2551
  };
@@ -2083,7 +2596,7 @@ function hmac(key, value) {
2083
2596
  function queryHash(key, query) {
2084
2597
  return hmac(key, canonical(shape(query)));
2085
2598
  }
2086
- function encodeQueryCursor(generation, schema, query, row, signingKey) {
2599
+ function encodeLegacyCursor(generation, schema, query, row, signingKey) {
2087
2600
  if (query.collection != schema.name) throw new Error("Cursor collection mismatch");
2088
2601
  const values = (query.orderBy ?? []).map(({ field }) => {
2089
2602
  if (field == "$id") return row.id;
@@ -2106,7 +2619,7 @@ function encodeQueryCursor(generation, schema, query, row, signingKey) {
2106
2619
  signature: hmac(signingKey, payload)
2107
2620
  })).toString("base64url");
2108
2621
  }
2109
- function decodeQueryCursor(cursor, generation, schema, query, signingKey) {
2622
+ function decodeLegacyCursor(cursor, generation, schema, query, signingKey) {
2110
2623
  let parsed;
2111
2624
  try {
2112
2625
  parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
@@ -2134,6 +2647,108 @@ function decodeQueryCursor(cursor, generation, schema, query, signingKey) {
2134
2647
  })
2135
2648
  };
2136
2649
  }
2650
+ function cursorKeys(value) {
2651
+ if (value instanceof Uint8Array) {
2652
+ if (value.byteLength < 32) throw new Error("Cursor key must contain at least 32 bytes");
2653
+ return {
2654
+ activeKeyId: "default",
2655
+ keys: { default: createHash("sha256").update(value).digest() },
2656
+ ttlMs: 9e5
2657
+ };
2658
+ }
2659
+ if (!value || !/^[A-Za-z0-9_-]{1,32}$/.test(value.activeKeyId) || !Object.hasOwn(value.keys, value.activeKeyId)) throw new Error("Invalid cursor keyring");
2660
+ 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");
2661
+ if (Object.keys(value.keys).length > 16) throw new Error("Cursor keyring is too large");
2662
+ if (value.ttlMs !== void 0 && (!Number.isSafeInteger(value.ttlMs) || value.ttlMs < 1)) throw new Error("Invalid cursor expiry");
2663
+ return value;
2664
+ }
2665
+ function encodeQueryCursor(generation, schema, query, row, keys, namespace = "") {
2666
+ const ring = cursorKeys(keys);
2667
+ const key = ring.keys[ring.activeKeyId];
2668
+ const legacy = JSON.parse(Buffer.from(encodeLegacyCursor(generation, schema, query, row, key), "base64url").toString());
2669
+ const nonce = randomBytes(12);
2670
+ const cipher = createCipheriv("aes-256-gcm", key, nonce);
2671
+ cipher.setAAD(Buffer.from(canonical({
2672
+ version: 3,
2673
+ keyId: ring.activeKeyId,
2674
+ namespace
2675
+ })));
2676
+ const payload = JSON.stringify({
2677
+ ...legacy.payload,
2678
+ version: 3,
2679
+ namespace,
2680
+ expiresAt: Date.now() + (ring.ttlMs ?? 9e5)
2681
+ });
2682
+ const ciphertext = Buffer.concat([cipher.update(payload, "utf8"), cipher.final()]);
2683
+ const cursor = Buffer.from(JSON.stringify({
2684
+ version: 3,
2685
+ keyId: ring.activeKeyId,
2686
+ nonce: nonce.toString("base64url"),
2687
+ ciphertext: ciphertext.toString("base64url"),
2688
+ tag: cipher.getAuthTag().toString("base64url")
2689
+ })).toString("base64url");
2690
+ if (cursor.length > 16384) throw new Error("Query cursor exceeds maximum size");
2691
+ return cursor;
2692
+ }
2693
+ function decodeQueryCursor(cursor, generation, schema, query, keys, namespace = "") {
2694
+ if (typeof cursor != "string" || !cursor.length || cursor.length > 16384 || !/^[A-Za-z0-9_-]+$/.test(cursor)) throw new Error("Invalid query cursor");
2695
+ const ring = cursorKeys(keys);
2696
+ let outer;
2697
+ try {
2698
+ outer = JSON.parse(Buffer.from(cursor, "base64url").toString());
2699
+ } catch {
2700
+ throw new Error("Invalid query cursor");
2701
+ }
2702
+ if (!outer || typeof outer != "object" || Array.isArray(outer)) throw new Error("Invalid query cursor");
2703
+ if (outer.version !== 3) {
2704
+ if (!namespace && ring.allowLegacySigned && ring.legacySigningKey) return decodeLegacyCursor(cursor, generation, schema, query, ring.legacySigningKey);
2705
+ throw new Error("Legacy signed cursors are disabled; restart pagination");
2706
+ }
2707
+ 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");
2708
+ const binary = (value) => {
2709
+ if (typeof value != "string" || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("Invalid query cursor");
2710
+ const result = Buffer.from(value, "base64url");
2711
+ if (result.toString("base64url") != value) throw new Error("Invalid query cursor");
2712
+ return result;
2713
+ };
2714
+ const nonce = binary(outer.nonce);
2715
+ const tag = binary(outer.tag);
2716
+ const ciphertext = binary(outer.ciphertext);
2717
+ if (nonce.length != 12 || tag.length != 16) throw new Error("Invalid query cursor");
2718
+ const key = ring.keys[outer.keyId];
2719
+ let payload;
2720
+ try {
2721
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce);
2722
+ decipher.setAAD(Buffer.from(canonical({
2723
+ version: 3,
2724
+ keyId: outer.keyId,
2725
+ namespace
2726
+ })));
2727
+ decipher.setAuthTag(tag);
2728
+ payload = JSON.parse(Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString());
2729
+ } catch {
2730
+ throw new Error("Invalid query cursor authentication");
2731
+ }
2732
+ if (!payload || typeof payload != "object" || Array.isArray(payload)) throw new Error("Invalid query cursor payload");
2733
+ 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");
2734
+ if (payload.generation != generation) throw new Error("Query cursor snapshot generation is unavailable");
2735
+ if (payload.queryHash != queryHash(key, query) || query.collection != schema.name) throw new Error("Query cursor is incompatible with this query");
2736
+ 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");
2737
+ const values = payload.values.map((value, index) => {
2738
+ if (value && typeof value == "object" && Object.keys(value).join(",") == "missing" && value.missing === true) return void 0;
2739
+ if (value !== null && typeof value != "string" && typeof value != "boolean" && (typeof value != "number" || !Number.isFinite(value))) throw new Error("Invalid cursor scalar");
2740
+ if (fieldDefinition(schema, query.orderBy[index].field)?.type == "date" && typeof value == "string") {
2741
+ const date = new Date(value);
2742
+ if (!Number.isFinite(date.getTime()) || date.toISOString() != value) throw new Error("Invalid cursor date");
2743
+ return date;
2744
+ }
2745
+ return value;
2746
+ });
2747
+ return {
2748
+ id: payload.id,
2749
+ values
2750
+ };
2751
+ }
2137
2752
  // src/query/validation/query-validator.ts
2138
2753
  var MAX_PREDICATE_DEPTH = 64;
2139
2754
  var MAX_IN_VALUES = 1e4;
@@ -2204,10 +2819,36 @@ function predicate(schema, value, depth) {
2204
2819
  default: throw new Error("Unknown query predicate");
2205
2820
  }
2206
2821
  }
2207
- function validateQuery(query, catalog) {
2822
+ function validatePredicateComplexity(query, maxDepth = 32, maxNodes = 4096) {
2823
+ const stack = [{
2824
+ value: query.where,
2825
+ depth: 0
2826
+ }];
2827
+ let count = 0;
2828
+ while (stack.length) {
2829
+ const { value, depth } = stack.pop();
2830
+ if (value == null) continue;
2831
+ if (++count > maxNodes || depth > maxDepth) throw new Error("Query predicate complexity limit exceeded");
2832
+ if (!value || typeof value != "object") throw new Error("Invalid query predicate");
2833
+ const node = value;
2834
+ if (Array.isArray(node.predicates)) {
2835
+ if (node.predicates.length + count + stack.length > maxNodes) throw new Error("Query predicate complexity limit exceeded");
2836
+ for (const child of node.predicates) stack.push({
2837
+ value: child,
2838
+ depth: depth + 1
2839
+ });
2840
+ }
2841
+ if (node.predicate) stack.push({
2842
+ value: node.predicate,
2843
+ depth: depth + 1
2844
+ });
2845
+ }
2846
+ }
2847
+ function validateQuery(query, catalog, limits) {
2208
2848
  if (!query || typeof query != "object" || !isValidSchemaName(query.collection)) throw new Error("Invalid logical query");
2209
2849
  const schema = catalog.get(query.collection);
2210
2850
  if (!schema) throw new Error(`Unknown collection: ${query.collection}`);
2851
+ validatePredicateComplexity(query, limits?.maxPredicateDepth, limits?.maxPredicateNodes);
2211
2852
  if (query.where) predicate(schema, query.where, 0);
2212
2853
  const orders = /* @__PURE__ */ new Set();
2213
2854
  for (const order of query.orderBy ?? []) {
@@ -2422,12 +3063,24 @@ var Sort = class {
2422
3063
  const maximum = this.options.maxRowsInMemory ?? 1e4;
2423
3064
  if (!Number.isSafeInteger(maximum) || maximum < 2) throw new Error("Invalid sort memory limit");
2424
3065
  const compare = (a, b) => compareRows(schema, this.orders, a, b);
3066
+ const memory = context.resources.child({});
3067
+ const chunkMemory = memory.reserve({});
3068
+ let chunkBytes = 0;
3069
+ let spilledBytes = 0;
3070
+ const disk = memory.reserve({});
2425
3071
  const spill = this.options.spill;
2426
3072
  let chunk = [];
2427
3073
  let runs = [];
2428
3074
  const active = /* @__PURE__ */ new Set();
2429
3075
  const write = async (rows) => {
2430
- const handle = await spill.write(rows);
3076
+ const bounded = async function* () {
3077
+ for await (const row of rows) {
3078
+ spilledBytes += estimateBytes(row);
3079
+ disk.resize({ spillBytes: spilledBytes });
3080
+ yield row;
3081
+ }
3082
+ };
3083
+ const handle = await spill.write(bounded());
2431
3084
  active.add(handle);
2432
3085
  return handle;
2433
3086
  };
@@ -2449,12 +3102,24 @@ var Sort = class {
2449
3102
  };
2450
3103
  try {
2451
3104
  for await (const row of this.input.execute(context)) {
3105
+ const size = estimateBytes(row);
3106
+ if (chunkBytes + size > Math.floor(context.limits.maxQueryWorkingBytes / 2) && chunk.length && spill) {
3107
+ chunk.sort(compare);
3108
+ runs.push(await write(chunk));
3109
+ chunk = [];
3110
+ chunkBytes = 0;
3111
+ chunkMemory.resize({});
3112
+ }
3113
+ chunkMemory.resize({ workingBytes: chunkBytes + size });
3114
+ chunkBytes += size;
2452
3115
  chunk.push(row);
2453
3116
  if (chunk.length < maximum) continue;
2454
3117
  if (!this.options.spill) throw new QueryMemoryLimitError();
2455
3118
  chunk.sort(compare);
2456
3119
  runs.push(await write(chunk));
2457
3120
  chunk = [];
3121
+ chunkBytes = 0;
3122
+ chunkMemory.resize({});
2458
3123
  }
2459
3124
  if (runs.length == 0) {
2460
3125
  chunk.sort(compare);
@@ -2481,7 +3146,12 @@ var Sort = class {
2481
3146
  }
2482
3147
  yield* merge(runs);
2483
3148
  } finally {
2484
- await Promise.all([...active].map((handle) => spill.delete(handle)));
3149
+ try {
3150
+ const failures = (await Promise.allSettled([...active].map((handle) => spill.delete(handle)))).filter((r) => r.status == "rejected");
3151
+ if (failures.length) throw new AggregateError(failures.map((r) => r.reason), "Sort spill cleanup failed");
3152
+ } finally {
3153
+ memory.close();
3154
+ }
2485
3155
  }
2486
3156
  }
2487
3157
  };
@@ -2538,9 +3208,15 @@ var SetOperator = class {
2538
3208
  }
2539
3209
  async ids(context, input) {
2540
3210
  const result = /* @__PURE__ */ new Map();
3211
+ const memory = context.resources.reserve({});
3212
+ let bytes = 0;
2541
3213
  for await (const row of input.execute(context)) {
2542
3214
  context.assertActive();
2543
3215
  if (result.size >= this.maxSetEntries && !result.has(row.id)) throw new QueryMemoryLimitError();
3216
+ if (!result.has(row.id)) {
3217
+ bytes += estimateBytes(row);
3218
+ memory.resize({ workingBytes: bytes });
3219
+ }
2544
3220
  result.set(row.id, row);
2545
3221
  }
2546
3222
  return result;
@@ -2550,10 +3226,14 @@ var Union = class extends SetOperator {
2550
3226
  name = "Union";
2551
3227
  async *execute(context) {
2552
3228
  const seen = /* @__PURE__ */ new Set();
3229
+ const memory = context.resources.reserve({});
3230
+ let bytes = 0;
2553
3231
  for (const input of this.inputs) for await (const row of input.execute(context)) {
2554
3232
  context.assertActive();
2555
3233
  if (seen.has(row.id)) continue;
2556
3234
  if (seen.size >= this.maxSetEntries) throw new QueryMemoryLimitError();
3235
+ bytes += row.id.length * 2 + 48;
3236
+ memory.resize({ workingBytes: bytes });
2557
3237
  seen.add(row.id);
2558
3238
  yield row;
2559
3239
  }
@@ -2566,7 +3246,7 @@ var Intersection = class extends SetOperator {
2566
3246
  const candidates = await this.ids(context, first);
2567
3247
  for (const input of rest) {
2568
3248
  const current = await this.ids(context, input);
2569
- for (const id of [...candidates.keys()]) if (!current.has(id)) candidates.delete(id);
3249
+ for (const id of candidates.keys()) if (!current.has(id)) candidates.delete(id);
2570
3250
  }
2571
3251
  for (const row of candidates.values()) {
2572
3252
  context.assertActive();
@@ -2584,7 +3264,15 @@ var Difference = class extends SetOperator {
2584
3264
  this.excluded = excluded;
2585
3265
  }
2586
3266
  async *execute(context) {
2587
- const excluded = await this.ids(context, this.excluded);
3267
+ const excluded = /* @__PURE__ */ new Set();
3268
+ const memory = context.resources.reserve({});
3269
+ let bytes = 0;
3270
+ for await (const row of this.excluded.execute(context)) if (!excluded.has(row.id)) {
3271
+ if (excluded.size >= this.maxSetEntries) throw new QueryMemoryLimitError();
3272
+ bytes += row.id.length * 2 + 48;
3273
+ memory.resize({ workingBytes: bytes });
3274
+ excluded.add(row.id);
3275
+ }
2588
3276
  for await (const row of this.universe.execute(context)) {
2589
3277
  context.assertActive();
2590
3278
  if (!excluded.has(row.id)) yield row;
@@ -2650,7 +3338,7 @@ var QueryExecutor = class {
2650
3338
  }
2651
3339
  }
2652
3340
  semanticPipeline(context, query, source, forceDeterministicSort = false, executionLimit = query.limit) {
2653
- validateQuery(query, context.catalog);
3341
+ validateQuery(query, context.catalog, context.limits);
2654
3342
  let operator = source;
2655
3343
  if (query.where) operator = new Filter(operator, query.where, query.collection);
2656
3344
  const orderBy = query.orderBy ?? [];
@@ -2659,7 +3347,7 @@ var QueryExecutor = class {
2659
3347
  spill: this.options.sortSpill
2660
3348
  });
2661
3349
  if (query.cursor) {
2662
- const cursor = decodeQueryCursor(query.cursor, context.generation, context.catalog.get(query.collection), query, this.signingKey());
3350
+ const cursor = decodeQueryCursor(query.cursor, context.generation, context.catalog.get(query.collection), query, this.signingKey(), this.options.cursorNamespace);
2663
3351
  operator = new CursorAfter(operator, orderBy, cursor.values, cursor.id, query.collection);
2664
3352
  }
2665
3353
  if (executionLimit != null) operator = new Limit(operator, executionLimit);
@@ -2670,6 +3358,7 @@ var QueryExecutor = class {
2670
3358
  return produced?.deterministic == true && produced.fields.length == requested.length && produced.fields.every((field, index) => field.field == requested[index].field && field.direction == requested[index].direction);
2671
3359
  }
2672
3360
  signingKey() {
3361
+ if (this.options.cursorEncryption) return this.options.cursorEncryption;
2673
3362
  const key = this.options.cursorSigningKey;
2674
3363
  if (!(key instanceof Uint8Array) || key.byteLength < 32) throw new Error("Cursor operations require a signing key of at least 32 bytes");
2675
3364
  return key;
@@ -2683,11 +3372,19 @@ var QueryExecutor = class {
2683
3372
  const lookahead = query.limit == null ? void 0 : query.limit + 1;
2684
3373
  const operator = this.semanticPipeline(context, query, source, true, lookahead);
2685
3374
  const raw = [];
2686
- for await (const row of operator.execute(context)) raw.push(row);
3375
+ const results = materialize(context.resources, context.limits);
3376
+ try {
3377
+ for await (const row of operator.execute(context)) {
3378
+ results.add(row);
3379
+ raw.push(row);
3380
+ }
3381
+ } finally {
3382
+ results.close();
3383
+ }
2687
3384
  const schema = context.catalog.get(query.collection);
2688
3385
  const hasMore = query.limit != null && query.limit > 0 && raw.length > query.limit;
2689
3386
  if (hasMore) raw.pop();
2690
- const nextCursor = hasMore && raw.length ? encodeQueryCursor(context.generation, schema, query, raw[raw.length - 1], this.signingKey()) : null;
3387
+ const nextCursor = hasMore && raw.length ? encodeQueryCursor(context.generation, schema, query, raw[raw.length - 1], this.signingKey(), this.options.cursorNamespace) : null;
2691
3388
  return {
2692
3389
  rows: query.projection ? raw.map((row) => ({
2693
3390
  id: row.id,
@@ -2949,8 +3646,8 @@ var RuleBasedPlanner = class {
2949
3646
  constructor(enumerator = new AccessPathEnumerator()) {
2950
3647
  this.enumerator = enumerator;
2951
3648
  }
2952
- plan(query, catalog) {
2953
- const schema = validateQuery(query, catalog);
3649
+ plan(query, catalog, limits) {
3650
+ const schema = validateQuery(query, catalog, limits);
2954
3651
  const selected = this.choose(query, schema, query.where);
2955
3652
  const required = query.orderBy ?? [];
2956
3653
  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));
@@ -3087,23 +3784,70 @@ var Transaction = class {
3087
3784
  storage;
3088
3785
  keys;
3089
3786
  cursorSigningKey;
3787
+ operationSignal;
3788
+ onPublication;
3789
+ assertAccessScope;
3790
+ runtimeHooks;
3791
+ id = randomUUID();
3792
+ pendingCleanup = /* @__PURE__ */ new Set();
3793
+ localCancellation = new AbortController();
3794
+ signal;
3795
+ resources;
3796
+ limits;
3797
+ writeReservations = /* @__PURE__ */ new Map();
3798
+ schemaReservations = /* @__PURE__ */ new Map();
3090
3799
  writes = /* @__PURE__ */ new Map();
3091
3800
  schemas = /* @__PURE__ */ new Map();
3092
- capturedSnapshot;
3093
- reader;
3801
+ snapshotValue;
3802
+ get capturedSnapshot() {
3803
+ if (!this.snapshotValue) throw new TransactionStateError("Transaction is closed");
3804
+ return this.snapshotValue;
3805
+ }
3806
+ set capturedSnapshot(value) {
3807
+ this.snapshotValue = value;
3808
+ }
3809
+ readerValue;
3810
+ get reader() {
3811
+ if (!this.readerValue) throw new TransactionStateError("Transaction is closed");
3812
+ return this.readerValue;
3813
+ }
3814
+ set reader(value) {
3815
+ this.readerValue = value;
3816
+ }
3094
3817
  stateValue = "ACTIVE";
3095
3818
  pendingReads = 0;
3096
3819
  readWaiters = [];
3097
3820
  queryContexts = /* @__PURE__ */ new Set();
3098
3821
  planner = new RuleBasedPlanner();
3099
3822
  planCompiler = new PlanCompiler();
3100
- constructor(storage, snapshot, keys = new StorageKeyManager(), cursorSigningKey) {
3823
+ constructor(storage, snapshot, keys = new StorageKeyManager(), cursorSigningKey, parentResources, limits = resourceLimits(), operationSignal, onPublication, assertAccessScope, runtimeHooks = {}) {
3101
3824
  this.storage = storage;
3102
3825
  this.keys = keys;
3103
3826
  this.cursorSigningKey = cursorSigningKey;
3827
+ this.operationSignal = operationSignal;
3828
+ this.onPublication = onPublication;
3829
+ this.assertAccessScope = assertAccessScope;
3830
+ this.runtimeHooks = runtimeHooks;
3831
+ this.signal = operationSignal ? AbortSignal.any([operationSignal, this.localCancellation.signal]) : this.localCancellation.signal;
3832
+ this.limits = limits;
3833
+ this.resources = (parentResources ?? new ResourceScope({})).child({
3834
+ workingBytes: limits.maxTransactionWorkingBytes,
3835
+ writes: limits.maxPendingWrites,
3836
+ writeBytes: limits.maxPendingWriteBytes
3837
+ });
3838
+ this.resources.reserve({ transactions: 1 });
3839
+ this.resources.reserve({ workingBytes: estimateBytes([...snapshot.manifest.catalog]) });
3104
3840
  this.capturedSnapshot = cloneSnapshot(snapshot);
3105
3841
  this.reader = new ManifestSnapshotReader(this.storage, this.capturedSnapshot, keys);
3106
3842
  }
3843
+ get expectedStorageVersion() {
3844
+ this.assertActive();
3845
+ return this.capturedSnapshot.storageVersion;
3846
+ }
3847
+ get hasChanges() {
3848
+ this.assertActive();
3849
+ return this.writes.size + this.schemas.size > 0;
3850
+ }
3107
3851
  get state() {
3108
3852
  return this.stateValue;
3109
3853
  }
@@ -3120,6 +3864,9 @@ var Transaction = class {
3120
3864
  const result = await this.reader.get(key);
3121
3865
  this.assertActive();
3122
3866
  return result;
3867
+ } catch (error) {
3868
+ if (this.stateValue != "ACTIVE" && !this.operationSignal?.aborted && error instanceof OperationCancelledError) throw new TransactionStateError("Transaction is no longer active");
3869
+ throw error;
3123
3870
  } finally {
3124
3871
  this.pendingReads--;
3125
3872
  if (this.pendingReads == 0) for (const resolve of this.readWaiters.splice(0)) resolve();
@@ -3135,14 +3882,14 @@ var Transaction = class {
3135
3882
  this.assertActive();
3136
3883
  this.validateKey(key);
3137
3884
  if (key.startsWith("@duraxis/records/")) throw new Error("Reserved internal collection key");
3138
- this.writes.set(key, { type: "delete" });
3885
+ this.stageDelete(key);
3139
3886
  }
3140
3887
  defineCollection(definition) {
3141
3888
  this.assertActive();
3142
3889
  validateCollection(definition);
3143
3890
  if (this.schemas.get(definition.name) === null) throw new Error("Cannot recreate a dropped collection in the same transaction");
3144
3891
  if (this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3145
- this.schemas.set(definition.name, cloneSchema(definition));
3892
+ this.stageSchema(definition.name, cloneSchema(definition));
3146
3893
  }
3147
3894
  defineCollections(definitions) {
3148
3895
  this.assertActive();
@@ -3152,7 +3899,7 @@ var Transaction = class {
3152
3899
  if (names.has(definition.name) || this.schemas.has(definition.name) || this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3153
3900
  names.add(definition.name);
3154
3901
  }
3155
- for (const definition of definitions) this.schemas.set(definition.name, cloneSchema(definition));
3902
+ for (const definition of definitions) this.stageSchema(definition.name, cloneSchema(definition));
3156
3903
  }
3157
3904
  getCollectionDefinitions() {
3158
3905
  this.assertActive();
@@ -3165,12 +3912,12 @@ var Transaction = class {
3165
3912
  this.assertActive();
3166
3913
  this.requireCollection(name);
3167
3914
  if (name != definition.name) throw new Error("Collection replacement cannot rename a collection");
3168
- this.schemas.set(name, cloneSchema(definition));
3915
+ this.stageSchema(name, cloneSchema(definition));
3169
3916
  }
3170
3917
  dropCollection(name) {
3171
3918
  this.assertActive();
3172
3919
  this.requireCollection(name);
3173
- this.schemas.set(name, null);
3920
+ this.stageSchema(name, null);
3174
3921
  }
3175
3922
  async getMetadata(namespace) {
3176
3923
  this.assertActive();
@@ -3209,13 +3956,13 @@ var Transaction = class {
3209
3956
  indexes: [...current.indexes, index]
3210
3957
  };
3211
3958
  validateCollection(updated);
3212
- this.schemas.set(collection, cloneSchema(updated));
3959
+ this.stageSchema(collection, cloneSchema(updated));
3213
3960
  }
3214
3961
  removeIndex(collection, indexName) {
3215
3962
  this.assertActive();
3216
3963
  const current = this.requireCollection(collection);
3217
3964
  if (!current.indexes.some((index) => index.name == indexName)) throw new Error(`Unknown index: ${collection}/${indexName}`);
3218
- this.schemas.set(collection, cloneSchema({
3965
+ this.stageSchema(collection, cloneSchema({
3219
3966
  ...current,
3220
3967
  indexes: current.indexes.filter((index) => index.name != indexName)
3221
3968
  }));
@@ -3233,6 +3980,16 @@ var Transaction = class {
3233
3980
  else catalog.set(name, cloneSchema(schema));
3234
3981
  let context;
3235
3982
  context = new QueryContext(this.storage, cloneSnapshot(this.capturedSnapshot), this.keys, {
3983
+ assertAccess: this.assertAccessScope,
3984
+ onPendingCleanup: (promise) => {
3985
+ this.pendingCleanup.add(promise);
3986
+ this.runtimeHooks.onPendingCleanup?.(promise);
3987
+ const complete = () => this.pendingCleanup.delete(promise);
3988
+ promise.then(complete, complete);
3989
+ },
3990
+ onCleanupFailure: this.runtimeHooks.onCleanupFailure,
3991
+ resources: this.resources,
3992
+ limits: this.limits,
3236
3993
  writes: this.writes,
3237
3994
  catalog,
3238
3995
  onIteratorStart: () => {
@@ -3248,18 +4005,21 @@ var Transaction = class {
3248
4005
  const context = this.createQueryContext();
3249
4006
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3250
4007
  const options = explicit ? explicitOptions : sourceOrOptions;
3251
- const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog), context.catalog);
4008
+ const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog, context.limits), context.catalog);
3252
4009
  const executor = new QueryExecutor(this.queryOptions(options));
3253
4010
  const transaction = this;
3254
- return (async function* () {
3255
- const unbindSignal = transaction.bindSignal(context, options?.signal);
4011
+ const iterator = (async function* () {
4012
+ let unbindSignal = () => {};
3256
4013
  try {
4014
+ unbindSignal = transaction.bindSignal(context, options?.signal);
3257
4015
  yield* executor.execute(context, query, source);
3258
4016
  } finally {
3259
4017
  unbindSignal();
3260
4018
  context.close();
3261
4019
  }
3262
4020
  })();
4021
+ context.bindCancellation(() => iterator.return(void 0));
4022
+ return iterator;
3263
4023
  }
3264
4024
  async queryPage(query, sourceOrOptions, explicitOptions) {
3265
4025
  const context = this.createQueryContext();
@@ -3268,7 +4028,7 @@ var Transaction = class {
3268
4028
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3269
4029
  const options = explicit ? explicitOptions : sourceOrOptions;
3270
4030
  unbindSignal = this.bindSignal(context, options?.signal);
3271
- const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog), context.catalog);
4031
+ const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog, context.limits), context.catalog);
3272
4032
  return await new QueryExecutor(this.queryOptions(options)).page(context, query, source);
3273
4033
  } finally {
3274
4034
  unbindSignal();
@@ -3278,22 +4038,29 @@ var Transaction = class {
3278
4038
  putDocument(collection, id, document) {
3279
4039
  this.assertActive();
3280
4040
  const schema = this.requireCollection(collection);
3281
- const parsed = validateDocument(schema, document);
3282
- const data = encodeDocument(parsed);
3283
- for (const index of schema.indexes) for (const part of index.fields ?? (index.field ? [{
3284
- field: index.field,
3285
- order: "ASC"
3286
- }] : [])) indexedValue(parsed, part.field, fieldDefinition(schema, part.field));
3287
- this.stagePut(recordKey(collection, id), data);
4041
+ const estimate = estimateBytes(document, this.limits.maxDocumentBytes * 4, this.limits.maxDocumentDepth);
4042
+ const encoding = this.resources.reserve({ workingBytes: estimate * 4 });
4043
+ try {
4044
+ const parsed = validateDocument(schema, document);
4045
+ const data = encodeDocument(parsed);
4046
+ for (const index of schema.indexes) for (const part of index.fields ?? (index.field ? [{
4047
+ field: index.field,
4048
+ order: "ASC"
4049
+ }] : [])) indexedValue(parsed, part.field, fieldDefinition(schema, part.field));
4050
+ this.stagePut(recordKey(collection, id), data);
4051
+ } finally {
4052
+ encoding.release();
4053
+ }
3288
4054
  }
3289
4055
  deleteDocument(collection, id) {
3290
4056
  this.assertActive();
3291
4057
  this.requireCollection(collection);
3292
- this.writes.set(recordKey(collection, id), { type: "delete" });
4058
+ this.stageDelete(recordKey(collection, id));
3293
4059
  }
3294
4060
  prepareForCommit() {
3295
4061
  this.assertActive();
3296
4062
  if (this.pendingReads != 0) throw new TransactionStateError("Transaction has pending reads; await all tx.get() calls");
4063
+ this.resources.reserve({ workingBytes: [...this.writes].reduce((n, [key, op]) => n + key.length * 2 + 96 + (op.type == "put" ? op.data.byteLength : 0), 0) });
3297
4064
  this.stateValue = "PREPARING";
3298
4065
  const writes = /* @__PURE__ */ new Map();
3299
4066
  for (const [key, operation] of this.writes) writes.set(key, operation.type == "delete" ? { type: "delete" } : {
@@ -3313,7 +4080,9 @@ var Transaction = class {
3313
4080
  });
3314
4081
  }
3315
4082
  beginPublication() {
4083
+ this.assertAccessScope?.();
3316
4084
  if (this.stateValue != "PREPARING") throw new TransactionStateError("Transaction is not preparing");
4085
+ this.onPublication?.();
3317
4086
  this.stateValue = "COMMITTING";
3318
4087
  }
3319
4088
  markCommitted() {
@@ -3324,17 +4093,56 @@ var Transaction = class {
3324
4093
  this.stateValue = "UNKNOWN";
3325
4094
  }
3326
4095
  abort() {
4096
+ if (this.stateValue == "COMMITTING") return;
3327
4097
  if (this.stateValue != "COMMITTED" && this.stateValue != "UNKNOWN") this.stateValue = "ABORTED";
3328
4098
  }
4099
+ rejectPublication() {
4100
+ if (this.stateValue != "COMMITTING") throw new TransactionStateError("No publication in progress");
4101
+ this.stateValue = "ABORTED";
4102
+ }
3329
4103
  close() {
4104
+ if (this.stateValue == "COMMITTING") return;
4105
+ this.localCancellation.abort(new TransactionStateError("Transaction is closed"));
3330
4106
  if (this.stateValue == "ACTIVE" || this.stateValue == "PREPARING") this.abort();
3331
- for (const context of [...this.queryContexts]) context.close();
4107
+ for (const context of [...this.queryContexts]) context.cancel(new TransactionStateError("Transaction is closed"));
3332
4108
  this.queryContexts.clear();
3333
4109
  this.writes.clear();
3334
4110
  this.schemas.clear();
4111
+ this.writeReservations.clear();
4112
+ this.schemaReservations.clear();
4113
+ if (this.pendingCleanup.size) Promise.allSettled([...this.pendingCleanup]).then(() => this.resources.close());
4114
+ else this.resources.close();
4115
+ this.snapshotValue = void 0;
4116
+ this.readerValue = void 0;
4117
+ }
4118
+ createMaterializationBudget() {
4119
+ return materialize(this.resources, this.limits);
4120
+ }
4121
+ reserveWrite(key, bytes) {
4122
+ if (bytes > this.limits.maxDocumentBytes) throw new ResourceExhaustedError("documentBytes", this.limits.maxDocumentBytes);
4123
+ const amounts = {
4124
+ writes: 1,
4125
+ writeBytes: bytes,
4126
+ workingBytes: bytes + key.length * 2 + 128
4127
+ };
4128
+ const current = this.writeReservations.get(key);
4129
+ if (current) current.resize(amounts);
4130
+ else this.writeReservations.set(key, this.resources.reserve(amounts));
4131
+ }
4132
+ stageDelete(key) {
4133
+ this.reserveWrite(key, 0);
4134
+ this.writes.set(key, { type: "delete" });
4135
+ }
4136
+ stageSchema(name, schema) {
4137
+ const amounts = { workingBytes: estimateBytes(schema) + 128 };
4138
+ const current = this.schemaReservations.get(name);
4139
+ if (current) current.resize(amounts);
4140
+ else this.schemaReservations.set(name, this.resources.reserve(amounts));
4141
+ this.schemas.set(name, schema);
3335
4142
  }
3336
4143
  stagePut(key, data) {
3337
4144
  if (!(data instanceof Uint8Array)) throw new TypeError("Storage value must be Uint8Array");
4145
+ this.reserveWrite(key, data.byteLength);
3338
4146
  this.writes.set(key, {
3339
4147
  type: "put",
3340
4148
  data: new Uint8Array(data)
@@ -3347,13 +4155,15 @@ var Transaction = class {
3347
4155
  queryOptions(options) {
3348
4156
  return {
3349
4157
  ...options,
3350
- cursorSigningKey: options?.cursorSigningKey ?? this.cursorSigningKey
4158
+ cursorSigningKey: this.cursorSigningKey,
4159
+ cursorEncryption: this.runtimeHooks.cursorEncryption,
4160
+ cursorNamespace: this.keys.namespace
3351
4161
  };
3352
4162
  }
3353
4163
  bindSignal(context, signal) {
3354
4164
  if (!signal) return () => {};
3355
4165
  const cancel = () => context.cancel(signal.reason ?? /* @__PURE__ */ new Error("Query cancelled"));
3356
- if (signal.aborted) cancel();
4166
+ if (signal.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
3357
4167
  else signal.addEventListener("abort", cancel, { once: true });
3358
4168
  return () => signal.removeEventListener("abort", cancel);
3359
4169
  }
@@ -3369,9 +4179,12 @@ var Transaction = class {
3369
4179
  return schema;
3370
4180
  }
3371
4181
  assertActive() {
4182
+ this.assertAccessScope?.();
4183
+ this.operationSignal?.throwIfAborted();
3372
4184
  if (this.stateValue != "ACTIVE") throw new TransactionStateError("Transaction is no longer active");
3373
4185
  }
3374
4186
  validateKey(key) {
4187
+ if (Buffer.byteLength(key) > 1024) throw new ResourceExhaustedError("keyBytes", 1024);
3375
4188
  this.keys.validateLogicalKey(key);
3376
4189
  encodeIndexKey(new TextEncoder().encode(key));
3377
4190
  }
@@ -3421,6 +4234,196 @@ var RecoveryManager = class {
3421
4234
  return count;
3422
4235
  }
3423
4236
  };
4237
+ // src/gc/reachability-scanner.ts
4238
+ var MAX_REFERENCES = 1e5;
4239
+ var MAX_BYTES = 33554432;
4240
+ var ManifestReachabilityScanner = class {
4241
+ keys;
4242
+ nodes;
4243
+ primary;
4244
+ constructor(keys, storage) {
4245
+ this.keys = keys;
4246
+ this.nodes = new BPlusTreeNodeStore(storage, keys);
4247
+ this.primary = new PrimaryIndex(storage, keys);
4248
+ }
4249
+ async scan(snapshot, options = {}) {
4250
+ const maximum = options.maxReferences ?? MAX_REFERENCES;
4251
+ const maxBytes = options.maxBytes ?? MAX_BYTES;
4252
+ const reachable = /* @__PURE__ */ new Set();
4253
+ let bytes = 0;
4254
+ const add = (ref) => {
4255
+ if (reachable.has(ref)) return;
4256
+ const size = ref.length * 2 + 64;
4257
+ if (reachable.size >= maximum || bytes + size > maxBytes) throw new ResourceExhaustedError("gcReachability", maxBytes);
4258
+ bytes += size;
4259
+ reachable.add(ref);
4260
+ };
4261
+ const path = /* @__PURE__ */ new Set();
4262
+ const visit = async (ref, depth) => {
4263
+ options.signal?.throwIfAborted();
4264
+ if (path.has(ref) || depth >= 128) throw new Error("Invalid B+tree cycle or depth during reachability scan");
4265
+ if (reachable.has(ref)) return;
4266
+ this.keys.validateIndexNodeKey(ref);
4267
+ add(ref);
4268
+ path.add(ref);
4269
+ try {
4270
+ const node = await this.nodes.read(ref);
4271
+ if (node.type == "internal") for (const child of node.children) await visit(child, depth + 1);
4272
+ } finally {
4273
+ path.delete(ref);
4274
+ }
4275
+ };
4276
+ if (snapshot.manifest.primaryRoot) await visit(snapshot.manifest.primaryRoot, 0);
4277
+ for (const root of snapshot.manifest.indexRoots.values()) if (root) await visit(root, 0);
4278
+ for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot)) {
4279
+ options.signal?.throwIfAborted();
4280
+ add(entry.ref);
4281
+ }
4282
+ return reachable;
4283
+ }
4284
+ };
4285
+ // src/gc/garbage-collector.ts
4286
+ var DEFAULT_GRACE_PERIOD_MS = 864e5;
4287
+ var GarbageCollector = class {
4288
+ storage;
4289
+ keys;
4290
+ activeSnapshots;
4291
+ scanner;
4292
+ resourceParent;
4293
+ constructor(storage, keys, activeSnapshots, scanner = new ManifestReachabilityScanner(keys, storage), resourceParent = new ResourceScope({ workingBytes: 67108864 })) {
4294
+ this.storage = storage;
4295
+ this.keys = keys;
4296
+ this.activeSnapshots = activeSnapshots;
4297
+ this.scanner = scanner;
4298
+ this.resourceParent = resourceParent;
4299
+ }
4300
+ async collect(options = {}) {
4301
+ const started = performance.now();
4302
+ const dryRun = options.dryRun != false;
4303
+ if (!dryRun && options.exclusiveMaintenance != true) throw new Error("Deletion requires explicit exclusive maintenance intent and verified driver ownership");
4304
+ const coordination = storageCoordination(this.storage);
4305
+ if (coordination.maintenance) throw new Error("Maintenance is already active");
4306
+ if (!dryRun && (coordination.active || this.activeSnapshots().length)) throw new Error("Cannot delete objects with active snapshots or operations");
4307
+ if (!dryRun && !this.storage.verifyExclusiveOwnership) throw new Error("Destructive GC is unsupported without verified single-owner storage; shared/distributed storage must use dry-run");
4308
+ if (!this.storage.iterate) throw new Error("GC requires incremental storage listing support");
4309
+ coordination.maintenance = true;
4310
+ const maxMarkBytes = options.maxMarkBytes ?? 33554432;
4311
+ const maxReferences = options.maxReferences ?? 1e5;
4312
+ if (!Number.isSafeInteger(maxMarkBytes) || maxMarkBytes < 1 || !Number.isSafeInteger(maxReferences) || maxReferences < 1) {
4313
+ coordination.maintenance = false;
4314
+ throw new RangeError("Invalid GC mark budget");
4315
+ }
4316
+ const resources = this.resourceParent.child({ workingBytes: maxMarkBytes * 2 });
4317
+ const reservation = resources.reserve({});
4318
+ let markBytes = 0;
4319
+ try {
4320
+ if (!dryRun) await this.storage.verifyExclusiveOwnership();
4321
+ const olderThanMs = options.olderThanMs ?? DEFAULT_GRACE_PERIOD_MS;
4322
+ if (!Number.isSafeInteger(olderThanMs) || olderThanMs < 0) throw new Error("Invalid GC grace period");
4323
+ const batchSize = options.batchSize ?? 256;
4324
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1e5) throw new Error("Invalid GC batch size");
4325
+ if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
4326
+ const current = await this.storage.get(this.keys.manifestKey);
4327
+ const snapshot = {
4328
+ manifest: current ? decodeManifest(current.data, this.keys) : emptyManifest(),
4329
+ storageVersion: current?.version ?? null
4330
+ };
4331
+ const reachable = /* @__PURE__ */ new Set();
4332
+ if (coordination.snapshots.size > maxReferences) throw new ResourceExhaustedError("gcSnapshots", maxReferences);
4333
+ const retainedSnapshots = [snapshot, .../* @__PURE__ */ new Set([...this.activeSnapshots(), ...coordination.snapshots])];
4334
+ const mark = (ref) => {
4335
+ if (reachable.has(ref)) return;
4336
+ if (reachable.size >= maxReferences) throw new ResourceExhaustedError("gcReferences", maxReferences);
4337
+ const size = ref.length * 2 + 64;
4338
+ if (markBytes + size > maxMarkBytes) throw new ResourceExhaustedError("gcMarkBytes", maxMarkBytes);
4339
+ reservation.resize({ workingBytes: markBytes + size });
4340
+ markBytes += size;
4341
+ reachable.add(ref);
4342
+ };
4343
+ for (const item of retainedSnapshots) {
4344
+ const scanLease = resources.reserve({ workingBytes: maxMarkBytes });
4345
+ try {
4346
+ const refs = await this.scanner.scan(item, {
4347
+ maxReferences,
4348
+ maxBytes: maxMarkBytes,
4349
+ signal: options.signal
4350
+ });
4351
+ for (const ref of refs) mark(ref);
4352
+ } finally {
4353
+ scanLease.release();
4354
+ }
4355
+ }
4356
+ for (const retained of retainedSnapshots) {
4357
+ let cursor = retained.manifest.commitHead;
4358
+ let count = 0;
4359
+ while (cursor) {
4360
+ if (reachable.has(cursor)) break;
4361
+ if (++count > 1e6) throw new Error("Commit history scan limit exceeded during GC");
4362
+ mark(cursor);
4363
+ cursor = (await readCommitRecord(this.storage, this.keys, cursor)).previous;
4364
+ }
4365
+ }
4366
+ const cutoff = Date.now() - olderThanMs;
4367
+ let candidates = 0;
4368
+ let deleted = 0;
4369
+ let failed = 0;
4370
+ let scanned = 0;
4371
+ let nodesScanned = 0;
4372
+ let commitsScanned = 0;
4373
+ let position = 0;
4374
+ for (const prefix of [
4375
+ this.keys.objectPrefix,
4376
+ this.keys.indexNodePrefix,
4377
+ this.keys.commitPrefix
4378
+ ]) for await (const object of this.storage.iterate(prefix, {
4379
+ pageSize: Math.min(batchSize, 1e3),
4380
+ signal: options.signal
4381
+ })) {
4382
+ if (prefix == this.keys.objectPrefix) scanned++;
4383
+ else if (prefix == this.keys.indexNodePrefix) nodesScanned++;
4384
+ else commitsScanned++;
4385
+ position++;
4386
+ if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
4387
+ if (object.key.startsWith(this.keys.objectPrefix)) this.keys.validateObjectKey(object.key);
4388
+ else if (object.key.startsWith(this.keys.indexNodePrefix)) this.keys.validateIndexNodeKey(object.key);
4389
+ else this.keys.validateCommitKey(object.key);
4390
+ if (!Number.isSafeInteger(object.createdAt)) throw new Error(`Invalid object timestamp: ${object.key}`);
4391
+ if (reachable.has(object.key) || object.createdAt > cutoff) continue;
4392
+ candidates++;
4393
+ if (dryRun) {
4394
+ if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
4395
+ continue;
4396
+ }
4397
+ try {
4398
+ await this.storage.verifyExclusiveOwnership();
4399
+ if ((await this.storage.delete(object.key, { condition: {
4400
+ type: "if-version",
4401
+ version: object.version
4402
+ } })).success) deleted++;
4403
+ else failed++;
4404
+ } catch (error) {
4405
+ failed++;
4406
+ if (!options.continueOnError) throw error;
4407
+ }
4408
+ if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
4409
+ }
4410
+ return {
4411
+ scanned,
4412
+ nodesScanned,
4413
+ reachable: reachable.size,
4414
+ candidates,
4415
+ deleted,
4416
+ failed,
4417
+ commitsScanned,
4418
+ durationMs: performance.now() - started,
4419
+ dryRun
4420
+ };
4421
+ } finally {
4422
+ resources.close();
4423
+ coordination.maintenance = false;
4424
+ }
4425
+ }
4426
+ };
3424
4427
  // src/indexes/bptree/bptree-validator.ts
3425
4428
  var BPlusTreeValidator = class {
3426
4429
  nodes;
@@ -3522,125 +4525,6 @@ var BPlusTreeValidator = class {
3522
4525
  return found;
3523
4526
  }
3524
4527
  };
3525
- // src/gc/reachability-scanner.ts
3526
- var ManifestReachabilityScanner = class {
3527
- keys;
3528
- nodes;
3529
- primary;
3530
- constructor(keys, storage) {
3531
- this.keys = keys;
3532
- this.nodes = new BPlusTreeNodeStore(storage, keys);
3533
- this.primary = new PrimaryIndex(storage, keys);
3534
- }
3535
- async scan(snapshot) {
3536
- const reachable = /* @__PURE__ */ new Set();
3537
- const roots = /* @__PURE__ */ new Set();
3538
- if (snapshot.manifest.primaryRoot != null) roots.add(snapshot.manifest.primaryRoot);
3539
- for (const root of snapshot.manifest.indexRoots.values()) if (root != null) roots.add(root);
3540
- const validator = new BPlusTreeValidator(this.nodes);
3541
- for (const root of roots) {
3542
- this.keys.validateIndexNodeKey(root);
3543
- const references = await validator.reachableNodes(root);
3544
- for (const ref of references) reachable.add(ref);
3545
- }
3546
- for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot)) reachable.add(entry.ref);
3547
- return reachable;
3548
- }
3549
- };
3550
- // src/gc/garbage-collector.ts
3551
- var DEFAULT_GRACE_PERIOD_MS = 864e5;
3552
- var GarbageCollector = class {
3553
- storage;
3554
- keys;
3555
- activeSnapshots;
3556
- scanner;
3557
- constructor(storage, keys, activeSnapshots, scanner = new ManifestReachabilityScanner(keys, storage)) {
3558
- this.storage = storage;
3559
- this.keys = keys;
3560
- this.activeSnapshots = activeSnapshots;
3561
- this.scanner = scanner;
3562
- }
3563
- async collect(options = {}) {
3564
- const started = performance.now();
3565
- const dryRun = options.dryRun != false;
3566
- if (!dryRun && options.exclusiveMaintenance != true) throw new Error("Deletion requires externally guaranteed exclusive maintenance");
3567
- if (!dryRun && this.activeSnapshots().length != 0) throw new Error("Cannot delete objects with active snapshots");
3568
- const olderThanMs = options.olderThanMs ?? DEFAULT_GRACE_PERIOD_MS;
3569
- if (!Number.isSafeInteger(olderThanMs) || olderThanMs < 0) throw new Error("Invalid GC grace period");
3570
- const batchSize = options.batchSize ?? 256;
3571
- if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1e5) throw new Error("Invalid GC batch size");
3572
- if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
3573
- const current = await this.storage.get(this.keys.manifestKey);
3574
- const snapshot = {
3575
- manifest: current ? decodeManifest(current.data, this.keys) : emptyManifest(),
3576
- storageVersion: current?.version ?? null
3577
- };
3578
- const reachable = /* @__PURE__ */ new Set();
3579
- const retainedSnapshots = [snapshot, ...this.activeSnapshots()];
3580
- for (const item of retainedSnapshots) {
3581
- const refs = await this.scanner.scan(item);
3582
- for (const ref of refs) reachable.add(ref);
3583
- }
3584
- const objects = await this.storage.list(this.keys.objectPrefix);
3585
- const nodes = await this.storage.list(this.keys.indexNodePrefix);
3586
- const commits = await this.storage.list(this.keys.commitPrefix);
3587
- const reachableCommits = /* @__PURE__ */ new Set();
3588
- for (const retained of retainedSnapshots) {
3589
- let cursor = retained.manifest.commitHead;
3590
- let count = 0;
3591
- while (cursor) {
3592
- if (reachableCommits.has(cursor)) break;
3593
- if (++count > 1e6) throw new Error("Commit history scan limit exceeded during GC");
3594
- reachableCommits.add(cursor);
3595
- cursor = (await readCommitRecord(this.storage, this.keys, cursor)).previous;
3596
- }
3597
- }
3598
- const cutoff = Date.now() - olderThanMs;
3599
- let candidates = 0;
3600
- let deleted = 0;
3601
- let failed = 0;
3602
- const candidatesForScan = [
3603
- ...objects,
3604
- ...nodes,
3605
- ...commits
3606
- ];
3607
- for (let position = 0; position < candidatesForScan.length; position++) {
3608
- if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
3609
- const object = candidatesForScan[position];
3610
- if (object.key.startsWith(this.keys.objectPrefix)) this.keys.validateObjectKey(object.key);
3611
- else if (object.key.startsWith(this.keys.indexNodePrefix)) this.keys.validateIndexNodeKey(object.key);
3612
- else this.keys.validateCommitKey(object.key);
3613
- if (!Number.isSafeInteger(object.createdAt)) throw new Error(`Invalid object timestamp: ${object.key}`);
3614
- if (reachable.has(object.key) || reachableCommits.has(object.key) || object.createdAt > cutoff) continue;
3615
- candidates++;
3616
- if (dryRun) {
3617
- if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
3618
- continue;
3619
- }
3620
- try {
3621
- if ((await this.storage.delete(object.key, { condition: {
3622
- type: "if-version",
3623
- version: object.version
3624
- } })).success) deleted++;
3625
- } catch (error) {
3626
- failed++;
3627
- if (!options.continueOnError) throw error;
3628
- }
3629
- if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
3630
- }
3631
- return {
3632
- scanned: objects.length,
3633
- nodesScanned: nodes.length,
3634
- reachable: reachable.size,
3635
- candidates,
3636
- deleted,
3637
- failed,
3638
- commitsScanned: commits.length,
3639
- durationMs: performance.now() - started,
3640
- dryRun
3641
- };
3642
- }
3643
- };
3644
4528
  // src/indexes/index-consistency-checker.ts
3645
4529
  var decoder = new TextDecoder();
3646
4530
  var IndexConsistencyChecker = class {
@@ -3733,13 +4617,13 @@ function immutableCollection(definition) {
3733
4617
  ...foreignKeys.length == 0 ? {} : { foreignKeys }
3734
4618
  });
3735
4619
  }
3736
- var DuraxisDatabase = class {
4620
+ var DuraxisDatabase = class DuraxisDatabase {
4621
+ resourceLimits;
4622
+ resources;
4623
+ cursorEncryption;
4624
+ accessScope;
3737
4625
  storage;
3738
4626
  keys;
3739
- coordinator;
3740
- recovery;
3741
- primary;
3742
- secondary;
3743
4627
  cursorSigningKey;
3744
4628
  planner = new RuleBasedPlanner();
3745
4629
  planCompiler = new PlanCompiler();
@@ -3755,48 +4639,173 @@ var DuraxisDatabase = class {
3755
4639
  garbageCollectionDurationMs: 0
3756
4640
  };
3757
4641
  active = /* @__PURE__ */ new Set();
4642
+ owners = /* @__PURE__ */ new Map();
4643
+ operations = /* @__PURE__ */ new Set();
4644
+ closePromise;
4645
+ cleanupFailures = [];
4646
+ outcomes = /* @__PURE__ */ new Map();
4647
+ drainWaiters = /* @__PURE__ */ new Set();
3758
4648
  maintenance = false;
3759
4649
  pendingSnapshotAcquisitions = 0;
3760
4650
  closed = false;
3761
4651
  constructor(options) {
4652
+ if (options.storage.capabilities?.boundedReads !== true) throw new Error("Core requires a storage driver with verified bounded-read support; update the driver contract");
4653
+ this.resourceLimits = resourceLimits(options.resources);
4654
+ this.resources = databaseScope(this.resourceLimits);
4655
+ this.accessScope = options.accessScope ? Object.freeze({ ...options.accessScope }) : void 0;
4656
+ 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");
4657
+ this.cursorEncryption = options.cursorEncryption ? {
4658
+ ...options.cursorEncryption,
4659
+ keys: Object.fromEntries(Object.entries(options.cursorEncryption.keys).map(([id, key]) => [id, new Uint8Array(key)]))
4660
+ } : void 0;
3762
4661
  this.storage = options.storage;
3763
4662
  this.keys = new StorageKeyManager(options.namespace);
3764
- this.coordinator = new CommitCoordinator(this.storage, this.keys);
3765
- this.recovery = new RecoveryManager(this.storage, this.keys);
3766
- this.primary = new PrimaryIndex(this.storage, this.keys);
3767
- this.secondary = new SecondaryIndexManager(this.storage, this.keys);
3768
4663
  this.cursorSigningKey = options.cursorSigningKey == null ? randomBytes(32) : new Uint8Array(options.cursorSigningKey);
3769
4664
  if (this.cursorSigningKey.byteLength < 32) throw new Error("Cursor signing key must contain at least 32 bytes");
3770
4665
  }
4666
+ get namespace() {
4667
+ return this.keys.namespace;
4668
+ }
4669
+ static forTenant(options) {
4670
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(options.tenant)) throw new Error("Invalid tenant identifier");
4671
+ return new DuraxisDatabase({
4672
+ ...options,
4673
+ namespace: `tenants/${options.tenant}/v1`,
4674
+ accessScope: {
4675
+ tenant: options.tenant,
4676
+ currentTenant: options.currentTenant
4677
+ }
4678
+ });
4679
+ }
4680
+ assertAccess() {
4681
+ if (this.accessScope && this.accessScope.currentTenant() !== this.accessScope.tenant) throw new Error("Missing or incorrect tenant access scope");
4682
+ }
3771
4683
  async transaction(callback) {
4684
+ this.assertAccess();
3772
4685
  this.metrics.transactionsStarted++;
3773
- const snapshot = await this.acquireSnapshot();
3774
- const tx = new Transaction(this.storage, snapshot, this.keys, this.cursorSigningKey);
4686
+ const snapshot = await this.acquireSnapshot("transaction");
4687
+ const owner = this.owners.get(snapshot);
4688
+ let tx;
4689
+ try {
4690
+ tx = new Transaction(owner.storage, snapshot, this.keys, this.cursorSigningKey, owner.scope, this.resourceLimits, owner.signal, () => owner.protectPublication(), () => this.assertAccess(), {
4691
+ cursorEncryption: this.cursorEncryption,
4692
+ onPendingCleanup: (promise) => owner.holdCleanup(promise),
4693
+ onCleanupFailure: (error) => {
4694
+ if (this.cleanupFailures.length < 16) this.cleanupFailures.push(/* @__PURE__ */ new Error("Deferred query cleanup failed; inspect storage health"));
4695
+ }
4696
+ });
4697
+ } catch (error) {
4698
+ owner.finish();
4699
+ throw error;
4700
+ }
4701
+ const abort = () => tx.close();
4702
+ owner.signal.addEventListener("abort", abort, { once: true });
3775
4703
  try {
3776
- const result = await callback(tx);
4704
+ const result = await owner.wait(Promise.resolve().then(() => callback(tx)));
3777
4705
  const started = performance.now();
3778
4706
  try {
3779
- await this.coordinator.commit(tx);
4707
+ await new CommitCoordinator(owner.storage, this.keys, this.storage).commit(tx);
3780
4708
  } finally {
3781
4709
  this.metrics.commitDurationMs += performance.now() - started;
3782
4710
  }
4711
+ this.rememberOutcome(tx.id, "COMMITTED");
3783
4712
  this.metrics.transactionsCommitted++;
3784
4713
  return result;
3785
4714
  } catch (error) {
3786
4715
  if (error instanceof TransactionConflictError) this.metrics.transactionConflicts++;
3787
4716
  if (error instanceof CommitOutcomeUnknownError) this.metrics.commitOutcomesUnknown++;
4717
+ if (!(error instanceof CommitOutcomeUnknownError)) this.rememberOutcome(tx.id, "NOT_COMMITTED");
3788
4718
  tx.abort();
3789
4719
  throw error;
3790
4720
  } finally {
4721
+ owner.signal.removeEventListener("abort", abort);
3791
4722
  this.releaseSnapshot(snapshot, tx);
3792
4723
  }
3793
4724
  }
4725
+ rememberOutcome(id, status) {
4726
+ if (this.outcomes.size >= 1024) this.outcomes.delete(this.outcomes.keys().next().value);
4727
+ this.outcomes.set(id, {
4728
+ status,
4729
+ expires: Date.now() + 864e5
4730
+ });
4731
+ }
4732
+ async resolveCommitOutcome(id) {
4733
+ this.assertAccess();
4734
+ const retained = this.outcomes.get(id);
4735
+ if (retained && retained.expires > Date.now()) return retained.status;
4736
+ if (await this.transaction(async (tx) => {
4737
+ const bytes = await tx.getMetadata("idempotency");
4738
+ if (!bytes) return false;
4739
+ const entries = JSON.parse(new TextDecoder().decode(bytes));
4740
+ return Object.values(entries).some((entry) => entry.id == id && entry.expires > Date.now());
4741
+ })) return "COMMITTED";
4742
+ return await this.getCommitStatus(id) == "committed" ? "COMMITTED" : "UNKNOWN";
4743
+ }
4744
+ async transactionOnce(operationId, callback) {
4745
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(operationId)) throw new Error("Invalid idempotency identifier");
4746
+ try {
4747
+ return await this.transaction(async (tx) => {
4748
+ const bytes = await tx.getMetadata("idempotency");
4749
+ const ledger = bytes ? JSON.parse(new TextDecoder().decode(bytes)) : {};
4750
+ const existing = Object.hasOwn(ledger, operationId) ? ledger[operationId] : void 0;
4751
+ if (existing && existing.expires > Date.now()) return {
4752
+ applied: false,
4753
+ transactionId: existing.id
4754
+ };
4755
+ const live = Object.fromEntries(Object.entries(ledger).filter(([, entry]) => entry.expires > Date.now()));
4756
+ if (Object.keys(live).length >= 1024) throw new Error("Idempotency retention capacity exceeded; wait for expiration or use a separate namespace");
4757
+ const result = await callback(tx);
4758
+ Object.defineProperty(live, operationId, {
4759
+ value: {
4760
+ id: tx.id,
4761
+ expires: Date.now() + 864e5
4762
+ },
4763
+ enumerable: true
4764
+ });
4765
+ tx.putMetadata("idempotency", new TextEncoder().encode(JSON.stringify(live)));
4766
+ return {
4767
+ applied: true,
4768
+ transactionId: tx.id,
4769
+ result
4770
+ };
4771
+ });
4772
+ } catch (error) {
4773
+ if (!(error instanceof TransactionConflictError) && !(error instanceof CommitOutcomeUnknownError)) throw error;
4774
+ const receipt = await this.transaction(async (tx) => {
4775
+ const bytes = await tx.getMetadata("idempotency");
4776
+ if (!bytes) return void 0;
4777
+ const ledger = JSON.parse(new TextDecoder().decode(bytes));
4778
+ return Object.hasOwn(ledger, operationId) && ledger[operationId].expires > Date.now() ? ledger[operationId] : void 0;
4779
+ });
4780
+ if (receipt) return {
4781
+ applied: false,
4782
+ transactionId: receipt.id
4783
+ };
4784
+ throw error;
4785
+ }
4786
+ }
3794
4787
  async snapshot(callback) {
3795
4788
  const snapshot = await this.acquireSnapshot();
3796
- const tx = new Transaction(this.storage, snapshot, this.keys, this.cursorSigningKey);
4789
+ const owner = this.owners.get(snapshot);
4790
+ let tx;
4791
+ try {
4792
+ tx = new Transaction(owner.storage, snapshot, this.keys, this.cursorSigningKey, owner.scope, this.resourceLimits, owner.signal, () => owner.protectPublication(), () => this.assertAccess(), {
4793
+ cursorEncryption: this.cursorEncryption,
4794
+ onPendingCleanup: (promise) => owner.holdCleanup(promise),
4795
+ onCleanupFailure: (error) => {
4796
+ if (this.cleanupFailures.length < 16) this.cleanupFailures.push(/* @__PURE__ */ new Error("Deferred query cleanup failed; inspect storage health"));
4797
+ }
4798
+ });
4799
+ } catch (error) {
4800
+ owner.finish();
4801
+ throw error;
4802
+ }
4803
+ const abort = () => tx.close();
4804
+ owner.signal.addEventListener("abort", abort, { once: true });
3797
4805
  try {
3798
- return await callback({ get: (key) => tx.get(key) });
4806
+ return await owner.wait(Promise.resolve().then(() => callback({ get: (key) => tx.get(key) })));
3799
4807
  } finally {
4808
+ owner.signal.removeEventListener("abort", abort);
3800
4809
  this.releaseSnapshot(snapshot, tx);
3801
4810
  }
3802
4811
  }
@@ -3813,7 +4822,7 @@ var DuraxisDatabase = class {
3813
4822
  try {
3814
4823
  return Object.freeze([...snapshot.manifest.catalog.values()].map((definition) => immutableCollection(definition)).sort((left, right) => left.name.localeCompare(right.name)));
3815
4824
  } finally {
3816
- this.active.delete(snapshot);
4825
+ this.finishSnapshot(snapshot);
3817
4826
  }
3818
4827
  }
3819
4828
  async addIndex(collection, index) {
@@ -3826,65 +4835,79 @@ var DuraxisDatabase = class {
3826
4835
  }
3827
4836
  query(query, sourceOrOptions, explicitOptions) {
3828
4837
  const database = this;
3829
- return (async function* () {
4838
+ const iterator = (async function* () {
3830
4839
  const started = performance.now();
3831
4840
  database.metrics.queries++;
3832
- const snapshot = await database.acquireSnapshot();
3833
- const context = new QueryContext(database.storage, snapshot, database.keys);
4841
+ const snapshot = await database.acquireSnapshot("query");
4842
+ const context = database.queryContext(snapshot);
4843
+ context.bindCancellation(() => iterator.return(void 0));
3834
4844
  let unbindSignal = () => {};
3835
4845
  try {
3836
4846
  const explicit = database.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3837
4847
  const options = explicit ? explicitOptions : sourceOrOptions;
3838
4848
  unbindSignal = database.bindSignal(context, options?.signal);
3839
- const source = explicit ?? database.planCompiler.compile(database.planner.plan(query, context.catalog), context.catalog);
4849
+ const source = explicit ?? database.planCompiler.compile(database.planner.plan(query, context.catalog, context.limits), context.catalog);
3840
4850
  yield* new QueryExecutor(database.queryOptions(options)).execute(context, query, source);
3841
4851
  } finally {
3842
4852
  unbindSignal();
3843
4853
  database.metrics.queryDurationMs += performance.now() - started;
3844
4854
  context.close();
3845
- database.active.delete(snapshot);
4855
+ database.finishSnapshot(snapshot);
3846
4856
  }
3847
4857
  })();
4858
+ return iterator;
3848
4859
  }
3849
4860
  async queryPage(query, sourceOrOptions, explicitOptions) {
3850
4861
  const started = performance.now();
3851
4862
  this.metrics.queries++;
3852
4863
  const snapshot = await this.acquireSnapshot();
3853
- const context = new QueryContext(this.storage, snapshot, this.keys);
4864
+ const context = this.queryContext(snapshot);
3854
4865
  let unbindSignal = () => {};
3855
4866
  try {
3856
4867
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3857
4868
  const options = explicit ? explicitOptions : sourceOrOptions;
3858
4869
  unbindSignal = this.bindSignal(context, options?.signal);
3859
- const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog), context.catalog);
4870
+ const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog, context.limits), context.catalog);
3860
4871
  return await new QueryExecutor(this.queryOptions(options)).page(context, query, source);
3861
4872
  } finally {
3862
4873
  unbindSignal();
3863
4874
  this.metrics.queryDurationMs += performance.now() - started;
3864
4875
  context.close();
3865
- this.active.delete(snapshot);
4876
+ this.finishSnapshot(snapshot);
3866
4877
  }
3867
4878
  }
3868
4879
  async queryAll(query, options) {
3869
4880
  const rows = [];
3870
- for await (const row of this.query(query, options)) rows.push(row);
3871
- return rows;
4881
+ const results = materialize(this.resources, this.resourceLimits);
4882
+ try {
4883
+ for await (const row of this.query(query, options)) {
4884
+ results.add(row);
4885
+ rows.push(row);
4886
+ }
4887
+ return rows;
4888
+ } finally {
4889
+ results.close();
4890
+ }
4891
+ }
4892
+ createMaterializationBudget() {
4893
+ return materialize(this.resources, this.resourceLimits);
3872
4894
  }
3873
4895
  async explain(query) {
3874
4896
  const snapshot = await this.acquireSnapshot();
3875
4897
  try {
3876
- return explainPhysicalPlan(this.planner.plan(query, snapshot.manifest.catalog));
4898
+ return explainPhysicalPlan(this.planner.plan(query, snapshot.manifest.catalog, this.resourceLimits));
3877
4899
  } finally {
3878
- this.active.delete(snapshot);
4900
+ this.finishSnapshot(snapshot);
3879
4901
  }
3880
4902
  }
3881
4903
  executePlan(query, plan, options) {
3882
4904
  if (plan.collection != query.collection) throw new Error("Plan and query collections differ");
3883
4905
  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");
3884
4906
  const database = this;
3885
- return (async function* () {
3886
- const snapshot = await database.acquireSnapshot();
3887
- const context = new QueryContext(database.storage, snapshot, database.keys);
4907
+ const iterator = (async function* () {
4908
+ const snapshot = await database.acquireSnapshot("query");
4909
+ const context = database.queryContext(snapshot);
4910
+ context.bindCancellation(() => iterator.return(void 0));
3888
4911
  const unbindSignal = database.bindSignal(context, options?.signal);
3889
4912
  try {
3890
4913
  const source = database.planCompiler.compile(plan, context.catalog);
@@ -3892,67 +4915,74 @@ var DuraxisDatabase = class {
3892
4915
  } finally {
3893
4916
  unbindSignal();
3894
4917
  context.close();
3895
- database.active.delete(snapshot);
4918
+ database.finishSnapshot(snapshot);
3896
4919
  }
3897
4920
  })();
4921
+ return iterator;
3898
4922
  }
3899
4923
  async getDocument(collection, id) {
3900
4924
  return this.transaction((tx) => tx.getDocument(collection, id));
3901
4925
  }
3902
4926
  async findByIndex(collection, indexName, value, limit = 100) {
3903
4927
  const snapshot = await this.acquireSnapshot();
4928
+ const context = this.queryContext(snapshot);
4929
+ const memory = this.createMaterializationBudget();
4930
+ const rows = [];
3904
4931
  try {
3905
- const ids = await this.secondary.lookupIds(snapshot.manifest, collection, indexName, value, limit);
3906
- const rows = [];
3907
- for (const id of ids) {
3908
- const bytes = await this.primary.read(snapshot.manifest, recordKey(collection, id));
3909
- if (bytes == null) throw new Error(`Index references missing record: ${collection}/${id}`);
3910
- rows.push({
3911
- id,
3912
- document: decodeDocument(bytes)
3913
- });
4932
+ for await (const row of context.scanIndex(collection, indexName, {
4933
+ eq: value,
4934
+ limit
4935
+ })) {
4936
+ memory.add(row);
4937
+ rows.push(row);
3914
4938
  }
3915
4939
  return rows;
3916
4940
  } finally {
3917
- this.active.delete(snapshot);
4941
+ memory.close();
4942
+ context.close();
4943
+ this.finishSnapshot(snapshot);
3918
4944
  }
3919
4945
  }
3920
4946
  async scanCollection(collection, limit = 100) {
3921
- if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid scan limit");
3922
4947
  const snapshot = await this.acquireSnapshot();
4948
+ const context = this.queryContext(snapshot);
4949
+ const memory = this.createMaterializationBudget();
4950
+ const rows = [];
3923
4951
  try {
3924
- if (!snapshot.manifest.catalog.has(collection)) throw new Error(`Unknown collection: ${collection}`);
3925
- const rows = [];
3926
- if (limit == 0) return rows;
3927
- const prefix = new TextEncoder().encode(`${RECORD_PREFIX}${collection}/`);
3928
- const end = prefixSuccessor(prefix);
3929
- for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot, {
3930
- gte: prefix,
3931
- ...end == null ? {} : { lt: end }
3932
- })) {
3933
- const parsed = parseRecordKey(entry.key);
3934
- if (!parsed || parsed.collection != collection) continue;
3935
- rows.push({
3936
- id: parsed.id,
3937
- document: decodeDocument(await this.primary.readObject(entry.ref))
3938
- });
3939
- if (rows.length >= limit) break;
4952
+ for await (const row of context.scanCollection(collection, { limit })) {
4953
+ memory.add(row);
4954
+ rows.push(row);
3940
4955
  }
3941
4956
  return rows;
3942
4957
  } finally {
3943
- this.active.delete(snapshot);
4958
+ memory.close();
4959
+ context.close();
4960
+ this.finishSnapshot(snapshot);
3944
4961
  }
3945
4962
  }
3946
4963
  async getCommitStatus(transactionId) {
3947
- return this.recovery.getCommitStatus(transactionId);
4964
+ const snapshot = await this.acquireSnapshot();
4965
+ try {
4966
+ return await new RecoveryManager(this.owners.get(snapshot).storage, this.keys).getCommitStatus(transactionId);
4967
+ } finally {
4968
+ this.finishSnapshot(snapshot);
4969
+ }
3948
4970
  }
3949
4971
  async verifyHistory() {
3950
- return this.recovery.verifyHistory();
4972
+ const snapshot = await this.acquireSnapshot();
4973
+ try {
4974
+ return await new RecoveryManager(this.owners.get(snapshot).storage, this.keys).verifyHistory();
4975
+ } finally {
4976
+ this.finishSnapshot(snapshot);
4977
+ }
3951
4978
  }
3952
- /** Starts a new verifiable commit-history chain without changing data roots. */
3953
4979
  async checkpointHistory() {
4980
+ this.assertAccess();
3954
4981
  if (this.closed) throw new Error("Database is closed");
3955
4982
  if (this.maintenance || this.active.size || this.pendingSnapshotAcquisitions) throw new Error("History checkpoint requires exclusive database maintenance");
4983
+ const shared = storageCoordination(this.storage);
4984
+ if (shared.maintenance || shared.active) throw new Error("History checkpoint requires exclusive database maintenance");
4985
+ shared.maintenance = true;
3956
4986
  this.maintenance = true;
3957
4987
  const transactionId = randomUUID();
3958
4988
  try {
@@ -3982,26 +5012,29 @@ var DuraxisDatabase = class {
3982
5012
  return transactionId;
3983
5013
  } finally {
3984
5014
  this.maintenance = false;
5015
+ shared.maintenance = false;
3985
5016
  }
3986
5017
  }
3987
5018
  async verifyIntegrity() {
3988
5019
  const snapshot = await this.acquireSnapshot();
5020
+ const storage = this.owners.get(snapshot).storage;
5021
+ const primary = new PrimaryIndex(storage, this.keys);
3989
5022
  try {
3990
- const scanner = new ManifestReachabilityScanner(this.keys, this.storage);
3991
- const nodes = new BPlusTreeNodeStore(this.storage, this.keys);
5023
+ const scanner = new ManifestReachabilityScanner(this.keys, storage);
5024
+ const nodes = new BPlusTreeNodeStore(storage, this.keys);
3992
5025
  const reachable = await scanner.scan(snapshot);
3993
5026
  let objectsCount = 0;
3994
5027
  let nodesCount = 0;
3995
5028
  for (const ref of reachable) if (ref.startsWith(this.keys.objectPrefix)) {
3996
- await this.primary.readObject(ref);
5029
+ await primary.readObject(ref);
3997
5030
  objectsCount++;
3998
5031
  } else {
3999
5032
  this.keys.validateIndexNodeKey(ref);
4000
5033
  await nodes.read(ref);
4001
5034
  nodesCount++;
4002
5035
  }
4003
- const indexes = await new IndexConsistencyChecker(this.storage, this.keys).verify(snapshot.manifest);
4004
- const commits = await this.recovery.verifyHistory();
5036
+ const indexes = await new IndexConsistencyChecker(storage, this.keys).verify(snapshot.manifest);
5037
+ const commits = await new RecoveryManager(storage, this.keys).verifyHistory();
4005
5038
  return {
4006
5039
  objects: objectsCount,
4007
5040
  nodes: nodesCount,
@@ -4009,10 +5042,11 @@ var DuraxisDatabase = class {
4009
5042
  commits
4010
5043
  };
4011
5044
  } finally {
4012
- this.active.delete(snapshot);
5045
+ this.finishSnapshot(snapshot);
4013
5046
  }
4014
5047
  }
4015
5048
  async collectGarbage(storage, options = {}) {
5049
+ this.assertAccess();
4016
5050
  const started = performance.now();
4017
5051
  this.metrics.garbageCollections++;
4018
5052
  if (storage != this.storage) throw new Error("GC driver must match database storage");
@@ -4020,47 +5054,107 @@ var DuraxisDatabase = class {
4020
5054
  this.maintenance = true;
4021
5055
  try {
4022
5056
  if (options.dryRun == false && (this.active.size > 0 || this.pendingSnapshotAcquisitions > 0)) throw new Error("Active transactions or pending snapshots prevent GC");
4023
- return await new GarbageCollector(this.storage, this.keys, () => [...this.active]).collect(options);
5057
+ return await new GarbageCollector(this.storage, this.keys, () => [...this.active], new ManifestReachabilityScanner(this.keys, this.storage), this.resources).collect(options);
4024
5058
  } finally {
4025
5059
  this.metrics.garbageCollectionDurationMs += performance.now() - started;
4026
5060
  this.maintenance = false;
4027
5061
  }
4028
5062
  }
5063
+ finishSnapshot(snapshot) {
5064
+ this.owners.get(snapshot)?.finish();
5065
+ }
5066
+ queryContext(snapshot) {
5067
+ const owner = this.owners.get(snapshot);
5068
+ let context;
5069
+ const abort = () => context.cancel(owner.signal.reason);
5070
+ try {
5071
+ context = new QueryContext(owner.storage, snapshot, this.keys, {
5072
+ resources: owner.scope,
5073
+ limits: this.resourceLimits,
5074
+ assertAccess: () => this.assertAccess(),
5075
+ onPendingCleanup: (promise) => owner.holdCleanup(promise),
5076
+ onCleanupFailure: (error) => {
5077
+ if (this.cleanupFailures.length < 16) this.cleanupFailures.push(/* @__PURE__ */ new Error("Deferred query cleanup failed; inspect storage health"));
5078
+ },
5079
+ onClose: () => {
5080
+ owner.signal.removeEventListener("abort", abort);
5081
+ owner.finish();
5082
+ }
5083
+ });
5084
+ } catch (error) {
5085
+ owner.finish();
5086
+ throw error;
5087
+ }
5088
+ owner.signal.addEventListener("abort", abort, { once: true });
5089
+ if (owner.signal.aborted) abort();
5090
+ return context;
5091
+ }
4029
5092
  releaseSnapshot(snapshot, tx) {
4030
5093
  tx.close();
4031
- if (!tx.hasPendingReads) {
4032
- this.active.delete(snapshot);
4033
- return;
4034
- }
4035
- tx.waitForReads().then(() => {
4036
- this.active.delete(snapshot);
4037
- });
5094
+ this.finishSnapshot(snapshot);
4038
5095
  }
4039
5096
  queryOptions(options) {
4040
5097
  return {
4041
5098
  ...options,
4042
- cursorSigningKey: options?.cursorSigningKey ?? this.cursorSigningKey
5099
+ cursorSigningKey: this.cursorSigningKey,
5100
+ cursorEncryption: this.cursorEncryption,
5101
+ cursorNamespace: this.keys.namespace
4043
5102
  };
4044
5103
  }
4045
5104
  bindSignal(context, signal) {
4046
5105
  if (!signal) return () => {};
4047
5106
  const cancel = () => context.cancel(signal.reason ?? /* @__PURE__ */ new Error("Query cancelled"));
4048
- if (signal.aborted) cancel();
5107
+ if (signal.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
4049
5108
  else signal.addEventListener("abort", cancel, { once: true });
4050
5109
  return () => signal.removeEventListener("abort", cancel);
4051
5110
  }
4052
5111
  isOperator(value) {
4053
5112
  return value != null && typeof value.execute == "function";
4054
5113
  }
4055
- async acquireSnapshot() {
5114
+ async acquireSnapshot(kind = "snapshot") {
5115
+ this.assertAccess();
4056
5116
  if (this.closed) throw new Error("Database is closed");
4057
- if (this.maintenance) throw new Error("Database is in exclusive maintenance mode");
5117
+ if (this.maintenance || storageCoordination(this.storage).maintenance) throw new Error("Database is in exclusive maintenance mode");
5118
+ const scope = this.resources.child({ workingBytes: kind == "query" ? this.resourceLimits.maxQueryWorkingBytes : this.resourceLimits.maxTransactionWorkingBytes });
5119
+ try {
5120
+ scope.reserve({ snapshots: 1 });
5121
+ } catch (error) {
5122
+ scope.close();
5123
+ throw error;
5124
+ }
5125
+ const shared = storageCoordination(this.storage);
5126
+ shared.active++;
5127
+ let snapshot;
5128
+ 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), () => {
5129
+ if (snapshot) {
5130
+ this.active.delete(snapshot);
5131
+ this.owners.delete(snapshot);
5132
+ shared.snapshots.delete(snapshot);
5133
+ }
5134
+ shared.active--;
5135
+ this.operations.delete(owner);
5136
+ if (!this.operations.size) for (const resolve of [...this.drainWaiters]) resolve();
5137
+ }, this.resourceLimits.maxStorageReadBytes);
5138
+ this.operations.add(owner);
4058
5139
  this.pendingSnapshotAcquisitions++;
4059
5140
  try {
4060
- const snapshot = await this.createSnapshot();
4061
- if (this.maintenance) throw new Error("Database is in exclusive maintenance mode");
5141
+ const stored = await owner.wait(owner.storage.get(this.keys.manifestKey));
5142
+ if (this.maintenance || this.closed) throw new Error("Database is not accepting snapshots");
5143
+ snapshot = stored == null ? {
5144
+ manifest: emptyManifest(),
5145
+ storageVersion: null
5146
+ } : {
5147
+ manifest: decodeManifest(stored.data, this.keys),
5148
+ storageVersion: stored.version
5149
+ };
5150
+ scope.reserve({ workingBytes: estimateBytes([...snapshot.manifest.catalog]) + estimateBytes([...snapshot.manifest.indexRoots]) });
4062
5151
  this.active.add(snapshot);
5152
+ shared.snapshots.add(snapshot);
5153
+ this.owners.set(snapshot, owner);
4063
5154
  return snapshot;
5155
+ } catch (error) {
5156
+ owner.finish();
5157
+ throw error;
4064
5158
  } finally {
4065
5159
  this.pendingSnapshotAcquisitions--;
4066
5160
  }
@@ -4068,14 +5162,37 @@ var DuraxisDatabase = class {
4068
5162
  getMetrics() {
4069
5163
  return {
4070
5164
  ...this.metrics,
5165
+ resources: this.resources.metrics(),
4071
5166
  ...this.storage.getMetrics ? { storage: this.storage.getMetrics() } : {}
4072
5167
  };
4073
5168
  }
4074
- async close(options = {}) {
4075
- if (this.closed) return;
4076
- if (this.active.size || this.pendingSnapshotAcquisitions) throw new Error("Cannot close database with active transactions or queries");
5169
+ close(options = {}) {
5170
+ if (this.closePromise) return this.closePromise;
4077
5171
  this.closed = true;
4078
- if (options.closeStorage) await this.storage.close?.();
5172
+ const timeout = options.timeoutMs ?? 3e4;
5173
+ if (!Number.isSafeInteger(timeout) || timeout < 1) return Promise.reject(/* @__PURE__ */ new RangeError("Invalid shutdown deadline"));
5174
+ this.closePromise = (async () => {
5175
+ for (const owner of this.operations) owner.cancel(new OperationCancelledError("Database is shutting down"));
5176
+ if (this.operations.size) await new Promise((resolve, reject) => {
5177
+ const complete = () => {
5178
+ clearTimeout(timer);
5179
+ this.drainWaiters.delete(complete);
5180
+ resolve();
5181
+ };
5182
+ const timer = setTimeout(() => {
5183
+ this.drainWaiters.delete(complete);
5184
+ reject(new OperationCancelledError(`Shutdown deadline exceeded; ${this.operations.size} operations still protect storage. Storage was not closed`));
5185
+ }, timeout);
5186
+ this.drainWaiters.add(complete);
5187
+ if (!this.operations.size) complete();
5188
+ });
5189
+ if (options.closeStorage) await this.storage.close?.();
5190
+ if (this.cleanupFailures.length) throw new AggregateError(this.cleanupFailures.splice(0), "Deferred query cleanup failed");
5191
+ })();
5192
+ this.closePromise.catch(() => {
5193
+ this.closePromise = void 0;
5194
+ });
5195
+ return this.closePromise;
4079
5196
  }
4080
5197
  async createSnapshot() {
4081
5198
  const stored = await this.storage.get(this.keys.manifestKey);
@@ -4101,6 +5218,6 @@ var ReferenceQueryExecutor = class {
4101
5218
  return this.executor.page(context, query, new CollectionScan(query.collection));
4102
5219
  }
4103
5220
  };
4104
- export { AccessPathEnumerator, BPlusTree, BPlusTreeNodeCache, BPlusTreeNodeStore, BPlusTreeValidator, CollectionScan, CommitOutcomeUnknownError, Difference, DuraxisDatabase, Filter, ForeignKeyManager, ForeignKeyViolationError, GarbageCollector, Intersection, InvalidForeignKeyDefinitionError, Limit, ManifestReachabilityScanner, ManifestSnapshotReader, PlanCompiler, PredicateAnalyzer, PrimaryIndex, PrimaryLookup, Projection, QueryContext, QueryExecutor, QueryMemoryLimitError, RecoveryManager, ReferenceQueryExecutor, ReferencedRecordNotFoundError, ReferencedRecordRestrictedError, RuleBasedPlanner, SecondaryIndexManager, SecondaryIndexRangeScan, SecondaryIndexScan, Sort, Transaction, TransactionConflictError, TransactionStateError, Union, UniqueIndexLookup, UniqueIndexViolationError, compareBytes, compareIndexScalars, compareRows, compositePrefixBounds, decodeDocument, decodeQueryCursor, encodeCompositeKey, encodeDocument, encodeIdentifier, encodeQueryCursor, encodeScalar, encodeSecondaryKey, evaluatePredicate, explainPhysicalPlan, fieldDefinition, indexFields, indexId, indexRangeBounds, indexedValue, normalizeCollection, parseRecordKey, prefixBounds, prefixSuccessor, recordKey, secondaryIndexBounds, validateCollection, validateDocument, validateQuery };
5221
+ export { AccessPathEnumerator, BPlusTree, BPlusTreeNodeCache, BPlusTreeNodeStore, BPlusTreeValidator, CollectionScan, CommitOutcomeUnknownError, DEFAULT_RESOURCE_LIMITS, Difference, DuraxisDatabase, Filter, ForeignKeyManager, ForeignKeyViolationError, GarbageCollector, Intersection, InvalidForeignKeyDefinitionError, Limit, ManifestReachabilityScanner, ManifestSnapshotReader, OperationCancelledError, PlanCompiler, PredicateAnalyzer, PrimaryIndex, PrimaryLookup, Projection, QueryContext, QueryExecutor, QueryMemoryLimitError, RecoveryManager, ReferenceQueryExecutor, ReferencedRecordNotFoundError, ReferencedRecordRestrictedError, ResourceExhaustedError, ResourceScope, RuleBasedPlanner, SecondaryIndexManager, SecondaryIndexRangeScan, SecondaryIndexScan, Sort, Transaction, TransactionConflictError, TransactionStateError, Union, UniqueIndexLookup, UniqueIndexViolationError, compareBytes, compareIndexScalars, compareRows, compositePrefixBounds, decodeDocument, decodeQueryCursor, encodeCompositeKey, encodeDocument, encodeIdentifier, encodeQueryCursor, encodeScalar, encodeSecondaryKey, estimateBytes, evaluatePredicate, explainPhysicalPlan, fieldDefinition, indexFields, indexId, indexRangeBounds, indexedValue, materialize, normalizeCollection, parseRecordKey, prefixBounds, prefixSuccessor, recordKey, resourceLimits, secondaryIndexBounds, validateCollection, validateDocument, validateQuery };
4105
5222
 
4106
5223
  //# sourceMappingURL=index.js.map