defuss-dbsonl 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5,6 +5,151 @@ var backend = require('./backend-CU4f3EUz.cjs');
5
5
  var common = require('./common-2ybGl1zj.cjs');
6
6
  require('defuss-storage');
7
7
 
8
+ const STRING = 14, FLOAT64 = 15, ARRAY = 17, OBJECT = 18;
9
+ const utf16 = (text) => {
10
+ const bytes = new Uint8Array(4 + text.length * 2);
11
+ new DataView(bytes.buffer).setUint32(0, text.length, true);
12
+ for (let i = 0; i < text.length; i++) {
13
+ const code = text.charCodeAt(i);
14
+ bytes[4 + 2 * i] = code & 255;
15
+ bytes[5 + 2 * i] = code >>> 8;
16
+ }
17
+ return bytes;
18
+ };
19
+ const NAMES = new Map(["kind", "entries", "children", "key", "ref", "revision", "max", "count", "offset", "byteLength"].map((name) => [name, utf16(name)]));
20
+ const INDEX = Array.from({ length: 64 }, (_, i) => utf16(String(i)));
21
+ const CRC = new Int32Array(16 * 256);
22
+ for (let n = 0; n < 256; n++) {
23
+ let crc = n;
24
+ for (let i = 0; i < 8; i++) crc = crc >>> 1 ^ (crc & 1) * 2197175160;
25
+ CRC[n] = crc;
26
+ }
27
+ for (let n = 0; n < 256; n++) for (let k = 1; k < 16; k++) CRC[k * 256 + n] = CRC[(k - 1) * 256 + n] >>> 8 ^ CRC[CRC[(k - 1) * 256 + n] & 255];
28
+ function checksum(b, start, end) {
29
+ let crc = -1, i = start;
30
+ for (; i + 16 <= end; i += 16) {
31
+ const low = crc ^ (b[i] | b[i + 1] << 8 | b[i + 2] << 16 | b[i + 3] << 24);
32
+ crc = CRC[3840 + (low & 255)] ^ CRC[3584 + (low >>> 8 & 255)] ^ CRC[3328 + (low >>> 16 & 255)] ^ CRC[3072 + (low >>> 24)] ^ CRC[2816 + b[i + 4]] ^ CRC[2560 + b[i + 5]] ^ CRC[2304 + b[i + 6]] ^ CRC[2048 + b[i + 7]] ^ CRC[1792 + b[i + 8]] ^ CRC[1536 + b[i + 9]] ^ CRC[1280 + b[i + 10]] ^ CRC[1024 + b[i + 11]] ^ CRC[768 + b[i + 12]] ^ CRC[512 + b[i + 13]] ^ CRC[256 + b[i + 14]] ^ CRC[b[i + 15]];
33
+ }
34
+ for (; i < end; i++) crc = crc >>> 8 ^ CRC[(crc ^ b[i]) & 255];
35
+ return ~crc >>> 0;
36
+ }
37
+ const generic = new Error("generic");
38
+ const values = [], tags = [], starts = [], counts = [], names = [], refs = [];
39
+ const ids = /* @__PURE__ */ new Map();
40
+ function encodePage(page, maxRecordBytes) {
41
+ let used = 0, pairs = 0, size = 8;
42
+ const primitive = (value) => {
43
+ if (!(value === 0 && 1 / value < 0)) {
44
+ const id = ids.get(value);
45
+ if (id !== void 0) return id;
46
+ ids.set(value, used);
47
+ }
48
+ values[used] = value;
49
+ if (typeof value === "string") {
50
+ tags[used] = STRING;
51
+ size += 5 + value.length * 2;
52
+ } else {
53
+ tags[used] = FLOAT64;
54
+ size += 9;
55
+ }
56
+ return used++;
57
+ };
58
+ const container = (value) => {
59
+ values[used] = value;
60
+ tags[used] = Array.isArray(value) ? ARRAY : OBJECT;
61
+ return used++;
62
+ };
63
+ try {
64
+ container(page);
65
+ for (let i = 0; i < used; i++) {
66
+ const tag = tags[i];
67
+ if (tag !== OBJECT && tag !== ARRAY) continue;
68
+ const item = values[i];
69
+ starts[i] = pairs;
70
+ if (tag === ARRAY) {
71
+ const list = item;
72
+ size += 9;
73
+ for (let j = 0; j < list.length; j++) {
74
+ const member = list[j];
75
+ if (typeof member !== "object" || member === null) throw generic;
76
+ const name = INDEX[j] ?? utf16(String(j));
77
+ names[pairs] = name;
78
+ refs[pairs++] = container(member);
79
+ size += name.length + 4;
80
+ }
81
+ } else {
82
+ size += 5;
83
+ for (const key in item) {
84
+ const name = NAMES.get(key), member = item[key];
85
+ if (!name) throw generic;
86
+ const type = typeof member;
87
+ names[pairs] = name;
88
+ refs[pairs++] = type === "string" || type === "number" ? primitive(member) : type === "object" && member !== null ? container(member) : (() => {
89
+ throw generic;
90
+ })();
91
+ size += name.length + 4;
92
+ }
93
+ }
94
+ counts[i] = pairs - starts[i];
95
+ }
96
+ if (size > maxRecordBytes) throw generic;
97
+ const bytes = new Uint8Array(16 + size), view = new DataView(bytes.buffer);
98
+ bytes[16] = 68;
99
+ bytes[17] = 83;
100
+ bytes[18] = 66;
101
+ bytes[19] = 1;
102
+ view.setUint32(20, used, true);
103
+ let p = 24;
104
+ for (let i = 0; i < used; i++) {
105
+ const tag = tags[i];
106
+ bytes[p++] = tag;
107
+ if (tag === STRING) {
108
+ const text = values[i];
109
+ view.setUint32(p, text.length, true);
110
+ p += 4;
111
+ for (let k = 0; k < text.length; k++) {
112
+ const code = text.charCodeAt(k);
113
+ bytes[p++] = code & 255;
114
+ bytes[p++] = code >>> 8;
115
+ }
116
+ } else if (tag === FLOAT64) {
117
+ view.setFloat64(p, values[i], true);
118
+ p += 8;
119
+ } else {
120
+ if (tag === ARRAY) {
121
+ view.setUint32(p, values[i].length, true);
122
+ p += 4;
123
+ }
124
+ const start = starts[i], end = start + counts[i];
125
+ view.setUint32(p, end - start, true);
126
+ p += 4;
127
+ for (let j = start; j < end; j++) {
128
+ const name = names[j];
129
+ for (let x = 0; x < name.length; x++) bytes[p + x] = name[x];
130
+ p += name.length;
131
+ view.setUint32(p, refs[j], true);
132
+ p += 4;
133
+ }
134
+ }
135
+ }
136
+ bytes[0] = 68;
137
+ bytes[1] = 83;
138
+ bytes[2] = 81;
139
+ bytes[3] = 1;
140
+ view.setUint32(4, size, true);
141
+ view.setUint32(8, checksum(bytes, 16, 16 + size), true);
142
+ view.setUint32(12, checksum(bytes, 0, 12), true);
143
+ return bytes;
144
+ } catch (error) {
145
+ if (error === generic) return sequence.encodeFrame(page, { maxRecordBytes, trusted: true });
146
+ throw error;
147
+ } finally {
148
+ ids.clear();
149
+ values.fill(void 0, 0, used);
150
+ }
151
+ }
152
+
8
153
  const SLOT_BYTES = 4096;
