@the-w1zard/singularity 1.0.10 → 1.0.12

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.
@@ -0,0 +1,1475 @@
1
+ // IMPORTS
2
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
3
+ import { Worker } from "node:worker_threads";
4
+ import { mkdir, open, readFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { encodeRecordChain, decodeRecordChain, encodeFreePage } from "./pages";
8
+ import { decodeWalRecords, encodeWalRecord } from "./wal";
9
+ import { decodeManifest, encodeManifest } from "./manifest";
10
+ import { encodeUtf8, decodeUtf8 } from "./binary";
11
+ import { isWorkerError, NO_PAGE, OP_DELETE, OP_PUT, PAGE_SIZE } from "./types";
12
+ const workerPath = fileURLToPath(new URL("./storage-worker.ts", import.meta.url));
13
+ export function MaybePromise(v) {
14
+ return v !== undefined ? v : Promise.resolve(v);
15
+ }
16
+ export const rv = (v) => typeof v === "function" ? v() : v;
17
+ export const sameValue = (a, b) => Object.is(a, b) || (a instanceof Date && b instanceof Date && +a === +b);
18
+ export class O2 {
19
+ #data = Object.create(null);
20
+ f = this.forEachKV; // [FOR EACH]
21
+ #subs;
22
+ #hist;
23
+ #histLimit = 0;
24
+ #strict = false;
25
+ #iterating = 0;
26
+ #batching = 0;
27
+ #pending;
28
+ #derived;
29
+ #dependents;
30
+ constructor(entries) {
31
+ if (!entries)
32
+ return;
33
+ for (const [k, v] of entries)
34
+ this.#data[k] = v;
35
+ }
36
+ #rawHas(k) { return Object.prototype.hasOwnProperty.call(this.#data, k); }
37
+ #rawGet(k) { return this.#data[k]; }
38
+ #emit(e) {
39
+ if (this.#batching > 0) {
40
+ const pending = this.#pending[e.k];
41
+ this.#pending[e.k] = pending ? { ...e, prev: pending.prev, batch: true } : { ...e, batch: true };
42
+ return;
43
+ }
44
+ this.#record(e);
45
+ this.#subs?.forEach((sub) => {
46
+ try {
47
+ sub(e);
48
+ }
49
+ catch (err) {
50
+ process.emitWarning(err);
51
+ }
52
+ });
53
+ }
54
+ #record(e) {
55
+ if (!this.#hist)
56
+ return;
57
+ this.#hist.push(e);
58
+ if (this.#hist.length > this.#histLimit) {
59
+ this.#hist.splice(0, this.#hist.length - this.#histLimit);
60
+ }
61
+ }
62
+ #invalidate(k) {
63
+ const deps = this.#dependents?.[k];
64
+ if (!deps)
65
+ return;
66
+ for (const dk of deps) {
67
+ const d = this.#derived?.[dk];
68
+ if (!d || d.dirty)
69
+ continue;
70
+ d.dirty = true;
71
+ this.#emit({ op: "dirty", k: dk, has: d.has });
72
+ }
73
+ }
74
+ #computeDerived(k, d) {
75
+ const vals = d.deps.map((dep) => this.g(dep));
76
+ const next = d.fn(...vals);
77
+ const had = d.has;
78
+ const prev = d.value;
79
+ d.value = next;
80
+ d.has = true;
81
+ d.dirty = false;
82
+ if (!had || !sameValue(prev, next)) {
83
+ this.#emit({ op: had ? "upd" : "set", k, v: next, prev: prev, has: true });
84
+ }
85
+ return next;
86
+ }
87
+ #assertNotIterating(op) {
88
+ if (this.#strict && this.#iterating > 0) {
89
+ throw new Error(`O2.${op}() during iteration. Use filterKV(), collect keys first, or disable $strict().`);
90
+ }
91
+ }
92
+ // IN ORDER TO MATCH MAPS CALL API FOR INSTANT AND EASY CONVERSIONS
93
+ get(k) {
94
+ const d = this.#derived?.[k];
95
+ if (d) {
96
+ if (d.dirty || !d.has)
97
+ return this.#computeDerived(k, d);
98
+ return d.value;
99
+ }
100
+ return this.#rawGet(k);
101
+ }
102
+ set(k, v) {
103
+ this.#assertNotIterating("s");
104
+ const next = rv(v);
105
+ const has = this.h(k);
106
+ const prev = has ? this.g(k) : undefined;
107
+ this.#data[k] = next;
108
+ this.#invalidate(k);
109
+ this.#emit({ op: "set", k, v: next, prev: prev, has });
110
+ return this;
111
+ } // note: flipped to match Map's (key, value)
112
+ has(k) {
113
+ const d = this.#derived?.[k];
114
+ if (d) {
115
+ if (d.dirty || !d.has)
116
+ this.#computeDerived(k, d);
117
+ return true;
118
+ }
119
+ return this.#rawHas(k);
120
+ }
121
+ delete(k) {
122
+ this.#assertNotIterating("delete");
123
+ if (!this.h(k))
124
+ return false;
125
+ const prev = this.g(k);
126
+ delete this.#data[k];
127
+ this.#invalidate(k);
128
+ this.#emit({ op: "del", k, prev, has: false });
129
+ return true;
130
+ }
131
+ clear() {
132
+ this.#assertNotIterating("clear");
133
+ const entries = this.toArray();
134
+ this.#data = Object.create(null); // one object swap, no per-key delete
135
+ for (const [k, prev] of entries) {
136
+ this.#invalidate(k);
137
+ this.#emit({ op: "del", k, prev, has: false });
138
+ }
139
+ }
140
+ forEach(fn) { return this.forEachKV(fn); }
141
+ get length() { return this.size; }
142
+ static groupBy(items, fn) {
143
+ const out = new O2();
144
+ let i = 0;
145
+ for (const item of items)
146
+ out.getOrM(() => new A2(), fn(item, i++)).push(item);
147
+ return out;
148
+ }
149
+ get size() {
150
+ return Reflect.ownKeys(this.#data).length;
151
+ }
152
+ [Symbol.iterator]() { return this.entries(); }
153
+ on(fn) {
154
+ (this.#subs ??= new Set()).add(fn);
155
+ return () => this.off(fn);
156
+ }
157
+ off(fn) {
158
+ this.#subs?.delete(fn);
159
+ }
160
+ batch(fn) {
161
+ this.#batching++;
162
+ this.#pending ??= Object.create(null);
163
+ try {
164
+ fn();
165
+ }
166
+ finally {
167
+ this.#batching--;
168
+ if (this.#batching === 0) {
169
+ const pending = this.#pending;
170
+ this.#pending = undefined;
171
+ for (const k of Reflect.ownKeys(pending)) {
172
+ const e = pending[k];
173
+ this.#record(e);
174
+ this.#subs?.forEach((sub) => {
175
+ try {
176
+ sub(e);
177
+ }
178
+ catch (err) {
179
+ process.emitWarning(err);
180
+ }
181
+ });
182
+ }
183
+ }
184
+ }
185
+ return this;
186
+ }
187
+ s(v, k) {
188
+ this.#assertNotIterating("s");
189
+ const next = rv(v);
190
+ const has = this.h(k);
191
+ const prev = has ? this.g(k) : undefined;
192
+ this.#data[k] = next;
193
+ this.#invalidate(k);
194
+ this.#emit({ op: "set", k, v: next, prev: prev, has });
195
+ return this;
196
+ }
197
+ mutate(k, fn) {
198
+ this.#assertNotIterating("mutate");
199
+ if (!this.h(k))
200
+ return undefined;
201
+ const old = this.g(k);
202
+ const next = fn(old, true);
203
+ this.s(next, k);
204
+ return next;
205
+ }
206
+ d(k) {
207
+ this.#assertNotIterating("delete");
208
+ if (!this.h(k))
209
+ return false;
210
+ const prev = this.g(k);
211
+ delete this.#data[k];
212
+ this.#invalidate(k);
213
+ this.#emit({ op: "del", k, prev, has: false });
214
+ return true;
215
+ }
216
+ c() {
217
+ this.#assertNotIterating("clear");
218
+ const entries = this.toArray();
219
+ this.#data = Object.create(null); // one object swap, no per-key delete
220
+ for (const [k, prev] of entries) {
221
+ this.#invalidate(k);
222
+ this.#emit({ op: "del", k, prev, has: false });
223
+ }
224
+ }
225
+ dv(k, deps, fn) {
226
+ (this.#derived ??= Object.create(null))[k] = { deps, fn, dirty: true, has: false };
227
+ for (const dep of deps) {
228
+ const dependents = (this.#dependents ??= Object.create(null));
229
+ (dependents[dep] ??= new Set()).add(k);
230
+ }
231
+ return this;
232
+ }
233
+ dirty(...keys) {
234
+ for (const k of keys) {
235
+ const d = this.#derived?.[k];
236
+ if (d && !d.dirty) {
237
+ d.dirty = true;
238
+ this.#emit({ op: "dirty", k, has: d.has });
239
+ }
240
+ }
241
+ return this;
242
+ }
243
+ g(k) {
244
+ const d = this.#derived?.[k];
245
+ if (d) {
246
+ if (d.dirty || !d.has)
247
+ return this.#computeDerived(k, d);
248
+ return d.value;
249
+ }
250
+ return this.#rawGet(k);
251
+ }
252
+ h(k) {
253
+ const d = this.#derived?.[k];
254
+ if (d) {
255
+ if (d.dirty || !d.has)
256
+ this.#computeDerived(k, d);
257
+ return true;
258
+ }
259
+ return this.#rawHas(k);
260
+ }
261
+ $debug(limit = 256) {
262
+ this.#hist ??= [];
263
+ this.#histLimit = limit;
264
+ return this;
265
+ }
266
+ $strict() {
267
+ this.#strict = true;
268
+ return this;
269
+ }
270
+ $history() {
271
+ return this.#hist ? [...this.#hist] : [];
272
+ }
273
+ $why(k) {
274
+ if (!this.#hist)
275
+ return undefined;
276
+ for (let i = this.#hist.length - 1; i >= 0; i--) {
277
+ if (Object.is(this.#hist[i].k, k))
278
+ return this.#hist[i];
279
+ }
280
+ return undefined;
281
+ }
282
+ $diff(other) {
283
+ const add = [];
284
+ const del = [];
285
+ const chg = [];
286
+ for (const [k, v] of this) {
287
+ if (!other.h(k)) {
288
+ add.push([k, v]);
289
+ }
290
+ else if (!Object.is(other.g(k), v)) {
291
+ chg.push([k, v, other.g(k)]);
292
+ }
293
+ }
294
+ for (const k of other.keys()) {
295
+ if (!this.h(k))
296
+ del.push(k);
297
+ }
298
+ return { add, del, chg };
299
+ }
300
+ *entries() {
301
+ this.#iterating++;
302
+ try {
303
+ for (const k of Reflect.ownKeys(this.#data))
304
+ yield [k, this.#data[k]];
305
+ }
306
+ finally {
307
+ this.#iterating--;
308
+ }
309
+ }
310
+ *keys() {
311
+ this.#iterating++;
312
+ try {
313
+ for (const k of Reflect.ownKeys(this.#data))
314
+ yield k;
315
+ }
316
+ finally {
317
+ this.#iterating--;
318
+ }
319
+ }
320
+ *values() {
321
+ this.#iterating++;
322
+ try {
323
+ for (const k of Reflect.ownKeys(this.#data))
324
+ yield this.#data[k];
325
+ }
326
+ finally {
327
+ this.#iterating--;
328
+ }
329
+ }
330
+ swap(value, key) {
331
+ const next = rv(value);
332
+ const previous = this.h(key) ? this.g(key) : next; // h()/g() kept derived-aware
333
+ this.s(next, key);
334
+ return previous;
335
+ }
336
+ take(k) {
337
+ const value = this.g(k);
338
+ this.d(k);
339
+ return value;
340
+ }
341
+ peek(k) {
342
+ return this.h(k) ? this.g(k) : false;
343
+ }
344
+ getOrI(value, k) {
345
+ if (this.h(k))
346
+ return this.g(k);
347
+ const next = rv(value);
348
+ this.s(next, k);
349
+ return next;
350
+ }
351
+ getOrM(make, k) {
352
+ if (this.h(k))
353
+ return this.g(k);
354
+ const value = make();
355
+ this.s(value, k);
356
+ return value;
357
+ }
358
+ update(k, fn, initial) {
359
+ const has = this.h(k);
360
+ const old = has
361
+ ? this.g(k)
362
+ : initial === undefined
363
+ ? undefined
364
+ : rv(initial);
365
+ const next = rv(fn(old, has));
366
+ this.s(next, k);
367
+ return next;
368
+ }
369
+ setIfAbsent(value, k) {
370
+ if (this.h(k))
371
+ return false;
372
+ const next = rv(value);
373
+ this.s(next, k);
374
+ return true;
375
+ }
376
+ setIfPresent(value, k) {
377
+ if (!this.h(k))
378
+ return false;
379
+ const next = rv(value);
380
+ this.s(next, k);
381
+ return true;
382
+ }
383
+ replace(value, k) {
384
+ const next = rv(value);
385
+ return this.setIfPresent(next, k);
386
+ }
387
+ inc(key, by = 1) {
388
+ return this.update(key, (old) => ((old ?? 0) + by), 0);
389
+ }
390
+ touch(k) {
391
+ return this.setIfAbsent(undefined, k);
392
+ }
393
+ mapValues(fn) {
394
+ const out = new O2();
395
+ for (const [k, v] of this)
396
+ out.s(fn(v, k), k);
397
+ return out;
398
+ }
399
+ mapKeys(fn) {
400
+ const out = new O2();
401
+ for (const [k, v] of this)
402
+ out.s(v, fn(v, k));
403
+ return out;
404
+ }
405
+ filterKV(pred) {
406
+ for (const [k, v] of this) {
407
+ if (!pred(v, k))
408
+ this.d(k);
409
+ }
410
+ return this;
411
+ }
412
+ filterKeys(pred) {
413
+ return this.filterKV(pred);
414
+ }
415
+ partition(pred) {
416
+ const yes = new O2();
417
+ const no = new O2();
418
+ for (const [k, v] of this) {
419
+ (pred(v, k) ? yes : no).s(v, k);
420
+ }
421
+ return [yes, no];
422
+ }
423
+ find(pred) {
424
+ for (const [k, v] of this) {
425
+ if (pred(v, k))
426
+ return [k, v];
427
+ }
428
+ return undefined;
429
+ }
430
+ findKey(pred) {
431
+ for (const [k, v] of this) {
432
+ if (pred(v, k))
433
+ return k;
434
+ }
435
+ return undefined;
436
+ }
437
+ findValue(pred) {
438
+ for (const [k, v] of this) {
439
+ if (pred(v, k))
440
+ return v;
441
+ }
442
+ return undefined;
443
+ }
444
+ some(pred) {
445
+ for (const [k, v] of this) {
446
+ if (pred(v, k))
447
+ return true;
448
+ }
449
+ return false;
450
+ }
451
+ every(pred) {
452
+ for (const [k, v] of this) {
453
+ if (!pred(v, k))
454
+ return false;
455
+ }
456
+ return true;
457
+ }
458
+ reduce(fn, initial) {
459
+ let acc = initial;
460
+ for (const [k, v] of this)
461
+ acc = fn(acc, v, k);
462
+ return acc;
463
+ }
464
+ forEachKV(fn) {
465
+ for (const [k, v] of this)
466
+ fn(v, k, this);
467
+ }
468
+ invert() {
469
+ const out = new O2();
470
+ for (const [k, v] of this)
471
+ out.s(k, v);
472
+ return out;
473
+ }
474
+ unique(fn) {
475
+ const out = new O2();
476
+ for (const [k, v] of this) {
477
+ const key = (fn ? fn(v, k) : v);
478
+ if (!out.h(key))
479
+ out.s(v, key);
480
+ }
481
+ return out;
482
+ }
483
+ pick(keys) {
484
+ const out = new O2();
485
+ for (const k of keys) {
486
+ if (this.h(k))
487
+ out.s(this.g(k), k);
488
+ }
489
+ return out;
490
+ }
491
+ omit(keys) {
492
+ const omitted = new Set(keys);
493
+ const out = new O2();
494
+ for (const [k, v] of this) {
495
+ if (!omitted.has(k))
496
+ out.s(v, k);
497
+ }
498
+ return out;
499
+ }
500
+ merge(other) {
501
+ for (const [k, v] of other) {
502
+ const n = rv(v);
503
+ this.s(n, k);
504
+ }
505
+ return this;
506
+ }
507
+ clearAndSet(entries) {
508
+ return this.batch(() => {
509
+ this.c(); // (M2's version calls the native Map.clear() here
510
+ for (const [k, v] of entries) { // — silent, no del events; c() is almost
511
+ const n = rv(v); // certainly what was intended, so I used it)
512
+ this.s(n, k);
513
+ }
514
+ });
515
+ }
516
+ toObject() {
517
+ const out = {};
518
+ for (const [k, v] of this)
519
+ out[k] = v;
520
+ return out;
521
+ }
522
+ toObjectFast() {
523
+ return { ...this.#data };
524
+ }
525
+ snapshot() { return this.toObjectFast(); } // handy name for hook/selector use
526
+ toJSON() { return this.toObjectFast(); } // JSON.stringify(store) just works
527
+ select(fn) {
528
+ return fn(this.#data);
529
+ }
530
+ patch(partial) {
531
+ return this.batch(() => {
532
+ for (const k of Reflect.ownKeys(partial))
533
+ this.s(partial[k], k);
534
+ });
535
+ }
536
+ toValues() { return A2.from(this.values()); } // [TOVALUES]
537
+ toKeys() { return A2.from(this.keys()); } // [TOKEYS]
538
+ toArray() { return A2.from(this.entries()); } // [TOARRAY]
539
+ group(fn) {
540
+ const out = new O2();
541
+ for (const [k, v] of this)
542
+ out.getOrM(() => new A2(), fn(v, k)).push(v);
543
+ return out;
544
+ }
545
+ clone() {
546
+ return new O2(this);
547
+ }
548
+ equals(other) {
549
+ if (other === this)
550
+ return true;
551
+ if (this.size !== other.size)
552
+ return false;
553
+ for (const [k, v] of this) {
554
+ if (!other.h(k) || !sameValue(other.g(k), v))
555
+ return false;
556
+ }
557
+ return true;
558
+ }
559
+ static fromObject(obj) {
560
+ const out = new O2();
561
+ out.#data = { ...obj }; // direct copy, no per-key emits
562
+ return out;
563
+ }
564
+ static fromEntries(entries) {
565
+ return new O2(entries);
566
+ }
567
+ static from(source) {
568
+ const out = new O2();
569
+ out.#data = source instanceof O2 ? { ...source.#data } : { ...source };
570
+ return out;
571
+ }
572
+ }
573
+ export class A2 extends Array {
574
+ constructor(...items) {
575
+ super(...items);
576
+ Object.setPrototypeOf(this, new.target.prototype);
577
+ }
578
+ static get [Symbol.species]() {
579
+ return Array;
580
+ }
581
+ static from(arrayLike) {
582
+ return new A2(...Array.from(arrayLike));
583
+ }
584
+ static of(...items) {
585
+ return new A2(...items);
586
+ }
587
+ first() {
588
+ return this[0];
589
+ }
590
+ last() {
591
+ return this[this.length - 1];
592
+ }
593
+ isEmpty() {
594
+ return this.length === 0;
595
+ }
596
+ isNotEmpty() {
597
+ return this.length !== 0;
598
+ }
599
+ clear() {
600
+ this.length = 0;
601
+ return this;
602
+ }
603
+ clone() {
604
+ return new A2(...this);
605
+ }
606
+ unique() {
607
+ return new A2(...new Set(this));
608
+ }
609
+ compact() {
610
+ return new A2(...this.filter((value) => value != null));
611
+ }
612
+ take(count) {
613
+ return new A2(...this.slice(0, Math.max(0, count)));
614
+ }
615
+ takeLast(count) {
616
+ return new A2(...this.slice(Math.max(0, this.length - Math.max(0, count))));
617
+ }
618
+ drop(count) {
619
+ return new A2(...this.slice(Math.max(0, count)));
620
+ }
621
+ dropLast(count) {
622
+ return new A2(...this.slice(0, Math.max(0, this.length - Math.max(0, count))));
623
+ }
624
+ chunk(size) {
625
+ if (!Number.isInteger(size) || size < 1) {
626
+ throw new RangeError("Chunk size must be a positive integer.");
627
+ }
628
+ const result = new A2();
629
+ for (let i = 0; i < this.length; i += size) {
630
+ result.push(new A2(...this.slice(i, i + size)));
631
+ }
632
+ return result;
633
+ }
634
+ flatten(depth = Infinity) {
635
+ return new A2(...this.flat(depth));
636
+ }
637
+ flatMap(callback) {
638
+ return new A2(...this.flatMap((value, index) => callback(value, index, this)));
639
+ }
640
+ distinctBy(callback) {
641
+ const seen = new Set();
642
+ const result = new A2();
643
+ this.forEach((value, index) => {
644
+ const key = callback(value, index);
645
+ if (!seen.has(key)) {
646
+ seen.add(key);
647
+ result.push(value);
648
+ }
649
+ });
650
+ return result;
651
+ }
652
+ groupBy(callback) {
653
+ const result = new Map();
654
+ this.forEach((value, index) => {
655
+ const key = callback(value, index);
656
+ let group = result.get(key);
657
+ if (!group) {
658
+ group = new A2();
659
+ result.set(key, group);
660
+ }
661
+ group.push(value);
662
+ });
663
+ return result;
664
+ }
665
+ partition(callback) {
666
+ const yes = new A2();
667
+ const no = new A2();
668
+ this.forEach((value, index) => {
669
+ (callback(value, index) ? yes : no).push(value);
670
+ });
671
+ return [yes, no];
672
+ }
673
+ insert(index, ...items) {
674
+ this.splice(index, 0, ...items);
675
+ return this;
676
+ }
677
+ removeAt(index) {
678
+ const normalized = index < 0 ? this.length + index : index;
679
+ if (normalized < 0 || normalized >= this.length) {
680
+ return undefined;
681
+ }
682
+ return this.splice(normalized, 1)[0];
683
+ }
684
+ remove(value) {
685
+ const index = this.indexOf(value);
686
+ if (index === -1) {
687
+ return false;
688
+ }
689
+ this.splice(index, 1);
690
+ return true;
691
+ }
692
+ removeAll(value) {
693
+ let removed = 0;
694
+ for (let i = this.length - 1; i >= 0; i--) {
695
+ if (Object.is(this[i], value)) {
696
+ this.splice(i, 1);
697
+ removed++;
698
+ }
699
+ }
700
+ return removed;
701
+ }
702
+ replaceAt(index, value) {
703
+ const normalized = index < 0 ? this.length + index : index;
704
+ if (normalized < 0 || normalized >= this.length) {
705
+ return undefined;
706
+ }
707
+ const previous = this[normalized];
708
+ this[normalized] = value;
709
+ return previous;
710
+ }
711
+ move(from, to) {
712
+ const source = from < 0 ? this.length + from : from;
713
+ const target = to < 0 ? this.length + to : to;
714
+ if (source < 0 || source >= this.length ||
715
+ target < 0 || target >= this.length ||
716
+ source === target) {
717
+ return this;
718
+ }
719
+ const [item] = this.splice(source, 1);
720
+ this.splice(target, 0, item);
721
+ return this;
722
+ }
723
+ swap(first, second) {
724
+ const a = first < 0 ? this.length + first : first;
725
+ const b = second < 0 ? this.length + second : second;
726
+ if (a < 0 || a >= this.length ||
727
+ b < 0 || b >= this.length) {
728
+ return this;
729
+ }
730
+ [this[a], this[b]] = [this[b], this[a]];
731
+ return this;
732
+ }
733
+ sample() {
734
+ if (this.length === 0) {
735
+ return undefined;
736
+ }
737
+ return this[Math.floor(Math.random() * this.length)];
738
+ }
739
+ shuffle() {
740
+ for (let i = this.length - 1; i > 0; i--) {
741
+ const j = Math.floor(Math.random() * (i + 1));
742
+ [this[i], this[j]] = [this[j], this[i]];
743
+ }
744
+ return this;
745
+ }
746
+ countBy(callback) {
747
+ let count = 0;
748
+ this.forEach((value, index) => {
749
+ if (callback(value, index))
750
+ count++;
751
+ });
752
+ return count;
753
+ }
754
+ sum(callback) {
755
+ let total = 0;
756
+ this.forEach((value, index) => {
757
+ total += callback ? callback(value, index) : Number(value);
758
+ });
759
+ return total;
760
+ }
761
+ average(callback) {
762
+ return (this.length === 0 ? NaN : this.sum(callback) / this.length);
763
+ }
764
+ min(callback) {
765
+ if (this.length === 0)
766
+ return undefined;
767
+ return this.reduce((best, value, index) => {
768
+ const current = callback ? callback(value, index) : Number(value);
769
+ const bestValue = callback ? callback(best, this.indexOf(best)) : Number(best);
770
+ return current < bestValue ? value : best;
771
+ });
772
+ }
773
+ max(callback) {
774
+ if (this.length === 0)
775
+ return undefined;
776
+ return this.reduce((best, value, index) => {
777
+ const current = callback ? callback(value, index) : Number(value);
778
+ const bestValue = callback ? callback(best, this.indexOf(best)) : Number(best);
779
+ return current > bestValue ? value : best;
780
+ });
781
+ }
782
+ equals(array) {
783
+ return this.length === array.length &&
784
+ this.every((value, index) => Object.is(value, array[index]));
785
+ }
786
+ includesAll(values) {
787
+ return values.every(value => this.includes(value));
788
+ }
789
+ intersects(values) {
790
+ return values.some(value => this.includes(value));
791
+ }
792
+ }
793
+ export class SERVER_KVDB {
794
+ // CONSTANTS
795
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
796
+ r = "THE_WIZARD_ROOT_REG";
797
+ m = "SAURON_MASTER_REG";
798
+ s = "SAURON_SLAVE_REG";
799
+ k = "__SAURON__";
800
+ #hot_cache = Object.create(null);
801
+ ///#hot_cache = new O2<S, A>();
802
+ #waiters = new O2();
803
+ #entries = new O2();
804
+ #options;
805
+ #directory;
806
+ #dataPath;
807
+ #walPath;
808
+ #manifestPath;
809
+ #worker;
810
+ #pending = new O2();
811
+ #freePages = [];
812
+ #dirtyPages = new O2();
813
+ #pageCount = 0;
814
+ #nextSequence = 1n;
815
+ #checkpointSequence = 0n;
816
+ #walSize = 0;
817
+ #batch;
818
+ #batchTimer;
819
+ #writeQueue = Promise.resolve();
820
+ #closed = false;
821
+ _onError;
822
+ constructor(k = "__SAURON__", s = "SAURON_SLAVE_REG", m = "SAURON_MASTER_REG", r = "THE_WIZARD_ROOT_REG", options = {}) {
823
+ this.k = k;
824
+ this.s = s;
825
+ this.m = m;
826
+ this.r = r;
827
+ this.#options = {
828
+ directory: options.directory ?? "./data/fastkv",
829
+ durability: options.durability ?? "group",
830
+ walBatchBytes: options.walBatchBytes ?? 256 * 1024,
831
+ walBatchRecords: options.walBatchRecords ?? 4096,
832
+ walFlushIntervalMs: options.walFlushIntervalMs ?? 1,
833
+ walHighWaterBytes: options.walHighWaterBytes ?? 16 * 1024 * 1024,
834
+ checkpointIntervalMs: options.checkpointIntervalMs ?? 5_000
835
+ };
836
+ }
837
+ // #endregion
838
+ // API
839
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
840
+ get = (() => {
841
+ const z = (k, s = this.s, m = this.m, r = this.r) => {
842
+ const cached = this.#hot_cache[k];
843
+ if (cached !== undefined)
844
+ return MaybePromise(cached);
845
+ else {
846
+ const entry = this.#entries.get(k);
847
+ if (!entry)
848
+ return undefined;
849
+ return MaybePromise(this.#workerRequest({
850
+ kind: "readPages",
851
+ pageNumbers: entry.pageNumbers
852
+ }).then((response) => {
853
+ if (response.kind !== "readPagesOk") {
854
+ throw new Error(response.kind === "error" ? response.error : "Unexpected worker response");
855
+ }
856
+ const decoded = this.#decodeRecordChainFromPages(response.pages, entry.pageNumbers);
857
+ if (!decoded) {
858
+ return undefined;
859
+ }
860
+ this.#hot_cache[k] = decoded.value;
861
+ return decoded.value;
862
+ }));
863
+ }
864
+ };
865
+ z.many = async (keys) => {
866
+ await Promise.all(Object.entries(keys).map(([k]) => this.get(k)));
867
+ };
868
+ z.hot = (k) => {
869
+ return this.#hot_cache[k];
870
+ };
871
+ return z;
872
+ })();
873
+ hot(k) {
874
+ return this.#hot_cache[k];
875
+ }
876
+ set = (() => {
877
+ const z = async (k, value, s = this.s, m = this.m, r = this.r, options = { durable: true }) => {
878
+ this.#hot_cache[k] = value;
879
+ // this.#hot_cache.set(k, value);
880
+ const wk = `__waiters_${k}`;
881
+ const ws = this.#waiters.get(wk);
882
+ if (ws) {
883
+ for (const resolve of ws)
884
+ resolve(value);
885
+ this.#waiters.delete(wk);
886
+ }
887
+ this._emit(k, value);
888
+ const valueBytes = typeof value === "string" ? encodeUtf8(value) : value;
889
+ const keyBytes = encodeUtf8(k);
890
+ return this.#enqueueWrite(async () => {
891
+ if (this.#closed) {
892
+ throw new Error("FastKV is closed");
893
+ }
894
+ this.#applyPut(k, keyBytes, valueBytes);
895
+ const record = encodeWalRecord({
896
+ sequence: this.#nextSequence++,
897
+ operation: OP_PUT,
898
+ key: keyBytes,
899
+ value: valueBytes
900
+ });
901
+ const durable = this.#resolveDurability(options.durable);
902
+ const flushPromise = this.#appendToBatch(record, durable);
903
+ if (options.durable === true || this.#options.durability === "strict") {
904
+ await flushPromise;
905
+ }
906
+ });
907
+ };
908
+ z.many = async (entries) => {
909
+ await Promise.all(Object.entries(entries).map(([k, v]) => this.set(k, v)));
910
+ };
911
+ return z;
912
+ })();
913
+ delete = (() => {
914
+ const z = async (key, options = {}) => {
915
+ const keyBytes = encodeUtf8(key);
916
+ this._emit(key, undefined);
917
+ return this.#enqueueWrite(async () => {
918
+ if (this.#closed) {
919
+ throw new Error("FastKV is closed");
920
+ }
921
+ if (!this.#entries.has(key)) {
922
+ return false;
923
+ }
924
+ this.#applyDelete(key);
925
+ const record = encodeWalRecord({
926
+ sequence: this.#nextSequence++,
927
+ operation: OP_DELETE,
928
+ key: keyBytes,
929
+ value: new Uint8Array(0)
930
+ });
931
+ const durable = this.#resolveDurability(options.durable);
932
+ const flushPromise = this.#appendToBatch(record, durable);
933
+ if (options.durable === true || this.#options.durability === "strict") {
934
+ await flushPromise;
935
+ }
936
+ return true;
937
+ });
938
+ };
939
+ z.many = async (keys) => { await Promise.all(keys.map((k) => this.delete(k))); };
940
+ return z;
941
+ })();
942
+ update = (() => {
943
+ const z = async (key, updater) => {
944
+ const prev = await this.get(key);
945
+ const next = updater(prev);
946
+ await this.set(key, next);
947
+ return next;
948
+ };
949
+ z.many = () => { };
950
+ return z;
951
+ })();
952
+ has(key) { return this.#entries.has(key); }
953
+ send = (() => {
954
+ const z = () => { };
955
+ z.many = () => { };
956
+ return z;
957
+ })();
958
+ // #endregion
959
+ // SUB
960
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
961
+ subscribe(key, cb) {
962
+ let set = this.#waiters.get(key);
963
+ if (!set) {
964
+ set = new Set();
965
+ this.#waiters.set(key, set);
966
+ }
967
+ set.add(cb);
968
+ const cached = this.#hot_cache[key];
969
+ if (cached) {
970
+ try {
971
+ cb(cached);
972
+ }
973
+ catch (e) {
974
+ this._onError(e);
975
+ }
976
+ }
977
+ return () => {
978
+ const s = this.#waiters.get(key);
979
+ if (!s)
980
+ return;
981
+ s.delete(cb);
982
+ if (s.size === 0)
983
+ this.#waiters.delete(key);
984
+ };
985
+ } /** Selector-based subscription — only fires when the selected slice changes. */
986
+ select(key, selector, cb, chain) {
987
+ let last;
988
+ let first = true;
989
+ return this.subscribe(key, (v) => {
990
+ const next = selector(v);
991
+ if (first || !Object.is(last, next)) {
992
+ first = false;
993
+ last = next;
994
+ cb(next);
995
+ }
996
+ });
997
+ }
998
+ _emit(key, value) {
999
+ const set = this.#waiters.get(key);
1000
+ if (!set)
1001
+ return;
1002
+ for (const cb of set) {
1003
+ try {
1004
+ cb(value);
1005
+ }
1006
+ catch (e) {
1007
+ this._onError(e);
1008
+ }
1009
+ }
1010
+ }
1011
+ _peek(key) {
1012
+ const v = this.#hot_cache[key];
1013
+ return v === undefined ? undefined : v;
1014
+ }
1015
+ waitFor(key) {
1016
+ const existing = this._peek(key);
1017
+ if (existing !== undefined)
1018
+ return Promise.resolve(existing);
1019
+ return new Promise((resolve) => {
1020
+ const waiterKey = `__waiters_${key}`;
1021
+ let waiters = this.#waiters.get(waiterKey);
1022
+ if (!waiters) {
1023
+ waiters = new Set();
1024
+ this.#waiters.set(waiterKey, waiters);
1025
+ }
1026
+ waiters.add(resolve);
1027
+ });
1028
+ }
1029
+ // #endregion
1030
+ // WORKER FNS
1031
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
1032
+ async open() {
1033
+ if (this.#worker) {
1034
+ throw new Error("FastKV is already open");
1035
+ }
1036
+ this.#directory = path.resolve(this.#options.directory);
1037
+ this.#dataPath = path.join(this.#directory, "data.paged");
1038
+ this.#walPath = path.join(this.#directory, "wal.log");
1039
+ this.#manifestPath = path.join(this.#directory, "manifest.bin");
1040
+ await mkdir(this.#directory, { recursive: true });
1041
+ const dataFile = await open(this.#dataPath, "a+");
1042
+ await dataFile.close();
1043
+ const walFile = await open(this.#walPath, "a+");
1044
+ await walFile.close();
1045
+ await this.#recover();
1046
+ await this.#startWorker();
1047
+ setInterval(() => {
1048
+ void this.#checkpointIfRequired();
1049
+ }, this.#options.checkpointIntervalMs).unref();
1050
+ }
1051
+ async flush() {
1052
+ await this.#enqueueWrite(async () => {
1053
+ await this.#flushCurrentBatch();
1054
+ });
1055
+ }
1056
+ async checkpoint() {
1057
+ await this.#enqueueWrite(async () => {
1058
+ await this.#checkpoint();
1059
+ });
1060
+ }
1061
+ async compact() {
1062
+ await this.#enqueueWrite(async () => {
1063
+ await this.#flushCurrentBatch();
1064
+ const compactPath = `${this.#dataPath}.compact`;
1065
+ await this.#workerRequest({ kind: "compactBegin", compactPath });
1066
+ const livePages = [];
1067
+ let nextPage = 0;
1068
+ // const oldEntries = new O2(this.#entries);
1069
+ // const oldValues = new O2(this.#hot_cache);
1070
+ const oldEntries = Object.assign(Object.create(null), this.#entries);
1071
+ const oldValues = Object.assign(Object.create(null), this.#hot_cache);
1072
+ this.#entries.clear();
1073
+ // this.#hot_cache.clear();
1074
+ this.#hot_cache = Object.create(null);
1075
+ this.#freePages = [];
1076
+ this.#dirtyPages.clear();
1077
+ this.#pageCount = 0;
1078
+ for (const [key, entry] of oldEntries) {
1079
+ const value = oldValues.get(key);
1080
+ if (!value)
1081
+ continue;
1082
+ // this.#hot_cache.set(key, value);
1083
+ this.#hot_cache[key] = value;
1084
+ const keyBytes = encodeUtf8(key);
1085
+ const chain = encodeRecordChain(keyBytes, value, () => nextPage++);
1086
+ for (const page of chain.pages) {
1087
+ livePages.push({
1088
+ pageNumber: chain.pageNumbers[0],
1089
+ buffer: page
1090
+ });
1091
+ }
1092
+ this.#entries.set(key, {
1093
+ pageNumber: chain.pageNumbers[0],
1094
+ pageNumbers: chain.pageNumbers
1095
+ });
1096
+ }
1097
+ this.#pageCount = nextPage;
1098
+ const manifest = encodeManifest({ checkpointSequence: this.#nextSequence, pageCount: this.#pageCount });
1099
+ await this.#workerRequest({ kind: "compactWrite", pages: livePages });
1100
+ await this.#workerRequest({
1101
+ kind: "compactCommit",
1102
+ dataPath: this.#dataPath,
1103
+ compactPath,
1104
+ manifest,
1105
+ walPath: this.#walPath
1106
+ });
1107
+ this.#checkpointSequence = this.#nextSequence;
1108
+ this.#walSize = 0;
1109
+ });
1110
+ }
1111
+ async close() {
1112
+ if (this.#closed)
1113
+ return;
1114
+ this.#closed = true;
1115
+ await this.#enqueueWrite(async () => {
1116
+ await this.#checkpoint();
1117
+ });
1118
+ await this.#workerRequest({
1119
+ kind: "close"
1120
+ });
1121
+ await this.#worker?.terminate();
1122
+ this.#worker = undefined;
1123
+ }
1124
+ get stats() {
1125
+ return {
1126
+ keys: this.#entries.size,
1127
+ pages: this.#pageCount,
1128
+ freePages: this.#freePages.length,
1129
+ dirtyPages: this.#dirtyPages.size,
1130
+ walBytes: this.#walSize,
1131
+ checkpointSequence: this.#checkpointSequence,
1132
+ nextSequence: this.#nextSequence,
1133
+ durability: this.#options.durability
1134
+ };
1135
+ }
1136
+ #resolveDurability(requested) {
1137
+ if (requested !== undefined) {
1138
+ return requested;
1139
+ }
1140
+ return (this.#options.durability === "group" ||
1141
+ this.#options.durability === "strict");
1142
+ }
1143
+ #applyPut(key, keyBytes, valueBytes, replay = false) {
1144
+ const previous = this.#entries.get(key);
1145
+ const chain = encodeRecordChain(keyBytes, valueBytes, () => {
1146
+ const reused = this.#freePages.pop();
1147
+ if (reused !== undefined) {
1148
+ return reused;
1149
+ }
1150
+ return this.#pageCount++;
1151
+ });
1152
+ if (previous) {
1153
+ for (const pageNumber of previous.pageNumbers) {
1154
+ this.#dirtyPages.set(pageNumber, encodeFreePage());
1155
+ this.#freePages.push(pageNumber);
1156
+ }
1157
+ }
1158
+ for (let index = 0; index < chain.pages.length; index++) {
1159
+ this.#dirtyPages.set(chain.pageNumbers[index], chain.pages[index]);
1160
+ }
1161
+ this.#entries.set(key, {
1162
+ pageNumber: chain.pageNumbers[0],
1163
+ pageNumbers: chain.pageNumbers
1164
+ });
1165
+ // this.#hot_cache.set(key, valueBytes);
1166
+ if (replay) {
1167
+ this.#nextSequence = this.#nextSequence;
1168
+ }
1169
+ }
1170
+ #applyDelete(key, replay = false) {
1171
+ const previous = this.#entries.get(key);
1172
+ if (!previous)
1173
+ return;
1174
+ for (const pageNumber of previous.pageNumbers) {
1175
+ this.#dirtyPages.set(pageNumber, encodeFreePage());
1176
+ this.#freePages.push(pageNumber);
1177
+ }
1178
+ this.#entries.delete(key);
1179
+ //this.#hot_cache.delete(key);
1180
+ delete this.#hot_cache[key];
1181
+ if (replay) {
1182
+ this.#nextSequence = this.#nextSequence;
1183
+ }
1184
+ }
1185
+ #enqueueWrite(operation) {
1186
+ const result = this.#writeQueue.then(operation, operation);
1187
+ this.#writeQueue = result.catch(() => undefined);
1188
+ return result;
1189
+ }
1190
+ #appendToBatch(record, durable) {
1191
+ if (!this.#batch) {
1192
+ this.#batch = {
1193
+ batchId: crypto.randomUUID(),
1194
+ records: [],
1195
+ byteLength: 0,
1196
+ durable: false,
1197
+ waiters: []
1198
+ };
1199
+ }
1200
+ const batch = this.#batch;
1201
+ batch.records.push(record);
1202
+ batch.byteLength += record.length;
1203
+ batch.durable ||= durable;
1204
+ return new Promise((resolve) => {
1205
+ batch.waiters.push(resolve);
1206
+ if (batch.byteLength >= this.#options.walBatchBytes ||
1207
+ batch.records.length >= this.#options.walBatchRecords) {
1208
+ void this.#flushCurrentBatch();
1209
+ return;
1210
+ }
1211
+ this.#batchTimer ??= setTimeout(() => {
1212
+ this.#batchTimer = undefined;
1213
+ void this.#flushCurrentBatch();
1214
+ }, this.#options.walFlushIntervalMs);
1215
+ });
1216
+ }
1217
+ #workerRequest(request) {
1218
+ if (!this.#worker) {
1219
+ return Promise.reject(new Error("FastKV is not open"));
1220
+ }
1221
+ const id = crypto.randomUUID();
1222
+ return new Promise((resolve, reject) => {
1223
+ this.#pending.set(id, {
1224
+ resolve,
1225
+ reject
1226
+ });
1227
+ this.#worker.postMessage({
1228
+ ...request,
1229
+ id
1230
+ });
1231
+ });
1232
+ }
1233
+ // pages.ts
1234
+ #decodeRecordChainFromPages(pages, pageNumbers) {
1235
+ const pageByNumber = new Map();
1236
+ for (let index = 0; index < pageNumbers.length; index++) {
1237
+ const pageNumber = pageNumbers[index];
1238
+ const page = pages[index];
1239
+ if (page) {
1240
+ pageByNumber.set(pageNumber, page);
1241
+ }
1242
+ }
1243
+ const firstPageNumber = pageNumbers[0];
1244
+ if (firstPageNumber === undefined) {
1245
+ return undefined;
1246
+ }
1247
+ return decodeRecordChain((pageNumber) => pageByNumber.get(pageNumber), firstPageNumber);
1248
+ }
1249
+ async #recover() {
1250
+ const manifestBytes = await readFile(this.#manifestPath, { flag: "r" }).catch(() => undefined);
1251
+ const manifest = manifestBytes ? decodeManifest(manifestBytes) : undefined;
1252
+ this.#checkpointSequence = manifest?.checkpointSequence ?? 0n;
1253
+ const dataFile = await open(this.#dataPath, "r");
1254
+ try {
1255
+ const fileSize = Number((await dataFile.stat()).size);
1256
+ const pageCount = Math.floor(fileSize / PAGE_SIZE);
1257
+ const pageCache = new Map();
1258
+ for (let pageNumber = 0; pageNumber < pageCount; pageNumber++) {
1259
+ const page = new Uint8Array(PAGE_SIZE);
1260
+ const buffer = Buffer.from(page.buffer, page.byteOffset, page.byteLength);
1261
+ const result = await dataFile.read(buffer, 0, PAGE_SIZE, pageNumber * PAGE_SIZE);
1262
+ if (result.bytesRead !== PAGE_SIZE)
1263
+ break;
1264
+ pageCache.set(pageNumber, page);
1265
+ }
1266
+ const readPage = (pageNumber) => pageCache.get(pageNumber);
1267
+ for (const pageNumber of pageCache.keys()) {
1268
+ const page = pageCache.get(pageNumber);
1269
+ const view = new DataView(page.buffer, page.byteOffset, page.byteLength);
1270
+ const state = view.getUint32(0, true);
1271
+ if (state === 0) {
1272
+ this.#freePages.push(pageNumber);
1273
+ continue;
1274
+ }
1275
+ if (state !== 1)
1276
+ continue;
1277
+ const decoded = decodeRecordChain(readPage, pageNumber);
1278
+ if (!decoded)
1279
+ continue;
1280
+ const key = decodeUtf8(decoded.key);
1281
+ const pageNumbers = [];
1282
+ let cursor = pageNumber;
1283
+ while (cursor !== undefined && cursor !== NO_PAGE) {
1284
+ pageNumbers.push(cursor);
1285
+ const currentPage = pageCache.get(cursor);
1286
+ const currentView = new DataView(currentPage.buffer, currentPage.byteOffset, currentPage.byteLength);
1287
+ const nextPage = currentView.getUint32(4, true);
1288
+ cursor = nextPage === NO_PAGE ? undefined : nextPage;
1289
+ }
1290
+ this.#entries.set(key, {
1291
+ pageNumber,
1292
+ pageNumbers
1293
+ });
1294
+ //this.#hot_cache.set(key, decoded.value);
1295
+ this.#hot_cache[key] = decoded.value;
1296
+ }
1297
+ this.#pageCount = pageCount;
1298
+ }
1299
+ finally {
1300
+ await dataFile.close();
1301
+ }
1302
+ const walBytes = await readFile(this.#walPath)
1303
+ .catch(() => new Uint8Array(0));
1304
+ const decoded = decodeWalRecords(walBytes, this.#checkpointSequence);
1305
+ for (const record of decoded.records) {
1306
+ const key = decodeUtf8(record.key);
1307
+ if (record.operation === OP_PUT) {
1308
+ this.#applyPut(key, record.key, record.value, true);
1309
+ }
1310
+ else if (record.operation === OP_DELETE) {
1311
+ this.#applyDelete(key, true);
1312
+ }
1313
+ this.#nextSequence = record.sequence + 1n;
1314
+ }
1315
+ this.#walSize = decoded.validBytes;
1316
+ }
1317
+ async #flushCurrentBatch() {
1318
+ const batch = this.#batch;
1319
+ if (!batch || batch.records.length === 0) {
1320
+ return;
1321
+ }
1322
+ this.#batch = undefined;
1323
+ if (this.#batchTimer) {
1324
+ clearTimeout(this.#batchTimer);
1325
+ this.#batchTimer = undefined;
1326
+ }
1327
+ let totalLength = 0;
1328
+ for (const record of batch.records) {
1329
+ totalLength += record.length;
1330
+ }
1331
+ const bytes = new Uint8Array(totalLength);
1332
+ let offset = 0;
1333
+ for (const record of batch.records) {
1334
+ bytes.set(record, offset);
1335
+ offset += record.length;
1336
+ }
1337
+ try {
1338
+ const response = await this.#workerRequest({
1339
+ kind: "appendWal",
1340
+ batchId: batch.batchId,
1341
+ bytes,
1342
+ durable: batch.durable
1343
+ });
1344
+ if (isWorkerError(response)) {
1345
+ throw new Error(`WAL append failed: ${response.error}`);
1346
+ }
1347
+ if (response.kind !== "walOk") {
1348
+ throw new Error(`Unexpected WAL response: ${response.kind}`);
1349
+ }
1350
+ this.#walSize = response.walSize;
1351
+ for (const resolve of batch.waiters) {
1352
+ resolve();
1353
+ }
1354
+ }
1355
+ catch (error) {
1356
+ for (const waiter of batch.waiters) {
1357
+ // Resolve rather than reject: durability waiters must not hang.
1358
+ waiter();
1359
+ }
1360
+ throw error;
1361
+ }
1362
+ }
1363
+ async #checkpointIfRequired() {
1364
+ if (this.#walSize >= this.#options.walHighWaterBytes) {
1365
+ await this.checkpoint();
1366
+ }
1367
+ }
1368
+ async #checkpoint() {
1369
+ if (!this.#worker) {
1370
+ throw new Error("FastKV is not open");
1371
+ }
1372
+ await this.#flushCurrentBatch();
1373
+ const pages = [];
1374
+ for (const [pageNumber, buffer] of this.#dirtyPages) {
1375
+ pages.push({
1376
+ pageNumber,
1377
+ buffer: buffer.slice()
1378
+ });
1379
+ }
1380
+ const manifest = encodeManifest({
1381
+ checkpointSequence: this.#nextSequence - 1n,
1382
+ pageCount: this.#pageCount
1383
+ });
1384
+ await this.#workerRequest({
1385
+ kind: "checkpoint",
1386
+ pages,
1387
+ manifest
1388
+ });
1389
+ this.#dirtyPages.clear();
1390
+ this.#checkpointSequence = this.#nextSequence - 1n;
1391
+ this.#walSize = 0;
1392
+ }
1393
+ async #startWorker() {
1394
+ this.#worker = new Worker(workerPath);
1395
+ this.#worker.on("message", (response) => {
1396
+ const pending = this.#pending.get(response.id);
1397
+ if (!pending)
1398
+ return;
1399
+ this.#pending.delete(response.id);
1400
+ if (isWorkerError(response)) {
1401
+ pending.reject(new Error(response.error));
1402
+ return;
1403
+ }
1404
+ pending.resolve(response);
1405
+ });
1406
+ this.#worker.on("error", (error) => {
1407
+ for (const pending of this.#pending.values()) {
1408
+ pending.reject(error);
1409
+ }
1410
+ this.#pending.clear();
1411
+ });
1412
+ await this.#workerRequest({
1413
+ kind: "init",
1414
+ dataPath: this.#dataPath,
1415
+ walPath: this.#walPath
1416
+ });
1417
+ }
1418
+ }
1419
+ // #endregion
1420
+ /**
1421
+ I am building a durable file-backed key-value database in TypeScript/Node.
1422
+ i wanted it so that the db uses the exact same 4 tiered scope channel format that every other aspect of the platform uses...
1423
+ r = root key or db name in this case
1424
+ m = master key, but this is used for workspace id so each workspace would have a seperate db tables specifically for that workspace only
1425
+ s = comp or category key, this would be the finaly folder within the db file/folider io
1426
+
1427
+ k = key
1428
+
1429
+ now if the user doesnt touch any of the keys other than k and s, and has worspaces toggled on, then the user autoamtilcy has a workspace aware db... at the same time... it allows the user with surgical precision and ease to very quickly change tables, giving the user an amazing dx to organize data....
1430
+ Architecture:
1431
+ - Worker thread: the actual storage engine.
1432
+ - Worker owns: channel index, WAL, page allocation, dirty pages, free pages,
1433
+ recovery, checkpointing, compaction, and all file I/O.
1434
+
1435
+ Key identity:
1436
+ - Every record is identified by the platform’s four-tier channel:
1437
+ r = root/database
1438
+ m = master/workspace
1439
+ s = category/table
1440
+ k = key
1441
+ - k/s/m/r are first-class parts of the stored record identity.
1442
+ - Do NOT flatten them into an “internal key” string.
1443
+ - Public methods take k plus optional s, m, r, with instance defaults:
1444
+ get(k, s = this.s, m = this.m, r = this.r)
1445
+ set(k, value, s = this.s, m = this.m, r = this.r)
1446
+ delete(k, s = this.s, m = this.m, r = this.r)
1447
+ has(k, s = this.s, m = this.m, r = this.r)
1448
+
1449
+ Durability:
1450
+ - Every write is durable. Period.
1451
+ - There is no durable option, no durability mode, and no options object
1452
+ exposed on set/delete.
1453
+ - set() resolves only after its WAL record has been flushed/synced.
1454
+ - WAL batching/group commit is internal only.
1455
+
1456
+ Read path:
1457
+ - get() checks hot cache first.
1458
+ - On hit: return value synchronously.
1459
+ - On miss: send channel identity to worker.
1460
+ - Worker looks up the channel in its index, reads/decodes the value,
1461
+ and returns the decoded value.
1462
+ - Main thread caches the decoded value.
1463
+ - There is no page-read API exposed to the main thread.
1464
+
1465
+ Worker responses:
1466
+ - Use explicit response kinds.
1467
+ - Do not use a generic ok response with optional fields for different ops.
1468
+ - Example:
1469
+ readOk / notFound / writeOk / deleteOk / error
1470
+
1471
+ Important:
1472
+ - Do not add abstractions I did not ask for.
1473
+ - Do not invent internal keys, durability options, or extra caches.
1474
+ - Keep the API minimal: k, value, s, m, r
1475
+ */