@duraxis/core 0.2.2 → 0.4.0

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