9
154
  const generationFile = (name, generation) => `${name}.g-${generation}.dsq`;
10
155
  const headFile = (name) => `${name}.head`;
@@ -66,33 +211,38 @@ async function readHead(backend$1, name, cache) {
66
211
  }
67
212
  return head;
68
213
  }
69
- async function publish(backend$1, name, head) {
214
+ async function publish(backend$1, name, head, cache) {
70
215
  common.natural(head.publication, "publication", 1);
71
- const bytes = sequence.encodeFrame(head, { maxRecordBytes: SLOT_BYTES - 16 });
216
+ const bytes = sequence.encodeFrame(head, { maxRecordBytes: SLOT_BYTES - 16, trusted: true });
72
217
  const slot = new Uint8Array(SLOT_BYTES);
73
218
  slot.set(bytes);
74
- await backend.withFile(backend$1, headFile(name), { create: true }, async (file) => {
75
- await backend.writeBytes(file, head.publication % 2 * SLOT_BYTES, slot, backend$1.writeChunkBytes);
219
+ const offset = head.publication % 2 * SLOT_BYTES;
220
+ await backend.withFile(backend$1, headFile(name), {}, async (file) => {
221
+ await backend.writeBytes(file, offset, slot, backend$1.writeChunkBytes);
76
222
  await file.flush();
77
223
  });
78
- await backend$1.coordinator.syncDirectory();
224
+ if (cache?.bytes?.length === SLOT_BYTES * 2) {
225
+ const next = cache.bytes.slice();
226
+ next.set(slot, offset);
227
+ cache.bytes = next;
228
+ cache.head = head;
229
+ }
79
230
  }
80
231
  const PAGE_BYTES = 512 * 1024;
81
232
  async function readValue(backend$1, name, head, ref, maxRecordBytes, window) {
82
233
  common.reference(ref, head.end);
83
234
  if (ref.byteLength - 16 > maxRecordBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
84
235
  let bytes;
85
- if (window?.bytes && window.offset !== void 0 && ref.offset >= window.offset && ref.offset + ref.byteLength <= window.offset + window.bytes.length) {
236
+ if (window && windowContains(window, ref)) {
86
237
  bytes = window.bytes.subarray(ref.offset - window.offset, ref.offset - window.offset + ref.byteLength);
87
238
  } else {
88
- const length = backend$1.read && window && ref.byteLength <= 65536 ? Math.min(65536, head.end - ref.offset) : ref.byteLength;
239
+ const length = window && ref.byteLength <= 65536 ? Math.min(65536, head.end - ref.offset) : ref.byteLength;
89
240
  const filename = generationFile(name, head.generation);
90
241
  const data = backend$1.read ? await backend$1.read(filename, ref.offset, length) : (
91
- // Portable handles also benefit from known, bounded reference lengths:
92
- // fetch header and payload together rather than allocate and copy twice.
242
+ // Portable handles read the same bounded window, so a scan opens the file once per window, not per row.
93
243
  await backend.withFile(backend$1, filename, { readOnly: true }, (file) => readExact(file, ref.offset, length))
94
244
  );
95
- if (window && backend$1.read) {
245
+ if (window) {
96
246
  window.offset = ref.offset;
97
247
  window.bytes = length <= 65536 ? data : new Uint8Array(0);
98
248
  }
@@ -100,6 +250,28 @@ async function readValue(backend$1, name, head, ref, maxRecordBytes, window) {
100
250
  }
101
251
  return decodeRef(bytes, ref, maxRecordBytes);
102
252
  }
253
+ function windowContains(window, ref) {
254
+ return !!window.bytes && window.offset !== void 0 && ref.offset >= window.offset && ref.offset + ref.byteLength <= window.offset + window.bytes.length;
255
+ }
256
+ function readCachedValue(head, ref, maxRecordBytes, window) {
257
+ common.reference(ref, head.end);
258
+ if (ref.byteLength - 16 > maxRecordBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
259
+ return decodeRef(window.bytes.subarray(ref.offset - window.offset, ref.offset - window.offset + ref.byteLength), ref, maxRecordBytes);
260
+ }
261
+ function readCachedValues(entries, start, end, maxRecordBytes, window) {
262
+ try {
263
+ const offsets = [];
264
+ for (let i = start; i < end; i++) offsets.push(entries[i].ref.offset - window.offset);
265
+ const frames = sequence.decodeFrames(window.bytes, offsets, { maxRecordBytes, maxDepth: 512, maxReferences: 1e6 }), values = [];
266
+ for (let i = 0; i < frames.length; i++) {
267
+ if (frames[i].byteLength !== entries[start + i].ref.byteLength) return [];
268
+ values.push(frames[i].value);
269
+ }
270
+ return values;
271
+ } catch {
272
+ return [];
273
+ }
274
+ }
103
275
  function decodeRef(bytes, ref, maxRecordBytes) {
104
276
  if (bytes.length !== ref.byteLength) common.corrupt("Committed record is truncated.");
105
277
  try {
@@ -134,10 +306,20 @@ class Appender {
134
306
  this.flushedEnd += this.used;
135
307
  this.used = 0;
136
308
  }
137
- async bytes(bytes) {
309
+ /** Synchronous unless the buffer must be written first; most frames only need a copy. */
310
+ bytes(bytes) {
138
311
  const ref = { offset: this.end, byteLength: bytes.length };
139
312
  common.natural(this.end + bytes.length, "file end");
140
- if (bytes.length > this.buffer.length - this.used) await this.flush();
313
+ if (bytes.length <= this.buffer.length - this.used) {
314
+ this.buffer.set(bytes, this.used);
315
+ this.used += bytes.length;
316
+ this.end += bytes.length;
317
+ return ref;
318
+ }
319
+ return this.spill(bytes, ref);
320
+ }
321
+ async spill(bytes, ref) {
322
+ await this.flush();
141
323
  if (bytes.length > this.buffer.length) {
142
324
  await backend.writeBytes(this.file, this.end, bytes, this.chunkSize);
143
325
  this.flushedEnd += bytes.length;
@@ -149,7 +331,7 @@ class Appender {
149
331
  return ref;
150
332
  }
151
333
  async value(value, page = false) {
152
- return this.bytes(sequence.encodeFrame(value, { maxRecordBytes: page ? PAGE_BYTES : this.limits.maxRecordBytes }));
334
+ return this.bytes(page ? encodePage(value, PAGE_BYTES) : sequence.encodeFrame(value, { maxRecordBytes: this.limits.maxRecordBytes }));
153
335
  }
154
336
  /** Committed pages only: the writer's own handle is exclusive, so it cannot reopen the file. */
155
337
  async read(ref) {
@@ -231,36 +413,98 @@ async function* entries(load, root, gte, lt, depth = 0) {
231
413
  }
232
414
  }
233
415
  }
416
+ async function* entryPages(load, root, gte, lt, depth = 0) {
417
+ if (!root) return;
418
+ if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
419
+ const loaded = load(root), page = "kind" in loaded ? loaded : await loaded;
420
+ if (page.kind === "leaf") {
421
+ const start = gte === void 0 ? 0 : lower(page.entries, gte, (item) => item.key);
422
+ const end = lt === void 0 ? page.entries.length : lower(page.entries, lt, (item) => item.key);
423
+ if (end > start) yield start === 0 && end === page.entries.length ? page.entries : page.entries.slice(start, end);
424
+ } else {
425
+ let prior;
426
+ for (const child of page.children) {
427
+ if (lt !== void 0 && prior !== void 0 && prior >= lt) break;
428
+ if (gte === void 0 || child.max >= gte) yield* entryPages(load, child.ref, gte, lt, depth + 1);
429
+ prior = child.max;
430
+ }
431
+ }
432
+ }
234
433
  class BatchTree {
235
- constructor(writer, root, count, byteBudget) {
434
+ /** cached returns an already validated committed page, or undefined to read it through the writer. */
435
+ constructor(writer, root, count, byteBudget, cached = () => void 0) {
236
436
  this.writer = writer;
237
437
  this.byteBudget = byteBudget;
438
+ this.cached = cached;
238
439
  this.root = root;
239
440
  this.count = count;
240
441
  }
241
442
  writer;
242
443
  byteBudget;
444
+ cached;
243
445
  root;
244
446
  count;
245
447
  loadedBytes = 0;
246
- async editable(link) {
448
+ /** Live key count after the edits applied so far. */
449
+ get size() {
450
+ return this.count;
451
+ }
452
+ /** Pages this batch appended, for the caller to cache once the root is published. */
453
+ written = [];
454
+ /** Committed pages on the next edit's path, found by missing(); each becomes a dirty copy in editable(). */
455
+ fetched = /* @__PURE__ */ new Map();
456
+ editable(link) {
247
457
  if (!link) return { kind: "leaf", entries: [] };
248
458
  if ("kind" in link) return link;
249
459
  if (this.loadedBytes + link.byteLength > this.byteBudget) throw new common.DbsonlError("LIMIT_EXCEEDED", "Dirty index paths exceed the transaction byte budget.");
250
460
  this.loadedBytes += link.byteLength;
251
- const page = validatePage(await this.writer.read(link), link);
461
+ const page = this.fetched.get(link);
462
+ this.fetched.delete(link);
252
463
  return page.kind === "leaf" ? { kind: "leaf", entries: page.entries.slice() } : { kind: "branch", children: page.children.slice() };
253
464
  }
465
+ /** Collect the committed pages on key's path; return the first one that needs a read, if any. */
466
+ missing(key2) {
467
+ let link = this.root;
468
+ for (let depth = 0; link; depth++) {
469
+ if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
470
+ let page;
471
+ if ("kind" in link) page = link;
472
+ else {
473
+ const known = this.fetched.get(link) ?? this.cached(link);
474
+ if (!known) return link;
475
+ this.fetched.set(link, known);
476
+ page = known;
477
+ }
478
+ if (page.kind === "leaf") return void 0;
479
+ link = page.children[Math.min(page.children.length - 1, lower(page.children, key2, (item) => item.max))].ref;
480
+ }
481
+ return void 0;
482
+ }
254
483
  route(page) {
255
484
  const max = page.kind === "leaf" ? page.entries.at(-1).key : page.children.at(-1).max;
256
485
  const count = page.kind === "leaf" ? page.entries.length : page.children.reduce((sum, item) => sum + item.count, 0);
257
486
  common.natural(count, "key count");
258
487
  return { max, count, ref: page };
259
488
  }
260
- async apply(key2, entry) {
261
- const edit = async (link, depth) => {
489
+ /**
490
+ * Synchronous when every page on the key's path is dirty or cached, the common case; a promise only
491
+ * when a page must be read. A 1000-write batch awaited about five times per write before.
492
+ */
493
+ apply(key2, entry) {
494
+ const ref = this.missing(key2);
495
+ if (!ref) {
496
+ this.edit(key2, entry);
497
+ return;
498
+ }
499
+ return this.writer.read(ref).then((value) => {
500
+ this.fetched.set(ref, validatePage(value, ref));
501
+ return this.apply(key2, entry);
502
+ });
503
+ }
504
+ edit(key2, entry) {
505
+ const edit = (link, depth) => {
262
506
  if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
263
- const page = await this.editable(link);
507
+ const page = this.editable(link);
264
508
  if (page.kind === "leaf") {
265
509
  const at = lower(page.entries, key2, (item) => item.key), exists = page.entries[at]?.key === key2;
266
510
  if (entry) page.entries.splice(at, exists ? 1 : 0, entry);
@@ -272,7 +516,7 @@ class BatchTree {
272
516
  }
273
517
  } else {
274
518
  const at = Math.min(page.children.length - 1, lower(page.children, key2, (item) => item.max));
275
- page.children.splice(at, 1, ...await edit(page.children[at].ref, depth + 1));
519
+ page.children.splice(at, 1, ...edit(page.children[at].ref, depth + 1));
276
520
  if (!page.children.length) return [];
277
521
  if (page.children.length > FANOUT) {
278
522
  const right = page.children.splice(Math.ceil(page.children.length / 2));
@@ -281,7 +525,7 @@ class BatchTree {
281
525
  }
282
526
  return [this.route(page)];
283
527
  };
284
- const changed = await edit(this.root, 0);
528
+ const changed = edit(this.root, 0);
285
529
  if (!changed.length) {
286
530
  this.root = null;
287
531
  this.count = 0;
@@ -303,7 +547,9 @@ class BatchTree {
303
547
  for (const child of link.children) children.push({ ...child, ref: await persist(child.ref) });
304
548
  page = { kind: "branch", children };
305
549
  }
306
- return this.writer.value(page, true);
550
+ const ref = await this.writer.value(page, true);
551
+ this.written.push({ ref, page: validatePage(page, ref) });
552
+ return ref;
307
553
  };
308
554
  return { root: this.root ? await persist(this.root) : null, count: this.count };
309
555
  }
@@ -347,6 +593,9 @@ class BulkTree {
347
593
  }
348
594
  }
349
595
 
596
+ const GROUP_MEMBERS = 64;
597
+ const clock = globalThis;
598
+ const encodedBytes = (input) => input.reduce((sum, item) => sum + (item.bytes?.length ?? 0) + item.key.length * 2 + 64, 0);
350
599
  function newGeneration() {
351
600
  const crypto = globalThis.crypto;
352
601
  if (!crypto?.randomUUID) throw new common.DbsonlError("UNSUPPORTED", "A secure randomUUID implementation is required.");
@@ -355,6 +604,7 @@ function newGeneration() {
355
604
  function code(error) {
356
605
  return error?.code;
357
606
  }
607
+ const pageId = (head, ref) => `${head.generation}:${ref.offset}:${ref.byteLength}`;
358
608
  class ReadSession {
359
609
  /** @internal Sessions are created only by the database factory. */
360
610
  constructor(db, head, release) {
@@ -373,9 +623,9 @@ class ReadSession {
373
623
  pending = /* @__PURE__ */ new Set();
374
624
  revision;
375
625
  count;
376
- work(fn) {
626
+ work(fn, invokesUserCode = false) {
377
627
  if (this.closed) return Promise.reject(new common.DbsonlError("CLOSED", "Snapshot is closed."));
378
- const promise = fn();
628
+ const promise = invokesUserCode ? Promise.resolve().then(fn) : fn();
379
629
  this.pending.add(promise);
380
630
  void promise.then(() => this.pending.delete(promise), () => this.pending.delete(promise));
381
631
  return promise;
@@ -414,6 +664,71 @@ class ReadSession {
414
664
  throw: (error) => iterator.throw(error)
415
665
  };
416
666
  }
667
+ /** Native bounded batches: one tracked pull per batch and one async traversal per leaf. */
668
+ scanBatches(options = {}) {
669
+ const { gte, lt, signal, sizeOf } = options;
670
+ if (gte !== void 0) common.key(gte);
671
+ if (lt !== void 0) common.key(lt);
672
+ const limit = common.natural(options.limit ?? Number.MAX_SAFE_INTEGER, "scan limit");
673
+ const batchSize = common.natural(options.batchSize ?? 256, "batchSize", 1);
674
+ const maxBytes = common.natural(options.maxBatchBytes ?? 4 * 1024 * 1024, "maxBatchBytes", 1);
675
+ if (sizeOf !== void 0 && typeof sizeOf !== "function") throw new TypeError("sizeOf must be a function.");
676
+ const { db, head } = this;
677
+ async function* batches() {
678
+ let count = 0, bytes = 0, batch = [];
679
+ const window = {};
680
+ common.abort(signal);
681
+ if (!limit) return;
682
+ for await (const page of entryPages((ref) => db.load(head, ref), head.root, gte, lt)) {
683
+ let first = 0, last = 0, run = [];
684
+ for (let i = 0; i < page.length; i++) {
685
+ const entry = page[i];
686
+ common.abort(signal);
687
+ if (i >= last && windowContains(window, entry.ref)) {
688
+ const stop = Math.min(page.length, i + limit - count, i + batchSize - batch.length);
689
+ first = i;
690
+ last = i + 1;
691
+ while (last < stop && windowContains(window, page[last].ref)) last++;
692
+ run = last - first > 1 ? db.cachedValues(page, first, last, window) : [];
693
+ }
694
+ const value = i < last && run.length ? run[i - first] : windowContains(window, entry.ref) ? db.cachedValue(head, entry.ref, window) : await db.value(head, entry.ref, window);
695
+ common.abort(signal);
696
+ const row = { key: entry.key, revision: entry.revision, value };
697
+ const size = common.natural(sizeOf ? sizeOf(row) : entry.ref.byteLength, "batch row bytes");
698
+ if (size > maxBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "One row exceeds the batch byte budget.");
699
+ if (batch.length && bytes + size > maxBytes) {
700
+ yield batch;
701
+ batch = [];
702
+ bytes = 0;
703
+ common.abort(signal);
704
+ }
705
+ batch.push(row);
706
+ bytes += size;
707
+ count++;
708
+ if (batch.length === batchSize) {
709
+ yield batch;
710
+ batch = [];
711
+ bytes = 0;
712
+ common.abort(signal);
713
+ }
714
+ if (count === limit) {
715
+ if (batch.length) yield batch;
716
+ return;
717
+ }
718
+ }
719
+ }
720
+ if (batch.length) yield batch;
721
+ }
722
+ const iterator = batches();
723
+ return {
724
+ [Symbol.asyncIterator]() {
725
+ return this;
726
+ },
727
+ next: () => this.work(() => iterator.next(), true),
728
+ return: () => iterator.return(void 0),
729
+ throw: (error) => iterator.throw(error)
730
+ };
731
+ }
417
732
  /** Drain admitted reads before releasing the generation pin used by garbage collection. */
418
733
  close() {
419
734
  if (this.closing) return this.closing;
@@ -445,6 +760,20 @@ class Dbsonl {
445
760
  reservedBytes = 0;
446
761
  limits;
447
762
  headCache = {};
763
+ queue = [];
764
+ draining = false;
765
+ /** The running drain; close() waits for it, because receipts resolve before the group releases the lock. */
766
+ drained = Promise.resolve();
767
+ /** The flushed head while this handle's commit group holds the commit lock; see snapshot(). */
768
+ lockedHead;
769
+ /** Pins taken under lockedHead; the group keeps the lock until they are granted. */
770
+ pinning = /* @__PURE__ */ new Set();
771
+ /** Transactions on this handle that hold a snapshot and have not queued their commit yet; see gather(). */
772
+ preparing = /* @__PURE__ */ new Set();
773
+ /** Wakes a group waiting in gather() when a commit arrives or a preparing transaction ends. */
774
+ arrival;
775
+ /** Wall time of the last group publication in ms, which bounds gather(). */
776
+ groupCost = 0;
448
777
  run(fn) {
449
778
  if (this.closed) return Promise.reject(new common.DbsonlError("CLOSED", "Database is closed."));
450
779
  if (this.pending.size >= this.limits.maxPendingOperations) return Promise.reject(new common.DbsonlError("QUEUE_FULL", "Too many admitted operations."));
@@ -455,28 +784,35 @@ class Dbsonl {
455
784
  }
456
785
  /** Internal cache returns immutable implementation-owned pages, never application values. */
457
786
  load(head, ref) {
458
- const id = `${head.generation}:${ref.offset}:${ref.byteLength}`;
459
- const cached = this.cache.get(id);
460
- if (cached) {
461
- this.cache.delete(id);
462
- this.cache.set(id, cached);
463
- return cached.page;
464
- }
465
- return this.loadUncached(head, ref, id);
787
+ const id = pageId(head, ref);
788
+ return this.cached(id) ?? this.loadUncached(head, ref, id);
789
+ }
790
+ /**
791
+ * Second-chance eviction instead of exact LRU: a hit only marks its page, and eviction moves a marked page
792
+ * to the back once instead of dropping it. Reordering the Map on every hit took about 5% of a memory commit.
793
+ */
794
+ cached(id) {
795
+ const hit = this.cache.get(id);
796
+ if (hit) hit.used = true;
797
+ return hit?.page;
466
798
  }
467
799
  /** The cold path alone allocates an asynchronous load operation. */
468
800
  async loadUncached(head, ref, id) {
469
- const page = validatePage(await readValue(this.backend, this.name, head, ref, PAGE_BYTES), ref);
470
- if (ref.byteLength <= this.limits.maxCacheBytes && this.limits.maxCachePages) {
471
- const existing = this.cache.get(id);
472
- if (existing) return existing.page;
473
- this.cache.set(id, { page, bytes: ref.byteLength });
474
- this.cacheBytes += ref.byteLength;
475
- while (this.cacheBytes > this.limits.maxCacheBytes || this.cache.size > this.limits.maxCachePages) {
476
- const oldest = this.cache.keys().next().value;
477
- this.cacheBytes -= this.cache.get(oldest).bytes;
478
- this.cache.delete(oldest);
479
- }
801
+ return this.remember(id, validatePage(await readValue(this.backend, this.name, head, ref, PAGE_BYTES), ref), ref.byteLength);
802
+ }
803
+ remember(id, page, bytes) {
804
+ if (bytes > this.limits.maxCacheBytes || !this.limits.maxCachePages) return page;
805
+ const existing = this.cache.get(id);
806
+ if (existing) return existing.page;
807
+ this.cache.set(id, { page, bytes, used: true });
808
+ this.cacheBytes += bytes;
809
+ while (this.cacheBytes > this.limits.maxCacheBytes || this.cache.size > this.limits.maxCachePages) {
810
+ const [oldest, entry] = this.cache.entries().next().value;
811
+ this.cache.delete(oldest);
812
+ if (entry.used) {
813
+ entry.used = false;
814
+ this.cache.set(oldest, entry);
815
+ } else this.cacheBytes -= entry.bytes;
480
816
  }
481
817
  return page;
482
818
  }
@@ -485,17 +821,33 @@ class Dbsonl {
485
821
  return readValue(this.backend, this.name, head, ref, this.limits.maxRecordBytes, window);
486
822
  }
487
823
  async snapshot() {
824
+ if (this.lockedHead) {
825
+ const head = this.lockedHead;
826
+ const pinning = this.pin(head);
827
+ this.pinning.add(pinning);
828
+ try {
829
+ return this.session(head, await pinning);
830
+ } finally {
831
+ this.pinning.delete(pinning);
832
+ }
833
+ }
488
834
  return backend.locked(this.backend, `commit-${this.name}`, async () => {
489
835
  const head = await readHead(this.backend, this.name, this.headCache);
490
- const release = await this.backend.coordinator.acquire(`pin-${generationFile(this.name, head.generation)}`, true);
491
- if (!release) throw new Error("Coordinator did not grant generation pin.");
492
- const session = new ReadSession({ load: (head2, ref) => this.load(head2, ref), value: (head2, ref, window) => this.value(head2, ref, window), forget: (session2) => {
493
- this.sessions.delete(session2);
494
- } }, Object.freeze(head), release);
495
- this.sessions.add(session);
496
- return session;
836
+ return this.session(head, await this.pin(head));
497
837
  });
498
838
  }
839
+ async pin(head) {
840
+ const release = await this.backend.coordinator.acquire(`pin-${generationFile(this.name, head.generation)}`, true);
841
+ if (!release) throw new Error("Coordinator did not grant generation pin.");
842
+ return release;
843
+ }
844
+ session(head, release) {
845
+ const session = new ReadSession({ load: (head2, ref) => this.load(head2, ref), value: (head2, ref, window) => this.value(head2, ref, window), cachedValue: (head2, ref, window) => readCachedValue(head2, ref, this.limits.maxRecordBytes, window), cachedValues: (entries2, start, end, window) => readCachedValues(entries2, start, end, this.limits.maxRecordBytes, window), forget: (session2) => {
846
+ this.sessions.delete(session2);
847
+ } }, Object.freeze(head), release);
848
+ this.sessions.add(session);
849
+ return session;
850
+ }
499
851
  /** Pin the currently published root; subsequent writers do not wait for its lifetime. */
500
852
  beginRead() {
501
853
  return this.run(() => this.snapshot());
@@ -541,35 +893,197 @@ class Dbsonl {
541
893
  return { key: operation.key, bytes: encoded };
542
894
  });
543
895
  }
544
- async commit(input, options) {
545
- common.abort(options.signal);
546
- return backend.locked(this.backend, `commit-${this.name}`, async () => {
547
- const head = await readHead(this.backend, this.name, this.headCache);
548
- if (options.ifRevision !== void 0 && common.natural(options.ifRevision, "ifRevision") !== head.revision) throw new common.DbsonlError("CONFLICT", "Database changed since the transaction snapshot.");
549
- if (!input.length) return { revision: head.revision, count: head.count };
550
- const revision = common.natural(head.revision + 1, "revision");
896
+ /**
897
+ * Queue a commit. The next holder of the commit lock publishes every queued commit with one write,
898
+ * one data flush and one head flush; each keeps its own revision, checks and receipt, so the result
899
+ * equals committing them one by one with no reader in between.
900
+ */
901
+ commit(input, options) {
902
+ try {
903
+ common.abort(options.signal);
904
+ if (options.ifRevision !== void 0) common.natural(options.ifRevision, "ifRevision");
905
+ } catch (error) {
906
+ return Promise.reject(error);
907
+ }
908
+ return new Promise((resolve, reject) => {
909
+ const member = {
910
+ input,
911
+ ifRevision: options.ifRevision,
912
+ reads: options.reads,
913
+ signal: options.signal,
914
+ done: false,
915
+ resolve: (commit) => {
916
+ member.done = true;
917
+ resolve(commit);
918
+ },
919
+ reject: (error) => {
920
+ member.done = true;
921
+ reject(error);
922
+ }
923
+ };
924
+ this.queue.push(member);
925
+ this.arrival?.();
926
+ if (!this.draining) this.drained = this.drain();
927
+ });
928
+ }
929
+ /** Reject cancelled members; true once nobody is left waiting. */
930
+ prune() {
931
+ this.queue = this.queue.filter((member) => {
932
+ try {
933
+ common.abort(member.signal);
934
+ return true;
935
+ } catch (error) {
936
+ member.reject(error);
937
+ return false;
938
+ }
939
+ });
940
+ return !this.queue.length;
941
+ }
942
+ async drain() {
943
+ this.draining = true;
944
+ const prune = () => this.prune();
945
+ const waiting = { get aborted() {
946
+ return prune();
947
+ } };
948
+ try {
949
+ while (this.queue.length) {
950
+ try {
951
+ await backend.locked(this.backend, `commit-${this.name}`, async () => {
952
+ const head = await readHead(this.backend, this.name, this.headCache);
953
+ this.lockedHead = head;
954
+ try {
955
+ await this.gather();
956
+ let bytes = 0, operations = 0;
957
+ const group = [];
958
+ while (this.queue.length && group.length < GROUP_MEMBERS) {
959
+ const next = this.queue[0], size = encodedBytes(next.input);
960
+ if (group.length && (bytes + size > this.limits.maxTransactionBytes || operations + next.input.length > this.limits.maxTransactionOperations)) break;
961
+ bytes += size;
962
+ operations += next.input.length;
963
+ group.push(this.queue.shift());
964
+ }
965
+ const started = clock.performance.now();
966
+ if (group.length) await this.publishGroup(group, head);
967
+ this.groupCost = clock.performance.now() - started;
968
+ } finally {
969
+ this.lockedHead = void 0;
970
+ await Promise.allSettled(this.pinning);
971
+ }
972
+ }, waiting);
973
+ } catch (error) {
974
+ if (code(error) !== "ABORTED") for (const member of this.queue.splice(0)) member.reject(error);
975
+ }
976
+ }
977
+ } finally {
978
+ this.draining = false;
979
+ }
980
+ }
981
+ /**
982
+ * Caller holds the commit lock and lockedHead is set. A transaction that already holds its snapshot would
983
+ * otherwise commit just after this group formed and need a group of its own: four writers on one handle
984
+ * alternated between groups of one and three members, each paying both flushes. So wait while such
985
+ * transactions remain, waking on every arrival, for at most half the last group's publication time. One
986
+ * that outlasts the wait is not waited for again, and a lone writer never waits.
987
+ */
988
+ async gather() {
989
+ if (!this.preparing.size || !this.groupCost) return;
990
+ const deadline = clock.performance.now() + this.groupCost / 2;
991
+ while (this.preparing.size) {
992
+ const remaining = deadline - clock.performance.now();
993
+ if (remaining <= 0) {
994
+ this.preparing.clear();
995
+ break;
996
+ }
997
+ await new Promise((resolve) => {
998
+ const timer = clock.setTimeout(() => {
999
+ this.arrival = void 0;
1000
+ resolve();
1001
+ }, remaining);
1002
+ this.arrival = () => {
1003
+ clock.clearTimeout(timer);
1004
+ this.arrival = void 0;
1005
+ resolve();
1006
+ };
1007
+ });
1008
+ }
1009
+ }
1010
+ /** Caller holds the commit lock. Never throws: every member is settled. head is the current head, if known. */
1011
+ async publishGroup(group, known) {
1012
+ let publishing = false;
1013
+ try {
1014
+ const head = known ?? await readHead(this.backend, this.name, this.headCache);
1015
+ this.lockedHead = head;
1016
+ let revision = head.revision;
1017
+ const written = /* @__PURE__ */ new Set(), accepted = [];
1018
+ for (const member of group) {
1019
+ try {
1020
+ common.abort(member.signal);
1021
+ if (member.ifRevision !== void 0 && member.ifRevision !== revision) throw new common.DbsonlError("CONFLICT", "Database changed since the transaction snapshot.");
1022
+ if (member.reads && member.reads.snapshot !== revision) await this.validate(head, member.reads, written);
1023
+ } catch (error) {
1024
+ member.reject(error);
1025
+ continue;
1026
+ }
1027
+ if (member.input.length) {
1028
+ revision = common.natural(revision + 1, "revision");
1029
+ for (const operation of member.input) written.add(operation.key);
1030
+ }
1031
+ accepted.push({ member, revision });
1032
+ }
1033
+ if (revision === head.revision) {
1034
+ for (const { member } of accepted) member.resolve({ revision, count: head.count });
1035
+ return;
1036
+ }
551
1037
  const next = await backend.withFile(this.backend, generationFile(this.name, head.generation), {}, async (file) => {
552
- if (await file.size() < head.end) common.corrupt("Committed generation is truncated.");
553
- await file.truncate(head.end);
1038
+ const size = await file.size();
1039
+ if (size < head.end) common.corrupt("Committed generation is truncated.");
1040
+ if (size > head.end) await file.truncate(head.end);
554
1041
  const writer = new Appender(file, head.end, this.limits, this.backend.writeChunkBytes);
555
- const tree = new BatchTree(writer, head.root, head.count, this.limits.maxTransactionBytes);
556
- for (const operation of input) {
557
- common.abort(options.signal);
558
- const entry = operation.bytes ? { key: operation.key, ref: await writer.bytes(operation.bytes), revision } : void 0;
559
- await tree.apply(operation.key, entry);
1042
+ const tree = new BatchTree(writer, head.root, head.count, this.limits.maxTransactionBytes, (ref) => this.cached(pageId(head, ref)));
1043
+ const counts = [];
1044
+ for (const { member, revision: revision2 } of accepted) {
1045
+ for (const operation of member.input) {
1046
+ common.abort(member.signal);
1047
+ let entry;
1048
+ if (operation.bytes) {
1049
+ const ref = writer.bytes(operation.bytes);
1050
+ entry = { key: operation.key, ref: ref instanceof Promise ? await ref : ref, revision: revision2 };
1051
+ }
1052
+ const applying = tree.apply(operation.key, entry);
1053
+ if (applying) await applying;
1054
+ }
1055
+ counts.push(tree.size);
560
1056
  }
561
1057
  const { root, count } = await tree.finish();
562
1058
  await writer.flush();
563
1059
  await file.flush();
564
- return { ...head, publication: common.natural(head.publication + 1, "publication"), revision, root, count, end: writer.end };
1060
+ return { head: { ...head, publication: common.natural(head.publication + 1, "publication"), revision, root, count, end: writer.end }, written: tree.written, counts };
565
1061
  });
1062
+ publishing = true;
566
1063
  try {
567
- await publish(this.backend, this.name, next);
1064
+ await publish(this.backend, this.name, next.head, this.headCache);
568
1065
  } catch (cause) {
1066
+ this.lockedHead = void 0;
569
1067
  throw new common.DbsonlError("COMMIT_UNCERTAIN", "Head publication failed; read the current revision before retrying.", { cause });
570
1068
  }
571
- return { revision, count: next.count };
572
- }, options.signal);
1069
+ this.lockedHead = next.head;
1070
+ for (const { ref, page } of next.written) this.remember(pageId(next.head, ref), page, ref.byteLength);
1071
+ accepted.forEach(({ member, revision: revision2 }, index) => member.resolve({ revision: revision2, count: next.counts[index] }));
1072
+ } catch (error) {
1073
+ if (!publishing && group.length > 1) {
1074
+ for (const member of group) if (!member.done) await this.publishGroup([member]);
1075
+ return;
1076
+ }
1077
+ for (const member of group) if (!member.done) member.reject(error);
1078
+ }
1079
+ }
1080
+ /** Each point read must still see the entry revision it saw, or absence (0); a scan needs the whole database unchanged. */
1081
+ async validate(head, reads, written) {
1082
+ if (reads.whole) throw new common.DbsonlError("CONFLICT", "Database changed since the transaction snapshot.");
1083
+ for (const [id, seen] of reads.keys) {
1084
+ const entry = written.has(id) ? void 0 : await find((ref) => this.load(head, ref), head.root, id);
1085
+ if (written.has(id) || (entry?.revision ?? 0) !== seen) throw new common.DbsonlError("CONFLICT", "A key the transaction read changed after its snapshot.");
1086
+ }
573
1087
  }
574
1088
  /** Encode at call time, then publish the entire operation list under one new revision. */
575
1089
  batch(input, options = {}) {
@@ -582,7 +1096,7 @@ class Dbsonl {
582
1096
  } catch (error) {
583
1097
  return Promise.reject(error);
584
1098
  }
585
- const bytes = encoded.reduce((sum, item) => sum + (item.bytes?.length ?? 0) + item.key.length * 2 + 64, 0);
1099
+ const bytes = encodedBytes(encoded);
586
1100
  if (this.reservedBytes + bytes > this.limits.maxPendingBytes) return Promise.reject(new common.DbsonlError("QUEUE_FULL", "Pending encoded-byte capacity exceeded."));
587
1101
  this.reservedBytes += bytes;
588
1102
  const commitOptions = { ...options };
@@ -605,8 +1119,23 @@ class Dbsonl {
605
1119
  transaction(callback, options = {}) {
606
1120
  return this.run(async () => {
607
1121
  const session = await this.snapshot();
1122
+ const token = {};
1123
+ this.preparing.add(token);
1124
+ const prepared = () => {
1125
+ if (this.preparing.delete(token)) this.arrival?.();
1126
+ };
608
1127
  const staged = /* @__PURE__ */ new Map();
609
1128
  let size = 0, active = true;
1129
+ const reads = { snapshot: session.revision, keys: /* @__PURE__ */ new Map(), whole: false };
1130
+ const observe = (id, lookup) => {
1131
+ if (reads.whole || reads.keys.has(id)) return;
1132
+ if (reads.keys.size >= this.limits.maxTransactionOperations) {
1133
+ reads.whole = true;
1134
+ reads.keys.clear();
1135
+ return;
1136
+ }
1137
+ reads.keys.set(id, lookup.found ? lookup.revision : 0);
1138
+ };
610
1139
  const check = () => {
611
1140
  if (!active) throw new common.DbsonlError("CLOSED", "Transaction callback has finished.");
612
1141
  common.abort(options.signal);
@@ -628,12 +1157,17 @@ class Dbsonl {
628
1157
  check();
629
1158
  common.key(id);
630
1159
  const item = staged.get(id);
631
- return item ? item.bytes ? { found: true, value: sequence.decodeFrame(item.bytes).value, revision: session.revision + 1 } : { found: false } : session.get(id);
1160
+ if (item) return item.bytes ? { found: true, value: sequence.decodeFrame(item.bytes).value, revision: session.revision + 1 } : { found: false };
1161
+ const lookup = await session.get(id);
1162
+ observe(id, lookup);
1163
+ return lookup;
632
1164
  },
633
1165
  put: (id, value) => stage({ operation: "put", key: id, value }),
634
1166
  delete: (id) => stage({ operation: "delete", key: id }),
635
1167
  async *scan(scan = {}) {
636
1168
  check();
1169
+ reads.whole = true;
1170
+ reads.keys.clear();
637
1171
  const overlay = [...staged.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
638
1172
  let at = 0, emitted = 0;
639
1173
  const limit = common.natural(scan.limit ?? Number.MAX_SAFE_INTEGER, "scan limit");
@@ -669,9 +1203,11 @@ class Dbsonl {
669
1203
  try {
670
1204
  const result = await callback(tx);
671
1205
  active = false;
672
- const commit = await this.commit([...staged.values()], { ...options, ifRevision: session.revision });
1206
+ this.preparing.delete(token);
1207
+ const commit = await this.commit([...staged.values()], { ...options, reads });
673
1208
  return { result, ...commit };
674
1209
  } finally {
1210
+ prepared();
675
1211
  active = false;
676
1212
  this.reservedBytes -= size;
677
1213
  await session.close();
@@ -766,8 +1302,8 @@ class Dbsonl {
766
1302
  const current = await readHead(this.backend, this.name, this.headCache);
767
1303
  if (current.publication !== head.publication) throw new common.DbsonlError("CONFLICT", "Database changed during compaction; retry or use exclusive mode.");
768
1304
  try {
769
- await publish(this.backend, this.name, next);
770
- await publish(this.backend, this.name, { ...next, publication: common.natural(next.publication + 1, "publication") });
1305
+ await publish(this.backend, this.name, next, this.headCache);
1306
+ await publish(this.backend, this.name, { ...next, publication: common.natural(next.publication + 1, "publication") }, this.headCache);
771
1307
  } catch (cause) {
772
1308
  throw new common.DbsonlError("COMMIT_UNCERTAIN", "Compaction publication failed; reopen or inspect stats.", { cause });
773
1309
  }
@@ -786,7 +1322,7 @@ class Dbsonl {
786
1322
  collect() {
787
1323
  return this.run(() => backend.locked(this.backend, `commit-${this.name}`, async () => {
788
1324
  const head = await readHead(this.backend, this.name, this.headCache);
789
- await publish(this.backend, this.name, { ...head, publication: common.natural(head.publication + 1, "publication") });
1325
+ await publish(this.backend, this.name, { ...head, publication: common.natural(head.publication + 1, "publication") }, this.headCache);
790
1326
  const current = generationFile(this.name, head.generation);
791
1327
  const removed = [], retained = [];
792
1328
  for (const filename of await this.backend.storage.list()) {
@@ -815,6 +1351,7 @@ class Dbsonl {
815
1351
  this.closed = true;
816
1352
  this.closing = (async () => {
817
1353
  await Promise.allSettled(this.pending);
1354
+ await this.drained;
818
1355
  try {
819
1356
  await Promise.all([...this.sessions].map((session) => session.close()));
820
1357
  } finally {