defuss-dbsonl 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -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,16 +211,22 @@ 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) {
@@ -134,10 +285,20 @@ class Appender {
134
285
  this.flushedEnd += this.used;
135
286
  this.used = 0;
136
287
  }
137
- async bytes(bytes) {
288
+ /** Synchronous unless the buffer must be written first; most frames only need a copy. */
289
+ bytes(bytes) {
138
290
  const ref = { offset: this.end, byteLength: bytes.length };
139
291
  common.natural(this.end + bytes.length, "file end");
140
- if (bytes.length > this.buffer.length - this.used) await this.flush();
292
+ if (bytes.length <= this.buffer.length - this.used) {
293
+ this.buffer.set(bytes, this.used);
294
+ this.used += bytes.length;
295
+ this.end += bytes.length;
296
+ return ref;
297
+ }
298
+ return this.spill(bytes, ref);
299
+ }
300
+ async spill(bytes, ref) {
301
+ await this.flush();
141
302
  if (bytes.length > this.buffer.length) {
142
303
  await backend.writeBytes(this.file, this.end, bytes, this.chunkSize);
143
304
  this.flushedEnd += bytes.length;
@@ -149,7 +310,7 @@ class Appender {
149
310
  return ref;
150
311
  }
151
312
  async value(value, page = false) {
152
- return this.bytes(sequence.encodeFrame(value, { maxRecordBytes: page ? PAGE_BYTES : this.limits.maxRecordBytes }));
313
+ return this.bytes(page ? encodePage(value, PAGE_BYTES) : sequence.encodeFrame(value, { maxRecordBytes: this.limits.maxRecordBytes }));
153
314
  }
154
315
  /** Committed pages only: the writer's own handle is exclusive, so it cannot reopen the file. */
155
316
  async read(ref) {
@@ -232,35 +393,80 @@ async function* entries(load, root, gte, lt, depth = 0) {
232
393
  }
233
394
  }
234
395
  class BatchTree {
235
- constructor(writer, root, count, byteBudget) {
396
+ /** cached returns an already validated committed page, or undefined to read it through the writer. */
397
+ constructor(writer, root, count, byteBudget, cached = () => void 0) {
236
398
  this.writer = writer;
237
399
  this.byteBudget = byteBudget;
400
+ this.cached = cached;
238
401
  this.root = root;
239
402
  this.count = count;
240
403
  }
241
404
  writer;
242
405
  byteBudget;
406
+ cached;
243
407
  root;
244
408
  count;
245
409
  loadedBytes = 0;
246
- async editable(link) {
410
+ /** Live key count after the edits applied so far. */
411
+ get size() {
412
+ return this.count;
413
+ }
414
+ /** Pages this batch appended, for the caller to cache once the root is published. */
415
+ written = [];
416
+ /** Committed pages on the next edit's path, found by missing(); each becomes a dirty copy in editable(). */
417
+ fetched = /* @__PURE__ */ new Map();
418
+ editable(link) {
247
419
  if (!link) return { kind: "leaf", entries: [] };
248
420
  if ("kind" in link) return link;
249
421
  if (this.loadedBytes + link.byteLength > this.byteBudget) throw new common.DbsonlError("LIMIT_EXCEEDED", "Dirty index paths exceed the transaction byte budget.");
250
422
  this.loadedBytes += link.byteLength;
251
- const page = validatePage(await this.writer.read(link), link);
423
+ const page = this.fetched.get(link);
424
+ this.fetched.delete(link);
252
425
  return page.kind === "leaf" ? { kind: "leaf", entries: page.entries.slice() } : { kind: "branch", children: page.children.slice() };
253
426
  }
427
+ /** Collect the committed pages on key's path; return the first one that needs a read, if any. */
428
+ missing(key2) {
429
+ let link = this.root;
430
+ for (let depth = 0; link; depth++) {
431
+ if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
432
+ let page;
433
+ if ("kind" in link) page = link;
434
+ else {
435
+ const known = this.fetched.get(link) ?? this.cached(link);
436
+ if (!known) return link;
437
+ this.fetched.set(link, known);
438
+ page = known;
439
+ }
440
+ if (page.kind === "leaf") return void 0;
441
+ link = page.children[Math.min(page.children.length - 1, lower(page.children, key2, (item) => item.max))].ref;
442
+ }
443
+ return void 0;
444
+ }
254
445
  route(page) {
255
446
  const max = page.kind === "leaf" ? page.entries.at(-1).key : page.children.at(-1).max;
256
447
  const count = page.kind === "leaf" ? page.entries.length : page.children.reduce((sum, item) => sum + item.count, 0);
257
448
  common.natural(count, "key count");
258
449
  return { max, count, ref: page };
259
450
  }
260
- async apply(key2, entry) {
261
- const edit = async (link, depth) => {
451
+ /**
452
+ * Synchronous when every page on the key's path is dirty or cached, the common case; a promise only
453
+ * when a page must be read. A 1000-write batch awaited about five times per write before.
454
+ */
455
+ apply(key2, entry) {
456
+ const ref = this.missing(key2);
457
+ if (!ref) {
458
+ this.edit(key2, entry);
459
+ return;
460
+ }
461
+ return this.writer.read(ref).then((value) => {
462
+ this.fetched.set(ref, validatePage(value, ref));
463
+ return this.apply(key2, entry);
464
+ });
465
+ }
466
+ edit(key2, entry) {
467
+ const edit = (link, depth) => {
262
468
  if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
263
- const page = await this.editable(link);
469
+ const page = this.editable(link);
264
470
  if (page.kind === "leaf") {
265
471
  const at = lower(page.entries, key2, (item) => item.key), exists = page.entries[at]?.key === key2;
266
472
  if (entry) page.entries.splice(at, exists ? 1 : 0, entry);
@@ -272,7 +478,7 @@ class BatchTree {
272
478
  }
273
479
  } else {
274
480
  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));
481
+ page.children.splice(at, 1, ...edit(page.children[at].ref, depth + 1));
276
482
  if (!page.children.length) return [];
277
483
  if (page.children.length > FANOUT) {
278
484
  const right = page.children.splice(Math.ceil(page.children.length / 2));
@@ -281,7 +487,7 @@ class BatchTree {
281
487
  }
282
488
  return [this.route(page)];
283
489
  };
284
- const changed = await edit(this.root, 0);
490
+ const changed = edit(this.root, 0);
285
491
  if (!changed.length) {
286
492
  this.root = null;
287
493
  this.count = 0;
@@ -303,7 +509,9 @@ class BatchTree {
303
509
  for (const child of link.children) children.push({ ...child, ref: await persist(child.ref) });
304
510
  page = { kind: "branch", children };
305
511
  }
306
- return this.writer.value(page, true);
512
+ const ref = await this.writer.value(page, true);
513
+ this.written.push({ ref, page: validatePage(page, ref) });
514
+ return ref;
307
515
  };
308
516
  return { root: this.root ? await persist(this.root) : null, count: this.count };
309
517
  }
@@ -347,6 +555,9 @@ class BulkTree {
347
555
  }
348
556
  }
349
557
 
558
+ const GROUP_MEMBERS = 64;
559
+ const clock = globalThis;
560
+ const encodedBytes = (input) => input.reduce((sum, item) => sum + (item.bytes?.length ?? 0) + item.key.length * 2 + 64, 0);
350
561
  function newGeneration() {
351
562
  const crypto = globalThis.crypto;
352
563
  if (!crypto?.randomUUID) throw new common.DbsonlError("UNSUPPORTED", "A secure randomUUID implementation is required.");
@@ -355,6 +566,7 @@ function newGeneration() {
355
566
  function code(error) {
356
567
  return error?.code;
357
568
  }
569
+ const pageId = (head, ref) => `${head.generation}:${ref.offset}:${ref.byteLength}`;
358
570
  class ReadSession {
359
571
  /** @internal Sessions are created only by the database factory. */
360
572
  constructor(db, head, release) {
@@ -445,6 +657,20 @@ class Dbsonl {
445
657
  reservedBytes = 0;
446
658
  limits;
447
659
  headCache = {};
660
+ queue = [];
661
+ draining = false;
662
+ /** The running drain; close() waits for it, because receipts resolve before the group releases the lock. */
663
+ drained = Promise.resolve();
664
+ /** The flushed head while this handle's commit group holds the commit lock; see snapshot(). */
665
+ lockedHead;
666
+ /** Pins taken under lockedHead; the group keeps the lock until they are granted. */
667
+ pinning = /* @__PURE__ */ new Set();
668
+ /** Transactions on this handle that hold a snapshot and have not queued their commit yet; see gather(). */
669
+ preparing = /* @__PURE__ */ new Set();
670
+ /** Wakes a group waiting in gather() when a commit arrives or a preparing transaction ends. */
671
+ arrival;
672
+ /** Wall time of the last group publication in ms, which bounds gather(). */
673
+ groupCost = 0;
448
674
  run(fn) {
449
675
  if (this.closed) return Promise.reject(new common.DbsonlError("CLOSED", "Database is closed."));
450
676
  if (this.pending.size >= this.limits.maxPendingOperations) return Promise.reject(new common.DbsonlError("QUEUE_FULL", "Too many admitted operations."));
@@ -455,28 +681,35 @@ class Dbsonl {
455
681
  }
456
682
  /** Internal cache returns immutable implementation-owned pages, never application values. */
457
683
  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);
684
+ const id = pageId(head, ref);
685
+ return this.cached(id) ?? this.loadUncached(head, ref, id);
686
+ }
687
+ /**
688
+ * Second-chance eviction instead of exact LRU: a hit only marks its page, and eviction moves a marked page
689
+ * to the back once instead of dropping it. Reordering the Map on every hit took about 5% of a memory commit.
690
+ */
691
+ cached(id) {
692
+ const hit = this.cache.get(id);
693
+ if (hit) hit.used = true;
694
+ return hit?.page;
466
695
  }
467
696
  /** The cold path alone allocates an asynchronous load operation. */
468
697
  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
- }
698
+ return this.remember(id, validatePage(await readValue(this.backend, this.name, head, ref, PAGE_BYTES), ref), ref.byteLength);
699
+ }
700
+ remember(id, page, bytes) {
701
+ if (bytes > this.limits.maxCacheBytes || !this.limits.maxCachePages) return page;
702
+ const existing = this.cache.get(id);
703
+ if (existing) return existing.page;
704
+ this.cache.set(id, { page, bytes, used: true });
705
+ this.cacheBytes += bytes;
706
+ while (this.cacheBytes > this.limits.maxCacheBytes || this.cache.size > this.limits.maxCachePages) {
707
+ const [oldest, entry] = this.cache.entries().next().value;
708
+ this.cache.delete(oldest);
709
+ if (entry.used) {
710
+ entry.used = false;
711
+ this.cache.set(oldest, entry);
712
+ } else this.cacheBytes -= entry.bytes;
480
713
  }
481
714
  return page;
482
715
  }
@@ -485,17 +718,33 @@ class Dbsonl {
485
718
  return readValue(this.backend, this.name, head, ref, this.limits.maxRecordBytes, window);
486
719
  }
487
720
  async snapshot() {
721
+ if (this.lockedHead) {
722
+ const head = this.lockedHead;
723
+ const pinning = this.pin(head);
724
+ this.pinning.add(pinning);
725
+ try {
726
+ return this.session(head, await pinning);
727
+ } finally {
728
+ this.pinning.delete(pinning);
729
+ }
730
+ }
488
731
  return backend.locked(this.backend, `commit-${this.name}`, async () => {
489
732
  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;
733
+ return this.session(head, await this.pin(head));
497
734
  });
498
735
  }
736
+ async pin(head) {
737
+ const release = await this.backend.coordinator.acquire(`pin-${generationFile(this.name, head.generation)}`, true);
738
+ if (!release) throw new Error("Coordinator did not grant generation pin.");
739
+ return release;
740
+ }
741
+ session(head, release) {
742
+ const session = new ReadSession({ load: (head2, ref) => this.load(head2, ref), value: (head2, ref, window) => this.value(head2, ref, window), forget: (session2) => {
743
+ this.sessions.delete(session2);
744
+ } }, Object.freeze(head), release);
745
+ this.sessions.add(session);
746
+ return session;
747
+ }
499
748
  /** Pin the currently published root; subsequent writers do not wait for its lifetime. */
500
749
  beginRead() {
501
750
  return this.run(() => this.snapshot());
@@ -541,35 +790,197 @@ class Dbsonl {
541
790
  return { key: operation.key, bytes: encoded };
542
791
  });
543
792
  }
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");
793
+ /**
794
+ * Queue a commit. The next holder of the commit lock publishes every queued commit with one write,
795
+ * one data flush and one head flush; each keeps its own revision, checks and receipt, so the result
796
+ * equals committing them one by one with no reader in between.
797
+ */
798
+ commit(input, options) {
799
+ try {
800
+ common.abort(options.signal);
801
+ if (options.ifRevision !== void 0) common.natural(options.ifRevision, "ifRevision");
802
+ } catch (error) {
803
+ return Promise.reject(error);
804
+ }
805
+ return new Promise((resolve, reject) => {
806
+ const member = {
807
+ input,
808
+ ifRevision: options.ifRevision,
809
+ reads: options.reads,
810
+ signal: options.signal,
811
+ done: false,
812
+ resolve: (commit) => {
813
+ member.done = true;
814
+ resolve(commit);
815
+ },
816
+ reject: (error) => {
817
+ member.done = true;
818
+ reject(error);
819
+ }
820
+ };
821
+ this.queue.push(member);
822
+ this.arrival?.();
823
+ if (!this.draining) this.drained = this.drain();
824
+ });
825
+ }
826
+ /** Reject cancelled members; true once nobody is left waiting. */
827
+ prune() {
828
+ this.queue = this.queue.filter((member) => {
829
+ try {
830
+ common.abort(member.signal);
831
+ return true;
832
+ } catch (error) {
833
+ member.reject(error);
834
+ return false;
835
+ }
836
+ });
837
+ return !this.queue.length;
838
+ }
839
+ async drain() {
840
+ this.draining = true;
841
+ const prune = () => this.prune();
842
+ const waiting = { get aborted() {
843
+ return prune();
844
+ } };
845
+ try {
846
+ while (this.queue.length) {
847
+ try {
848
+ await backend.locked(this.backend, `commit-${this.name}`, async () => {
849
+ const head = await readHead(this.backend, this.name, this.headCache);
850
+ this.lockedHead = head;
851
+ try {
852
+ await this.gather();
853
+ let bytes = 0, operations = 0;
854
+ const group = [];
855
+ while (this.queue.length && group.length < GROUP_MEMBERS) {
856
+ const next = this.queue[0], size = encodedBytes(next.input);
857
+ if (group.length && (bytes + size > this.limits.maxTransactionBytes || operations + next.input.length > this.limits.maxTransactionOperations)) break;
858
+ bytes += size;
859
+ operations += next.input.length;
860
+ group.push(this.queue.shift());
861
+ }
862
+ const started = clock.performance.now();
863
+ if (group.length) await this.publishGroup(group, head);
864
+ this.groupCost = clock.performance.now() - started;
865
+ } finally {
866
+ this.lockedHead = void 0;
867
+ await Promise.allSettled(this.pinning);
868
+ }
869
+ }, waiting);
870
+ } catch (error) {
871
+ if (code(error) !== "ABORTED") for (const member of this.queue.splice(0)) member.reject(error);
872
+ }
873
+ }
874
+ } finally {
875
+ this.draining = false;
876
+ }
877
+ }
878
+ /**
879
+ * Caller holds the commit lock and lockedHead is set. A transaction that already holds its snapshot would
880
+ * otherwise commit just after this group formed and need a group of its own: four writers on one handle
881
+ * alternated between groups of one and three members, each paying both flushes. So wait while such
882
+ * transactions remain, waking on every arrival, for at most half the last group's publication time. One
883
+ * that outlasts the wait is not waited for again, and a lone writer never waits.
884
+ */
885
+ async gather() {
886
+ if (!this.preparing.size || !this.groupCost) return;
887
+ const deadline = clock.performance.now() + this.groupCost / 2;
888
+ while (this.preparing.size) {
889
+ const remaining = deadline - clock.performance.now();
890
+ if (remaining <= 0) {
891
+ this.preparing.clear();
892
+ break;
893
+ }
894
+ await new Promise((resolve) => {
895
+ const timer = clock.setTimeout(() => {
896
+ this.arrival = void 0;
897
+ resolve();
898
+ }, remaining);
899
+ this.arrival = () => {
900
+ clock.clearTimeout(timer);
901
+ this.arrival = void 0;
902
+ resolve();
903
+ };
904
+ });
905
+ }
906
+ }
907
+ /** Caller holds the commit lock. Never throws: every member is settled. head is the current head, if known. */
908
+ async publishGroup(group, known) {
909
+ let publishing = false;
910
+ try {
911
+ const head = known ?? await readHead(this.backend, this.name, this.headCache);
912
+ this.lockedHead = head;
913
+ let revision = head.revision;
914
+ const written = /* @__PURE__ */ new Set(), accepted = [];
915
+ for (const member of group) {
916
+ try {
917
+ common.abort(member.signal);
918
+ if (member.ifRevision !== void 0 && member.ifRevision !== revision) throw new common.DbsonlError("CONFLICT", "Database changed since the transaction snapshot.");
919
+ if (member.reads && member.reads.snapshot !== revision) await this.validate(head, member.reads, written);
920
+ } catch (error) {
921
+ member.reject(error);
922
+ continue;
923
+ }
924
+ if (member.input.length) {
925
+ revision = common.natural(revision + 1, "revision");
926
+ for (const operation of member.input) written.add(operation.key);
927
+ }
928
+ accepted.push({ member, revision });
929
+ }
930
+ if (revision === head.revision) {
931
+ for (const { member } of accepted) member.resolve({ revision, count: head.count });
932
+ return;
933
+ }
551
934
  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);
935
+ const size = await file.size();
936
+ if (size < head.end) common.corrupt("Committed generation is truncated.");
937
+ if (size > head.end) await file.truncate(head.end);
554
938
  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);
939
+ const tree = new BatchTree(writer, head.root, head.count, this.limits.maxTransactionBytes, (ref) => this.cached(pageId(head, ref)));
940
+ const counts = [];
941
+ for (const { member, revision: revision2 } of accepted) {
942
+ for (const operation of member.input) {
943
+ common.abort(member.signal);
944
+ let entry;
945
+ if (operation.bytes) {
946
+ const ref = writer.bytes(operation.bytes);
947
+ entry = { key: operation.key, ref: ref instanceof Promise ? await ref : ref, revision: revision2 };
948
+ }
949
+ const applying = tree.apply(operation.key, entry);
950
+ if (applying) await applying;
951
+ }
952
+ counts.push(tree.size);
560
953
  }
561
954
  const { root, count } = await tree.finish();
562
955
  await writer.flush();
563
956
  await file.flush();
564
- return { ...head, publication: common.natural(head.publication + 1, "publication"), revision, root, count, end: writer.end };
957
+ return { head: { ...head, publication: common.natural(head.publication + 1, "publication"), revision, root, count, end: writer.end }, written: tree.written, counts };
565
958
  });
959
+ publishing = true;
566
960
  try {
567
- await publish(this.backend, this.name, next);
961
+ await publish(this.backend, this.name, next.head, this.headCache);
568
962
  } catch (cause) {
963
+ this.lockedHead = void 0;
569
964
  throw new common.DbsonlError("COMMIT_UNCERTAIN", "Head publication failed; read the current revision before retrying.", { cause });
570
965
  }
571
- return { revision, count: next.count };
572
- }, options.signal);
966
+ this.lockedHead = next.head;
967
+ for (const { ref, page } of next.written) this.remember(pageId(next.head, ref), page, ref.byteLength);
968
+ accepted.forEach(({ member, revision: revision2 }, index) => member.resolve({ revision: revision2, count: next.counts[index] }));
969
+ } catch (error) {
970
+ if (!publishing && group.length > 1) {
971
+ for (const member of group) if (!member.done) await this.publishGroup([member]);
972
+ return;
973
+ }
974
+ for (const member of group) if (!member.done) member.reject(error);
975
+ }
976
+ }
977
+ /** Each point read must still see the entry revision it saw, or absence (0); a scan needs the whole database unchanged. */
978
+ async validate(head, reads, written) {
979
+ if (reads.whole) throw new common.DbsonlError("CONFLICT", "Database changed since the transaction snapshot.");
980
+ for (const [id, seen] of reads.keys) {
981
+ const entry = written.has(id) ? void 0 : await find((ref) => this.load(head, ref), head.root, id);
982
+ if (written.has(id) || (entry?.revision ?? 0) !== seen) throw new common.DbsonlError("CONFLICT", "A key the transaction read changed after its snapshot.");
983
+ }
573
984
  }
574
985
  /** Encode at call time, then publish the entire operation list under one new revision. */
575
986
  batch(input, options = {}) {
@@ -582,7 +993,7 @@ class Dbsonl {
582
993
  } catch (error) {
583
994
  return Promise.reject(error);
584
995
  }
585
- const bytes = encoded.reduce((sum, item) => sum + (item.bytes?.length ?? 0) + item.key.length * 2 + 64, 0);
996
+ const bytes = encodedBytes(encoded);
586
997
  if (this.reservedBytes + bytes > this.limits.maxPendingBytes) return Promise.reject(new common.DbsonlError("QUEUE_FULL", "Pending encoded-byte capacity exceeded."));
587
998
  this.reservedBytes += bytes;
588
999
  const commitOptions = { ...options };
@@ -605,8 +1016,23 @@ class Dbsonl {
605
1016
  transaction(callback, options = {}) {
606
1017
  return this.run(async () => {
607
1018
  const session = await this.snapshot();
1019
+ const token = {};
1020
+ this.preparing.add(token);
1021
+ const prepared = () => {
1022
+ if (this.preparing.delete(token)) this.arrival?.();
1023
+ };
608
1024
  const staged = /* @__PURE__ */ new Map();
609
1025
  let size = 0, active = true;
1026
+ const reads = { snapshot: session.revision, keys: /* @__PURE__ */ new Map(), whole: false };
1027
+ const observe = (id, lookup) => {
1028
+ if (reads.whole || reads.keys.has(id)) return;
1029
+ if (reads.keys.size >= this.limits.maxTransactionOperations) {
1030
+ reads.whole = true;
1031
+ reads.keys.clear();
1032
+ return;
1033
+ }
1034
+ reads.keys.set(id, lookup.found ? lookup.revision : 0);
1035
+ };
610
1036
  const check = () => {
611
1037
  if (!active) throw new common.DbsonlError("CLOSED", "Transaction callback has finished.");
612
1038
  common.abort(options.signal);
@@ -628,12 +1054,17 @@ class Dbsonl {
628
1054
  check();
629
1055
  common.key(id);
630
1056
  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);
1057
+ if (item) return item.bytes ? { found: true, value: sequence.decodeFrame(item.bytes).value, revision: session.revision + 1 } : { found: false };
1058
+ const lookup = await session.get(id);
1059
+ observe(id, lookup);
1060
+ return lookup;
632
1061
  },
633
1062
  put: (id, value) => stage({ operation: "put", key: id, value }),
634
1063
  delete: (id) => stage({ operation: "delete", key: id }),
635
1064
  async *scan(scan = {}) {
636
1065
  check();
1066
+ reads.whole = true;
1067
+ reads.keys.clear();
637
1068
  const overlay = [...staged.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
638
1069
  let at = 0, emitted = 0;
639
1070
  const limit = common.natural(scan.limit ?? Number.MAX_SAFE_INTEGER, "scan limit");
@@ -669,9 +1100,11 @@ class Dbsonl {
669
1100
  try {
670
1101
  const result = await callback(tx);
671
1102
  active = false;
672
- const commit = await this.commit([...staged.values()], { ...options, ifRevision: session.revision });
1103
+ this.preparing.delete(token);
1104
+ const commit = await this.commit([...staged.values()], { ...options, reads });
673
1105
  return { result, ...commit };
674
1106
  } finally {
1107
+ prepared();
675
1108
  active = false;
676
1109
  this.reservedBytes -= size;
677
1110
  await session.close();
@@ -766,8 +1199,8 @@ class Dbsonl {
766
1199
  const current = await readHead(this.backend, this.name, this.headCache);
767
1200
  if (current.publication !== head.publication) throw new common.DbsonlError("CONFLICT", "Database changed during compaction; retry or use exclusive mode.");
768
1201
  try {
769
- await publish(this.backend, this.name, next);
770
- await publish(this.backend, this.name, { ...next, publication: common.natural(next.publication + 1, "publication") });
1202
+ await publish(this.backend, this.name, next, this.headCache);
1203
+ await publish(this.backend, this.name, { ...next, publication: common.natural(next.publication + 1, "publication") }, this.headCache);
771
1204
  } catch (cause) {
772
1205
  throw new common.DbsonlError("COMMIT_UNCERTAIN", "Compaction publication failed; reopen or inspect stats.", { cause });
773
1206
  }
@@ -786,7 +1219,7 @@ class Dbsonl {
786
1219
  collect() {
787
1220
  return this.run(() => backend.locked(this.backend, `commit-${this.name}`, async () => {
788
1221
  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") });
1222
+ await publish(this.backend, this.name, { ...head, publication: common.natural(head.publication + 1, "publication") }, this.headCache);
790
1223
  const current = generationFile(this.name, head.generation);
791
1224
  const removed = [], retained = [];
792
1225
  for (const filename of await this.backend.storage.list()) {
@@ -815,6 +1248,7 @@ class Dbsonl {
815
1248
  this.closed = true;
816
1249
  this.closing = (async () => {
817
1250
  await Promise.allSettled(this.pending);
1251
+ await this.drained;
818
1252
  try {
819
1253
  await Promise.all([...this.sessions].map((session) => session.close()));
820
1254
  } finally {