@duraxis/core 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,6 +1,348 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let node_crypto = require("node:crypto");
3
3
  let _duraxis_storage = require("@duraxis/storage");
4
+ let node_fs = require("node:fs");
5
+ let node_path = require("node:path");
6
+ let node_url = require("node:url");
7
+ // src/resources/resource-manager.ts
8
+ var DEFAULT_RESOURCE_LIMITS = Object.freeze({
9
+ maxQueuedOperations: 64,
10
+ maxConcurrentTransactions: 64,
11
+ maxConcurrentQueries: 64,
12
+ maxOpenSnapshots: 128,
13
+ maxOpenIterators: 256,
14
+ maxPendingOperations: 256,
15
+ maxPendingWrites: 1e5,
16
+ maxPendingWriteBytes: 67108864,
17
+ maxResultRows: 1e4,
18
+ maxResultBytes: 16777216,
19
+ maxQueryWorkingBytes: 33554432,
20
+ maxTransactionWorkingBytes: 134217728,
21
+ maxDatabaseWorkingBytes: 536870912,
22
+ maxDocumentBytes: 1048576,
23
+ maxStorageReadBytes: 4194304,
24
+ maxDocumentDepth: 64,
25
+ maxPredicateDepth: 32,
26
+ maxPredicateNodes: 4096,
27
+ maxTransactionDurationMs: 6e4,
28
+ maxQueryDurationMs: 3e4,
29
+ maxSnapshotLifetimeMs: 6e4,
30
+ maxSpillBytes: 268435456
31
+ });
32
+ var ResourceExhaustedError = class extends Error {
33
+ resource;
34
+ limit;
35
+ constructor(resource, limit) {
36
+ super(`Duraxis resource limit exceeded: ${resource} (limit ${limit}); reduce the workload or explicitly configure a larger budget`);
37
+ this.resource = resource;
38
+ this.limit = limit;
39
+ this.name = "ResourceExhaustedError";
40
+ }
41
+ };
42
+ var OperationCancelledError = class extends Error {
43
+ constructor(message = "Duraxis operation cancelled or deadline exceeded") {
44
+ super(message);
45
+ this.name = "OperationCancelledError";
46
+ }
47
+ };
48
+ function resourceLimits(options = {}) {
49
+ const result = {
50
+ ...DEFAULT_RESOURCE_LIMITS,
51
+ ...options
52
+ };
53
+ for (const [name, value] of Object.entries(result)) if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`Invalid resource limit: ${name}`);
54
+ return Object.freeze(result);
55
+ }
56
+ var ResourceScope = class ResourceScope {
57
+ limits;
58
+ parent;
59
+ usage = {};
60
+ high = {};
61
+ children = /* @__PURE__ */ new Set();
62
+ closed = false;
63
+ constructor(limits, parent) {
64
+ this.limits = limits;
65
+ this.parent = parent;
66
+ parent?.children.add(this);
67
+ }
68
+ child(limits) {
69
+ this.assertOpen();
70
+ return new ResourceScope(limits, this);
71
+ }
72
+ assertOpen() {
73
+ if (this.closed) throw new OperationCancelledError("Resource scope is closed");
74
+ }
75
+ change(delta) {
76
+ const chain = [];
77
+ for (let scope = this; scope; scope = scope.parent) {
78
+ scope.assertOpen();
79
+ chain.push(scope);
80
+ for (const [key, value] of Object.entries(delta)) {
81
+ const next = (scope.usage[key] ?? 0) + value;
82
+ if (next < 0) throw new Error("Resource accounting underflow");
83
+ if (next > (scope.limits[key] ?? Number.MAX_SAFE_INTEGER)) throw new ResourceExhaustedError(key, scope.limits[key]);
84
+ }
85
+ }
86
+ for (const scope of chain) for (const [key, value] of Object.entries(delta)) {
87
+ scope.usage[key] = (scope.usage[key] ?? 0) + value;
88
+ scope.high[key] = Math.max(scope.high[key] ?? 0, scope.usage[key]);
89
+ }
90
+ }
91
+ reserve(initial) {
92
+ let held = {};
93
+ let released = false;
94
+ const resize = (amounts) => {
95
+ if (released || this.closed) throw new OperationCancelledError("Reservation is closed");
96
+ const delta = {};
97
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(held), ...Object.keys(amounts)])) {
98
+ const amount = amounts[key] ?? 0;
99
+ if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError("Invalid resource reservation");
100
+ delta[key] = amount - (held[key] ?? 0);
101
+ }
102
+ this.change(delta);
103
+ held = { ...amounts };
104
+ };
105
+ resize(initial);
106
+ return {
107
+ resize,
108
+ release: () => {
109
+ if (released) return;
110
+ released = true;
111
+ if (!this.closed) this.change(Object.fromEntries(Object.entries(held).map(([key, value]) => [key, -value])));
112
+ held = {};
113
+ }
114
+ };
115
+ }
116
+ metrics() {
117
+ return {
118
+ current: { ...this.usage },
119
+ highWater: { ...this.high }
120
+ };
121
+ }
122
+ close() {
123
+ if (this.closed) return;
124
+ for (const child of [...this.children]) child.close();
125
+ this.change(Object.fromEntries(Object.entries(this.usage).map(([key, value]) => [key, -value])));
126
+ this.closed = true;
127
+ this.parent?.children.delete(this);
128
+ }
129
+ };
130
+ function databaseScope(limits) {
131
+ return new ResourceScope({
132
+ workingBytes: limits.maxDatabaseWorkingBytes,
133
+ transactions: limits.maxConcurrentTransactions,
134
+ queries: limits.maxConcurrentQueries,
135
+ snapshots: limits.maxOpenSnapshots,
136
+ iterators: limits.maxOpenIterators,
137
+ pendingOperations: limits.maxPendingOperations,
138
+ queuedOperations: limits.maxQueuedOperations
139
+ });
140
+ }
141
+ function estimateBytes(value, maximum = 134217728, maxDepth = 64) {
142
+ let bytes = 0;
143
+ const ancestors = /* @__PURE__ */ new Set();
144
+ const visit = (item, depth) => {
145
+ if (depth > maxDepth) throw new ResourceExhaustedError("documentDepth", maxDepth);
146
+ if (typeof item == "string") bytes += item.length * 2 + 24;
147
+ else if (item == null || typeof item != "object") bytes += 16;
148
+ else if (item instanceof Uint8Array) bytes += item.byteLength + 64;
149
+ else if (item instanceof Date) bytes += 32;
150
+ else {
151
+ if (ancestors.has(item)) throw new TypeError("Cyclic values are not supported");
152
+ ancestors.add(item);
153
+ bytes += 64;
154
+ for (const key in item) if (Object.hasOwn(item, key)) {
155
+ if (key == "__proto__") throw new TypeError("Unsafe object property");
156
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
157
+ if (!("value" in descriptor)) throw new TypeError("Accessor properties are not supported");
158
+ bytes += key.length * 2 + 32;
159
+ visit(descriptor.value, depth + 1);
160
+ if (bytes > maximum) throw new ResourceExhaustedError("workingBytes", maximum);
161
+ }
162
+ ancestors.delete(item);
163
+ }
164
+ if (bytes > maximum) throw new ResourceExhaustedError("workingBytes", maximum);
165
+ };
166
+ visit(value, 0);
167
+ return bytes;
168
+ }
169
+ function materialize(scope, limits) {
170
+ const reservation = scope.reserve({});
171
+ let rows = 0;
172
+ let bytes = 0;
173
+ let working = 0;
174
+ return {
175
+ add(value) {
176
+ if (rows + 1 > limits.maxResultRows) throw new ResourceExhaustedError("resultRows", limits.maxResultRows);
177
+ const size = estimateBytes(value, limits.maxQueryWorkingBytes, limits.maxDocumentDepth + 4);
178
+ reservation.resize({ workingBytes: working + size * 8 });
179
+ let encoded;
180
+ try {
181
+ encoded = JSON.stringify(value);
182
+ } finally {
183
+ reservation.resize({ workingBytes: working + size });
184
+ }
185
+ if (encoded === void 0) throw new TypeError("Result is not JSON serializable");
186
+ const next = bytes + Buffer.byteLength(encoded);
187
+ if (next > limits.maxResultBytes) throw new ResourceExhaustedError("resultBytes", limits.maxResultBytes);
188
+ working += size;
189
+ bytes = next;
190
+ rows++;
191
+ },
192
+ close: () => reservation.release()
193
+ };
194
+ }
195
+ // src/gc/storage-coordination.ts
196
+ var states = /* @__PURE__ */ new WeakMap();
197
+ function storageCoordination(storage) {
198
+ let state = states.get(storage);
199
+ if (!state) {
200
+ state = {
201
+ active: 0,
202
+ maintenance: false,
203
+ snapshots: /* @__PURE__ */ new Set()
204
+ };
205
+ states.set(storage, state);
206
+ }
207
+ return state;
208
+ }
209
+ var commits = /* @__PURE__ */ new WeakMap();
210
+ async function coordinateCommit(storage, maximum, action) {
211
+ let state = commits.get(storage);
212
+ if (!state) {
213
+ state = {
214
+ tail: Promise.resolve(),
215
+ queued: 0
216
+ };
217
+ commits.set(storage, state);
218
+ }
219
+ if (state.queued >= maximum) throw new ResourceExhaustedError("queuedOperations", maximum);
220
+ state.queued++;
221
+ const previous = state.tail;
222
+ let release;
223
+ state.tail = new Promise((resolve) => {
224
+ release = resolve;
225
+ });
226
+ try {
227
+ await previous;
228
+ return await action();
229
+ } finally {
230
+ state.queued--;
231
+ release();
232
+ }
233
+ }
234
+ // src/resources/operation-owner.ts
235
+ var OperationOwner = class {
236
+ scope;
237
+ onDispose;
238
+ controller = new AbortController();
239
+ storage;
240
+ pending = 0;
241
+ ended = false;
242
+ disposed = false;
243
+ publishing = false;
244
+ timer;
245
+ constructor(scope, storage, durationMs, onDispose, maxReadBytes = 16777216) {
246
+ this.scope = scope;
247
+ this.onDispose = onDispose;
248
+ this.timer = setTimeout(() => this.cancel(new OperationCancelledError("Operation lifetime expired")), durationMs);
249
+ this.timer.unref();
250
+ this.storage = {
251
+ capabilities: storage.capabilities,
252
+ get: (key, options) => this.track(async () => {
253
+ const signal = options?.signal ? AbortSignal.any([this.signal, options.signal]) : this.signal;
254
+ const value = await storage.get(key, {
255
+ signal,
256
+ maxBytes: Math.min(maxReadBytes, options?.maxBytes ?? maxReadBytes)
257
+ });
258
+ if (value && value.data.byteLength > maxReadBytes) throw new Error("Storage read exceeds configured byte limit");
259
+ return value;
260
+ }, maxReadBytes * 3),
261
+ put: (key, data, options) => this.track(() => storage.put(key, data, options), data.byteLength * 2),
262
+ delete: (key, options) => this.track(() => storage.delete(key, options)),
263
+ list: (prefix) => this.track(() => storage.list(prefix))
264
+ };
265
+ }
266
+ get signal() {
267
+ return this.controller.signal;
268
+ }
269
+ get isDisposed() {
270
+ return this.disposed;
271
+ }
272
+ get pendingOperations() {
273
+ return this.pending;
274
+ }
275
+ assertActive() {
276
+ this.signal.throwIfAborted();
277
+ if (this.ended) throw new OperationCancelledError("Operation is closed");
278
+ }
279
+ async track(action, bytes = 0) {
280
+ this.assertActive();
281
+ const lease = this.scope.reserve({
282
+ pendingOperations: 1,
283
+ workingBytes: bytes
284
+ });
285
+ this.pending++;
286
+ try {
287
+ const value = await action();
288
+ if (!this.publishing) this.signal.throwIfAborted();
289
+ return value;
290
+ } finally {
291
+ lease.release();
292
+ this.pending--;
293
+ this.disposeIfReady();
294
+ }
295
+ }
296
+ protectPublication() {
297
+ this.assertActive();
298
+ this.publishing = true;
299
+ clearTimeout(this.timer);
300
+ }
301
+ cancel(reason = new OperationCancelledError()) {
302
+ if (this.publishing) return;
303
+ if (!this.signal.aborted) this.controller.abort(reason);
304
+ this.finish();
305
+ }
306
+ finish() {
307
+ if (this.ended) return;
308
+ this.ended = true;
309
+ clearTimeout(this.timer);
310
+ this.disposeIfReady();
311
+ }
312
+ disposeIfReady() {
313
+ if (!this.ended || this.pending || this.disposed) return;
314
+ this.disposed = true;
315
+ this.scope.close();
316
+ this.onDispose();
317
+ }
318
+ holdCleanup(promise) {
319
+ this.pending++;
320
+ const complete = () => {
321
+ this.pending--;
322
+ this.disposeIfReady();
323
+ };
324
+ promise.then(complete, complete);
325
+ }
326
+ async wait(promise) {
327
+ this.assertActive();
328
+ return new Promise((resolve, reject) => {
329
+ const abort = () => {
330
+ cleanup();
331
+ reject(this.signal.reason);
332
+ };
333
+ const cleanup = () => this.signal.removeEventListener("abort", abort);
334
+ this.signal.addEventListener("abort", abort, { once: true });
335
+ promise.then((value) => {
336
+ cleanup();
337
+ resolve(value);
338
+ }, (error) => {
339
+ cleanup();
340
+ reject(error);
341
+ });
342
+ if (this.signal.aborted) abort();
343
+ });
344
+ }
345
+ };
4
346
  // src/integrity/integrity.ts
