defuss-dbsonl 0.6.0 → 0.7.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/ARCH.md +38 -6
- package/CHANGELOG.md +22 -0
- package/README.md +18 -2
- package/dist/{backend-CU4f3EUz.cjs → backend-Bq8hVmuI.cjs} +9 -5
- package/dist/browser.cjs +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/{common-0JC30Xiv.mjs → common-R-Fl2aza.mjs} +2 -2
- package/dist/index.cjs +353 -69
- package/dist/index.d.cts +51 -19
- package/dist/index.d.mts +51 -19
- package/dist/index.mjs +3 -1408
- package/dist/scan-worker.mjs +18 -0
- package/dist/server-BXybcXSY.mjs +722 -0
- package/dist/server.cjs +361 -12
- package/dist/server.d.cts +16 -1
- package/dist/server.d.mts +16 -1
- package/dist/server.mjs +13 -285
- package/dist/store-Bd1KZ-N7.mjs +1766 -0
- package/dist/{types-7kcIxgpp.d.cts → types-CSHnjgvj.d.cts} +54 -2
- package/dist/{types-7kcIxgpp.d.mts → types-CSHnjgvj.d.mts} +54 -2
- package/docs/API.md +12 -6
- package/docs/FORMAT.md +26 -6
- package/docs/PERFORMANCE.md +80 -25
- package/package.json +5 -2
- package/dist/backend-c-pjfpXZ.mjs +0 -76
- package/dist/{common-2ybGl1zj.cjs → common-YqfTK8sQ.cjs} +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var sequence = require('defuss-dson/sequence');
|
|
4
|
-
var backend = require('./backend-
|
|
5
|
-
var common = require('./common-
|
|
4
|
+
var backend = require('./backend-Bq8hVmuI.cjs');
|
|
5
|
+
var common = require('./common-YqfTK8sQ.cjs');
|
|
6
6
|
require('defuss-storage');
|
|
7
7
|
|
|
8
8
|
const STRING = 14, FLOAT64 = 15, ARRAY = 17, OBJECT = 18;
|
|
@@ -173,6 +173,15 @@ function equalBytes(a, b) {
|
|
|
173
173
|
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
174
174
|
return true;
|
|
175
175
|
}
|
|
176
|
+
function checkHead(value) {
|
|
177
|
+
const h = value;
|
|
178
|
+
if (!h || h.dbsonl !== 2 && h.dbsonl !== 3) throw new common.DbsonlError("UNSUPPORTED", "Unsupported database manifest version.");
|
|
179
|
+
if (h.dbsonl === 3 ? typeof h.seal !== "string" || !/^[0-9a-f]{32}$/.test(h.seal) : h.seal !== void 0) common.corrupt("Invalid manifest seal.");
|
|
180
|
+
if (!Number.isSafeInteger(h.publication) || h.publication < 1 || !Number.isSafeInteger(h.revision) || h.revision < 0 || !Number.isSafeInteger(h.count) || h.count < 0 || !Number.isSafeInteger(h.end) || h.end < 0 || typeof h.generation !== "string" || !/^[0-9a-f]{32}$/.test(h.generation)) common.corrupt("Invalid manifest fields.");
|
|
181
|
+
if (h.root !== null) common.reference(h.root, h.end);
|
|
182
|
+
if (h.root === null !== (h.count === 0)) common.corrupt("Empty root and count disagree.");
|
|
183
|
+
return h;
|
|
184
|
+
}
|
|
176
185
|
async function readHead(backend$1, name, cache) {
|
|
177
186
|
const data = backend$1.read ? await backend$1.read(headFile(name), 0, SLOT_BYTES * 2 + 1) : await backend.withFile(backend$1, headFile(name), { readOnly: true }, async (file) => {
|
|
178
187
|
const size2 = await file.size();
|
|
@@ -195,12 +204,7 @@ async function readHead(backend$1, name, cache) {
|
|
|
195
204
|
} catch {
|
|
196
205
|
continue;
|
|
197
206
|
}
|
|
198
|
-
|
|
199
|
-
if (!h || h.dbsonl !== 2) throw new common.DbsonlError("UNSUPPORTED", "Unsupported database manifest version.");
|
|
200
|
-
if (!Number.isSafeInteger(h.publication) || h.publication < 1 || !Number.isSafeInteger(h.revision) || h.revision < 0 || !Number.isSafeInteger(h.count) || h.count < 0 || !Number.isSafeInteger(h.end) || h.end < 0 || !/^[0-9a-f]{32}$/.test(h.generation)) common.corrupt("Invalid manifest fields.");
|
|
201
|
-
if (h.root !== null) common.reference(h.root, h.end);
|
|
202
|
-
if (h.root === null !== (h.count === 0)) common.corrupt("Empty root and count disagree.");
|
|
203
|
-
heads.push(h);
|
|
207
|
+
heads.push(checkHead(value));
|
|
204
208
|
}
|
|
205
209
|
if (!heads.length) common.corrupt("No valid commit slot. Refuse automatic data loss recovery.");
|
|
206
210
|
heads.sort((a, b) => b.publication - a.publication);
|
|
@@ -211,7 +215,7 @@ async function readHead(backend$1, name, cache) {
|
|
|
211
215
|
}
|
|
212
216
|
return head;
|
|
213
217
|
}
|
|
214
|
-
async function publish(backend$1, name, head, cache) {
|
|
218
|
+
async function publish(backend$1, name, head, cache, flush = true) {
|
|
215
219
|
common.natural(head.publication, "publication", 1);
|
|
216
220
|
const bytes = sequence.encodeFrame(head, { maxRecordBytes: SLOT_BYTES - 16, trusted: true });
|
|
217
221
|
const slot = new Uint8Array(SLOT_BYTES);
|
|
@@ -219,7 +223,7 @@ async function publish(backend$1, name, head, cache) {
|
|
|
219
223
|
const offset = head.publication % 2 * SLOT_BYTES;
|
|
220
224
|
await backend.withFile(backend$1, headFile(name), {}, async (file) => {
|
|
221
225
|
await backend.writeBytes(file, offset, slot, backend$1.writeChunkBytes);
|
|
222
|
-
await file.flush();
|
|
226
|
+
if (flush) await file.flush();
|
|
223
227
|
});
|
|
224
228
|
if (cache?.bytes?.length === SLOT_BYTES * 2) {
|
|
225
229
|
const next = cache.bytes.slice();
|
|
@@ -228,6 +232,64 @@ async function publish(backend$1, name, head, cache) {
|
|
|
228
232
|
cache.head = head;
|
|
229
233
|
}
|
|
230
234
|
}
|
|
235
|
+
const CRC_TABLE = (() => {
|
|
236
|
+
const table = new Uint32Array(256);
|
|
237
|
+
for (let n = 0; n < 256; n++) {
|
|
238
|
+
let c = n;
|
|
239
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? c >>> 1 ^ 2197175160 : c >>> 1;
|
|
240
|
+
table[n] = c >>> 0;
|
|
241
|
+
}
|
|
242
|
+
return table;
|
|
243
|
+
})();
|
|
244
|
+
function crc32c(bytes) {
|
|
245
|
+
let c = 4294967295;
|
|
246
|
+
for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 255] ^ c >>> 8;
|
|
247
|
+
return (c ^ 4294967295) >>> 0;
|
|
248
|
+
}
|
|
249
|
+
const RECORD_BYTES = 1024;
|
|
250
|
+
function commitRecord(head, offset, prev) {
|
|
251
|
+
return sequence.encodeFrame({ dbsonl: 3, seal: head.seal, publication: head.publication, revision: head.revision, root: head.root, count: head.count, offset, prev }, { maxRecordBytes: RECORD_BYTES - 16, trusted: true });
|
|
252
|
+
}
|
|
253
|
+
async function recoverTail(file, head, size) {
|
|
254
|
+
if (head.dbsonl !== 3) return void 0;
|
|
255
|
+
let position = head.end, prev = head.end, found;
|
|
256
|
+
while (position + sequence.FRAME_HEADER_BYTES <= size) {
|
|
257
|
+
let frame;
|
|
258
|
+
try {
|
|
259
|
+
frame = sequence.inspectFrame(await readExact(file, position, sequence.FRAME_HEADER_BYTES), 0, { maxRecordBytes: size });
|
|
260
|
+
} catch {
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
const length = frame.byteLength;
|
|
264
|
+
if (position + length > size) break;
|
|
265
|
+
const bytes = await readExact(file, position, length);
|
|
266
|
+
if (length > RECORD_BYTES) {
|
|
267
|
+
if (crc32c(bytes.subarray(frame.payloadOffset, frame.payloadOffset + frame.payloadLength)) !== frame.checksum) break;
|
|
268
|
+
position += length;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
let value;
|
|
272
|
+
try {
|
|
273
|
+
value = sequence.decodeFrame(bytes, 0, { maxRecordBytes: RECORD_BYTES, maxDepth: 512, maxReferences: 1e6 }).value;
|
|
274
|
+
} catch {
|
|
275
|
+
break;
|
|
276
|
+
}
|
|
277
|
+
const record = value;
|
|
278
|
+
if (record && typeof record === "object" && record.dbsonl === 3 && record.seal === head.seal && record.offset === position && record.prev === prev) {
|
|
279
|
+
let next;
|
|
280
|
+
try {
|
|
281
|
+
next = checkHead({ dbsonl: 3, seal: head.seal, publication: record.publication, revision: record.revision, generation: head.generation, root: record.root, count: record.count, end: position + length });
|
|
282
|
+
} catch {
|
|
283
|
+
break;
|
|
284
|
+
}
|
|
285
|
+
if (next.publication <= (found ?? head).publication) break;
|
|
286
|
+
found = next;
|
|
287
|
+
prev = next.end;
|
|
288
|
+
}
|
|
289
|
+
position += length;
|
|
290
|
+
}
|
|
291
|
+
return found;
|
|
292
|
+
}
|
|
231
293
|
const PAGE_BYTES = 512 * 1024;
|
|
232
294
|
async function readValue(backend$1, name, head, ref, maxRecordBytes, window) {
|
|
233
295
|
common.reference(ref, head.end);
|
|
@@ -284,6 +346,13 @@ function decodeRef(bytes, ref, maxRecordBytes) {
|
|
|
284
346
|
}
|
|
285
347
|
}
|
|
286
348
|
class Appender {
|
|
349
|
+
end;
|
|
350
|
+
buffer;
|
|
351
|
+
used = 0;
|
|
352
|
+
flushedEnd;
|
|
353
|
+
file;
|
|
354
|
+
limits;
|
|
355
|
+
chunkSize;
|
|
287
356
|
constructor(file, end, limits, chunkSize) {
|
|
288
357
|
this.file = file;
|
|
289
358
|
this.limits = limits;
|
|
@@ -292,13 +361,6 @@ class Appender {
|
|
|
292
361
|
this.flushedEnd = end;
|
|
293
362
|
this.buffer = new Uint8Array(Math.min(chunkSize, 65536));
|
|
294
363
|
}
|
|
295
|
-
file;
|
|
296
|
-
limits;
|
|
297
|
-
chunkSize;
|
|
298
|
-
end;
|
|
299
|
-
buffer;
|
|
300
|
-
used = 0;
|
|
301
|
-
flushedEnd;
|
|
302
364
|
/** Coalesce small frames, but preserve the data-before-manifest durability barrier. */
|
|
303
365
|
async flush() {
|
|
304
366
|
if (!this.used) return;
|
|
@@ -431,17 +493,6 @@ async function* entryPages(load, root, gte, lt, depth = 0) {
|
|
|
431
493
|
}
|
|
432
494
|
}
|
|
433
495
|
class BatchTree {
|
|
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) {
|
|
436
|
-
this.writer = writer;
|
|
437
|
-
this.byteBudget = byteBudget;
|
|
438
|
-
this.cached = cached;
|
|
439
|
-
this.root = root;
|
|
440
|
-
this.count = count;
|
|
441
|
-
}
|
|
442
|
-
writer;
|
|
443
|
-
byteBudget;
|
|
444
|
-
cached;
|
|
445
496
|
root;
|
|
446
497
|
count;
|
|
447
498
|
loadedBytes = 0;
|
|
@@ -451,6 +502,17 @@ class BatchTree {
|
|
|
451
502
|
}
|
|
452
503
|
/** Pages this batch appended, for the caller to cache once the root is published. */
|
|
453
504
|
written = [];
|
|
505
|
+
/** cached returns an already validated committed page, or undefined to read it through the writer. */
|
|
506
|
+
writer;
|
|
507
|
+
byteBudget;
|
|
508
|
+
cached;
|
|
509
|
+
constructor(writer, root, count, byteBudget, cached = () => void 0) {
|
|
510
|
+
this.writer = writer;
|
|
511
|
+
this.byteBudget = byteBudget;
|
|
512
|
+
this.cached = cached;
|
|
513
|
+
this.root = root;
|
|
514
|
+
this.count = count;
|
|
515
|
+
}
|
|
454
516
|
/** Committed pages on the next edit's path, found by missing(); each becomes a dirty copy in editable(). */
|
|
455
517
|
fetched = /* @__PURE__ */ new Map();
|
|
456
518
|
editable(link) {
|
|
@@ -554,13 +616,94 @@ class BatchTree {
|
|
|
554
616
|
return { root: this.root ? await persist(this.root) : null, count: this.count };
|
|
555
617
|
}
|
|
556
618
|
}
|
|
619
|
+
async function firstKey(load, piece) {
|
|
620
|
+
if (piece.key !== void 0) return piece.key;
|
|
621
|
+
let ref = piece.ref;
|
|
622
|
+
for (let depth = 0; ; depth++) {
|
|
623
|
+
if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
|
|
624
|
+
const loaded = load(ref), page = "kind" in loaded ? loaded : await loaded;
|
|
625
|
+
if (page.kind === "leaf") return page.entries[0].key;
|
|
626
|
+
ref = page.children[0].ref;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
async function open(load, piece, next) {
|
|
630
|
+
const loaded = load(piece.ref), page = "kind" in loaded ? loaded : await loaded;
|
|
631
|
+
if (page.kind === "leaf") {
|
|
632
|
+
for (const entry of page.entries) next.push({ count: 1, key: entry.key });
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
let low = piece.low;
|
|
636
|
+
for (const child of page.children) {
|
|
637
|
+
next.push({ count: child.count, ref: child.ref, ...low !== void 0 && { low }, high: child.max });
|
|
638
|
+
low = child.max;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
async function split(load, root, total, parts, gte, lt) {
|
|
642
|
+
const whole = (count2) => [{ ...gte !== void 0 && { gte }, ...lt !== void 0 && { lt }, count: count2 }];
|
|
643
|
+
if (!root || gte !== void 0 && lt !== void 0 && gte >= lt) return whole(0);
|
|
644
|
+
if (gte === void 0 && lt === void 0 && parts === 1) return whole(total);
|
|
645
|
+
let pieces = await within(load, root, total, gte, lt);
|
|
646
|
+
const rows = pieces.reduce((sum, piece) => sum + piece.count, 0);
|
|
647
|
+
if (!rows || parts === 1) return whole(rows);
|
|
648
|
+
const limit = Math.max(1, Math.floor(rows / parts / 8));
|
|
649
|
+
for (let depth = 0; pieces.some((piece) => piece.ref && piece.count > limit); depth++) {
|
|
650
|
+
if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
|
|
651
|
+
const next = [];
|
|
652
|
+
for (const piece of pieces) if (!piece.ref || piece.count <= limit) next.push(piece);
|
|
653
|
+
else await open(load, piece, next);
|
|
654
|
+
pieces = next;
|
|
655
|
+
}
|
|
656
|
+
const out = [];
|
|
657
|
+
let used = 0, count = 0, low = gte;
|
|
658
|
+
for (let i = 0; i < pieces.length; i++) {
|
|
659
|
+
count += pieces[i].count;
|
|
660
|
+
used += pieces[i].count;
|
|
661
|
+
if (i + 1 < pieces.length && out.length + 1 < parts && used * parts >= rows * (out.length + 1)) {
|
|
662
|
+
const high = await firstKey(load, pieces[i + 1]);
|
|
663
|
+
out.push(low === void 0 ? { lt: high, count } : { gte: low, lt: high, count });
|
|
664
|
+
low = high;
|
|
665
|
+
count = 0;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
out.push({ ...low !== void 0 && { gte: low }, ...lt !== void 0 && { lt }, count });
|
|
669
|
+
return out;
|
|
670
|
+
}
|
|
671
|
+
async function keyAt(load, root, total, index, gte, lt) {
|
|
672
|
+
if (!root || gte !== void 0 && lt !== void 0 && gte >= lt) return void 0;
|
|
673
|
+
let pieces = await within(load, root, total, gte, lt);
|
|
674
|
+
for (let depth = 0; ; depth++) {
|
|
675
|
+
if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
|
|
676
|
+
let i = 0;
|
|
677
|
+
for (; i < pieces.length && index >= pieces[i].count; i++) index -= pieces[i].count;
|
|
678
|
+
const piece = pieces[i];
|
|
679
|
+
if (!piece) return void 0;
|
|
680
|
+
if (piece.key !== void 0) return piece.key;
|
|
681
|
+
const next = [];
|
|
682
|
+
await open(load, piece, next);
|
|
683
|
+
pieces = next;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
async function within(load, root, total, gte, lt) {
|
|
687
|
+
const inside = (piece) => piece.key !== void 0 ? (gte === void 0 || piece.key >= gte) && (lt === void 0 || piece.key < lt) : (gte === void 0 || piece.low !== void 0 && piece.low >= gte) && (lt === void 0 || piece.high < lt);
|
|
688
|
+
const outside = (piece) => piece.key !== void 0 ? !inside(piece) : gte !== void 0 && piece.high < gte || lt !== void 0 && piece.low !== void 0 && piece.low >= lt;
|
|
689
|
+
let pieces = [{ count: total, ref: root }];
|
|
690
|
+
for (let depth = 0; pieces.some((piece) => !inside(piece) && !outside(piece)); depth++) {
|
|
691
|
+
if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
|
|
692
|
+
const next = [];
|
|
693
|
+
for (const piece of pieces) if (outside(piece)) continue;
|
|
694
|
+
else if (inside(piece)) next.push(piece);
|
|
695
|
+
else await open(load, piece, next);
|
|
696
|
+
pieces = next.filter((piece) => !outside(piece));
|
|
697
|
+
}
|
|
698
|
+
return pieces;
|
|
699
|
+
}
|
|
557
700
|
class BulkTree {
|
|
701
|
+
leaf = [];
|
|
702
|
+
levels = [];
|
|
703
|
+
writer;
|
|
558
704
|
constructor(writer) {
|
|
559
705
|
this.writer = writer;
|
|
560
706
|
}
|
|
561
|
-
writer;
|
|
562
|
-
leaf = [];
|
|
563
|
-
levels = [];
|
|
564
707
|
async push(child, level) {
|
|
565
708
|
const items = this.levels[level] ?? (this.levels[level] = []);
|
|
566
709
|
items.push(child);
|
|
@@ -594,8 +737,16 @@ class BulkTree {
|
|
|
594
737
|
}
|
|
595
738
|
|
|
596
739
|
const GROUP_MEMBERS = 64;
|
|
740
|
+
const HEAD_FLUSH_BYTES = 16 * 1024 * 1024;
|
|
741
|
+
class Recovered {
|
|
742
|
+
head;
|
|
743
|
+
constructor(head) {
|
|
744
|
+
this.head = head;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
597
747
|
const clock = globalThis;
|
|
598
|
-
const
|
|
748
|
+
const batchSizes = /* @__PURE__ */ new WeakMap();
|
|
749
|
+
const encodedBytes = (input) => batchSizes.get(input) ?? input.reduce((sum, item) => sum + (item.bytes?.length ?? 0) + item.key.length * 2 + 64, 0);
|
|
599
750
|
function newGeneration() {
|
|
600
751
|
const crypto = globalThis.crypto;
|
|
601
752
|
if (!crypto?.randomUUID) throw new common.DbsonlError("UNSUPPORTED", "A secure randomUUID implementation is required.");
|
|
@@ -605,7 +756,19 @@ function code(error) {
|
|
|
605
756
|
return error?.code;
|
|
606
757
|
}
|
|
607
758
|
const pageId = (head, ref) => `${head.generation}:${ref.offset}:${ref.byteLength}`;
|
|
759
|
+
const batchBytes = /* @__PURE__ */ new WeakMap();
|
|
760
|
+
const TASK_BYTES = 1024 * 1024, MAX_TASKS = 1024;
|
|
608
761
|
class ReadSession {
|
|
762
|
+
closed = false;
|
|
763
|
+
closing;
|
|
764
|
+
pending = /* @__PURE__ */ new Set();
|
|
765
|
+
/** Scans running in workers; close() stops them, so their worker pins end with this snapshot. */
|
|
766
|
+
scans = /* @__PURE__ */ new Set();
|
|
767
|
+
revision;
|
|
768
|
+
count;
|
|
769
|
+
head;
|
|
770
|
+
db;
|
|
771
|
+
release;
|
|
609
772
|
/** @internal Sessions are created only by the database factory. */
|
|
610
773
|
constructor(db, head, release) {
|
|
611
774
|
this.db = db;
|
|
@@ -615,14 +778,6 @@ class ReadSession {
|
|
|
615
778
|
this.revision = head.revision;
|
|
616
779
|
this.count = head.count;
|
|
617
780
|
}
|
|
618
|
-
db;
|
|
619
|
-
head;
|
|
620
|
-
release;
|
|
621
|
-
closed = false;
|
|
622
|
-
closing;
|
|
623
|
-
pending = /* @__PURE__ */ new Set();
|
|
624
|
-
revision;
|
|
625
|
-
count;
|
|
626
781
|
work(fn, invokesUserCode = false) {
|
|
627
782
|
if (this.closed) return Promise.reject(new common.DbsonlError("CLOSED", "Snapshot is closed."));
|
|
628
783
|
const promise = invokesUserCode ? Promise.resolve().then(fn) : fn();
|
|
@@ -673,12 +828,30 @@ class ReadSession {
|
|
|
673
828
|
const batchSize = common.natural(options.batchSize ?? 256, "batchSize", 1);
|
|
674
829
|
const maxBytes = common.natural(options.maxBatchBytes ?? 4 * 1024 * 1024, "maxBatchBytes", 1);
|
|
675
830
|
if (sizeOf !== void 0 && typeof sizeOf !== "function") throw new TypeError("sizeOf must be a function.");
|
|
676
|
-
const { db, head } = this;
|
|
831
|
+
const { db, head, scans } = this, plan = (gte2, lt2, limit2, batchSize2, maxBatchBytes) => this.parallel(gte2, lt2, limit2, batchSize2, maxBatchBytes);
|
|
677
832
|
async function* batches() {
|
|
678
833
|
let count = 0, bytes = 0, batch = [];
|
|
679
834
|
const window = {};
|
|
680
835
|
common.abort(signal);
|
|
681
836
|
if (!limit) return;
|
|
837
|
+
const parallel = sizeOf === void 0 ? await plan(gte, lt, limit, batchSize, maxBytes) : void 0;
|
|
838
|
+
if (parallel) {
|
|
839
|
+
scans.add(parallel);
|
|
840
|
+
try {
|
|
841
|
+
for (let rows = await parallel.next(); rows; rows = await parallel.next()) {
|
|
842
|
+
common.abort(signal);
|
|
843
|
+
if (count + rows.length > limit) rows = rows.slice(0, limit - count);
|
|
844
|
+
count += rows.length;
|
|
845
|
+
yield rows;
|
|
846
|
+
if (count === limit) return;
|
|
847
|
+
common.abort(signal);
|
|
848
|
+
}
|
|
849
|
+
} finally {
|
|
850
|
+
scans.delete(parallel);
|
|
851
|
+
await parallel.close();
|
|
852
|
+
}
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
682
855
|
for await (const page of entryPages((ref) => db.load(head, ref), head.root, gte, lt)) {
|
|
683
856
|
let first = 0, last = 0, run = [];
|
|
684
857
|
for (let i = 0; i < page.length; i++) {
|
|
@@ -697,6 +870,7 @@ class ReadSession {
|
|
|
697
870
|
const size = common.natural(sizeOf ? sizeOf(row) : entry.ref.byteLength, "batch row bytes");
|
|
698
871
|
if (size > maxBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "One row exceeds the batch byte budget.");
|
|
699
872
|
if (batch.length && bytes + size > maxBytes) {
|
|
873
|
+
batchBytes.set(batch, bytes);
|
|
700
874
|
yield batch;
|
|
701
875
|
batch = [];
|
|
702
876
|
bytes = 0;
|
|
@@ -706,18 +880,25 @@ class ReadSession {
|
|
|
706
880
|
bytes += size;
|
|
707
881
|
count++;
|
|
708
882
|
if (batch.length === batchSize) {
|
|
883
|
+
batchBytes.set(batch, bytes);
|
|
709
884
|
yield batch;
|
|
710
885
|
batch = [];
|
|
711
886
|
bytes = 0;
|
|
712
887
|
common.abort(signal);
|
|
713
888
|
}
|
|
714
889
|
if (count === limit) {
|
|
715
|
-
if (batch.length)
|
|
890
|
+
if (batch.length) {
|
|
891
|
+
batchBytes.set(batch, bytes);
|
|
892
|
+
yield batch;
|
|
893
|
+
}
|
|
716
894
|
return;
|
|
717
895
|
}
|
|
718
896
|
}
|
|
719
897
|
}
|
|
720
|
-
if (batch.length)
|
|
898
|
+
if (batch.length) {
|
|
899
|
+
batchBytes.set(batch, bytes);
|
|
900
|
+
yield batch;
|
|
901
|
+
}
|
|
721
902
|
}
|
|
722
903
|
const iterator = batches();
|
|
723
904
|
return {
|
|
@@ -729,12 +910,37 @@ class ReadSession {
|
|
|
729
910
|
throw: (error) => iterator.throw(error)
|
|
730
911
|
};
|
|
731
912
|
}
|
|
913
|
+
/** Ranges and a running worker scan for a large scanBatches call, or undefined to scan in this thread. */
|
|
914
|
+
async parallel(gte, lt, limit, batchSize, maxBatchBytes) {
|
|
915
|
+
const parallel = this.db.parallel, { head } = this;
|
|
916
|
+
if (!parallel?.workers || head.count < parallel.threshold || limit < parallel.threshold || gte !== void 0 && lt !== void 0 && gte >= lt) return void 0;
|
|
917
|
+
const load = (ref) => this.db.load(head, ref);
|
|
918
|
+
const [counted] = await split(load, head.root, head.count, 1, gte, lt);
|
|
919
|
+
const rows = Math.min(counted.count, limit);
|
|
920
|
+
if (rows < parallel.threshold) return void 0;
|
|
921
|
+
const end = rows < counted.count ? await keyAt(load, head.root, head.count, rows, gte, lt) : lt;
|
|
922
|
+
const parts = Math.min(MAX_TASKS, Math.max(parallel.workers * 2, Math.ceil(rows * (head.end / head.count) / TASK_BYTES)));
|
|
923
|
+
const ranges = (await split(load, head.root, head.count, parts, gte, end)).map((range) => ({ ...range.gte !== void 0 && { gte: range.gte }, ...range.lt !== void 0 && { lt: range.lt } }));
|
|
924
|
+
return ranges.length < 2 ? void 0 : parallel.scan(head, ranges, batchSize, maxBatchBytes);
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* Cut this snapshot into at most parts contiguous key ranges of near-equal size, for scans in parallel. The ranges
|
|
928
|
+
* cover every key in order without overlap, and each count is exact. Other workers scan them through
|
|
929
|
+
* beginRead({ at: session.head }) on handles of their own.
|
|
930
|
+
*/
|
|
931
|
+
split(parts, range = {}) {
|
|
932
|
+
common.natural(parts, "parts", 1);
|
|
933
|
+
if (range.gte !== void 0) common.key(range.gte);
|
|
934
|
+
if (range.lt !== void 0) common.key(range.lt);
|
|
935
|
+
return this.work(() => split((ref) => this.db.load(this.head, ref), this.head.root, this.head.count, parts, range.gte, range.lt));
|
|
936
|
+
}
|
|
732
937
|
/** Drain admitted reads before releasing the generation pin used by garbage collection. */
|
|
733
938
|
close() {
|
|
734
939
|
if (this.closing) return this.closing;
|
|
735
940
|
this.closed = true;
|
|
736
941
|
this.closing = (async () => {
|
|
737
942
|
await Promise.allSettled(this.pending);
|
|
943
|
+
await Promise.allSettled([...this.scans].map((scan) => scan.close()));
|
|
738
944
|
await this.release();
|
|
739
945
|
this.db.forget(this);
|
|
740
946
|
})();
|
|
@@ -742,15 +948,6 @@ class ReadSession {
|
|
|
742
948
|
}
|
|
743
949
|
}
|
|
744
950
|
class Dbsonl {
|
|
745
|
-
constructor(backend, name, options, closeBackend) {
|
|
746
|
-
this.backend = backend;
|
|
747
|
-
this.name = name;
|
|
748
|
-
this.closeBackend = closeBackend;
|
|
749
|
-
this.limits = common.options(options);
|
|
750
|
-
}
|
|
751
|
-
backend;
|
|
752
|
-
name;
|
|
753
|
-
closeBackend;
|
|
754
951
|
closed = false;
|
|
755
952
|
closing;
|
|
756
953
|
pending = /* @__PURE__ */ new Set();
|
|
@@ -774,6 +971,21 @@ class Dbsonl {
|
|
|
774
971
|
arrival;
|
|
775
972
|
/** Wall time of the last group publication in ms, which bounds gather(). */
|
|
776
973
|
groupCost = 0;
|
|
974
|
+
/** Format 3: the generation end of this handle's last flushed head slot; see HEAD_FLUSH_BYTES. */
|
|
975
|
+
headFlushed = 0;
|
|
976
|
+
/** The backend's scan workers, bound to this database's name and decoder budgets. */
|
|
977
|
+
scanner;
|
|
978
|
+
backend;
|
|
979
|
+
name;
|
|
980
|
+
closeBackend;
|
|
981
|
+
constructor(backend, name, options, closeBackend) {
|
|
982
|
+
this.backend = backend;
|
|
983
|
+
this.name = name;
|
|
984
|
+
this.closeBackend = closeBackend;
|
|
985
|
+
this.limits = common.options(options);
|
|
986
|
+
const parallel = backend.parallel, { maxRecordBytes, maxCacheBytes, maxCachePages } = this.limits;
|
|
987
|
+
this.scanner = parallel && { workers: parallel.workers, threshold: parallel.threshold, scan: (head, ranges, batchSize, maxBatchBytes) => parallel.scan({ name, head, ranges, batchSize, maxBatchBytes, limits: { maxRecordBytes, maxCacheBytes, maxCachePages } }) };
|
|
988
|
+
}
|
|
777
989
|
run(fn) {
|
|
778
990
|
if (this.closed) return Promise.reject(new common.DbsonlError("CLOSED", "Database is closed."));
|
|
779
991
|
if (this.pending.size >= this.limits.maxPendingOperations) return Promise.reject(new common.DbsonlError("QUEUE_FULL", "Too many admitted operations."));
|
|
@@ -844,13 +1056,39 @@ class Dbsonl {
|
|
|
844
1056
|
session(head, release) {
|
|
845
1057
|
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
1058
|
this.sessions.delete(session2);
|
|
847
|
-
} }, Object.freeze(head), release);
|
|
1059
|
+
}, parallel: this.scanner }, Object.freeze(head), release);
|
|
848
1060
|
this.sessions.add(session);
|
|
849
1061
|
return session;
|
|
850
1062
|
}
|
|
851
|
-
/**
|
|
852
|
-
|
|
853
|
-
|
|
1063
|
+
/**
|
|
1064
|
+
* Pin the currently published root; subsequent writers do not wait for its lifetime. With at, pin the head of a
|
|
1065
|
+
* snapshot that is still open on any handle, worker or process of this database, so parallel scans read one root.
|
|
1066
|
+
*/
|
|
1067
|
+
beginRead(options = {}) {
|
|
1068
|
+
if (options.at === void 0) return this.run(() => this.snapshot());
|
|
1069
|
+
let head;
|
|
1070
|
+
try {
|
|
1071
|
+
const at = options.at, root = at.root && { offset: at.root.offset, byteLength: at.root.byteLength };
|
|
1072
|
+
head = checkHead({ dbsonl: at.dbsonl, publication: at.publication, revision: at.revision, generation: at.generation, root, count: at.count, end: at.end, ...at.seal !== void 0 && { seal: at.seal } });
|
|
1073
|
+
} catch (cause) {
|
|
1074
|
+
throw new TypeError("options.at must be the head of a snapshot of this database.", { cause });
|
|
1075
|
+
}
|
|
1076
|
+
return this.run(() => backend.locked(this.backend, `commit-${this.name}`, async () => {
|
|
1077
|
+
const current = await readHead(this.backend, this.name, this.headCache);
|
|
1078
|
+
if (head.generation === current.generation) {
|
|
1079
|
+
if (head.end > current.end || head.publication > current.publication) throw new TypeError("options.at is newer than the published head.");
|
|
1080
|
+
} else {
|
|
1081
|
+
let size;
|
|
1082
|
+
try {
|
|
1083
|
+
size = await backend.withFile(this.backend, generationFile(this.name, head.generation), { readOnly: true }, (file) => file.size());
|
|
1084
|
+
} catch (cause) {
|
|
1085
|
+
if (code(cause) === "NOT_FOUND") throw new common.DbsonlError("CONFLICT", "The snapshot was collected; begin a new read.", { cause });
|
|
1086
|
+
throw cause;
|
|
1087
|
+
}
|
|
1088
|
+
if (size < head.end) common.corrupt("Committed generation is truncated.");
|
|
1089
|
+
}
|
|
1090
|
+
return this.session(head, await this.pin(head));
|
|
1091
|
+
}, void 0, true));
|
|
854
1092
|
}
|
|
855
1093
|
/** Internal lookup only: callers must hold a commit lock or generation pin. */
|
|
856
1094
|
async lookup(head, id) {
|
|
@@ -884,14 +1122,16 @@ class Dbsonl {
|
|
|
884
1122
|
encode(input) {
|
|
885
1123
|
if (!Array.isArray(input) || input.length > this.limits.maxTransactionOperations) throw new common.DbsonlError("LIMIT_EXCEEDED", "Transaction operation capacity exceeded.");
|
|
886
1124
|
let bytes = 0;
|
|
887
|
-
|
|
1125
|
+
const encoded = input.map((operation) => {
|
|
888
1126
|
common.key(operation.key);
|
|
889
1127
|
if (operation.operation !== "put" && operation.operation !== "delete") throw new TypeError("Unknown mutation operation.");
|
|
890
|
-
const
|
|
891
|
-
bytes += (
|
|
1128
|
+
const encoded2 = operation.operation === "put" ? sequence.encodeFrame(operation.value, { maxRecordBytes: this.limits.maxRecordBytes }) : void 0;
|
|
1129
|
+
bytes += (encoded2?.length ?? 0) + operation.key.length * 2 + 64;
|
|
892
1130
|
if (bytes > this.limits.maxTransactionBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Transaction encoded-byte capacity exceeded.");
|
|
893
|
-
return { key: operation.key, bytes:
|
|
1131
|
+
return { key: operation.key, bytes: encoded2 };
|
|
894
1132
|
});
|
|
1133
|
+
batchSizes.set(encoded, bytes);
|
|
1134
|
+
return encoded;
|
|
895
1135
|
}
|
|
896
1136
|
/**
|
|
897
1137
|
* Queue a commit. The next holder of the commit lock publishes every queued commit with one write,
|
|
@@ -1037,7 +1277,11 @@ class Dbsonl {
|
|
|
1037
1277
|
const next = await backend.withFile(this.backend, generationFile(this.name, head.generation), {}, async (file) => {
|
|
1038
1278
|
const size = await file.size();
|
|
1039
1279
|
if (size < head.end) common.corrupt("Committed generation is truncated.");
|
|
1040
|
-
if (size > head.end)
|
|
1280
|
+
if (size > head.end) {
|
|
1281
|
+
const found = await recoverTail(file, head, size);
|
|
1282
|
+
if (found) throw new Recovered(found);
|
|
1283
|
+
await file.truncate(head.end);
|
|
1284
|
+
}
|
|
1041
1285
|
const writer = new Appender(file, head.end, this.limits, this.backend.writeChunkBytes);
|
|
1042
1286
|
const tree = new BatchTree(writer, head.root, head.count, this.limits.maxTransactionBytes, (ref) => this.cached(pageId(head, ref)));
|
|
1043
1287
|
const counts = [];
|
|
@@ -1055,13 +1299,21 @@ class Dbsonl {
|
|
|
1055
1299
|
counts.push(tree.size);
|
|
1056
1300
|
}
|
|
1057
1301
|
const { root, count } = await tree.finish();
|
|
1302
|
+
const published = { ...head, publication: common.natural(head.publication + 1, "publication"), revision, root, count, end: writer.end };
|
|
1303
|
+
if (head.dbsonl === 3) {
|
|
1304
|
+
const ref = writer.bytes(commitRecord(published, writer.end, head.end));
|
|
1305
|
+
if (ref instanceof Promise) await ref;
|
|
1306
|
+
published.end = writer.end;
|
|
1307
|
+
}
|
|
1058
1308
|
await writer.flush();
|
|
1059
1309
|
await file.flush();
|
|
1060
|
-
return { head:
|
|
1310
|
+
return { head: published, written: tree.written, counts };
|
|
1061
1311
|
});
|
|
1062
1312
|
publishing = true;
|
|
1313
|
+
const flush = !(next.head.dbsonl === 3 && this.backend.coherent) || next.head.end - this.headFlushed >= HEAD_FLUSH_BYTES;
|
|
1063
1314
|
try {
|
|
1064
|
-
await publish(this.backend, this.name, next.head, this.headCache);
|
|
1315
|
+
await publish(this.backend, this.name, next.head, this.headCache, flush);
|
|
1316
|
+
if (flush) this.headFlushed = next.head.end;
|
|
1065
1317
|
} catch (cause) {
|
|
1066
1318
|
this.lockedHead = void 0;
|
|
1067
1319
|
throw new common.DbsonlError("COMMIT_UNCERTAIN", "Head publication failed; read the current revision before retrying.", { cause });
|
|
@@ -1070,6 +1322,17 @@ class Dbsonl {
|
|
|
1070
1322
|
for (const { ref, page } of next.written) this.remember(pageId(next.head, ref), page, ref.byteLength);
|
|
1071
1323
|
accepted.forEach(({ member, revision: revision2 }, index) => member.resolve({ revision: revision2, count: next.counts[index] }));
|
|
1072
1324
|
} catch (error) {
|
|
1325
|
+
if (error instanceof Recovered) {
|
|
1326
|
+
try {
|
|
1327
|
+
await publish(this.backend, this.name, error.head, this.headCache);
|
|
1328
|
+
this.headFlushed = error.head.end;
|
|
1329
|
+
} catch (cause) {
|
|
1330
|
+
const error2 = new common.DbsonlError("COMMIT_UNCERTAIN", "Publishing recovered commits failed; read the current revision before retrying.", { cause });
|
|
1331
|
+
for (const member of group) if (!member.done) member.reject(error2);
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
return this.publishGroup(group.filter((member) => !member.done));
|
|
1335
|
+
}
|
|
1073
1336
|
if (!publishing && group.length > 1) {
|
|
1074
1337
|
for (const member of group) if (!member.done) await this.publishGroup([member]);
|
|
1075
1338
|
return;
|
|
@@ -1077,6 +1340,23 @@ class Dbsonl {
|
|
|
1077
1340
|
for (const member of group) if (!member.done) member.reject(error);
|
|
1078
1341
|
}
|
|
1079
1342
|
}
|
|
1343
|
+
/** Under the commit lock: the published head, after adopting format 3 commits whose head slot did not reach the disk. */
|
|
1344
|
+
async settledHead() {
|
|
1345
|
+
const head = await readHead(this.backend, this.name, this.headCache);
|
|
1346
|
+
if (head.dbsonl !== 3) return head;
|
|
1347
|
+
const found = await backend.withFile(this.backend, generationFile(this.name, head.generation), { readOnly: true }, async (file) => {
|
|
1348
|
+
const size = await file.size();
|
|
1349
|
+
return size > head.end ? recoverTail(file, head, size) : void 0;
|
|
1350
|
+
});
|
|
1351
|
+
if (!found) return head;
|
|
1352
|
+
try {
|
|
1353
|
+
await publish(this.backend, this.name, found, this.headCache);
|
|
1354
|
+
this.headFlushed = found.end;
|
|
1355
|
+
} catch (cause) {
|
|
1356
|
+
throw new common.DbsonlError("COMMIT_UNCERTAIN", "Publishing recovered commits failed; read the current revision before retrying.", { cause });
|
|
1357
|
+
}
|
|
1358
|
+
return found;
|
|
1359
|
+
}
|
|
1080
1360
|
/** Each point read must still see the entry revision it saw, or absence (0); a scan needs the whole database unchanged. */
|
|
1081
1361
|
async validate(head, reads, written) {
|
|
1082
1362
|
if (reads.whole) throw new common.DbsonlError("CONFLICT", "Database changed since the transaction snapshot.");
|
|
@@ -1272,7 +1552,7 @@ class Dbsonl {
|
|
|
1272
1552
|
const generation = newGeneration();
|
|
1273
1553
|
const filename = generationFile(this.name, generation);
|
|
1274
1554
|
const prepare = async () => {
|
|
1275
|
-
head = await
|
|
1555
|
+
head = await this.settledHead();
|
|
1276
1556
|
sourcePin = await this.backend.coordinator.acquire(`pin-${generationFile(this.name, head.generation)}`, true);
|
|
1277
1557
|
pin = await this.backend.coordinator.acquire(`pin-${filename}`, true);
|
|
1278
1558
|
};
|
|
@@ -1294,7 +1574,7 @@ class Dbsonl {
|
|
|
1294
1574
|
if (packed.count !== head.count) common.corrupt("Compaction key count disagrees with manifest.");
|
|
1295
1575
|
await writer.flush();
|
|
1296
1576
|
await file.flush();
|
|
1297
|
-
return { ...head, ...packed, generation, end: writer.end, publication: common.natural(head.publication + 1, "publication") };
|
|
1577
|
+
return { ...head, ...packed, generation, end: writer.end, publication: common.natural(head.publication + 1, "publication"), ...head.dbsonl === 3 && { seal: newGeneration() } };
|
|
1298
1578
|
});
|
|
1299
1579
|
await this.backend.coordinator.syncDirectory();
|
|
1300
1580
|
const install = async () => {
|
|
@@ -1321,7 +1601,7 @@ class Dbsonl {
|
|
|
1321
1601
|
/** Reclaim unreferenced generations only after every process has released its pin. */
|
|
1322
1602
|
collect() {
|
|
1323
1603
|
return this.run(() => backend.locked(this.backend, `commit-${this.name}`, async () => {
|
|
1324
|
-
const head = await
|
|
1604
|
+
const head = await this.settledHead();
|
|
1325
1605
|
await publish(this.backend, this.name, { ...head, publication: common.natural(head.publication + 1, "publication") }, this.headCache);
|
|
1326
1606
|
const current = generationFile(this.name, head.generation);
|
|
1327
1607
|
const removed = [], retained = [];
|
|
@@ -1391,13 +1671,17 @@ async function openDbsonl(backend$1, name, options = {}) {
|
|
|
1391
1671
|
await backend.withFile(backend$1, generationFile(name, generation), { create: true, exclusive: true }, (file) => file.flush());
|
|
1392
1672
|
if (missing) await backend.withFile(backend$1, headFile(name), { create: true, exclusive: true }, (file) => file.flush());
|
|
1393
1673
|
await backend$1.coordinator.syncDirectory();
|
|
1394
|
-
head = { dbsonl:
|
|
1674
|
+
head = { dbsonl: 3, publication: 1, revision: 0, generation, root: null, count: 0, end: 0, seal: newGeneration() };
|
|
1395
1675
|
await publish(backend$1, name, head);
|
|
1396
1676
|
await publish(backend$1, name, { ...head, publication: 2 });
|
|
1397
1677
|
}
|
|
1398
|
-
|
|
1399
|
-
|
|
1678
|
+
const opened = head;
|
|
1679
|
+
const found = await backend.withFile(backend$1, generationFile(name, opened.generation), { readOnly: true }, async (file) => {
|
|
1680
|
+
const size = await file.size();
|
|
1681
|
+
if (size < opened.end) common.corrupt("Committed generation is truncated.");
|
|
1682
|
+
return size > opened.end ? recoverTail(file, opened, size) : void 0;
|
|
1400
1683
|
});
|
|
1684
|
+
if (found) await publish(backend$1, name, found);
|
|
1401
1685
|
}, options.signal);
|
|
1402
1686
|
return new Dbsonl(backend$1, name, options, connection?.close);
|
|
1403
1687
|
} catch (error) {
|