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