5
347
  function sha256(bytes) {
6
348
  return (0, node_crypto.createHash)("sha256").update(bytes).digest("hex");
@@ -25,7 +367,7 @@ var StorageKeyManager = class {
25
367
  objectPattern;
26
368
  commitPattern;
27
369
  constructor(namespace = "__duraxis/v1") {
28
- if (!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(namespace)) throw new Error("Invalid Duraxis storage namespace");
370
+ if (typeof namespace != "string" || Buffer.byteLength(namespace) > 256 || !/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(namespace)) throw new Error("Invalid Duraxis storage namespace");
29
371
  this.namespace = namespace;
30
372
  this.manifestKey = `${namespace}/manifest`;
31
373
  this.objectPrefix = `${namespace}/objects/`;
@@ -34,6 +376,7 @@ var StorageKeyManager = class {
34
376
  this.indexNodePattern = new RegExp(`^${escapeRegex$1(this.indexNodePrefix)}${UUID$1}-([a-f0-9]{64})$`);
35
377
  this.objectPattern = new RegExp(`^${escapeRegex$1(this.objectPrefix)}(${UUID$1})(?:-([a-f0-9]{64}))?$`);
36
378
  this.commitPattern = new RegExp(`^${escapeRegex$1(this.commitPrefix)}(${UUID$1})-([a-f0-9]{64})$`);
379
+ Object.freeze(this);
37
380
  }
38
381
  validateLogicalKey(key) {
39
382
  (0, _duraxis_storage.assertStorageKey)(key);
@@ -448,6 +791,34 @@ async function readCommitRecord(storage, keys, key) {
448
791
  if (keys.commitKey(record.transactionId, object.data) != key) throw new Error("Commit record identity mismatch");
449
792
  return record;
450
793
  }
794
+ // src/resources/prepared-writes.ts
795
+ var PreparedWrites = class extends Map {
796
+ limits;
797
+ bytes = 0;
798
+ encodedBytes = 0;
799
+ reservation;
800
+ constructor(scope, limits, source) {
801
+ super();
802
+ this.limits = limits;
803
+ this.reservation = scope.reserve({});
804
+ for (const [key, value] of source) this.set(key, value);
805
+ }
806
+ sizeOf(key, value) {
807
+ return key.length * 2 + 512 + (value.type === "put" ? value.data.byteLength * 8 : 0);
808
+ }
809
+ set(key, value) {
810
+ const previous = this.get(key);
811
+ if (!previous && this.size >= this.limits.maxPendingWrites) throw new ResourceExhaustedError("writes", this.limits.maxPendingWrites);
812
+ if (value.type === "put" && value.data.byteLength > this.limits.maxDocumentBytes) throw new ResourceExhaustedError("documentBytes", this.limits.maxDocumentBytes);
813
+ const next = this.bytes - (previous ? this.sizeOf(key, previous) : 0) + this.sizeOf(key, value);
814
+ const encoded = this.encodedBytes - (previous?.type === "put" ? previous.data.byteLength : 0) + (value.type === "put" ? value.data.byteLength : 0);
815
+ if (encoded > this.limits.maxPendingWriteBytes) throw new ResourceExhaustedError("preparedWriteBytes", this.limits.maxPendingWriteBytes);
816
+ this.reservation.resize({ workingBytes: next });
817
+ this.bytes = next;
818
+ this.encodedBytes = encoded;
819
+ return super.set(key, value);
820
+ }
821
+ };
451
822
  // src/indexes/bptree/bptree-codec.ts
452
823
  var encoder$3 = new TextEncoder();
453
824
  var decoder$3 = new TextDecoder("utf-8", { fatal: true });
@@ -1097,16 +1468,22 @@ var PrimaryIndex = class {
1097
1468
  }
1098
1469
  };
1099
1470
  // src/indexes/bptree/bptree-node-cache.ts
1100
- /** Query-scoped LRU for already integrity-checked immutable nodes. */
1101
1471
  var BPlusTreeNodeCache = class {
1102
1472
  source;
1103
1473
  capacity;
1474
+ maxBytes;
1104
1475
  entries = /* @__PURE__ */ new Map();
1476
+ sizes = /* @__PURE__ */ new Map();
1477
+ bytes = 0;
1478
+ reservation;
1105
1479
  hits = 0;
1106
1480
  misses = 0;
1107
- constructor(source, capacity = 256) {
1481
+ constructor(source, capacity = 256, maxBytes = 4194304, resources = new ResourceScope({})) {
1108
1482
  this.source = source;
1109
1483
  this.capacity = capacity;
1484
+ this.maxBytes = maxBytes;
1485
+ this.reservation = resources.reserve({});
1486
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new RangeError("Invalid cache byte limit");
1110
1487
  if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 65536) throw new Error("Invalid B+tree node cache capacity");
1111
1488
  }
1112
1489
  async read(ref) {
@@ -1119,8 +1496,19 @@ var BPlusTreeNodeCache = class {
1119
1496
  }
1120
1497
  this.misses++;
1121
1498
  const node = await this.source.read(ref);
1499
+ if (this.entries.has(ref)) return this.entries.get(ref);
1500
+ const size = estimateBytes(node);
1501
+ if (size > this.maxBytes) return node;
1502
+ while (this.entries.size >= this.capacity || this.bytes + size > this.maxBytes) {
1503
+ const oldest = this.entries.keys().next().value;
1504
+ this.bytes -= this.sizes.get(oldest);
1505
+ this.sizes.delete(oldest);
1506
+ this.entries.delete(oldest);
1507
+ }
1508
+ this.reservation.resize({ workingBytes: this.bytes + size });
1509
+ this.bytes += size;
1510
+ this.sizes.set(ref, size);
1122
1511
  this.entries.set(ref, node);
1123
- if (this.entries.size > this.capacity) this.entries.delete(this.entries.keys().next().value);
1124
1512
  return node;
1125
1513
  }
1126
1514
  write(node) {
@@ -1128,11 +1516,15 @@ var BPlusTreeNodeCache = class {
1128
1516
  }
1129
1517
  clear() {
1130
1518
  this.entries.clear();
1519
+ this.sizes.clear();
1520
+ this.bytes = 0;
1521
+ this.reservation.resize({});
1131
1522
  }
1132
1523
  getMetrics() {
1133
1524
  return {
1134
1525
  hits: this.hits,
1135
- misses: this.misses
1526
+ misses: this.misses,
1527
+ bytes: this.bytes
1136
1528
  };
1137
1529
  }
1138
1530
  };
@@ -1268,14 +1660,14 @@ function hasValue(value) {
1268
1660
  }
1269
1661
  function secondaryIndexBounds(index, options) {
1270
1662
  const hasEquality = options.eq !== void 0;
1271
- const legacy = [
1663
+ const tupleBounds = [
1272
1664
  options.gt,
1273
1665
  options.gte,
1274
1666
  options.lt,
1275
1667
  options.lte
1276
1668
  ].filter((value) => value !== void 0);
1277
- if (hasEquality && (options.prefix || options.range || legacy.length)) throw new Error("Equality cannot be combined with index ranges");
1278
- if (options.range && legacy.length) throw new Error("Use either range or tuple range shorthands");
1669
+ if (hasEquality && (options.prefix || options.range || tupleBounds.length)) throw new Error("Equality cannot be combined with index ranges");
1670
+ if (options.range && tupleBounds.length) throw new Error("Use either range or tuple range shorthands");
1279
1671
  const orders = indexFields(index).map((part) => part.order);
1280
1672
  const encode = (values) => {
1281
1673
  if (values.length == 0 || values.length > orders.length) throw new Error("Invalid compound key arity");
@@ -1291,13 +1683,13 @@ function secondaryIndexBounds(index, options) {
1291
1683
  }
1292
1684
  let prefix = options.prefix ?? [];
1293
1685
  let range = options.range;
1294
- if (legacy.length) {
1686
+ if (tupleBounds.length) {
1295
1687
  if (options.prefix) throw new Error("Tuple range shorthands already contain their prefix");
1296
- const arity = legacy[0].length;
1297
- if (arity == 0 || legacy.some((value) => value.length != arity)) throw new Error("Index range arity mismatch");
1298
- prefix = legacy[0].slice(0, -1);
1688
+ const arity = tupleBounds[0].length;
1689
+ if (arity == 0 || tupleBounds.some((value) => value.length != arity)) throw new Error("Index range arity mismatch");
1690
+ prefix = tupleBounds[0].slice(0, -1);
1299
1691
  const encodedPrefix = prefix.length ? encode(prefix) : /* @__PURE__ */ new Uint8Array();
1300
- for (const value of legacy.slice(1)) {
1692
+ for (const value of tupleBounds.slice(1)) {
1301
1693
  const other = value.slice(0, -1);
1302
1694
  if (compareBytes(encodedPrefix, other.length ? encode(other) : /* @__PURE__ */ new Uint8Array()) != 0) throw new Error("Compound range bounds must share an equality prefix");
1303
1695
  }
@@ -1363,13 +1755,13 @@ var SecondaryIndexManager = class {
1363
1755
  this.nodes = nodes;
1364
1756
  this.primary = new PrimaryIndex(storage, keys, nodes);
1365
1757
  }
1366
- async prepare(previousManifest, nextPrimaryRoot, writes, catalog) {
1758
+ async prepare(previousManifest, nextPrimaryRoot, writes, catalog, resources) {
1367
1759
  const roots = new Map(previousManifest.indexRoots);
1368
1760
  const declared = /* @__PURE__ */ new Set();
1369
1761
  const tree = new BPlusTree(this.nodes);
1370
1762
  for (const [collectionName, schema] of catalog) {
1371
1763
  const previousSchema = previousManifest.catalog.get(collectionName);
1372
- const changes = await this.collectChanges(previousManifest, collectionName, writes);
1764
+ const changes = await this.collectChanges(previousManifest, collectionName, writes, resources);
1373
1765
  for (const index of schema.indexes) {
1374
1766
  const id = indexId(collectionName, index.name);
1375
1767
  declared.add(id);
@@ -1422,15 +1814,20 @@ var SecondaryIndexManager = class {
1422
1814
  for (const id of [...roots.keys()]) if (!declared.has(id)) roots.delete(id);
1423
1815
  return roots;
1424
1816
  }
1425
- async collectChanges(manifest, collection, writes) {
1817
+ async collectChanges(manifest, collection, writes, resources) {
1426
1818
  const changes = [];
1819
+ const memory = resources?.reserve({});
1820
+ let bytes = 0;
1427
1821
  for (const [key, operation] of writes) {
1428
1822
  const parsed = parseRecordKey(key);
1429
1823
  if (parsed == null || parsed.collection != collection) continue;
1430
1824
  const previousRef = await this.primary.getReference(manifest, key);
1825
+ const previousData = previousRef == null ? void 0 : await this.primary.readObject(previousRef);
1826
+ bytes += 512 + (previousData?.byteLength ?? 0) * 8 + (operation.type == "put" ? operation.data.byteLength * 8 : 0);
1827
+ memory?.resize({ workingBytes: bytes });
1431
1828
  changes.push({
1432
1829
  recordId: parsed.id,
1433
- previous: previousRef == null ? void 0 : decodeDocument(await this.primary.readObject(previousRef)),
1830
+ previous: previousRef == null ? void 0 : decodeDocument(previousData),
1434
1831
  next: operation.type == "put" ? decodeDocument(operation.data) : void 0
1435
1832
  });
1436
1833
  }
@@ -1521,8 +1918,10 @@ function cloneWrites(source) {
1521
1918
  return result;
1522
1919
  }
1523
1920
  var QueryContext = class {
1524
- snapshot;
1525
1921
  options;
1922
+ resources;
1923
+ limits;
1924
+ iteratorReservations = [];
1526
1925
  primary;
1527
1926
  secondary;
1528
1927
  nodeCache;
@@ -1531,6 +1930,8 @@ var QueryContext = class {
1531
1930
  startedAt = performance.now();
1532
1931
  active = true;
1533
1932
  iterators = 0;
1933
+ timer;
1934
+ cancellationReturns = /* @__PURE__ */ new Set();
1534
1935
  metrics = {
1535
1936
  storageReads: 0,
1536
1937
  storageWrites: 0,
@@ -1542,15 +1943,49 @@ var QueryContext = class {
1542
1943
  cacheMisses: 0,
1543
1944
  durationMs: 0
1544
1945
  };
1545
- catalog;
1946
+ snapshotValue;
1947
+ get snapshot() {
1948
+ this.assertActive();
1949
+ return this.snapshotValue;
1950
+ }
1951
+ catalogValue = /* @__PURE__ */ new Map();
1952
+ get catalog() {
1953
+ return this.catalogValue;
1954
+ }
1546
1955
  constructor(storage, snapshot, keys, options = {}) {
1547
- this.snapshot = snapshot;
1548
1956
  this.options = options;
1549
- this.nodeCache = new BPlusTreeNodeCache(new BPlusTreeNodeStore(storage, keys));
1550
- this.primary = new PrimaryIndex(storage, keys, this.nodeCache);
1551
- this.secondary = new SecondaryIndexManager(storage, keys, this.nodeCache);
1957
+ this.snapshotValue = snapshot;
1958
+ this.limits = options.limits ?? resourceLimits();
1959
+ this.resources = (options.resources ?? new ResourceScope({})).child({
1960
+ workingBytes: this.limits.maxQueryWorkingBytes,
1961
+ spillBytes: this.limits.maxSpillBytes
1962
+ });
1963
+ try {
1964
+ this.resources.reserve({
1965
+ queries: 1,
1966
+ iterators: 1,
1967
+ workingBytes: estimateBytes([...options.writes ?? []])
1968
+ });
1969
+ } catch (error) {
1970
+ this.resources.close();
1971
+ throw error;
1972
+ }
1973
+ const queryStorage = {
1974
+ put: storage.put.bind(storage),
1975
+ delete: storage.delete.bind(storage),
1976
+ list: storage.list.bind(storage),
1977
+ get: (key, options) => storage.get(key, {
1978
+ ...options,
1979
+ signal: options?.signal ? AbortSignal.any([this.signal, options.signal]) : this.signal
1980
+ })
1981
+ };
1982
+ this.nodeCache = new BPlusTreeNodeCache(new BPlusTreeNodeStore(queryStorage, keys), 256, Math.min(4194304, this.limits.maxQueryWorkingBytes), this.resources);
1983
+ this.primary = new PrimaryIndex(queryStorage, keys, this.nodeCache);
1984
+ this.secondary = new SecondaryIndexManager(queryStorage, keys, this.nodeCache);
1552
1985
  this.writes = cloneWrites(options.writes);
1553
- this.catalog = new Map(options.catalog ?? snapshot.manifest.catalog);
1986
+ for (const [name, definition] of options.catalog ?? snapshot.manifest.catalog) this.catalogValue.set(name, definition);
1987
+ this.timer = setTimeout(() => this.cancel(new OperationCancelledError("Query lifetime expired")), this.limits.maxQueryDurationMs);
1988
+ this.timer.unref();
1554
1989
  }
1555
1990
  get generation() {
1556
1991
  return this.snapshot.manifest.transactionId || "initial";
@@ -1561,30 +1996,78 @@ var QueryContext = class {
1561
1996
  get isActive() {
1562
1997
  return this.active;
1563
1998
  }
1564
- close(reason = /* @__PURE__ */ new Error("Query context is closed")) {
1999
+ bindCancellation(close) {
2000
+ this.cancellationReturns.add(close);
2001
+ return () => this.cancellationReturns.delete(close);
2002
+ }
2003
+ managed(factory) {
2004
+ const context = this;
2005
+ const iterator = (async function* () {
2006
+ const unbind = context.bindCancellation(() => iterator.return(void 0));
2007
+ try {
2008
+ yield* factory();
2009
+ } finally {
2010
+ unbind();
2011
+ }
2012
+ })();
2013
+ return iterator;
2014
+ }
2015
+ scanCollection(collection, options = {}) {
2016
+ return this.managed(() => this.scanCollectionRows(collection, options));
2017
+ }
2018
+ scanIndex(collection, index, options = {}) {
2019
+ return this.managed(() => this.scanIndexRows(collection, index, options));
2020
+ }
2021
+ close(reason = /* @__PURE__ */ new Error("Query context is closed"), cleanup) {
1565
2022
  if (!this.active) return;
1566
2023
  this.active = false;
2024
+ clearTimeout(this.timer);
2025
+ this.cancellationReturns.clear();
1567
2026
  const cache = this.nodeCache.getMetrics();
1568
2027
  this.metrics.cacheHits = cache.hits;
1569
2028
  this.metrics.cacheMisses = cache.misses;
1570
2029
  this.metrics.durationMs = performance.now() - this.startedAt;
1571
2030
  this.controller.abort(reason);
1572
2031
  this.nodeCache.clear();
1573
- this.options.onClose?.();
2032
+ this.writes.clear();
2033
+ this.catalogValue.clear();
2034
+ this.snapshotValue = void 0;
2035
+ while (this.iterators > 0) this.end();
2036
+ const finish = () => {
2037
+ this.resources.close();
2038
+ this.options.onClose?.();
2039
+ };
2040
+ if (cleanup) {
2041
+ const pending = Promise.resolve().then(cleanup);
2042
+ this.options.onPendingCleanup?.(pending);
2043
+ pending.then(finish, (error) => {
2044
+ this.options.onCleanupFailure?.(error);
2045
+ finish();
2046
+ });
2047
+ } else finish();
1574
2048
  }
1575
2049
  cancel(reason = /* @__PURE__ */ new Error("Query cancelled")) {
1576
- this.close(reason);
2050
+ const callbacks = [...this.cancellationReturns];
2051
+ this.cancellationReturns.clear();
2052
+ this.close(reason, callbacks.length ? async () => {
2053
+ const errors = (await Promise.allSettled(callbacks.map((callback) => Promise.resolve().then(callback)))).filter((result) => result.status == "rejected").map((result) => result.reason);
2054
+ if (errors.length) throw new AggregateError(errors, "Query iterator cleanup failed");
2055
+ } : void 0);
1577
2056
  }
1578
2057
  assertActive() {
2058
+ this.options.assertAccess?.();
1579
2059
  if (!this.active) throw this.controller.signal.reason ?? /* @__PURE__ */ new Error("Query context is closed");
1580
2060
  }
1581
2061
  begin() {
1582
2062
  this.assertActive();
2063
+ this.iteratorReservations.push(this.resources.reserve({ iterators: this.iterators ? 1 : 0 }));
1583
2064
  this.iterators++;
1584
2065
  this.options.onIteratorStart?.();
1585
2066
  }
1586
2067
  end() {
1587
- if (this.iterators > 0) this.iterators--;
2068
+ if (this.iterators == 0) return;
2069
+ this.iterators--;
2070
+ this.iteratorReservations.pop()?.release();
1588
2071
  this.options.onIteratorEnd?.();
1589
2072
  }
1590
2073
  schema(collection) {
@@ -1611,7 +2094,7 @@ var QueryContext = class {
1611
2094
  }
1612
2095
  return result;
1613
2096
  }
1614
- async *scanCollection(collection, options = {}) {
2097
+ async *scanCollectionRows(collection, options = {}) {
1615
2098
  this.begin();
1616
2099
  try {
1617
2100
  this.schema(collection);
@@ -1689,6 +2172,8 @@ var QueryContext = class {
1689
2172
  const bounds = secondaryIndexBounds(index, options);
1690
2173
  const matches = (key) => (bounds.gt == null || compareBytes(key, bounds.gt) > 0) && (bounds.gte == null || compareBytes(key, bounds.gte) >= 0) && (bounds.lt == null || compareBytes(key, bounds.lt) < 0) && (bounds.lte == null || compareBytes(key, bounds.lte) <= 0);
1691
2174
  const result = [];
2175
+ let bytes = 0;
2176
+ const memory = this.resources.reserve({});
1692
2177
  for (const [id, write] of this.pendingFor(collection)) {
1693
2178
  if (write.type != "put") continue;
1694
2179
  const document = decodeDocument(write.data);
@@ -1704,17 +2189,21 @@ var QueryContext = class {
1704
2189
  }
1705
2190
  if (missing) continue;
1706
2191
  const key = encodeSecondaryKey(values, index.unique ? void 0 : id, orders);
1707
- if (matches(key)) result.push({
1708
- key,
1709
- row: {
1710
- id,
1711
- document
1712
- }
1713
- });
2192
+ if (matches(key)) {
2193
+ bytes += estimateBytes(document) + key.byteLength + id.length * 2;
2194
+ memory.resize({ workingBytes: bytes });
2195
+ result.push({
2196
+ key,
2197
+ row: {
2198
+ id,
2199
+ document
2200
+ }
2201
+ });
2202
+ }
1714
2203
  }
1715
2204
  return result;
1716
2205
  }
1717
- async *scanIndex(collection, indexName, options = {}) {
2206
+ async *scanIndexRows(collection, indexName, options = {}) {
1718
2207
  this.begin();
1719
2208
  try {
1720
2209
  const schema = this.schema(collection);
@@ -1726,14 +2215,20 @@ var QueryContext = class {
1726
2215
  const parts = indexFields(index);
1727
2216
  const bounds = secondaryIndexBounds(index, options);
1728
2217
  const entries = [];
2218
+ const memory = this.resources.reserve({});
2219
+ let bytes = 0;
1729
2220
  for await (const row of this.scanCollection(collection, { signal: options.signal })) {
1730
2221
  const values = parts.map((part) => indexedValue(row.document, part.field, fieldDefinition(schema, part.field)));
1731
2222
  if (values.some((value) => value === void 0)) continue;
1732
2223
  const key = encodeSecondaryKey(values, index.unique ? void 0 : row.id, parts.map((part) => part.order));
1733
- if ((bounds.gt == null || compareBytes(key, bounds.gt) > 0) && (bounds.gte == null || compareBytes(key, bounds.gte) >= 0) && (bounds.lt == null || compareBytes(key, bounds.lt) < 0) && (bounds.lte == null || compareBytes(key, bounds.lte) <= 0)) entries.push({
1734
- key,
1735
- row
1736
- });
2224
+ 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)) {
2225
+ bytes += estimateBytes(row) + key.byteLength;
2226
+ memory.resize({ workingBytes: bytes });
2227
+ entries.push({
2228
+ key,
2229
+ row
2230
+ });
2231
+ }
1737
2232
  }
1738
2233
  const limit = options.limit ?? Number.MAX_SAFE_INTEGER;
1739
2234
  if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid query limit");
@@ -1803,7 +2298,7 @@ var TransactionConflictError = class extends Error {
1803
2298
  var CommitOutcomeUnknownError = class extends Error {
1804
2299
  transactionId;
1805
2300
  constructor(transactionId, cause) {
1806
- super(`Commit outcome is unknown for transaction ${transactionId}` + (cause instanceof Error ? `: ${cause.message}` : ""), { cause });
2301
+ super(`Commit outcome is unknown for transaction ${transactionId}; reconcile before retrying`, { cause });
1807
2302
  this.name = "CommitOutcomeUnknownError";
1808
2303
  this.transactionId = transactionId;
1809
2304
  }
@@ -1817,9 +2312,9 @@ var ForeignKeyManager = class {
1817
2312
  this.#primary = new PrimaryIndex(storage, keys);
1818
2313
  this.#secondary = new SecondaryIndexManager(storage, keys);
1819
2314
  }
1820
- async prepare(snapshot, sourceWrites, sourceCatalog) {
2315
+ async prepare(snapshot, sourceWrites, sourceCatalog, targetWrites) {
1821
2316
  const catalog = this.validateCatalog(sourceCatalog);
1822
- const writes = new Map(sourceWrites);
2317
+ const writes = targetWrites ?? new Map(sourceWrites);
1823
2318
  const incoming = this.incoming(catalog);
1824
2319
  const queue = [];
1825
2320
  const visited = /* @__PURE__ */ new Set();
@@ -1952,25 +2447,40 @@ var ForeignKeyManager = class {
1952
2447
  var CommitCoordinator = class {
1953
2448
  storage;
1954
2449
  keys;
2450
+ coordinationStorage;
1955
2451
  primary;
1956
2452
  secondary;
1957
2453
  foreignKeys;
1958
- constructor(storage, keys = new StorageKeyManager()) {
2454
+ constructor(storage, keys = new StorageKeyManager(), coordinationStorage = storage) {
1959
2455
  this.storage = storage;
1960
2456
  this.keys = keys;
2457
+ this.coordinationStorage = coordinationStorage;
1961
2458
  this.primary = new PrimaryIndex(storage, keys);
1962
2459
  this.secondary = new SecondaryIndexManager(storage, keys);
1963
2460
  this.foreignKeys = new ForeignKeyManager(storage, keys);
1964
2461
  }
1965
2462
  async commit(transaction) {
2463
+ const admission = transaction.resources.reserve({ queuedOperations: 1 });
2464
+ try {
2465
+ return await coordinateCommit(this.coordinationStorage, transaction.limits.maxQueuedOperations, async () => {
2466
+ if (transaction.hasChanges) {
2467
+ if (((await this.storage.get(this.keys.manifestKey))?.version ?? null) != transaction.expectedStorageVersion) throw new TransactionConflictError();
2468
+ }
2469
+ await this.publish(transaction);
2470
+ });
2471
+ } finally {
2472
+ admission.release();
2473
+ }
2474
+ }
2475
+ async publish(transaction) {
1966
2476
  const prepared = transaction.prepareForCommit();
1967
2477
  if (prepared.writes.size == 0 && prepared.schemaChanges.size == 0) {
1968
2478
  transaction.markCommitted();
1969
2479
  return;
1970
2480
  }
1971
- const transactionId = (0, node_crypto.randomUUID)();
2481
+ const transactionId = transaction.id;
1972
2482
  const catalog = new Map(prepared.snapshot.manifest.catalog);
1973
- const staged = new Map(prepared.writes);
2483
+ const staged = new PreparedWrites(transaction.resources, transaction.limits, prepared.writes);
1974
2484
  for (const [name, schema] of prepared.schemaChanges) {
1975
2485
  if (schema == null) catalog.delete(name);
1976
2486
  else catalog.set(name, schema);
@@ -1983,7 +2493,9 @@ var CommitCoordinator = class {
1983
2493
  });
1984
2494
  const context = new QueryContext(this.storage, prepared.snapshot, this.keys, {
1985
2495
  writes: staged,
1986
- catalog: scanCatalog
2496
+ catalog: scanCatalog,
2497
+ resources: transaction.resources,
2498
+ limits: transaction.limits
1987
2499
  });
1988
2500
  try {
1989
2501
  for await (const row of context.scanCollection(name)) staged.set(recordKey(name, row.id), schema == null ? { type: "delete" } : {
@@ -1994,7 +2506,8 @@ var CommitCoordinator = class {
1994
2506
  context.close();
1995
2507
  }
1996
2508
  }
1997
- const writes = await this.foreignKeys.prepare(prepared.snapshot, staged, catalog);
2509
+ const writes = await this.foreignKeys.prepare(prepared.snapshot, staged, catalog, staged);
2510
+ for (const [key, value] of writes) if (!staged.has(key)) staged.set(key, value);
1998
2511
  const changes = /* @__PURE__ */ new Map();
1999
2512
  for (const [key, operation] of writes) {
2000
2513
  if (operation.type == "delete") {
@@ -2006,7 +2519,7 @@ var CommitCoordinator = class {
2006
2519
  changes.set(key, ref);
2007
2520
  }
2008
2521
  const primaryRoot = await this.primary.prepare(prepared.snapshot.manifest.primaryRoot, changes);
2009
- const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog);
2522
+ const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog, transaction.resources);
2010
2523
  const commitBytes = encodeCommitRecord({
2011
2524
  format: 1,
2012
2525
  transactionId,
@@ -2033,7 +2546,10 @@ var CommitCoordinator = class {
2033
2546
  transaction.markUnknown();
2034
2547
  throw new CommitOutcomeUnknownError(transactionId, cause);
2035
2548
  }
2036
- if (!result.success) throw new TransactionConflictError();
2549
+ if (!result.success) {
2550
+ transaction.rejectPublication();
2551
+ throw new TransactionConflictError();
2552
+ }
2037
2553
  transaction.markCommitted();
2038
2554
  }
2039
2555
  };
@@ -2084,7 +2600,7 @@ function hmac(key, value) {
2084
2600
  function queryHash(key, query) {
2085
2601
  return hmac(key, canonical(shape(query)));
2086
2602
  }
2087
- function encodeQueryCursor(generation, schema, query, row, signingKey) {
2603
+ function cursorEnvelope(generation, schema, query, row, signingKey) {
2088
2604
  if (query.collection != schema.name) throw new Error("Cursor collection mismatch");
2089
2605
  const values = (query.orderBy ?? []).map(({ field }) => {
2090
2606
  if (field == "$id") return row.id;
@@ -2094,45 +2610,111 @@ function encodeQueryCursor(generation, schema, query, row, signingKey) {
2094
2610
  if (value === null || typeof value == "string" || typeof value == "number" || typeof value == "boolean") return value;
2095
2611
  throw new Error(`Cannot encode cursor value for ${field}`);
2096
2612
  });
2097
- const envelope = {
2098
- version: 2,
2613
+ return {
2614
+ version: 3,
2099
2615
  generation,
2100
2616
  queryHash: queryHash(signingKey, query),
2101
2617
  values,
2102
2618
  id: row.id
2103
2619
  };
2104
- const payload = canonical(envelope);
2105
- return Buffer.from(JSON.stringify({
2106
- payload: envelope,
2107
- signature: hmac(signingKey, payload)
2620
+ }
2621
+ function cursorKeys(value) {
2622
+ if (value instanceof Uint8Array) {
2623
+ if (value.byteLength < 32) throw new Error("Cursor key must contain at least 32 bytes");
2624
+ return {
2625
+ activeKeyId: "default",
2626
+ keys: { default: (0, node_crypto.createHash)("sha256").update(value).digest() },
2627
+ ttlMs: 9e5
2628
+ };
2629
+ }
2630
+ if (!value || !/^[A-Za-z0-9_-]{1,32}$/.test(value.activeKeyId) || !Object.hasOwn(value.keys, value.activeKeyId)) throw new Error("Invalid cursor keyring");
2631
+ 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");
2632
+ if (Object.keys(value.keys).length > 16) throw new Error("Cursor keyring is too large");
2633
+ if (value.ttlMs !== void 0 && (!Number.isSafeInteger(value.ttlMs) || value.ttlMs < 1)) throw new Error("Invalid cursor expiry");
2634
+ return value;
2635
+ }
2636
+ function encodeQueryCursor(generation, schema, query, row, keys, namespace = "") {
2637
+ const ring = cursorKeys(keys);
2638
+ const key = ring.keys[ring.activeKeyId];
2639
+ const envelope = cursorEnvelope(generation, schema, query, row, key);
2640
+ const nonce = (0, node_crypto.randomBytes)(12);
2641
+ const cipher = (0, node_crypto.createCipheriv)("aes-256-gcm", key, nonce);
2642
+ cipher.setAAD(Buffer.from(canonical({
2643
+ version: 3,
2644
+ keyId: ring.activeKeyId,
2645
+ namespace
2646
+ })));
2647
+ const payload = JSON.stringify({
2648
+ ...envelope,
2649
+ version: 3,
2650
+ namespace,
2651
+ expiresAt: Date.now() + (ring.ttlMs ?? 9e5)
2652
+ });
2653
+ const ciphertext = Buffer.concat([cipher.update(payload, "utf8"), cipher.final()]);
2654
+ const cursor = Buffer.from(JSON.stringify({
2655
+ version: 3,
2656
+ keyId: ring.activeKeyId,
2657
+ nonce: nonce.toString("base64url"),
2658
+ ciphertext: ciphertext.toString("base64url"),
2659
+ tag: cipher.getAuthTag().toString("base64url")
2108
2660
  })).toString("base64url");
2661
+ if (cursor.length > 16384) throw new Error("Query cursor exceeds maximum size");
2662
+ return cursor;
2109
2663
  }
2110
- function decodeQueryCursor(cursor, generation, schema, query, signingKey) {
2111
- let parsed;
2664
+ function decodeQueryCursor(cursor, generation, schema, query, keys, namespace = "") {
2665
+ if (typeof cursor != "string" || !cursor.length || cursor.length > 16384 || !/^[A-Za-z0-9_-]+$/.test(cursor)) throw new Error("Invalid query cursor");
2666
+ const ring = cursorKeys(keys);
2667
+ let outer;
2112
2668
  try {
2113
- parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
2669
+ outer = JSON.parse(Buffer.from(cursor, "base64url").toString());
2114
2670
  } catch {
2115
2671
  throw new Error("Invalid query cursor");
2116
2672
  }
2117
- if (!parsed || typeof parsed != "object" || Array.isArray(parsed)) throw new Error("Invalid query cursor");
2118
- const record = parsed;
2119
- const envelope = record.payload;
2120
- if (!envelope || envelope.version != 2 || typeof record.signature != "string") throw new Error("Invalid query cursor payload");
2121
- const expectedSignature = hmac(signingKey, canonical(envelope));
2122
- const actual = Buffer.from(record.signature, "hex");
2123
- const expected = Buffer.from(expectedSignature, "hex");
2124
- if (actual.length != expected.length || !(0, node_crypto.timingSafeEqual)(actual, expected)) throw new Error("Invalid query cursor signature");
2125
- if (envelope.generation != generation) throw new Error("Query cursor snapshot generation is unavailable");
2126
- if (envelope.queryHash != queryHash(signingKey, query) || query.collection != schema.name) throw new Error("Query cursor is incompatible with this query");
2127
- const orderBy = query.orderBy ?? [];
2128
- if (!Array.isArray(envelope.values) || envelope.values.length != orderBy.length || typeof envelope.id != "string") throw new Error("Invalid query cursor payload");
2673
+ if (!outer || typeof outer != "object" || Array.isArray(outer)) throw new Error("Invalid query cursor");
2674
+ if (outer.version !== 3) throw new Error("Unsupported cursor format; restart pagination");
2675
+ 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");
2676
+ const binary = (value) => {
2677
+ if (typeof value != "string" || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("Invalid query cursor");
2678
+ const result = Buffer.from(value, "base64url");
2679
+ if (result.toString("base64url") != value) throw new Error("Invalid query cursor");
2680
+ return result;
2681
+ };
2682
+ const nonce = binary(outer.nonce);
2683
+ const tag = binary(outer.tag);
2684
+ const ciphertext = binary(outer.ciphertext);
2685
+ if (nonce.length != 12 || tag.length != 16) throw new Error("Invalid query cursor");
2686
+ const key = ring.keys[outer.keyId];
2687
+ let payload;
2688
+ try {
2689
+ const decipher = (0, node_crypto.createDecipheriv)("aes-256-gcm", key, nonce);
2690
+ decipher.setAAD(Buffer.from(canonical({
2691
+ version: 3,
2692
+ keyId: outer.keyId,
2693
+ namespace
2694
+ })));
2695
+ decipher.setAuthTag(tag);
2696
+ payload = JSON.parse(Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString());
2697
+ } catch {
2698
+ throw new Error("Invalid query cursor authentication");
2699
+ }
2700
+ if (!payload || typeof payload != "object" || Array.isArray(payload)) throw new Error("Invalid query cursor payload");
2701
+ 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");
2702
+ if (payload.generation != generation) throw new Error("Query cursor snapshot generation is unavailable");
2703
+ if (payload.queryHash != queryHash(key, query) || query.collection != schema.name) throw new Error("Query cursor is incompatible with this query");
2704
+ 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");
2705
+ const values = payload.values.map((value, index) => {
2706
+ if (value && typeof value == "object" && Object.keys(value).join(",") == "missing" && value.missing === true) return void 0;
2707
+ if (value !== null && typeof value != "string" && typeof value != "boolean" && (typeof value != "number" || !Number.isFinite(value))) throw new Error("Invalid cursor scalar");
2708
+ if (fieldDefinition(schema, query.orderBy[index].field)?.type == "date" && typeof value == "string") {
2709
+ const date = new Date(value);
2710
+ if (!Number.isFinite(date.getTime()) || date.toISOString() != value) throw new Error("Invalid cursor date");
2711
+ return date;
2712
+ }
2713
+ return value;
2714
+ });
2129
2715
  return {
2130
- id: envelope.id,
2131
- values: envelope.values.map((item, index) => {
2132
- if (item && typeof item == "object" && "missing" in item) return void 0;
2133
- if (fieldDefinition(schema, orderBy[index].field)?.type == "date" && typeof item == "string") return new Date(item);
2134
- return item;
2135
- })
2716
+ id: payload.id,
2717
+ values
2136
2718
  };
2137
2719
  }
2138
2720
  // src/query/validation/query-validator.ts
@@ -2205,10 +2787,36 @@ function predicate(schema, value, depth) {
2205
2787
  default: throw new Error("Unknown query predicate");
2206
2788
  }
2207
2789
  }
2208
- function validateQuery(query, catalog) {
2790
+ function validatePredicateComplexity(query, maxDepth = 32, maxNodes = 4096) {
2791
+ const stack = [{
2792
+ value: query.where,
2793
+ depth: 0
2794
+ }];
2795
+ let count = 0;
2796
+ while (stack.length) {
2797
+ const { value, depth } = stack.pop();
2798
+ if (value == null) continue;
2799
+ if (++count > maxNodes || depth > maxDepth) throw new Error("Query predicate complexity limit exceeded");
2800
+ if (!value || typeof value != "object") throw new Error("Invalid query predicate");
2801
+ const node = value;
2802
+ if (Array.isArray(node.predicates)) {
2803
+ if (node.predicates.length + count + stack.length > maxNodes) throw new Error("Query predicate complexity limit exceeded");
2804
+ for (const child of node.predicates) stack.push({
2805
+ value: child,
2806
+ depth: depth + 1
2807
+ });
2808
+ }
2809
+ if (node.predicate) stack.push({
2810
+ value: node.predicate,
2811
+ depth: depth + 1
2812
+ });
2813
+ }
2814
+ }
2815
+ function validateQuery(query, catalog, limits) {
2209
2816
  if (!query || typeof query != "object" || !isValidSchemaName(query.collection)) throw new Error("Invalid logical query");
2210
2817
  const schema = catalog.get(query.collection);
2211
2818
  if (!schema) throw new Error(`Unknown collection: ${query.collection}`);
2819
+ validatePredicateComplexity(query, limits?.maxPredicateDepth, limits?.maxPredicateNodes);
2212
2820
  if (query.where) predicate(schema, query.where, 0);
2213
2821
  const orders = /* @__PURE__ */ new Set();
2214
2822
  for (const order of query.orderBy ?? []) {
@@ -2423,12 +3031,24 @@ var Sort = class {
2423
3031
  const maximum = this.options.maxRowsInMemory ?? 1e4;
2424
3032
  if (!Number.isSafeInteger(maximum) || maximum < 2) throw new Error("Invalid sort memory limit");
2425
3033
  const compare = (a, b) => compareRows(schema, this.orders, a, b);
3034
+ const memory = context.resources.child({});
3035
+ const chunkMemory = memory.reserve({});
3036
+ let chunkBytes = 0;
3037
+ let spilledBytes = 0;
3038
+ const disk = memory.reserve({});
2426
3039
  const spill = this.options.spill;
2427
3040
  let chunk = [];
2428
3041
  let runs = [];
2429
3042
  const active = /* @__PURE__ */ new Set();
2430
3043
  const write = async (rows) => {
2431
- const handle = await spill.write(rows);
3044
+ const bounded = async function* () {
3045
+ for await (const row of rows) {
3046
+ spilledBytes += estimateBytes(row);
3047
+ disk.resize({ spillBytes: spilledBytes });
3048
+ yield row;
3049
+ }
3050
+ };
3051
+ const handle = await spill.write(bounded());
2432
3052
  active.add(handle);
2433
3053
  return handle;
2434
3054
  };
@@ -2450,12 +3070,24 @@ var Sort = class {
2450
3070
  };
2451
3071
  try {
2452
3072
  for await (const row of this.input.execute(context)) {
3073
+ const size = estimateBytes(row);
3074
+ if (chunkBytes + size > Math.floor(context.limits.maxQueryWorkingBytes / 2) && chunk.length && spill) {
3075
+ chunk.sort(compare);
3076
+ runs.push(await write(chunk));
3077
+ chunk = [];
3078
+ chunkBytes = 0;
3079
+ chunkMemory.resize({});
3080
+ }
3081
+ chunkMemory.resize({ workingBytes: chunkBytes + size });
3082
+ chunkBytes += size;
2453
3083
  chunk.push(row);
2454
3084
  if (chunk.length < maximum) continue;
2455
3085
  if (!this.options.spill) throw new QueryMemoryLimitError();
2456
3086
  chunk.sort(compare);
2457
3087
  runs.push(await write(chunk));
2458
3088
  chunk = [];
3089
+ chunkBytes = 0;
3090
+ chunkMemory.resize({});
2459
3091
  }
2460
3092
  if (runs.length == 0) {
2461
3093
  chunk.sort(compare);
@@ -2482,7 +3114,12 @@ var Sort = class {
2482
3114
  }
2483
3115
  yield* merge(runs);
2484
3116
  } finally {
2485
- await Promise.all([...active].map((handle) => spill.delete(handle)));
3117
+ try {
3118
+ const failures = (await Promise.allSettled([...active].map((handle) => spill.delete(handle)))).filter((r) => r.status == "rejected");
3119
+ if (failures.length) throw new AggregateError(failures.map((r) => r.reason), "Sort spill cleanup failed");
3120
+ } finally {
3121
+ memory.close();
3122
+ }
2486
3123
  }
2487
3124
  }
2488
3125
  };
@@ -2539,9 +3176,15 @@ var SetOperator = class {
2539
3176
  }
2540
3177
  async ids(context, input) {
2541
3178
  const result = /* @__PURE__ */ new Map();
3179
+ const memory = context.resources.reserve({});
3180
+ let bytes = 0;
2542
3181
  for await (const row of input.execute(context)) {
2543
3182
  context.assertActive();
2544
3183
  if (result.size >= this.maxSetEntries && !result.has(row.id)) throw new QueryMemoryLimitError();
3184
+ if (!result.has(row.id)) {
3185
+ bytes += estimateBytes(row);
3186
+ memory.resize({ workingBytes: bytes });
3187
+ }
2545
3188
  result.set(row.id, row);
2546
3189
  }
2547
3190
  return result;
@@ -2551,10 +3194,14 @@ var Union = class extends SetOperator {
2551
3194
  name = "Union";
2552
3195
  async *execute(context) {
2553
3196
  const seen = /* @__PURE__ */ new Set();
3197
+ const memory = context.resources.reserve({});
3198
+ let bytes = 0;
2554
3199
  for (const input of this.inputs) for await (const row of input.execute(context)) {
2555
3200
  context.assertActive();
2556
3201
  if (seen.has(row.id)) continue;
2557
3202
  if (seen.size >= this.maxSetEntries) throw new QueryMemoryLimitError();
3203
+ bytes += row.id.length * 2 + 48;
3204
+ memory.resize({ workingBytes: bytes });
2558
3205
  seen.add(row.id);
2559
3206
  yield row;
2560
3207
  }
@@ -2567,7 +3214,7 @@ var Intersection = class extends SetOperator {
2567
3214
  const candidates = await this.ids(context, first);
2568
3215
  for (const input of rest) {
2569
3216
  const current = await this.ids(context, input);
2570
- for (const id of [...candidates.keys()]) if (!current.has(id)) candidates.delete(id);
3217
+ for (const id of candidates.keys()) if (!current.has(id)) candidates.delete(id);
2571
3218
  }
2572
3219
  for (const row of candidates.values()) {
2573
3220
  context.assertActive();
@@ -2585,7 +3232,15 @@ var Difference = class extends SetOperator {
2585
3232
  this.excluded = excluded;
2586
3233
  }
2587
3234
  async *execute(context) {
2588
- const excluded = await this.ids(context, this.excluded);
3235
+ const excluded = /* @__PURE__ */ new Set();
3236
+ const memory = context.resources.reserve({});
3237
+ let bytes = 0;
3238
+ for await (const row of this.excluded.execute(context)) if (!excluded.has(row.id)) {
3239
+ if (excluded.size >= this.maxSetEntries) throw new QueryMemoryLimitError();
3240
+ bytes += row.id.length * 2 + 48;
3241
+ memory.resize({ workingBytes: bytes });
3242
+ excluded.add(row.id);
3243
+ }
2589
3244
  for await (const row of this.universe.execute(context)) {
2590
3245
  context.assertActive();
2591
3246
  if (!excluded.has(row.id)) yield row;
@@ -2651,7 +3306,7 @@ var QueryExecutor = class {
2651
3306
  }
2652
3307
  }
2653
3308
  semanticPipeline(context, query, source, forceDeterministicSort = false, executionLimit = query.limit) {
2654
- validateQuery(query, context.catalog);
3309
+ validateQuery(query, context.catalog, context.limits);
2655
3310
  let operator = source;
2656
3311
  if (query.where) operator = new Filter(operator, query.where, query.collection);
2657
3312
  const orderBy = query.orderBy ?? [];
@@ -2660,7 +3315,7 @@ var QueryExecutor = class {
2660
3315
  spill: this.options.sortSpill
2661
3316
  });
2662
3317
  if (query.cursor) {
2663
- const cursor = decodeQueryCursor(query.cursor, context.generation, context.catalog.get(query.collection), query, this.signingKey());
3318
+ const cursor = decodeQueryCursor(query.cursor, context.generation, context.catalog.get(query.collection), query, this.signingKey(), this.options.cursorNamespace);
2664
3319
  operator = new CursorAfter(operator, orderBy, cursor.values, cursor.id, query.collection);
2665
3320
  }
2666
3321
  if (executionLimit != null) operator = new Limit(operator, executionLimit);
@@ -2671,6 +3326,7 @@ var QueryExecutor = class {
2671
3326
  return produced?.deterministic == true && produced.fields.length == requested.length && produced.fields.every((field, index) => field.field == requested[index].field && field.direction == requested[index].direction);
2672
3327
  }
2673
3328
  signingKey() {
3329
+ if (this.options.cursorEncryption) return this.options.cursorEncryption;
2674
3330
  const key = this.options.cursorSigningKey;
2675
3331
  if (!(key instanceof Uint8Array) || key.byteLength < 32) throw new Error("Cursor operations require a signing key of at least 32 bytes");
2676
3332
  return key;
@@ -2684,11 +3340,19 @@ var QueryExecutor = class {
2684
3340
  const lookahead = query.limit == null ? void 0 : query.limit + 1;
2685
3341
  const operator = this.semanticPipeline(context, query, source, true, lookahead);
2686
3342
  const raw = [];
2687
- for await (const row of operator.execute(context)) raw.push(row);
3343
+ const results = materialize(context.resources, context.limits);
3344
+ try {
3345
+ for await (const row of operator.execute(context)) {
3346
+ results.add(row);
3347
+ raw.push(row);
3348
+ }
3349
+ } finally {
3350
+ results.close();
3351
+ }
2688
3352
  const schema = context.catalog.get(query.collection);
2689
3353
  const hasMore = query.limit != null && query.limit > 0 && raw.length > query.limit;
2690
3354
  if (hasMore) raw.pop();
2691
- const nextCursor = hasMore && raw.length ? encodeQueryCursor(context.generation, schema, query, raw[raw.length - 1], this.signingKey()) : null;
3355
+ const nextCursor = hasMore && raw.length ? encodeQueryCursor(context.generation, schema, query, raw[raw.length - 1], this.signingKey(), this.options.cursorNamespace) : null;
2692
3356
  return {
2693
3357
  rows: query.projection ? raw.map((row) => ({
2694
3358
  id: row.id,
@@ -2950,8 +3614,8 @@ var RuleBasedPlanner = class {
2950
3614
  constructor(enumerator = new AccessPathEnumerator()) {
2951
3615
  this.enumerator = enumerator;
2952
3616
  }
2953
- plan(query, catalog) {
2954
- const schema = validateQuery(query, catalog);
3617
+ plan(query, catalog, limits) {
3618
+ const schema = validateQuery(query, catalog, limits);
2955
3619
  const selected = this.choose(query, schema, query.where);
2956
3620
  const required = query.orderBy ?? [];
2957
3621
  const requiresSort = required.length > 0 && (!selected.access.deterministicOrdering || selected.access.producedOrdering.length != required.length || selected.access.producedOrdering.some((item, index) => item.field != required[index].field || item.direction != required[index].direction));
@@ -3088,23 +3752,70 @@ var Transaction = class {
3088
3752
  storage;
3089
3753
  keys;
3090
3754
  cursorSigningKey;
3755
+ operationSignal;
3756
+ onPublication;
3757
+ assertAccessScope;
3758
+ runtimeHooks;
3759
+ id = (0, node_crypto.randomUUID)();
3760
+ pendingCleanup = /* @__PURE__ */ new Set();
3761
+ localCancellation = new AbortController();
3762
+ signal;
3763
+ resources;
3764
+ limits;
3765
+ writeReservations = /* @__PURE__ */ new Map();
3766
+ schemaReservations = /* @__PURE__ */ new Map();
3091
3767
  writes = /* @__PURE__ */ new Map();
3092
3768
  schemas = /* @__PURE__ */ new Map();
3093
- capturedSnapshot;
3094
- reader;
3769
+ snapshotValue;
3770
+ get capturedSnapshot() {
3771
+ if (!this.snapshotValue) throw new TransactionStateError("Transaction is closed");
3772
+ return this.snapshotValue;
3773
+ }
3774
+ set capturedSnapshot(value) {
3775
+ this.snapshotValue = value;
3776
+ }
3777
+ readerValue;
3778
+ get reader() {
3779
+ if (!this.readerValue) throw new TransactionStateError("Transaction is closed");
3780
+ return this.readerValue;
3781
+ }
3782
+ set reader(value) {
3783
+ this.readerValue = value;
3784
+ }
3095
3785
  stateValue = "ACTIVE";
3096
3786
  pendingReads = 0;
3097
3787
  readWaiters = [];
3098
3788
  queryContexts = /* @__PURE__ */ new Set();
3099
3789
  planner = new RuleBasedPlanner();
3100
3790
  planCompiler = new PlanCompiler();
3101
- constructor(storage, snapshot, keys = new StorageKeyManager(), cursorSigningKey) {
3791
+ constructor(storage, snapshot, keys = new StorageKeyManager(), cursorSigningKey, parentResources, limits = resourceLimits(), operationSignal, onPublication, assertAccessScope, runtimeHooks = {}) {
3102
3792
  this.storage = storage;
3103
3793
  this.keys = keys;
3104
3794
  this.cursorSigningKey = cursorSigningKey;
3795
+ this.operationSignal = operationSignal;
3796
+ this.onPublication = onPublication;
3797
+ this.assertAccessScope = assertAccessScope;
3798
+ this.runtimeHooks = runtimeHooks;
3799
+ this.signal = operationSignal ? AbortSignal.any([operationSignal, this.localCancellation.signal]) : this.localCancellation.signal;
3800
+ this.limits = limits;
3801
+ this.resources = (parentResources ?? new ResourceScope({})).child({
3802
+ workingBytes: limits.maxTransactionWorkingBytes,
3803
+ writes: limits.maxPendingWrites,
3804
+ writeBytes: limits.maxPendingWriteBytes
3805
+ });
3806
+ this.resources.reserve({ transactions: 1 });
3807
+ this.resources.reserve({ workingBytes: estimateBytes([...snapshot.manifest.catalog]) });
3105
3808
  this.capturedSnapshot = cloneSnapshot(snapshot);
3106
3809
  this.reader = new ManifestSnapshotReader(this.storage, this.capturedSnapshot, keys);
3107
3810
  }
3811
+ get expectedStorageVersion() {
3812
+ this.assertActive();
3813
+ return this.capturedSnapshot.storageVersion;
3814
+ }
3815
+ get hasChanges() {
3816
+ this.assertActive();
3817
+ return this.writes.size + this.schemas.size > 0;
3818
+ }
3108
3819
  get state() {
3109
3820
  return this.stateValue;
3110
3821
  }
@@ -3121,6 +3832,9 @@ var Transaction = class {
3121
3832
  const result = await this.reader.get(key);
3122
3833
  this.assertActive();
3123
3834
  return result;
3835
+ } catch (error) {
3836
+ if (this.stateValue != "ACTIVE" && !this.operationSignal?.aborted && error instanceof OperationCancelledError) throw new TransactionStateError("Transaction is no longer active");
3837
+ throw error;
3124
3838
  } finally {
3125
3839
  this.pendingReads--;
3126
3840
  if (this.pendingReads == 0) for (const resolve of this.readWaiters.splice(0)) resolve();
@@ -3136,14 +3850,14 @@ var Transaction = class {
3136
3850
  this.assertActive();
3137
3851
  this.validateKey(key);
3138
3852
  if (key.startsWith("@duraxis/records/")) throw new Error("Reserved internal collection key");
3139
- this.writes.set(key, { type: "delete" });
3853
+ this.stageDelete(key);
3140
3854
  }
3141
3855
  defineCollection(definition) {
3142
3856
  this.assertActive();
3143
3857
  validateCollection(definition);
3144
3858
  if (this.schemas.get(definition.name) === null) throw new Error("Cannot recreate a dropped collection in the same transaction");
3145
3859
  if (this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3146
- this.schemas.set(definition.name, cloneSchema(definition));
3860
+ this.stageSchema(definition.name, cloneSchema(definition));
3147
3861
  }
3148
3862
  defineCollections(definitions) {
3149
3863
  this.assertActive();
@@ -3153,7 +3867,7 @@ var Transaction = class {
3153
3867
  if (names.has(definition.name) || this.schemas.has(definition.name) || this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3154
3868
  names.add(definition.name);
3155
3869
  }
3156
- for (const definition of definitions) this.schemas.set(definition.name, cloneSchema(definition));
3870
+ for (const definition of definitions) this.stageSchema(definition.name, cloneSchema(definition));
3157
3871
  }
3158
3872
  getCollectionDefinitions() {
3159
3873
  this.assertActive();
@@ -3166,12 +3880,12 @@ var Transaction = class {
3166
3880
  this.assertActive();
3167
3881
  this.requireCollection(name);
3168
3882
  if (name != definition.name) throw new Error("Collection replacement cannot rename a collection");
3169
- this.schemas.set(name, cloneSchema(definition));
3883
+ this.stageSchema(name, cloneSchema(definition));
3170
3884
  }
3171
3885
  dropCollection(name) {
3172
3886
  this.assertActive();
3173
3887
  this.requireCollection(name);
3174
- this.schemas.set(name, null);
3888
+ this.stageSchema(name, null);
3175
3889
  }
3176
3890
  async getMetadata(namespace) {
3177
3891
  this.assertActive();
@@ -3210,13 +3924,13 @@ var Transaction = class {
3210
3924
  indexes: [...current.indexes, index]
3211
3925
  };
3212
3926
  validateCollection(updated);
3213
- this.schemas.set(collection, cloneSchema(updated));
3927
+ this.stageSchema(collection, cloneSchema(updated));
3214
3928
  }
3215
3929
  removeIndex(collection, indexName) {
3216
3930
  this.assertActive();
3217
3931
  const current = this.requireCollection(collection);
3218
3932
  if (!current.indexes.some((index) => index.name == indexName)) throw new Error(`Unknown index: ${collection}/${indexName}`);
3219
- this.schemas.set(collection, cloneSchema({
3933
+ this.stageSchema(collection, cloneSchema({
3220
3934
  ...current,
3221
3935
  indexes: current.indexes.filter((index) => index.name != indexName)
3222
3936
  }));
@@ -3234,6 +3948,16 @@ var Transaction = class {
3234
3948
  else catalog.set(name, cloneSchema(schema));
3235
3949
  let context;
3236
3950
  context = new QueryContext(this.storage, cloneSnapshot(this.capturedSnapshot), this.keys, {
3951
+ assertAccess: this.assertAccessScope,
3952
+ onPendingCleanup: (promise) => {
3953
+ this.pendingCleanup.add(promise);
3954
+ this.runtimeHooks.onPendingCleanup?.(promise);
3955
+ const complete = () => this.pendingCleanup.delete(promise);
3956
+ promise.then(complete, complete);
3957
+ },
3958
+ onCleanupFailure: this.runtimeHooks.onCleanupFailure,
3959
+ resources: this.resources,
3960
+ limits: this.limits,
3237
3961
  writes: this.writes,
3238
3962
  catalog,
3239
3963
  onIteratorStart: () => {
@@ -3249,18 +3973,21 @@ var Transaction = class {
3249
3973
  const context = this.createQueryContext();
3250
3974
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3251
3975
  const options = explicit ? explicitOptions : sourceOrOptions;
3252
- const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog), context.catalog);
3976
+ const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog, context.limits), context.catalog);
3253
3977
  const executor = new QueryExecutor(this.queryOptions(options));
3254
3978
  const transaction = this;
3255
- return (async function* () {
3256
- const unbindSignal = transaction.bindSignal(context, options?.signal);
3979
+ const iterator = (async function* () {
3980
+ let unbindSignal = () => {};
3257
3981
  try {
3982
+ unbindSignal = transaction.bindSignal(context, options?.signal);
3258
3983
  yield* executor.execute(context, query, source);
3259
3984
  } finally {
3260
3985
  unbindSignal();
3261
3986
  context.close();
3262
3987
  }
3263
3988
  })();
3989
+ context.bindCancellation(() => iterator.return(void 0));
3990
+ return iterator;
3264
3991
  }
3265
3992
  async queryPage(query, sourceOrOptions, explicitOptions) {
3266
3993
  const context = this.createQueryContext();
@@ -3269,7 +3996,7 @@ var Transaction = class {
3269
3996
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3270
3997
  const options = explicit ? explicitOptions : sourceOrOptions;
3271
3998
  unbindSignal = this.bindSignal(context, options?.signal);
3272
- const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog), context.catalog);
3999
+ const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog, context.limits), context.catalog);
3273
4000
  return await new QueryExecutor(this.queryOptions(options)).page(context, query, source);
3274
4001
  } finally {
3275
4002
  unbindSignal();
@@ -3279,22 +4006,29 @@ var Transaction = class {
3279
4006
  putDocument(collection, id, document) {
3280
4007
  this.assertActive();
3281
4008
  const schema = this.requireCollection(collection);
3282
- const parsed = validateDocument(schema, document);
3283
- const data = encodeDocument(parsed);
3284
- for (const index of schema.indexes) for (const part of index.fields ?? (index.field ? [{
3285
- field: index.field,
3286
- order: "ASC"
3287
- }] : [])) indexedValue(parsed, part.field, fieldDefinition(schema, part.field));
3288
- this.stagePut(recordKey(collection, id), data);
4009
+ const estimate = estimateBytes(document, this.limits.maxDocumentBytes * 4, this.limits.maxDocumentDepth);
4010
+ const encoding = this.resources.reserve({ workingBytes: estimate * 4 });
4011
+ try {
4012
+ const parsed = validateDocument(schema, document);
4013
+ const data = encodeDocument(parsed);
4014
+ for (const index of schema.indexes) for (const part of index.fields ?? (index.field ? [{
4015
+ field: index.field,
4016
+ order: "ASC"
4017
+ }] : [])) indexedValue(parsed, part.field, fieldDefinition(schema, part.field));
4018
+ this.stagePut(recordKey(collection, id), data);
4019
+ } finally {
4020
+ encoding.release();
4021
+ }
3289
4022
  }
3290
4023
  deleteDocument(collection, id) {
3291
4024
  this.assertActive();
3292
4025
  this.requireCollection(collection);
3293
- this.writes.set(recordKey(collection, id), { type: "delete" });
4026
+ this.stageDelete(recordKey(collection, id));
3294
4027
  }
3295
4028
  prepareForCommit() {
3296
4029
  this.assertActive();
3297
4030
  if (this.pendingReads != 0) throw new TransactionStateError("Transaction has pending reads; await all tx.get() calls");
4031
+ this.resources.reserve({ workingBytes: [...this.writes].reduce((n, [key, op]) => n + key.length * 2 + 96 + (op.type == "put" ? op.data.byteLength : 0), 0) });
3298
4032
  this.stateValue = "PREPARING";
3299
4033
  const writes = /* @__PURE__ */ new Map();
3300
4034
  for (const [key, operation] of this.writes) writes.set(key, operation.type == "delete" ? { type: "delete" } : {
@@ -3314,7 +4048,9 @@ var Transaction = class {
3314
4048
  });
3315
4049
  }
3316
4050
  beginPublication() {
4051
+ this.assertAccessScope?.();
3317
4052
  if (this.stateValue != "PREPARING") throw new TransactionStateError("Transaction is not preparing");
4053
+ this.onPublication?.();
3318
4054
  this.stateValue = "COMMITTING";
3319
4055
  }
3320
4056
  markCommitted() {
@@ -3325,17 +4061,56 @@ var Transaction = class {
3325
4061
  this.stateValue = "UNKNOWN";
3326
4062
  }
3327
4063
  abort() {
4064
+ if (this.stateValue == "COMMITTING") return;
3328
4065
  if (this.stateValue != "COMMITTED" && this.stateValue != "UNKNOWN") this.stateValue = "ABORTED";
3329
4066
  }
4067
+ rejectPublication() {
4068
+ if (this.stateValue != "COMMITTING") throw new TransactionStateError("No publication in progress");
4069
+ this.stateValue = "ABORTED";
4070
+ }
3330
4071
  close() {
4072
+ if (this.stateValue == "COMMITTING") return;
4073
+ this.localCancellation.abort(new TransactionStateError("Transaction is closed"));
3331
4074
  if (this.stateValue == "ACTIVE" || this.stateValue == "PREPARING") this.abort();
3332
- for (const context of [...this.queryContexts]) context.close();
4075
+ for (const context of [...this.queryContexts]) context.cancel(new TransactionStateError("Transaction is closed"));
3333
4076
  this.queryContexts.clear();
3334
4077
  this.writes.clear();
3335
4078
  this.schemas.clear();
4079
+ this.writeReservations.clear();
4080
+ this.schemaReservations.clear();
4081
+ if (this.pendingCleanup.size) Promise.allSettled([...this.pendingCleanup]).then(() => this.resources.close());
4082
+ else this.resources.close();
4083
+ this.snapshotValue = void 0;
4084
+ this.readerValue = void 0;
4085
+ }
4086
+ createMaterializationBudget() {
4087
+ return materialize(this.resources, this.limits);
4088
+ }
4089
+ reserveWrite(key, bytes) {
4090
+ if (bytes > this.limits.maxDocumentBytes) throw new ResourceExhaustedError("documentBytes", this.limits.maxDocumentBytes);
4091
+ const amounts = {
4092
+ writes: 1,
4093
+ writeBytes: bytes,
4094
+ workingBytes: bytes + key.length * 2 + 128
4095
+ };
4096
+ const current = this.writeReservations.get(key);
4097
+ if (current) current.resize(amounts);
4098
+ else this.writeReservations.set(key, this.resources.reserve(amounts));
4099
+ }
4100
+ stageDelete(key) {
4101
+ this.reserveWrite(key, 0);
4102
+ this.writes.set(key, { type: "delete" });
4103
+ }
4104
+ stageSchema(name, schema) {
4105
+ const amounts = { workingBytes: estimateBytes(schema) + 128 };
4106
+ const current = this.schemaReservations.get(name);
4107
+ if (current) current.resize(amounts);
4108
+ else this.schemaReservations.set(name, this.resources.reserve(amounts));
4109
+ this.schemas.set(name, schema);
3336
4110
  }
3337
4111
  stagePut(key, data) {
3338
4112
  if (!(data instanceof Uint8Array)) throw new TypeError("Storage value must be Uint8Array");
4113
+ this.reserveWrite(key, data.byteLength);
3339
4114
  this.writes.set(key, {
3340
4115
  type: "put",
3341
4116
  data: new Uint8Array(data)
@@ -3348,13 +4123,15 @@ var Transaction = class {
3348
4123
  queryOptions(options) {
3349
4124
  return {
3350
4125
  ...options,
3351
- cursorSigningKey: options?.cursorSigningKey ?? this.cursorSigningKey
4126
+ cursorSigningKey: this.cursorSigningKey,
4127
+ cursorEncryption: this.runtimeHooks.cursorEncryption,
4128
+ cursorNamespace: this.keys.namespace
3352
4129
  };
3353
4130
  }
3354
4131
  bindSignal(context, signal) {
3355
4132
  if (!signal) return () => {};
3356
4133
  const cancel = () => context.cancel(signal.reason ?? /* @__PURE__ */ new Error("Query cancelled"));
3357
- if (signal.aborted) cancel();
4134
+ if (signal.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
3358
4135
  else signal.addEventListener("abort", cancel, { once: true });
3359
4136
  return () => signal.removeEventListener("abort", cancel);
3360
4137
  }
@@ -3370,9 +4147,12 @@ var Transaction = class {
3370
4147
  return schema;
3371
4148
  }
3372
4149
  assertActive() {
4150
+ this.assertAccessScope?.();
4151
+ this.operationSignal?.throwIfAborted();
3373
4152
  if (this.stateValue != "ACTIVE") throw new TransactionStateError("Transaction is no longer active");
3374
4153
  }
3375
4154
  validateKey(key) {
4155
+ if (Buffer.byteLength(key) > 1024) throw new ResourceExhaustedError("keyBytes", 1024);
3376
4156
  this.keys.validateLogicalKey(key);
3377
4157
  encodeIndexKey(new TextEncoder().encode(key));
3378
4158
  }
@@ -3422,6 +4202,196 @@ var RecoveryManager = class {
3422
4202
  return count;
3423
4203
  }
3424
4204
  };
4205
+ // src/gc/reachability-scanner.ts
4206
+ var MAX_REFERENCES = 1e5;
4207
+ var MAX_BYTES = 33554432;
4208
+ var ManifestReachabilityScanner = class {
4209
+ keys;
4210
+ nodes;
4211
+ primary;
4212
+ constructor(keys, storage) {
4213
+ this.keys = keys;
4214
+ this.nodes = new BPlusTreeNodeStore(storage, keys);
4215
+ this.primary = new PrimaryIndex(storage, keys);
4216
+ }
4217
+ async scan(snapshot, options = {}) {
4218
+ const maximum = options.maxReferences ?? MAX_REFERENCES;
4219
+ const maxBytes = options.maxBytes ?? MAX_BYTES;
4220
+ const reachable = /* @__PURE__ */ new Set();
4221
+ let bytes = 0;
4222
+ const add = (ref) => {
4223
+ if (reachable.has(ref)) return;
4224
+ const size = ref.length * 2 + 64;
4225
+ if (reachable.size >= maximum || bytes + size > maxBytes) throw new ResourceExhaustedError("gcReachability", maxBytes);
4226
+ bytes += size;
4227
+ reachable.add(ref);
4228
+ };
4229
+ const path = /* @__PURE__ */ new Set();
4230
+ const visit = async (ref, depth) => {
4231
+ options.signal?.throwIfAborted();
4232
+ if (path.has(ref) || depth >= 128) throw new Error("Invalid B+tree cycle or depth during reachability scan");
4233
+ if (reachable.has(ref)) return;
4234
+ this.keys.validateIndexNodeKey(ref);
4235
+ add(ref);
4236
+ path.add(ref);
4237
+ try {
4238
+ const node = await this.nodes.read(ref);
4239
+ if (node.type == "internal") for (const child of node.children) await visit(child, depth + 1);
4240
+ } finally {
4241
+ path.delete(ref);
4242
+ }
4243
+ };
4244
+ if (snapshot.manifest.primaryRoot) await visit(snapshot.manifest.primaryRoot, 0);
4245
+ for (const root of snapshot.manifest.indexRoots.values()) if (root) await visit(root, 0);
4246
+ for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot)) {
4247
+ options.signal?.throwIfAborted();
4248
+ add(entry.ref);
4249
+ }
4250
+ return reachable;
4251
+ }
4252
+ };
4253
+ // src/gc/garbage-collector.ts
4254
+ var DEFAULT_GRACE_PERIOD_MS = 864e5;
4255
+ var GarbageCollector = class {
4256
+ storage;
4257
+ keys;
4258
+ activeSnapshots;
4259
+ scanner;
4260
+ resourceParent;
4261
+ constructor(storage, keys, activeSnapshots, scanner = new ManifestReachabilityScanner(keys, storage), resourceParent = new ResourceScope({ workingBytes: 67108864 })) {
4262
+ this.storage = storage;
4263
+ this.keys = keys;
4264
+ this.activeSnapshots = activeSnapshots;
4265
+ this.scanner = scanner;
4266
+ this.resourceParent = resourceParent;
4267
+ }
4268
+ async collect(options = {}) {
4269
+ const started = performance.now();
4270
+ const dryRun = options.dryRun != false;
4271
+ if (!dryRun && options.exclusiveMaintenance != true) throw new Error("Deletion requires explicit exclusive maintenance intent and verified driver ownership");
4272
+ const coordination = storageCoordination(this.storage);
4273
+ if (coordination.maintenance) throw new Error("Maintenance is already active");
4274
+ if (!dryRun && (coordination.active || this.activeSnapshots().length)) throw new Error("Cannot delete objects with active snapshots or operations");
4275
+ if (!dryRun && !this.storage.verifyExclusiveOwnership) throw new Error("Destructive GC is unsupported without verified single-owner storage; shared/distributed storage must use dry-run");
4276
+ if (!this.storage.iterate) throw new Error("GC requires incremental storage listing support");
4277
+ coordination.maintenance = true;
4278
+ const maxMarkBytes = options.maxMarkBytes ?? 33554432;
4279
+ const maxReferences = options.maxReferences ?? 1e5;
4280
+ if (!Number.isSafeInteger(maxMarkBytes) || maxMarkBytes < 1 || !Number.isSafeInteger(maxReferences) || maxReferences < 1) {
4281
+ coordination.maintenance = false;
4282
+ throw new RangeError("Invalid GC mark budget");
4283
+ }
4284
+ const resources = this.resourceParent.child({ workingBytes: maxMarkBytes * 2 });
4285
+ const reservation = resources.reserve({});
4286
+ let markBytes = 0;
4287
+ try {
4288
+ if (!dryRun) await this.storage.verifyExclusiveOwnership();
4289
+ const olderThanMs = options.olderThanMs ?? DEFAULT_GRACE_PERIOD_MS;
4290
+ if (!Number.isSafeInteger(olderThanMs) || olderThanMs < 0) throw new Error("Invalid GC grace period");
4291
+ const batchSize = options.batchSize ?? 256;
4292
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1e5) throw new Error("Invalid GC batch size");
4293
+ if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
4294
+ const current = await this.storage.get(this.keys.manifestKey);
4295
+ const snapshot = {
4296
+ manifest: current ? decodeManifest(current.data, this.keys) : emptyManifest(),
4297
+ storageVersion: current?.version ?? null
4298
+ };
4299
+ const reachable = /* @__PURE__ */ new Set();
4300
+ if (coordination.snapshots.size > maxReferences) throw new ResourceExhaustedError("gcSnapshots", maxReferences);
4301
+ const retainedSnapshots = [snapshot, .../* @__PURE__ */ new Set([...this.activeSnapshots(), ...coordination.snapshots])];
4302
+ const mark = (ref) => {
4303
+ if (reachable.has(ref)) return;
4304
+ if (reachable.size >= maxReferences) throw new ResourceExhaustedError("gcReferences", maxReferences);
4305
+ const size = ref.length * 2 + 64;
4306
+ if (markBytes + size > maxMarkBytes) throw new ResourceExhaustedError("gcMarkBytes", maxMarkBytes);
4307
+ reservation.resize({ workingBytes: markBytes + size });
4308
+ markBytes += size;
4309
+ reachable.add(ref);
4310
+ };
4311
+ for (const item of retainedSnapshots) {
4312
+ const scanLease = resources.reserve({ workingBytes: maxMarkBytes });
4313
+ try {
4314
+ const refs = await this.scanner.scan(item, {
4315
+ maxReferences,
4316
+ maxBytes: maxMarkBytes,
4317
+ signal: options.signal
4318
+ });
4319
+ for (const ref of refs) mark(ref);
4320
+ } finally {
4321
+ scanLease.release();
4322
+ }
4323
+ }
4324
+ for (const retained of retainedSnapshots) {
4325
+ let cursor = retained.manifest.commitHead;
4326
+ let count = 0;
4327
+ while (cursor) {
4328
+ if (reachable.has(cursor)) break;
4329
+ if (++count > 1e6) throw new Error("Commit history scan limit exceeded during GC");
4330
+ mark(cursor);
4331
+ cursor = (await readCommitRecord(this.storage, this.keys, cursor)).previous;
4332
+ }
4333
+ }
4334
+ const cutoff = Date.now() - olderThanMs;
4335
+ let candidates = 0;
4336
+ let deleted = 0;
4337
+ let failed = 0;
4338
+ let scanned = 0;
4339
+ let nodesScanned = 0;
4340
+ let commitsScanned = 0;
4341
+ let position = 0;
4342
+ for (const prefix of [
4343
+ this.keys.objectPrefix,
4344
+ this.keys.indexNodePrefix,
4345
+ this.keys.commitPrefix
4346
+ ]) for await (const object of this.storage.iterate(prefix, {
4347
+ pageSize: Math.min(batchSize, 1e3),
4348
+ signal: options.signal
4349
+ })) {
4350
+ if (prefix == this.keys.objectPrefix) scanned++;
4351
+ else if (prefix == this.keys.indexNodePrefix) nodesScanned++;
4352
+ else commitsScanned++;
4353
+ position++;
4354
+ if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
4355
+ if (object.key.startsWith(this.keys.objectPrefix)) this.keys.validateObjectKey(object.key);
4356
+ else if (object.key.startsWith(this.keys.indexNodePrefix)) this.keys.validateIndexNodeKey(object.key);
4357
+ else this.keys.validateCommitKey(object.key);
4358
+ if (!Number.isSafeInteger(object.createdAt)) throw new Error(`Invalid object timestamp: ${object.key}`);
4359
+ if (reachable.has(object.key) || object.createdAt > cutoff) continue;
4360
+ candidates++;
4361
+ if (dryRun) {
4362
+ if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
4363
+ continue;
4364
+ }
4365
+ try {
4366
+ await this.storage.verifyExclusiveOwnership();
4367
+ if ((await this.storage.delete(object.key, { condition: {
4368
+ type: "if-version",
4369
+ version: object.version
4370
+ } })).success) deleted++;
4371
+ else failed++;
4372
+ } catch (error) {
4373
+ failed++;
4374
+ if (!options.continueOnError) throw error;
4375
+ }
4376
+ if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
4377
+ }
4378
+ return {
4379
+ scanned,
4380
+ nodesScanned,
4381
+ reachable: reachable.size,
4382
+ candidates,
4383
+ deleted,
4384
+ failed,
4385
+ commitsScanned,
4386
+ durationMs: performance.now() - started,
4387
+ dryRun
4388
+ };
4389
+ } finally {
4390
+ resources.close();
4391
+ coordination.maintenance = false;
4392
+ }
4393
+ }
4394
+ };
3425
4395
  // src/indexes/bptree/bptree-validator.ts
3426
4396
  var BPlusTreeValidator = class {
3427
4397
  nodes;
@@ -3523,125 +4493,6 @@ var BPlusTreeValidator = class {
3523
4493
  return found;
3524
4494
  }
3525
4495
  };
3526
- // src/gc/reachability-scanner.ts
3527
- var ManifestReachabilityScanner = class {
3528
- keys;
3529
- nodes;
3530
- primary;
3531
- constructor(keys, storage) {
3532
- this.keys = keys;
3533
- this.nodes = new BPlusTreeNodeStore(storage, keys);
3534
- this.primary = new PrimaryIndex(storage, keys);
3535
- }
3536
- async scan(snapshot) {
3537
- const reachable = /* @__PURE__ */ new Set();
3538
- const roots = /* @__PURE__ */ new Set();
3539
- if (snapshot.manifest.primaryRoot != null) roots.add(snapshot.manifest.primaryRoot);
3540
- for (const root of snapshot.manifest.indexRoots.values()) if (root != null) roots.add(root);
3541
- const validator = new BPlusTreeValidator(this.nodes);
3542
- for (const root of roots) {
3543
- this.keys.validateIndexNodeKey(root);
3544
- const references = await validator.reachableNodes(root);
3545
- for (const ref of references) reachable.add(ref);
3546
- }
3547
- for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot)) reachable.add(entry.ref);
3548
- return reachable;
3549
- }
3550
- };
3551
- // src/gc/garbage-collector.ts
3552
- var DEFAULT_GRACE_PERIOD_MS = 864e5;
3553
- var GarbageCollector = class {
3554
- storage;
3555
- keys;
3556
- activeSnapshots;
3557
- scanner;
3558
- constructor(storage, keys, activeSnapshots, scanner = new ManifestReachabilityScanner(keys, storage)) {
3559
- this.storage = storage;
3560
- this.keys = keys;
3561
- this.activeSnapshots = activeSnapshots;
3562
- this.scanner = scanner;
3563
- }
3564
- async collect(options = {}) {
3565
- const started = performance.now();
3566
- const dryRun = options.dryRun != false;
3567
- if (!dryRun && options.exclusiveMaintenance != true) throw new Error("Deletion requires externally guaranteed exclusive maintenance");
3568
- if (!dryRun && this.activeSnapshots().length != 0) throw new Error("Cannot delete objects with active snapshots");
3569
- const olderThanMs = options.olderThanMs ?? DEFAULT_GRACE_PERIOD_MS;
3570
- if (!Number.isSafeInteger(olderThanMs) || olderThanMs < 0) throw new Error("Invalid GC grace period");
3571
- const batchSize = options.batchSize ?? 256;
3572
- if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1e5) throw new Error("Invalid GC batch size");
3573
- if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
3574
- const current = await this.storage.get(this.keys.manifestKey);
3575
- const snapshot = {
3576
- manifest: current ? decodeManifest(current.data, this.keys) : emptyManifest(),
3577
- storageVersion: current?.version ?? null
3578
- };
3579
- const reachable = /* @__PURE__ */ new Set();
3580
- const retainedSnapshots = [snapshot, ...this.activeSnapshots()];
3581
- for (const item of retainedSnapshots) {
3582
- const refs = await this.scanner.scan(item);
3583
- for (const ref of refs) reachable.add(ref);
3584
- }
3585
- const objects = await this.storage.list(this.keys.objectPrefix);
3586
- const nodes = await this.storage.list(this.keys.indexNodePrefix);
3587
- const commits = await this.storage.list(this.keys.commitPrefix);
3588
- const reachableCommits = /* @__PURE__ */ new Set();
3589
- for (const retained of retainedSnapshots) {
3590
- let cursor = retained.manifest.commitHead;
3591
- let count = 0;
3592
- while (cursor) {
3593
- if (reachableCommits.has(cursor)) break;
3594
- if (++count > 1e6) throw new Error("Commit history scan limit exceeded during GC");
3595
- reachableCommits.add(cursor);
3596
- cursor = (await readCommitRecord(this.storage, this.keys, cursor)).previous;
3597
- }
3598
- }
3599
- const cutoff = Date.now() - olderThanMs;
3600
- let candidates = 0;
3601
- let deleted = 0;
3602
- let failed = 0;
3603
- const candidatesForScan = [
3604
- ...objects,
3605
- ...nodes,
3606
- ...commits
3607
- ];
3608
- for (let position = 0; position < candidatesForScan.length; position++) {
3609
- if (options.signal?.aborted) throw options.signal.reason ?? /* @__PURE__ */ new Error("GC cancelled");
3610
- const object = candidatesForScan[position];
3611
- if (object.key.startsWith(this.keys.objectPrefix)) this.keys.validateObjectKey(object.key);
3612
- else if (object.key.startsWith(this.keys.indexNodePrefix)) this.keys.validateIndexNodeKey(object.key);
3613
- else this.keys.validateCommitKey(object.key);
3614
- if (!Number.isSafeInteger(object.createdAt)) throw new Error(`Invalid object timestamp: ${object.key}`);
3615
- if (reachable.has(object.key) || reachableCommits.has(object.key) || object.createdAt > cutoff) continue;
3616
- candidates++;
3617
- if (dryRun) {
3618
- if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
3619
- continue;
3620
- }
3621
- try {
3622
- if ((await this.storage.delete(object.key, { condition: {
3623
- type: "if-version",
3624
- version: object.version
3625
- } })).success) deleted++;
3626
- } catch (error) {
3627
- failed++;
3628
- if (!options.continueOnError) throw error;
3629
- }
3630
- if ((position + 1) % batchSize == 0) await new Promise((resolve) => setImmediate(resolve));
3631
- }
3632
- return {
3633
- scanned: objects.length,
3634
- nodesScanned: nodes.length,
3635
- reachable: reachable.size,
3636
- candidates,
3637
- deleted,
3638
- failed,
3639
- commitsScanned: commits.length,
3640
- durationMs: performance.now() - started,
3641
- dryRun
3642
- };
3643
- }
3644
- };
3645
4496
  // src/indexes/index-consistency-checker.ts
3646
4497
  var decoder = new TextDecoder();
3647
4498
  var IndexConsistencyChecker = class {
@@ -3734,13 +4585,13 @@ function immutableCollection(definition) {
3734
4585
  ...foreignKeys.length == 0 ? {} : { foreignKeys }
3735
4586
  });
3736
4587
  }
3737
- var DuraxisDatabase = class {
4588
+ var DuraxisDatabase = class DuraxisDatabase {
4589
+ resourceLimits;
4590
+ resources;
4591
+ cursorEncryption;
4592
+ accessScope;
3738
4593
  storage;
3739
4594
  keys;
3740
- coordinator;
3741
- recovery;
3742
- primary;
3743
- secondary;
3744
4595
  cursorSigningKey;
3745
4596
  planner = new RuleBasedPlanner();
3746
4597
  planCompiler = new PlanCompiler();
@@ -3756,48 +4607,173 @@ var DuraxisDatabase = class {
3756
4607
  garbageCollectionDurationMs: 0
3757
4608
  };
3758
4609
  active = /* @__PURE__ */ new Set();
4610
+ owners = /* @__PURE__ */ new Map();
4611
+ operations = /* @__PURE__ */ new Set();
4612
+ closePromise;
4613
+ cleanupFailures = [];
4614
+ outcomes = /* @__PURE__ */ new Map();
4615
+ drainWaiters = /* @__PURE__ */ new Set();
3759
4616
  maintenance = false;
3760
4617
  pendingSnapshotAcquisitions = 0;
3761
4618
  closed = false;
3762
4619
  constructor(options) {
4620
+ if (options.storage.capabilities?.boundedReads !== true) throw new Error("Core requires a storage driver with verified bounded-read support; update the driver contract");
4621
+ this.resourceLimits = resourceLimits(options.resources);
4622
+ this.resources = databaseScope(this.resourceLimits);
4623
+ this.accessScope = options.accessScope ? Object.freeze({ ...options.accessScope }) : void 0;
4624
+ 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");
4625
+ this.cursorEncryption = options.cursorEncryption ? {
4626
+ ...options.cursorEncryption,
4627
+ keys: Object.fromEntries(Object.entries(options.cursorEncryption.keys).map(([id, key]) => [id, new Uint8Array(key)]))
4628
+ } : void 0;
3763
4629
  this.storage = options.storage;
3764
4630
  this.keys = new StorageKeyManager(options.namespace);
3765
- this.coordinator = new CommitCoordinator(this.storage, this.keys);
3766
- this.recovery = new RecoveryManager(this.storage, this.keys);
3767
- this.primary = new PrimaryIndex(this.storage, this.keys);
3768
- this.secondary = new SecondaryIndexManager(this.storage, this.keys);
3769
4631
  this.cursorSigningKey = options.cursorSigningKey == null ? (0, node_crypto.randomBytes)(32) : new Uint8Array(options.cursorSigningKey);
3770
4632
  if (this.cursorSigningKey.byteLength < 32) throw new Error("Cursor signing key must contain at least 32 bytes");
3771
4633
  }
4634
+ get namespace() {
4635
+ return this.keys.namespace;
4636
+ }
4637
+ static forTenant(options) {
4638
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(options.tenant)) throw new Error("Invalid tenant identifier");
4639
+ return new DuraxisDatabase({
4640
+ ...options,
4641
+ namespace: `tenants/${options.tenant}/v1`,
4642
+ accessScope: {
4643
+ tenant: options.tenant,
4644
+ currentTenant: options.currentTenant
4645
+ }
4646
+ });
4647
+ }
4648
+ assertAccess() {
4649
+ if (this.accessScope && this.accessScope.currentTenant() !== this.accessScope.tenant) throw new Error("Missing or incorrect tenant access scope");
4650
+ }
3772
4651
  async transaction(callback) {
4652
+ this.assertAccess();
3773
4653
  this.metrics.transactionsStarted++;
3774
- const snapshot = await this.acquireSnapshot();
3775
- const tx = new Transaction(this.storage, snapshot, this.keys, this.cursorSigningKey);
4654
+ const snapshot = await this.acquireSnapshot("transaction");
4655
+ const owner = this.owners.get(snapshot);
4656
+ let tx;
4657
+ try {
4658
+ tx = new Transaction(owner.storage, snapshot, this.keys, this.cursorSigningKey, owner.scope, this.resourceLimits, owner.signal, () => owner.protectPublication(), () => this.assertAccess(), {
4659
+ cursorEncryption: this.cursorEncryption,
4660
+ onPendingCleanup: (promise) => owner.holdCleanup(promise),
4661
+ onCleanupFailure: (error) => {
4662
+ if (this.cleanupFailures.length < 16) this.cleanupFailures.push(/* @__PURE__ */ new Error("Deferred query cleanup failed; inspect storage health"));
4663
+ }
4664
+ });
4665
+ } catch (error) {
4666
+ owner.finish();
4667
+ throw error;
4668
+ }
4669
+ const abort = () => tx.close();
4670
+ owner.signal.addEventListener("abort", abort, { once: true });
3776
4671
  try {
3777
- const result = await callback(tx);
4672
+ const result = await owner.wait(Promise.resolve().then(() => callback(tx)));
3778
4673
  const started = performance.now();
3779
4674
  try {
3780
- await this.coordinator.commit(tx);
4675
+ await new CommitCoordinator(owner.storage, this.keys, this.storage).commit(tx);
3781
4676
  } finally {
3782
4677
  this.metrics.commitDurationMs += performance.now() - started;
3783
4678
  }
4679
+ this.rememberOutcome(tx.id, "COMMITTED");
3784
4680
  this.metrics.transactionsCommitted++;
3785
4681
  return result;
3786
4682
  } catch (error) {
3787
4683
  if (error instanceof TransactionConflictError) this.metrics.transactionConflicts++;
3788
4684
  if (error instanceof CommitOutcomeUnknownError) this.metrics.commitOutcomesUnknown++;
4685
+ if (!(error instanceof CommitOutcomeUnknownError)) this.rememberOutcome(tx.id, "NOT_COMMITTED");
3789
4686
  tx.abort();
3790
4687
  throw error;
3791
4688
  } finally {
4689
+ owner.signal.removeEventListener("abort", abort);
3792
4690
  this.releaseSnapshot(snapshot, tx);
3793
4691
  }
3794
4692
  }
4693
+ rememberOutcome(id, status) {
4694
+ if (this.outcomes.size >= 1024) this.outcomes.delete(this.outcomes.keys().next().value);
4695
+ this.outcomes.set(id, {
4696
+ status,
4697
+ expires: Date.now() + 864e5
4698
+ });
4699
+ }
4700
+ async resolveCommitOutcome(id) {
4701
+ this.assertAccess();
4702
+ const retained = this.outcomes.get(id);
4703
+ if (retained && retained.expires > Date.now()) return retained.status;
4704
+ if (await this.transaction(async (tx) => {
4705
+ const bytes = await tx.getMetadata("idempotency");
4706
+ if (!bytes) return false;
4707
+ const entries = JSON.parse(new TextDecoder().decode(bytes));
4708
+ return Object.values(entries).some((entry) => entry.id == id && entry.expires > Date.now());
4709
+ })) return "COMMITTED";
4710
+ return await this.getCommitStatus(id) == "committed" ? "COMMITTED" : "UNKNOWN";
4711
+ }
4712
+ async transactionOnce(operationId, callback) {
4713
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(operationId)) throw new Error("Invalid idempotency identifier");
4714
+ try {
4715
+ return await this.transaction(async (tx) => {
4716
+ const bytes = await tx.getMetadata("idempotency");
4717
+ const ledger = bytes ? JSON.parse(new TextDecoder().decode(bytes)) : {};
4718
+ const existing = Object.hasOwn(ledger, operationId) ? ledger[operationId] : void 0;
4719
+ if (existing && existing.expires > Date.now()) return {
4720
+ applied: false,
4721
+ transactionId: existing.id
4722
+ };
4723
+ const live = Object.fromEntries(Object.entries(ledger).filter(([, entry]) => entry.expires > Date.now()));
4724
+ if (Object.keys(live).length >= 1024) throw new Error("Idempotency retention capacity exceeded; wait for expiration or use a separate namespace");
4725
+ const result = await callback(tx);
4726
+ Object.defineProperty(live, operationId, {
4727
+ value: {
4728
+ id: tx.id,
4729
+ expires: Date.now() + 864e5
4730
+ },
4731
+ enumerable: true
4732
+ });
4733
+ tx.putMetadata("idempotency", new TextEncoder().encode(JSON.stringify(live)));
4734
+ return {
4735
+ applied: true,
4736
+ transactionId: tx.id,
4737
+ result
4738
+ };
4739
+ });
4740
+ } catch (error) {
4741
+ if (!(error instanceof TransactionConflictError) && !(error instanceof CommitOutcomeUnknownError)) throw error;
4742
+ const receipt = await this.transaction(async (tx) => {
4743
+ const bytes = await tx.getMetadata("idempotency");
4744
+ if (!bytes) return void 0;
4745
+ const ledger = JSON.parse(new TextDecoder().decode(bytes));
4746
+ return Object.hasOwn(ledger, operationId) && ledger[operationId].expires > Date.now() ? ledger[operationId] : void 0;
4747
+ });
4748
+ if (receipt) return {
4749
+ applied: false,
4750
+ transactionId: receipt.id
4751
+ };
4752
+ throw error;
4753
+ }
4754
+ }
3795
4755
  async snapshot(callback) {
3796
4756
  const snapshot = await this.acquireSnapshot();
3797
- const tx = new Transaction(this.storage, snapshot, this.keys, this.cursorSigningKey);
4757
+ const owner = this.owners.get(snapshot);
4758
+ let tx;
4759
+ try {
4760
+ tx = new Transaction(owner.storage, snapshot, this.keys, this.cursorSigningKey, owner.scope, this.resourceLimits, owner.signal, () => owner.protectPublication(), () => this.assertAccess(), {
4761
+ cursorEncryption: this.cursorEncryption,
4762
+ onPendingCleanup: (promise) => owner.holdCleanup(promise),
4763
+ onCleanupFailure: (error) => {
4764
+ if (this.cleanupFailures.length < 16) this.cleanupFailures.push(/* @__PURE__ */ new Error("Deferred query cleanup failed; inspect storage health"));
4765
+ }
4766
+ });
4767
+ } catch (error) {
4768
+ owner.finish();
4769
+ throw error;
4770
+ }
4771
+ const abort = () => tx.close();
4772
+ owner.signal.addEventListener("abort", abort, { once: true });
3798
4773
  try {
3799
- return await callback({ get: (key) => tx.get(key) });
4774
+ return await owner.wait(Promise.resolve().then(() => callback({ get: (key) => tx.get(key) })));
3800
4775
  } finally {
4776
+ owner.signal.removeEventListener("abort", abort);
3801
4777
  this.releaseSnapshot(snapshot, tx);
3802
4778
  }
3803
4779
  }
@@ -3814,7 +4790,7 @@ var DuraxisDatabase = class {
3814
4790
  try {
3815
4791
  return Object.freeze([...snapshot.manifest.catalog.values()].map((definition) => immutableCollection(definition)).sort((left, right) => left.name.localeCompare(right.name)));
3816
4792
  } finally {
3817
- this.active.delete(snapshot);
4793
+ this.finishSnapshot(snapshot);
3818
4794
  }
3819
4795
  }
3820
4796
  async addIndex(collection, index) {
@@ -3827,65 +4803,79 @@ var DuraxisDatabase = class {
3827
4803
  }
3828
4804
  query(query, sourceOrOptions, explicitOptions) {
3829
4805
  const database = this;
3830
- return (async function* () {
4806
+ const iterator = (async function* () {
3831
4807
  const started = performance.now();
3832
4808
  database.metrics.queries++;
3833
- const snapshot = await database.acquireSnapshot();
3834
- const context = new QueryContext(database.storage, snapshot, database.keys);
4809
+ const snapshot = await database.acquireSnapshot("query");
4810
+ const context = database.queryContext(snapshot);
4811
+ context.bindCancellation(() => iterator.return(void 0));
3835
4812
  let unbindSignal = () => {};
3836
4813
  try {
3837
4814
  const explicit = database.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3838
4815
  const options = explicit ? explicitOptions : sourceOrOptions;
3839
4816
  unbindSignal = database.bindSignal(context, options?.signal);
3840
- const source = explicit ?? database.planCompiler.compile(database.planner.plan(query, context.catalog), context.catalog);
4817
+ const source = explicit ?? database.planCompiler.compile(database.planner.plan(query, context.catalog, context.limits), context.catalog);
3841
4818
  yield* new QueryExecutor(database.queryOptions(options)).execute(context, query, source);
3842
4819
  } finally {
3843
4820
  unbindSignal();
3844
4821
  database.metrics.queryDurationMs += performance.now() - started;
3845
4822
  context.close();
3846
- database.active.delete(snapshot);
4823
+ database.finishSnapshot(snapshot);
3847
4824
  }
3848
4825
  })();
4826
+ return iterator;
3849
4827
  }
3850
4828
  async queryPage(query, sourceOrOptions, explicitOptions) {
3851
4829
  const started = performance.now();
3852
4830
  this.metrics.queries++;
3853
4831
  const snapshot = await this.acquireSnapshot();
3854
- const context = new QueryContext(this.storage, snapshot, this.keys);
4832
+ const context = this.queryContext(snapshot);
3855
4833
  let unbindSignal = () => {};
3856
4834
  try {
3857
4835
  const explicit = this.isOperator(sourceOrOptions) ? sourceOrOptions : void 0;
3858
4836
  const options = explicit ? explicitOptions : sourceOrOptions;
3859
4837
  unbindSignal = this.bindSignal(context, options?.signal);
3860
- const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog), context.catalog);
4838
+ const source = explicit ?? this.planCompiler.compile(this.planner.plan(query, context.catalog, context.limits), context.catalog);
3861
4839
  return await new QueryExecutor(this.queryOptions(options)).page(context, query, source);
3862
4840
  } finally {
3863
4841
  unbindSignal();
3864
4842
  this.metrics.queryDurationMs += performance.now() - started;
3865
4843
  context.close();
3866
- this.active.delete(snapshot);
4844
+ this.finishSnapshot(snapshot);
3867
4845
  }
3868
4846
  }
3869
4847
  async queryAll(query, options) {
3870
4848
  const rows = [];
3871
- for await (const row of this.query(query, options)) rows.push(row);
3872
- return rows;
4849
+ const results = materialize(this.resources, this.resourceLimits);
4850
+ try {
4851
+ for await (const row of this.query(query, options)) {
4852
+ results.add(row);
4853
+ rows.push(row);
4854
+ }
4855
+ return rows;
4856
+ } finally {
4857
+ results.close();
4858
+ }
4859
+ }
4860
+ createMaterializationBudget() {
4861
+ return materialize(this.resources, this.resourceLimits);
3873
4862
  }
3874
4863
  async explain(query) {
3875
4864
  const snapshot = await this.acquireSnapshot();
3876
4865
  try {
3877
- return explainPhysicalPlan(this.planner.plan(query, snapshot.manifest.catalog));
4866
+ return explainPhysicalPlan(this.planner.plan(query, snapshot.manifest.catalog, this.resourceLimits));
3878
4867
  } finally {
3879
- this.active.delete(snapshot);
4868
+ this.finishSnapshot(snapshot);
3880
4869
  }
3881
4870
  }
3882
4871
  executePlan(query, plan, options) {
3883
4872
  if (plan.collection != query.collection) throw new Error("Plan and query collections differ");
3884
4873
  if (plan.limit != query.limit || JSON.stringify(plan.projection ?? null) != JSON.stringify(query.projection ?? null) || JSON.stringify(plan.requiredOrdering) != JSON.stringify(query.orderBy ?? [])) throw new Error("Physical plan is incompatible with the logical query");
3885
4874
  const database = this;
3886
- return (async function* () {
3887
- const snapshot = await database.acquireSnapshot();
3888
- const context = new QueryContext(database.storage, snapshot, database.keys);
4875
+ const iterator = (async function* () {
4876
+ const snapshot = await database.acquireSnapshot("query");
4877
+ const context = database.queryContext(snapshot);
4878
+ context.bindCancellation(() => iterator.return(void 0));
3889
4879
  const unbindSignal = database.bindSignal(context, options?.signal);
3890
4880
  try {
3891
4881
  const source = database.planCompiler.compile(plan, context.catalog);
@@ -3893,67 +4883,74 @@ var DuraxisDatabase = class {
3893
4883
  } finally {
3894
4884
  unbindSignal();
3895
4885
  context.close();
3896
- database.active.delete(snapshot);
4886
+ database.finishSnapshot(snapshot);
3897
4887
  }
3898
4888
  })();
4889
+ return iterator;
3899
4890
  }
3900
4891
  async getDocument(collection, id) {
3901
4892
  return this.transaction((tx) => tx.getDocument(collection, id));
3902
4893
  }
3903
4894
  async findByIndex(collection, indexName, value, limit = 100) {
3904
4895
  const snapshot = await this.acquireSnapshot();
4896
+ const context = this.queryContext(snapshot);
4897
+ const memory = this.createMaterializationBudget();
4898
+ const rows = [];
3905
4899
  try {
3906
- const ids = await this.secondary.lookupIds(snapshot.manifest, collection, indexName, value, limit);
3907
- const rows = [];
3908
- for (const id of ids) {
3909
- const bytes = await this.primary.read(snapshot.manifest, recordKey(collection, id));
3910
- if (bytes == null) throw new Error(`Index references missing record: ${collection}/${id}`);
3911
- rows.push({
3912
- id,
3913
- document: decodeDocument(bytes)
3914
- });
4900
+ for await (const row of context.scanIndex(collection, indexName, {
4901
+ eq: value,
4902
+ limit
4903
+ })) {
4904
+ memory.add(row);
4905
+ rows.push(row);
3915
4906
  }
3916
4907
  return rows;
3917
4908
  } finally {
3918
- this.active.delete(snapshot);
4909
+ memory.close();
4910
+ context.close();
4911
+ this.finishSnapshot(snapshot);
3919
4912
  }
3920
4913
  }
3921
4914
  async scanCollection(collection, limit = 100) {
3922
- if (!Number.isSafeInteger(limit) || limit < 0) throw new Error("Invalid scan limit");
3923
4915
  const snapshot = await this.acquireSnapshot();
4916
+ const context = this.queryContext(snapshot);
4917
+ const memory = this.createMaterializationBudget();
4918
+ const rows = [];
3924
4919
  try {
3925
- if (!snapshot.manifest.catalog.has(collection)) throw new Error(`Unknown collection: ${collection}`);
3926
- const rows = [];
3927
- if (limit == 0) return rows;
3928
- const prefix = new TextEncoder().encode(`${RECORD_PREFIX}${collection}/`);
3929
- const end = prefixSuccessor(prefix);
3930
- for await (const entry of this.primary.scanReferences(snapshot.manifest.primaryRoot, {
3931
- gte: prefix,
3932
- ...end == null ? {} : { lt: end }
3933
- })) {
3934
- const parsed = parseRecordKey(entry.key);
3935
- if (!parsed || parsed.collection != collection) continue;
3936
- rows.push({
3937
- id: parsed.id,
3938
- document: decodeDocument(await this.primary.readObject(entry.ref))
3939
- });
3940
- if (rows.length >= limit) break;
4920
+ for await (const row of context.scanCollection(collection, { limit })) {
4921
+ memory.add(row);
4922
+ rows.push(row);
3941
4923
  }
3942
4924
  return rows;
3943
4925
  } finally {
3944
- this.active.delete(snapshot);
4926
+ memory.close();
4927
+ context.close();
4928
+ this.finishSnapshot(snapshot);
3945
4929
  }
3946
4930
  }
3947
4931
  async getCommitStatus(transactionId) {
3948
- return this.recovery.getCommitStatus(transactionId);
4932
+ const snapshot = await this.acquireSnapshot();
4933
+ try {
4934
+ return await new RecoveryManager(this.owners.get(snapshot).storage, this.keys).getCommitStatus(transactionId);
4935
+ } finally {
4936
+ this.finishSnapshot(snapshot);
4937
+ }
3949
4938
  }
3950
4939
  async verifyHistory() {
3951
- return this.recovery.verifyHistory();
4940
+ const snapshot = await this.acquireSnapshot();
4941
+ try {
4942
+ return await new RecoveryManager(this.owners.get(snapshot).storage, this.keys).verifyHistory();
4943
+ } finally {
4944
+ this.finishSnapshot(snapshot);
4945
+ }
3952
4946
  }
3953
- /** Starts a new verifiable commit-history chain without changing data roots. */
3954
4947
  async checkpointHistory() {
4948
+ this.assertAccess();
3955
4949
  if (this.closed) throw new Error("Database is closed");
3956
4950
  if (this.maintenance || this.active.size || this.pendingSnapshotAcquisitions) throw new Error("History checkpoint requires exclusive database maintenance");
4951
+ const shared = storageCoordination(this.storage);
4952
+ if (shared.maintenance || shared.active) throw new Error("History checkpoint requires exclusive database maintenance");
4953
+ shared.maintenance = true;
3957
4954
  this.maintenance = true;
3958
4955
  const transactionId = (0, node_crypto.randomUUID)();
3959
4956
  try {
@@ -3983,26 +4980,29 @@ var DuraxisDatabase = class {
3983
4980
  return transactionId;
3984
4981
  } finally {
3985
4982
  this.maintenance = false;
4983
+ shared.maintenance = false;
3986
4984
  }
3987
4985
  }
3988
4986
  async verifyIntegrity() {
3989
4987
  const snapshot = await this.acquireSnapshot();
4988
+ const storage = this.owners.get(snapshot).storage;
4989
+ const primary = new PrimaryIndex(storage, this.keys);
3990
4990
  try {
3991
- const scanner = new ManifestReachabilityScanner(this.keys, this.storage);
3992
- const nodes = new BPlusTreeNodeStore(this.storage, this.keys);
4991
+ const scanner = new ManifestReachabilityScanner(this.keys, storage);
4992
+ const nodes = new BPlusTreeNodeStore(storage, this.keys);
3993
4993
  const reachable = await scanner.scan(snapshot);
3994
4994
  let objectsCount = 0;
3995
4995
  let nodesCount = 0;
3996
4996
  for (const ref of reachable) if (ref.startsWith(this.keys.objectPrefix)) {
3997
- await this.primary.readObject(ref);
4997
+ await primary.readObject(ref);
3998
4998
  objectsCount++;
3999
4999
  } else {
4000
5000
  this.keys.validateIndexNodeKey(ref);
4001
5001
  await nodes.read(ref);
4002
5002
  nodesCount++;
4003
5003
  }
4004
- const indexes = await new IndexConsistencyChecker(this.storage, this.keys).verify(snapshot.manifest);
4005
- const commits = await this.recovery.verifyHistory();
5004
+ const indexes = await new IndexConsistencyChecker(storage, this.keys).verify(snapshot.manifest);
5005
+ const commits = await new RecoveryManager(storage, this.keys).verifyHistory();
4006
5006
  return {
4007
5007
  objects: objectsCount,
4008
5008
  nodes: nodesCount,
@@ -4010,10 +5010,11 @@ var DuraxisDatabase = class {
4010
5010
  commits
4011
5011
  };
4012
5012
  } finally {
4013
- this.active.delete(snapshot);
5013
+ this.finishSnapshot(snapshot);
4014
5014
  }
4015
5015
  }
4016
5016
  async collectGarbage(storage, options = {}) {
5017
+ this.assertAccess();
4017
5018
  const started = performance.now();
4018
5019
  this.metrics.garbageCollections++;
4019
5020
  if (storage != this.storage) throw new Error("GC driver must match database storage");
@@ -4021,47 +5022,107 @@ var DuraxisDatabase = class {
4021
5022
  this.maintenance = true;
4022
5023
  try {
4023
5024
  if (options.dryRun == false && (this.active.size > 0 || this.pendingSnapshotAcquisitions > 0)) throw new Error("Active transactions or pending snapshots prevent GC");
4024
- return await new GarbageCollector(this.storage, this.keys, () => [...this.active]).collect(options);
5025
+ return await new GarbageCollector(this.storage, this.keys, () => [...this.active], new ManifestReachabilityScanner(this.keys, this.storage), this.resources).collect(options);
4025
5026
  } finally {
4026
5027
  this.metrics.garbageCollectionDurationMs += performance.now() - started;
4027
5028
  this.maintenance = false;
4028
5029
  }
4029
5030
  }
5031
+ finishSnapshot(snapshot) {
5032
+ this.owners.get(snapshot)?.finish();
5033
+ }
5034
+ queryContext(snapshot) {
5035
+ const owner = this.owners.get(snapshot);
5036
+ let context;
5037
+ const abort = () => context.cancel(owner.signal.reason);
5038
+ try {
5039
+ context = new QueryContext(owner.storage, snapshot, this.keys, {
5040
+ resources: owner.scope,
5041
+ limits: this.resourceLimits,
5042
+ assertAccess: () => this.assertAccess(),
5043
+ onPendingCleanup: (promise) => owner.holdCleanup(promise),
5044
+ onCleanupFailure: (error) => {
5045
+ if (this.cleanupFailures.length < 16) this.cleanupFailures.push(/* @__PURE__ */ new Error("Deferred query cleanup failed; inspect storage health"));
5046
+ },
5047
+ onClose: () => {
5048
+ owner.signal.removeEventListener("abort", abort);
5049
+ owner.finish();
5050
+ }
5051
+ });
5052
+ } catch (error) {
5053
+ owner.finish();
5054
+ throw error;
5055
+ }
5056
+ owner.signal.addEventListener("abort", abort, { once: true });
5057
+ if (owner.signal.aborted) abort();
5058
+ return context;
5059
+ }
4030
5060
  releaseSnapshot(snapshot, tx) {
4031
5061
  tx.close();
4032
- if (!tx.hasPendingReads) {
4033
- this.active.delete(snapshot);
4034
- return;
4035
- }
4036
- tx.waitForReads().then(() => {
4037
- this.active.delete(snapshot);
4038
- });
5062
+ this.finishSnapshot(snapshot);
4039
5063
  }
4040
5064
  queryOptions(options) {
4041
5065
  return {
4042
5066
  ...options,
4043
- cursorSigningKey: options?.cursorSigningKey ?? this.cursorSigningKey
5067
+ cursorSigningKey: this.cursorSigningKey,
5068
+ cursorEncryption: this.cursorEncryption,
5069
+ cursorNamespace: this.keys.namespace
4044
5070
  };
4045
5071
  }
4046
5072
  bindSignal(context, signal) {
4047
5073
  if (!signal) return () => {};
4048
5074
  const cancel = () => context.cancel(signal.reason ?? /* @__PURE__ */ new Error("Query cancelled"));
4049
- if (signal.aborted) cancel();
5075
+ if (signal.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Query cancelled");
4050
5076
  else signal.addEventListener("abort", cancel, { once: true });
4051
5077
  return () => signal.removeEventListener("abort", cancel);
4052
5078
  }
4053
5079
  isOperator(value) {
4054
5080
  return value != null && typeof value.execute == "function";
4055
5081
  }
4056
- async acquireSnapshot() {
5082
+ async acquireSnapshot(kind = "snapshot") {
5083
+ this.assertAccess();
4057
5084
  if (this.closed) throw new Error("Database is closed");
4058
- if (this.maintenance) throw new Error("Database is in exclusive maintenance mode");
5085
+ if (this.maintenance || storageCoordination(this.storage).maintenance) throw new Error("Database is in exclusive maintenance mode");
5086
+ const scope = this.resources.child({ workingBytes: kind == "query" ? this.resourceLimits.maxQueryWorkingBytes : this.resourceLimits.maxTransactionWorkingBytes });
5087
+ try {
5088
+ scope.reserve({ snapshots: 1 });
5089
+ } catch (error) {
5090
+ scope.close();
5091
+ throw error;
5092
+ }
5093
+ const shared = storageCoordination(this.storage);
5094
+ shared.active++;
5095
+ let snapshot;
5096
+ 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), () => {
5097
+ if (snapshot) {
5098
+ this.active.delete(snapshot);
5099
+ this.owners.delete(snapshot);
5100
+ shared.snapshots.delete(snapshot);
5101
+ }
5102
+ shared.active--;
5103
+ this.operations.delete(owner);
5104
+ if (!this.operations.size) for (const resolve of [...this.drainWaiters]) resolve();
5105
+ }, this.resourceLimits.maxStorageReadBytes);
5106
+ this.operations.add(owner);
4059
5107
  this.pendingSnapshotAcquisitions++;
4060
5108
  try {
4061
- const snapshot = await this.createSnapshot();
4062
- if (this.maintenance) throw new Error("Database is in exclusive maintenance mode");
5109
+ const stored = await owner.wait(owner.storage.get(this.keys.manifestKey));
5110
+ if (this.maintenance || this.closed) throw new Error("Database is not accepting snapshots");
5111
+ snapshot = stored == null ? {
5112
+ manifest: emptyManifest(),
5113
+ storageVersion: null
5114
+ } : {
5115
+ manifest: decodeManifest(stored.data, this.keys),
5116
+ storageVersion: stored.version
5117
+ };
5118
+ scope.reserve({ workingBytes: estimateBytes([...snapshot.manifest.catalog]) + estimateBytes([...snapshot.manifest.indexRoots]) });
4063
5119
  this.active.add(snapshot);
5120
+ shared.snapshots.add(snapshot);
5121
+ this.owners.set(snapshot, owner);
4064
5122
  return snapshot;
5123
+ } catch (error) {
5124
+ owner.finish();
5125
+ throw error;
4065
5126
  } finally {
4066
5127
  this.pendingSnapshotAcquisitions--;
4067
5128
  }
@@ -4069,14 +5130,37 @@ var DuraxisDatabase = class {
4069
5130
  getMetrics() {
4070
5131
  return {
4071
5132
  ...this.metrics,
5133
+ resources: this.resources.metrics(),
4072
5134
  ...this.storage.getMetrics ? { storage: this.storage.getMetrics() } : {}
4073
5135
  };
4074
5136
  }
4075
- async close(options = {}) {
4076
- if (this.closed) return;
4077
- if (this.active.size || this.pendingSnapshotAcquisitions) throw new Error("Cannot close database with active transactions or queries");
5137
+ close(options = {}) {
5138
+ if (this.closePromise) return this.closePromise;
4078
5139
  this.closed = true;
4079
- if (options.closeStorage) await this.storage.close?.();
5140
+ const timeout = options.timeoutMs ?? 3e4;
5141
+ if (!Number.isSafeInteger(timeout) || timeout < 1) return Promise.reject(/* @__PURE__ */ new RangeError("Invalid shutdown deadline"));
5142
+ this.closePromise = (async () => {
5143
+ for (const owner of this.operations) owner.cancel(new OperationCancelledError("Database is shutting down"));
5144
+ if (this.operations.size) await new Promise((resolve, reject) => {
5145
+ const complete = () => {
5146
+ clearTimeout(timer);
5147
+ this.drainWaiters.delete(complete);
5148
+ resolve();
5149
+ };
5150
+ const timer = setTimeout(() => {
5151
+ this.drainWaiters.delete(complete);
5152
+ reject(new OperationCancelledError(`Shutdown deadline exceeded; ${this.operations.size} operations still protect storage. Storage was not closed`));
5153
+ }, timeout);
5154
+ this.drainWaiters.add(complete);
5155
+ if (!this.operations.size) complete();
5156
+ });
5157
+ if (options.closeStorage) await this.storage.close?.();
5158
+ if (this.cleanupFailures.length) throw new AggregateError(this.cleanupFailures.splice(0), "Deferred query cleanup failed");
5159
+ })();
5160
+ this.closePromise.catch(() => {
5161
+ this.closePromise = void 0;
5162
+ });
5163
+ return this.closePromise;
4080
5164
  }
4081
5165
  async createSnapshot() {
4082
5166
  const stored = await this.storage.get(this.keys.manifestKey);
@@ -4102,6 +5186,160 @@ var ReferenceQueryExecutor = class {
4102
5186
  return this.executor.page(context, query, new CollectionScan(query.collection));
4103
5187
  }
4104
5188
  };
5189
+ // src/config.ts
5190
+ var CONFIGURATION = Symbol.for("@duraxis/core/configuration");
5191
+ function isDuraxisConfiguration(value) {
5192
+ return typeof value === "object" && value !== null && Reflect.get(value, CONFIGURATION) === true;
5193
+ }
5194
+ function validateConnections(config) {
5195
+ if (!config.connections || typeof config.connections !== "object" || Array.isArray(config.connections)) throw new TypeError("Invalid Duraxis connections map");
5196
+ const prefixes = /* @__PURE__ */ new Set();
5197
+ for (const name of Object.keys(config.connections)) {
5198
+ validateConnectionName(name);
5199
+ const prefix = name.toUpperCase().replace(/-/g, "_");
5200
+ if (prefixes.has(prefix)) throw new Error("Connection names collide after environment variable normalization");
5201
+ prefixes.add(prefix);
5202
+ if (!config.connections[name] || typeof config.connections[name] !== "object") throw new TypeError(`Invalid Duraxis connection: ${name}`);
5203
+ const connection = config.connections[name];
5204
+ if (Object.keys(config.connections).length > 1 && connection.autoLoadEntities && (connection.autoLoadEntities === true || !connection.autoLoadEntities.directories?.length) && connection.entities === void 0) throw new Error(`Connection ${name} requires explicit discovery directories or entities in a multi-connection configuration`);
5205
+ }
5206
+ }
5207
+ function defineDuraxisConfig(config) {
5208
+ if (!config || typeof config !== "object") throw new TypeError("Invalid Duraxis configuration");
5209
+ if ("connections" in config) {
5210
+ validateConnections(config);
5211
+ const names = Object.keys(config.connections);
5212
+ if (!names.length) throw new Error("At least one Duraxis connection is required");
5213
+ for (const name of names) validateConnectionName(name);
5214
+ selectDuraxisConnection(config);
5215
+ } else if (!config || !config.driver) throw new Error("A Duraxis storage driver is required");
5216
+ Object.defineProperty(config, CONFIGURATION, { value: true });
5217
+ return config;
5218
+ }
5219
+ function validateConnectionName(name) {
5220
+ if (!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(name) || [
5221
+ "constructor",
5222
+ "prototype",
5223
+ "__proto__"
5224
+ ].includes(name)) throw new Error("Invalid Duraxis connection name");
5225
+ return name;
5226
+ }
5227
+ function selectDuraxisConnection(config, name) {
5228
+ if (!("connections" in config)) {
5229
+ if (name && name !== (config.name ?? "default")) throw new Error(`Unknown Duraxis connection: ${name}`);
5230
+ return config;
5231
+ }
5232
+ validateConnections(config);
5233
+ const selected = name ?? config.defaultConnection ?? Object.keys(config.connections).sort()[0];
5234
+ validateConnectionName(selected);
5235
+ if (!Object.hasOwn(config.connections, selected)) throw new Error(`Unknown Duraxis connection: ${selected}`);
5236
+ return {
5237
+ ...config.connections[selected],
5238
+ name: selected
5239
+ };
5240
+ }
5241
+ function duraxisDriverContext(options) {
5242
+ const directory = options.location ? (0, node_path.dirname)(options.location instanceof URL || options.location.startsWith("file:") ? (0, node_url.fileURLToPath)(options.location) : (0, node_path.resolve)(options.location)) : (0, node_path.resolve)(options.baseDirectory ?? ".");
5243
+ let root = directory;
5244
+ if (options.baseDirectory) root = (0, node_path.resolve)(directory, options.baseDirectory);
5245
+ else while (!(0, node_fs.existsSync)((0, node_path.resolve)(root, "package.json")) && (0, node_path.dirname)(root) !== root) root = (0, node_path.dirname)(root);
5246
+ if ((0, node_path.dirname)(root) === root && !(0, node_fs.existsSync)((0, node_path.resolve)(root, "package.json"))) root = directory;
5247
+ const name = validateConnectionName(options.name ?? "default");
5248
+ const prefix = name === "default" ? "DURAXIS" : `DURAXIS_${name.toUpperCase().replace(/-/g, "_")}`;
5249
+ const env = Object.fromEntries([
5250
+ "NAMESPACE",
5251
+ "STORAGE_DIRECTORY",
5252
+ "S3_BUCKET",
5253
+ "S3_PREFIX",
5254
+ "S3_ENDPOINT"
5255
+ ].map((key) => [key, process.env[`${prefix}_${key}`]]));
5256
+ return {
5257
+ root,
5258
+ directory,
5259
+ env,
5260
+ resolvePath: (path) => (0, node_path.isAbsolute)(path) ? path : (0, node_path.resolve)(root, path)
5261
+ };
5262
+ }
5263
+ function normalizeDuraxisConnection(options) {
5264
+ if (!options || typeof options.driver !== "function" && (typeof options.driver !== "object" || !options.driver)) throw new TypeError("Invalid Duraxis driver");
5265
+ if (options.migrations !== void 0 && typeof options.migrations !== "boolean" && (typeof options.migrations !== "object" || options.migrations === null || Array.isArray(options.migrations))) throw new TypeError("Invalid Duraxis migrations configuration");
5266
+ if (typeof options.migrations === "object") {
5267
+ for (const key of ["directory", "snapshots"]) if (options.migrations[key] !== void 0 && (typeof options.migrations[key] !== "string" || !options.migrations[key].trim())) throw new TypeError(`Invalid migration ${key}`);
5268
+ if (options.migrations.format !== void 0 && ![
5269
+ "ts",
5270
+ "js",
5271
+ "mts",
5272
+ "mjs"
5273
+ ].includes(options.migrations.format)) throw new TypeError("Invalid migration format");
5274
+ }
5275
+ if (options.schema && ![
5276
+ "create",
5277
+ "validate",
5278
+ "validate-managed"
5279
+ ].includes(options.schema.mode)) throw new TypeError("Invalid schema mode");
5280
+ if (options.autoLoadEntities !== void 0 && typeof options.autoLoadEntities !== "boolean" && (typeof options.autoLoadEntities !== "object" || !options.autoLoadEntities || Array.isArray(options.autoLoadEntities))) throw new TypeError("Invalid entity discovery options");
5281
+ if (typeof options.autoLoadEntities === "object" && options.autoLoadEntities.directories !== void 0 && (!Array.isArray(options.autoLoadEntities.directories) || !options.autoLoadEntities.directories.length || options.autoLoadEntities.directories.some((path) => typeof path !== "string" || !path.trim()))) throw new TypeError("Entity directories must be a nonempty array of paths");
5282
+ const context = duraxisDriverContext(options);
5283
+ if (options.migrations && options.schema?.mode === "create") throw new Error("Migrations require schema validation; automatic creation is disabled");
5284
+ const migrationOptions = typeof options.migrations === "object" ? options.migrations : {};
5285
+ const base = options.name && options.name !== "default" ? `duraxis/${validateConnectionName(options.name)}` : "duraxis";
5286
+ const database = {
5287
+ ...options.name && options.name !== "default" ? { namespace: options.name } : {},
5288
+ ...options.database,
5289
+ ...context.env.NAMESPACE !== void 0 ? { namespace: context.env.NAMESPACE } : {}
5290
+ };
5291
+ if (options.cursorKeyEnv) {
5292
+ const key = process.env[options.cursorKeyEnv];
5293
+ if (!key || !/^[a-fA-F0-9]{64}$/.test(key)) throw new Error(`Provision ${options.cursorKeyEnv} as 32 secret bytes encoded as hex`);
5294
+ database.cursorEncryption = {
5295
+ activeKeyId: "configured",
5296
+ keys: { configured: Buffer.from(key, "hex") }
5297
+ };
5298
+ }
5299
+ return {
5300
+ ...options,
5301
+ context,
5302
+ database,
5303
+ schema: options.schema ?? { mode: options.migrations ? "validate-managed" : "validate" },
5304
+ migrations: options.migrations ? {
5305
+ directory: context.resolvePath(migrationOptions.directory ?? `${base}/migrations`),
5306
+ snapshots: context.resolvePath(migrationOptions.snapshots ?? `${base}/snapshots`),
5307
+ format: migrationOptions.format ?? (options.location?.toString().match(/\.[cm]?js$/) ? "mjs" : "mts")
5308
+ } : void 0
5309
+ };
5310
+ }
5311
+ var ConfiguredDatabase = class extends DuraxisDatabase {
5312
+ owned;
5313
+ constructor(options, owned) {
5314
+ super(options);
5315
+ this.owned = owned;
5316
+ }
5317
+ close(options = {}) {
5318
+ return super.close({
5319
+ closeStorage: this.owned,
5320
+ ...options
5321
+ });
5322
+ }
5323
+ };
5324
+ async function createDatabase(config, name) {
5325
+ const options = normalizeDuraxisConnection(selectDuraxisConnection(config, name));
5326
+ const owned = options.closeStorage ?? typeof options.driver === "function";
5327
+ const driver = typeof options.driver === "function" ? await options.driver(options.context) : options.driver;
5328
+ try {
5329
+ if (!driver || driver.capabilities?.boundedReads !== true) throw new Error("Duraxis storage requires verified bounded-read support");
5330
+ return new ConfiguredDatabase({
5331
+ ...options.database,
5332
+ storage: driver
5333
+ }, owned);
5334
+ } catch (cause) {
5335
+ if (owned && driver?.close) try {
5336
+ await driver.close();
5337
+ } catch (cleanup) {
5338
+ throw new AggregateError([cause, cleanup], "Database initialization and cleanup failed");
5339
+ }
5340
+ throw cause;
5341
+ }
5342
+ }
4105
5343
  exports.AccessPathEnumerator = AccessPathEnumerator;
4106
5344
  exports.BPlusTree = BPlusTree;
4107
5345
  exports.BPlusTreeNodeCache = BPlusTreeNodeCache;
@@ -4109,6 +5347,7 @@ exports.BPlusTreeNodeStore = BPlusTreeNodeStore;
4109
5347
  exports.BPlusTreeValidator = BPlusTreeValidator;
4110
5348
  exports.CollectionScan = CollectionScan;
4111
5349
  exports.CommitOutcomeUnknownError = CommitOutcomeUnknownError;
5350
+ exports.DEFAULT_RESOURCE_LIMITS = DEFAULT_RESOURCE_LIMITS;
4112
5351
  exports.Difference = Difference;
4113
5352
  exports.DuraxisDatabase = DuraxisDatabase;
4114
5353
  exports.Filter = Filter;
@@ -4120,6 +5359,7 @@ exports.InvalidForeignKeyDefinitionError = InvalidForeignKeyDefinitionError;
4120
5359
  exports.Limit = Limit;
4121
5360
  exports.ManifestReachabilityScanner = ManifestReachabilityScanner;
4122
5361
  exports.ManifestSnapshotReader = ManifestSnapshotReader;
5362
+ exports.OperationCancelledError = OperationCancelledError;
4123
5363
  exports.PlanCompiler = PlanCompiler;
4124
5364
  exports.PredicateAnalyzer = PredicateAnalyzer;
4125
5365
  exports.PrimaryIndex = PrimaryIndex;
@@ -4132,6 +5372,8 @@ exports.RecoveryManager = RecoveryManager;
4132
5372
  exports.ReferenceQueryExecutor = ReferenceQueryExecutor;
4133
5373
  exports.ReferencedRecordNotFoundError = ReferencedRecordNotFoundError;
4134
5374
  exports.ReferencedRecordRestrictedError = ReferencedRecordRestrictedError;
5375
+ exports.ResourceExhaustedError = ResourceExhaustedError;
5376
+ exports.ResourceScope = ResourceScope;
4135
5377
  exports.RuleBasedPlanner = RuleBasedPlanner;
4136
5378
  exports.SecondaryIndexManager = SecondaryIndexManager;
4137
5379
  exports.SecondaryIndexRangeScan = SecondaryIndexRangeScan;
@@ -4147,14 +5389,18 @@ exports.compareBytes = compareBytes;
4147
5389
  exports.compareIndexScalars = compareIndexScalars;
4148
5390
  exports.compareRows = compareRows;
4149
5391
  exports.compositePrefixBounds = compositePrefixBounds;
5392
+ exports.createDatabase = createDatabase;
4150
5393
  exports.decodeDocument = decodeDocument;
4151
5394
  exports.decodeQueryCursor = decodeQueryCursor;
5395
+ exports.defineDuraxisConfig = defineDuraxisConfig;
5396
+ exports.duraxisDriverContext = duraxisDriverContext;
4152
5397
  exports.encodeCompositeKey = encodeCompositeKey;
4153
5398
  exports.encodeDocument = encodeDocument;
4154
5399
  exports.encodeIdentifier = encodeIdentifier;
4155
5400
  exports.encodeQueryCursor = encodeQueryCursor;
4156
5401
  exports.encodeScalar = encodeScalar;
4157
5402
  exports.encodeSecondaryKey = encodeSecondaryKey;
5403
+ exports.estimateBytes = estimateBytes;
4158
5404
  exports.evaluatePredicate = evaluatePredicate;
4159
5405
  exports.explainPhysicalPlan = explainPhysicalPlan;
4160
5406
  exports.fieldDefinition = fieldDefinition;
@@ -4162,13 +5408,19 @@ exports.indexFields = indexFields;
4162
5408
  exports.indexId = indexId;
4163
5409
  exports.indexRangeBounds = indexRangeBounds;
4164
5410
  exports.indexedValue = indexedValue;
5411
+ exports.isDuraxisConfiguration = isDuraxisConfiguration;
5412
+ exports.materialize = materialize;
4165
5413
  exports.normalizeCollection = normalizeCollection;
5414
+ exports.normalizeDuraxisConnection = normalizeDuraxisConnection;
4166
5415
  exports.parseRecordKey = parseRecordKey;
4167
5416
  exports.prefixBounds = prefixBounds;
4168
5417
  exports.prefixSuccessor = prefixSuccessor;
4169
5418
  exports.recordKey = recordKey;
5419
+ exports.resourceLimits = resourceLimits;
4170
5420
  exports.secondaryIndexBounds = secondaryIndexBounds;
5421
+ exports.selectDuraxisConnection = selectDuraxisConnection;
4171
5422
  exports.validateCollection = validateCollection;
5423
+ exports.validateConnectionName = validateConnectionName;
4172
5424
  exports.validateDocument = validateDocument;
4173
5425
  exports.validateQuery = validateQuery;
4174
5426