@the-w1zard/singularity 1.0.13 → 1.0.14

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.
Files changed (70) hide show
  1. package/README.html +450 -0
  2. package/README.md +112 -2
  3. package/dist/bus_db_rpc/RULE_OF_2_same_node.d.ts +139 -0
  4. package/dist/bus_db_rpc/RULE_OF_2_same_node.d.ts.map +1 -0
  5. package/dist/bus_db_rpc/RULE_OF_2_same_node.js +502 -0
  6. package/dist/class.d.ts +161 -0
  7. package/dist/class.d.ts.map +1 -0
  8. package/dist/class.js +804 -0
  9. package/dist/comps/DISRUPTOR_CRYPTO.d.ts +47 -0
  10. package/dist/comps/DISRUPTOR_CRYPTO.d.ts.map +1 -0
  11. package/dist/comps/RULE_OF_2_same_app.d.ts +175 -0
  12. package/dist/comps/RULE_OF_2_same_app.d.ts.map +1 -0
  13. package/dist/comps/RULE_OF_2_same_app.js +482 -0
  14. package/dist/comps/binary.d.ts +71 -0
  15. package/dist/comps/binary.d.ts.map +1 -0
  16. package/dist/comps/byte_id.d.ts +12 -0
  17. package/dist/comps/byte_id.d.ts.map +1 -0
  18. package/dist/comps/cell-worker.d.ts +9 -0
  19. package/dist/comps/cell-worker.d.ts.map +1 -0
  20. package/dist/comps/cell.d.ts +349 -0
  21. package/dist/comps/cell.d.ts.map +1 -0
  22. package/dist/comps/create_live_self.d.ts +22 -0
  23. package/dist/comps/create_live_self.d.ts.map +1 -0
  24. package/dist/comps/queue.d.ts +103 -0
  25. package/dist/comps/queue.d.ts.map +1 -0
  26. package/dist/comps/serializer.d.ts +30 -0
  27. package/dist/comps/serializer.d.ts.map +1 -0
  28. package/dist/comps/serializer.js +131 -0
  29. package/dist/comps/vm-types.d.ts +20 -0
  30. package/dist/comps/vm-types.d.ts.map +1 -0
  31. package/dist/db/binary.d.ts +76 -0
  32. package/dist/db/binary.d.ts.map +1 -0
  33. package/dist/db/binary.js +441 -0
  34. package/dist/db/client.d.ts +28 -0
  35. package/dist/db/client.d.ts.map +1 -0
  36. package/dist/db/client.js +82 -0
  37. package/dist/db/db.d.ts +141 -0
  38. package/dist/db/db.d.ts.map +1 -0
  39. package/dist/db/db.js +898 -0
  40. package/dist/db/op.d.ts +13 -0
  41. package/dist/db/op.d.ts.map +1 -0
  42. package/dist/db/op.js +11 -0
  43. package/dist/db/storage-worker.d.ts +2 -0
  44. package/dist/db/storage-worker.d.ts.map +1 -0
  45. package/dist/db/storage-worker.js +152 -0
  46. package/dist/db/types.d.ts +134 -0
  47. package/dist/db/types.d.ts.map +1 -0
  48. package/dist/db/types.js +14 -0
  49. package/dist/db/wal.d.ts +30 -0
  50. package/dist/db/wal.d.ts.map +1 -0
  51. package/dist/db/wal.js +217 -0
  52. package/dist/index.d.ts +2 -0
  53. package/dist/index.d.ts.map +1 -0
  54. package/dist/signals.js +10740 -5498
  55. package/dist/slab.d.ts +95 -0
  56. package/dist/slab.d.ts.map +1 -0
  57. package/dist/slab.js +575 -0
  58. package/dist/slab.types.d.ts +5 -0
  59. package/dist/slab.types.d.ts.map +1 -0
  60. package/dist/slab.types.js +1 -0
  61. package/dist/test.d.ts +152 -0
  62. package/dist/test.d.ts.map +1 -0
  63. package/dist/test.js +1183 -0
  64. package/dist/testt.d.ts +61 -0
  65. package/dist/testt.d.ts.map +1 -0
  66. package/dist/testt.js +143 -0
  67. package/dist/y.d.ts +152 -0
  68. package/dist/y.d.ts.map +1 -0
  69. package/dist/y.js +36 -65
  70. package/package.json +20 -19
package/dist/db/db.js ADDED
@@ -0,0 +1,898 @@
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 { encodeUtf8, decodeUtf8 } from "./binary";
8
+ import { isWorkerError, NO_PAGE, OP_DELETE, OP_PUT, PAGE_SIZE } from "./types";
9
+ import { decodeManifest, decodeRecordChain, decodeWalRecords, encodeFreePage, encodeManifest, encodeRecordChain, encodeWalRecord } from "./wal";
10
+ const workerPath = fileURLToPath(new URL("./storage-worker.ts", import.meta.url));
11
+ function MaybePromise(v) { return v !== undefined ? v : Promise.resolve(v); }
12
+ export const rv = (v) => typeof v === "function" ? v() : v;
13
+ export const sameValue = (a, b) => Object.is(a, b) || (a instanceof Date && b instanceof Date && +a === +b);
14
+ export class A2 extends Array {
15
+ constructor(...items) {
16
+ super(...items);
17
+ Object.setPrototypeOf(this, new.target.prototype);
18
+ }
19
+ static get [Symbol.species]() {
20
+ return Array;
21
+ }
22
+ static from(arrayLike) {
23
+ return new A2(...Array.from(arrayLike));
24
+ }
25
+ static of(...items) {
26
+ return new A2(...items);
27
+ }
28
+ first() {
29
+ return this[0];
30
+ }
31
+ last() {
32
+ return this[this.length - 1];
33
+ }
34
+ isEmpty() {
35
+ return this.length === 0;
36
+ }
37
+ isNotEmpty() {
38
+ return this.length !== 0;
39
+ }
40
+ clear() {
41
+ this.length = 0;
42
+ return this;
43
+ }
44
+ clone() {
45
+ return new A2(...this);
46
+ }
47
+ unique() {
48
+ return new A2(...new Set(this));
49
+ }
50
+ compact() {
51
+ return new A2(...this.filter((value) => value != null));
52
+ }
53
+ take(count) {
54
+ return new A2(...this.slice(0, Math.max(0, count)));
55
+ }
56
+ takeLast(count) {
57
+ return new A2(...this.slice(Math.max(0, this.length - Math.max(0, count))));
58
+ }
59
+ drop(count) {
60
+ return new A2(...this.slice(Math.max(0, count)));
61
+ }
62
+ dropLast(count) {
63
+ return new A2(...this.slice(0, Math.max(0, this.length - Math.max(0, count))));
64
+ }
65
+ chunk(size) {
66
+ if (!Number.isInteger(size) || size < 1) {
67
+ throw new RangeError("Chunk size must be a positive integer.");
68
+ }
69
+ const result = new A2();
70
+ for (let i = 0; i < this.length; i += size) {
71
+ result.push(new A2(...this.slice(i, i + size)));
72
+ }
73
+ return result;
74
+ }
75
+ flatten(depth = Infinity) {
76
+ return new A2(...this.flat(depth));
77
+ }
78
+ flatMap(callback) {
79
+ return new A2(...this.flatMap((value, index) => callback(value, index, this)));
80
+ }
81
+ distinctBy(callback) {
82
+ const seen = new Set();
83
+ const result = new A2();
84
+ this.forEach((value, index) => {
85
+ const key = callback(value, index);
86
+ if (!seen.has(key)) {
87
+ seen.add(key);
88
+ result.push(value);
89
+ }
90
+ });
91
+ return result;
92
+ }
93
+ groupBy(callback) {
94
+ const result = new Map();
95
+ this.forEach((value, index) => {
96
+ const key = callback(value, index);
97
+ let group = result.get(key);
98
+ if (!group) {
99
+ group = new A2();
100
+ result.set(key, group);
101
+ }
102
+ group.push(value);
103
+ });
104
+ return result;
105
+ }
106
+ partition(callback) {
107
+ const yes = new A2();
108
+ const no = new A2();
109
+ this.forEach((value, index) => {
110
+ (callback(value, index) ? yes : no).push(value);
111
+ });
112
+ return [yes, no];
113
+ }
114
+ insert(index, ...items) {
115
+ this.splice(index, 0, ...items);
116
+ return this;
117
+ }
118
+ removeAt(index) {
119
+ const normalized = index < 0 ? this.length + index : index;
120
+ if (normalized < 0 || normalized >= this.length) {
121
+ return undefined;
122
+ }
123
+ return this.splice(normalized, 1)[0];
124
+ }
125
+ remove(value) {
126
+ const index = this.indexOf(value);
127
+ if (index === -1) {
128
+ return false;
129
+ }
130
+ this.splice(index, 1);
131
+ return true;
132
+ }
133
+ removeAll(value) {
134
+ let removed = 0;
135
+ for (let i = this.length - 1; i >= 0; i--) {
136
+ if (Object.is(this[i], value)) {
137
+ this.splice(i, 1);
138
+ removed++;
139
+ }
140
+ }
141
+ return removed;
142
+ }
143
+ replaceAt(index, value) {
144
+ const normalized = index < 0 ? this.length + index : index;
145
+ if (normalized < 0 || normalized >= this.length) {
146
+ return undefined;
147
+ }
148
+ const previous = this[normalized];
149
+ this[normalized] = value;
150
+ return previous;
151
+ }
152
+ move(from, to) {
153
+ const source = from < 0 ? this.length + from : from;
154
+ const target = to < 0 ? this.length + to : to;
155
+ if (source < 0 || source >= this.length ||
156
+ target < 0 || target >= this.length ||
157
+ source === target) {
158
+ return this;
159
+ }
160
+ const [item] = this.splice(source, 1);
161
+ this.splice(target, 0, item);
162
+ return this;
163
+ }
164
+ swap(first, second) {
165
+ const a = first < 0 ? this.length + first : first;
166
+ const b = second < 0 ? this.length + second : second;
167
+ if (a < 0 || a >= this.length ||
168
+ b < 0 || b >= this.length) {
169
+ return this;
170
+ }
171
+ [this[a], this[b]] = [this[b], this[a]];
172
+ return this;
173
+ }
174
+ sample() {
175
+ if (this.length === 0) {
176
+ return undefined;
177
+ }
178
+ return this[Math.floor(Math.random() * this.length)];
179
+ }
180
+ shuffle() {
181
+ for (let i = this.length - 1; i > 0; i--) {
182
+ const j = Math.floor(Math.random() * (i + 1));
183
+ [this[i], this[j]] = [this[j], this[i]];
184
+ }
185
+ return this;
186
+ }
187
+ countBy(callback) {
188
+ let count = 0;
189
+ this.forEach((value, index) => {
190
+ if (callback(value, index))
191
+ count++;
192
+ });
193
+ return count;
194
+ }
195
+ sum(callback) {
196
+ let total = 0;
197
+ this.forEach((value, index) => {
198
+ total += callback ? callback(value, index) : Number(value);
199
+ });
200
+ return total;
201
+ }
202
+ average(callback) {
203
+ return (this.length === 0 ? NaN : this.sum(callback) / this.length);
204
+ }
205
+ min(callback) {
206
+ if (this.length === 0)
207
+ return undefined;
208
+ return this.reduce((best, value, index) => {
209
+ const current = callback ? callback(value, index) : Number(value);
210
+ const bestValue = callback ? callback(best, this.indexOf(best)) : Number(best);
211
+ return current < bestValue ? value : best;
212
+ });
213
+ }
214
+ max(callback) {
215
+ if (this.length === 0)
216
+ return undefined;
217
+ return this.reduce((best, value, index) => {
218
+ const current = callback ? callback(value, index) : Number(value);
219
+ const bestValue = callback ? callback(best, this.indexOf(best)) : Number(best);
220
+ return current > bestValue ? value : best;
221
+ });
222
+ }
223
+ equals(array) {
224
+ return this.length === array.length &&
225
+ this.every((value, index) => Object.is(value, array[index]));
226
+ }
227
+ includesAll(values) {
228
+ return values.every(value => this.includes(value));
229
+ }
230
+ intersects(values) {
231
+ return values.some(value => this.includes(value));
232
+ }
233
+ }
234
+ // #endregion
235
+ // DB
236
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
237
+ export class WAL_KVDB {
238
+ // CONSTANTS
239
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
240
+ r = "THE_WIZARD_ROOT_REG";
241
+ m = "SAURON_MASTER_REG";
242
+ s = "SAURON_SLAVE_REG";
243
+ k = "__SAURON__";
244
+ hot_cache = Object.create(null);
245
+ ///hot_cache = new O2<S, A>();
246
+ waiters = Object.create(null);
247
+ entries = Object.create(null);
248
+ pending = Object.create(null);
249
+ dirtyPages = Object.create(null);
250
+ #options;
251
+ #directory;
252
+ #dataPath;
253
+ #walPath;
254
+ #manifestPath;
255
+ #worker;
256
+ #freePages = [];
257
+ #pageCount = 0;
258
+ #nextSequence = 1n;
259
+ #checkpointSequence = 0n;
260
+ #walSize = 0;
261
+ #batch;
262
+ #batchTimer;
263
+ #writeQueue = Promise.resolve();
264
+ #closed = false;
265
+ _onError;
266
+ constructor(k = "__SAURON__", s = "SAURON_SLAVE_REG", m = "SAURON_MASTER_REG", r = "THE_WIZARD_ROOT_REG", options = {}) {
267
+ this.k = k;
268
+ this.s = s;
269
+ this.m = m;
270
+ this.r = r;
271
+ this.#options = {
272
+ directory: options.directory ?? "./data/fastkv",
273
+ durability: options.durability ?? "group",
274
+ walBatchBytes: options.walBatchBytes ?? 256 * 1024,
275
+ walBatchRecords: options.walBatchRecords ?? 4096,
276
+ walFlushIntervalMs: options.walFlushIntervalMs ?? 1,
277
+ walHighWaterBytes: options.walHighWaterBytes ?? 16 * 1024 * 1024,
278
+ checkpointIntervalMs: options.checkpointIntervalMs ?? 5_000
279
+ };
280
+ }
281
+ // #endregion
282
+ // API
283
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
284
+ get = (() => {
285
+ const z = (k, s = this.s, m = this.m, r = this.r) => {
286
+ const cached = this.hot_cache[k];
287
+ if (cached !== undefined)
288
+ return MaybePromise(cached);
289
+ else {
290
+ const entry = this.entries[k];
291
+ if (!entry)
292
+ return undefined;
293
+ return MaybePromise(this.#workerRequest({
294
+ kind: "readPages",
295
+ pageNumbers: entry.pageNumbers
296
+ }).then((response) => {
297
+ if (response.kind !== "readPagesOk") {
298
+ throw new Error(response.kind === "error" ? response.error : "Unexpected worker response");
299
+ }
300
+ const decoded = this.#decodeRecordChainFromPages(response.pages, entry.pageNumbers);
301
+ if (!decoded) {
302
+ return undefined;
303
+ }
304
+ this.hot_cache[k] = decoded.value;
305
+ return decoded.value;
306
+ }));
307
+ }
308
+ };
309
+ z.many = async (keys) => {
310
+ await Promise.all(Object.entries(keys).map(([k]) => this.get(k)));
311
+ };
312
+ z.hot = (k) => {
313
+ return this.hot_cache[k];
314
+ };
315
+ return z;
316
+ })();
317
+ hot(k) {
318
+ return this.hot_cache[k];
319
+ }
320
+ set = (() => {
321
+ const z = async (k, value, s = this.s, m = this.m, r = this.r, options = { durable: true }) => {
322
+ this.hot_cache[k] = value;
323
+ // this.hot_cache.set(k, value);
324
+ if (this.waiters.size !== 0) {
325
+ const wk = `__waiters_${k}`;
326
+ const ws = this.waiters.get(wk);
327
+ if (ws) {
328
+ for (const resolve of ws)
329
+ resolve(value);
330
+ this.waiters.delete(wk);
331
+ }
332
+ }
333
+ this._emit(k, value);
334
+ const valueBytes = typeof value === "string" ? encodeUtf8(value) : value;
335
+ const keyBytes = encodeUtf8(k);
336
+ return this.#enqueueWrite(async () => {
337
+ if (this.#closed) {
338
+ throw new Error("FastKV is closed");
339
+ }
340
+ this.#applyPut(k, keyBytes, valueBytes);
341
+ const record = encodeWalRecord({
342
+ sequence: this.#nextSequence++,
343
+ operation: OP_PUT,
344
+ key: keyBytes,
345
+ value: valueBytes
346
+ });
347
+ const durable = this.#resolveDurability(options.durable);
348
+ const flushPromise = this.#appendToBatch(record, durable);
349
+ if (options.durable === true || this.#options.durability === "strict") {
350
+ await flushPromise;
351
+ }
352
+ });
353
+ };
354
+ z.many = async (entries) => {
355
+ await Promise.all(Object.entries(entries).map(([k, v]) => this.set(k, v)));
356
+ };
357
+ return z;
358
+ })();
359
+ delete = (() => {
360
+ const z = async (key, options = {}) => {
361
+ const keyBytes = encodeUtf8(key);
362
+ this._emit(key, undefined);
363
+ return this.#enqueueWrite(async () => {
364
+ if (this.#closed) {
365
+ throw new Error("FastKV is closed");
366
+ }
367
+ if (!(key in this.entries)) {
368
+ return false;
369
+ }
370
+ this.#applyDelete(key);
371
+ const record = encodeWalRecord({
372
+ sequence: this.#nextSequence++,
373
+ operation: OP_DELETE,
374
+ key: keyBytes,
375
+ value: new Uint8Array(0)
376
+ });
377
+ const durable = this.#resolveDurability(options.durable);
378
+ const flushPromise = this.#appendToBatch(record, durable);
379
+ if (options.durable === true || this.#options.durability === "strict") {
380
+ await flushPromise;
381
+ }
382
+ return true;
383
+ });
384
+ };
385
+ z.many = async (keys) => { await Promise.all(keys.map((k) => this.delete(k))); };
386
+ return z;
387
+ })();
388
+ update = (() => {
389
+ const z = async (key, updater) => {
390
+ const prev = await this.get(key);
391
+ const next = updater(prev);
392
+ await this.set(key, next);
393
+ return next;
394
+ };
395
+ z.many = () => { };
396
+ return z;
397
+ })();
398
+ has(key) { return Object.hasOwn(this.entries, key); }
399
+ send = (() => {
400
+ const z = () => { };
401
+ z.many = () => { };
402
+ return z;
403
+ })();
404
+ // #endregion
405
+ // SUB
406
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
407
+ subscribe(key, cb) {
408
+ let set = this.waiters.get(key);
409
+ if (!set) {
410
+ set = new Set();
411
+ this.waiters.set(key, set);
412
+ }
413
+ set.add(cb);
414
+ const cached = this.hot_cache[key];
415
+ if (cached) {
416
+ try {
417
+ cb(cached);
418
+ }
419
+ catch (e) {
420
+ this._onError(e);
421
+ }
422
+ }
423
+ return () => {
424
+ const s = this.waiters.get(key);
425
+ if (!s)
426
+ return;
427
+ s.delete(cb);
428
+ if (s.size === 0)
429
+ this.waiters.delete(key);
430
+ };
431
+ } /** Selector-based subscription — only fires when the selected slice changes. */
432
+ select(key, selector, cb, chain) {
433
+ let last;
434
+ let first = true;
435
+ return this.subscribe(key, (v) => {
436
+ const next = selector(v);
437
+ if (first || !Object.is(last, next)) {
438
+ first = false;
439
+ last = next;
440
+ cb(next);
441
+ }
442
+ });
443
+ }
444
+ _emit(key, value) {
445
+ const set = this.waiters.get(key);
446
+ if (!set)
447
+ return;
448
+ for (const cb of set) {
449
+ try {
450
+ cb(value);
451
+ }
452
+ catch (e) {
453
+ this._onError(e);
454
+ }
455
+ }
456
+ }
457
+ _peek(key) {
458
+ const v = this.hot_cache[key];
459
+ return v === undefined ? undefined : v;
460
+ }
461
+ waitFor(key) {
462
+ const existing = this._peek(key);
463
+ if (existing !== undefined)
464
+ return Promise.resolve(existing);
465
+ return new Promise((resolve) => {
466
+ const waiterKey = `__waiters_${key}`;
467
+ let waiters = this.waiters.get(waiterKey);
468
+ if (!waiters) {
469
+ waiters = new Set();
470
+ this.waiters.set(waiterKey, waiters);
471
+ }
472
+ waiters.add(resolve);
473
+ });
474
+ }
475
+ // #endregion
476
+ // WORKER FNS
477
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
478
+ async open() {
479
+ if (this.#worker) {
480
+ throw new Error("FastKV is already open");
481
+ }
482
+ this.#directory = path.resolve(this.#options.directory);
483
+ this.#dataPath = path.join(this.#directory, "data.paged");
484
+ this.#walPath = path.join(this.#directory, "wal.log");
485
+ this.#manifestPath = path.join(this.#directory, "manifest.bin");
486
+ await mkdir(this.#directory, { recursive: true });
487
+ const dataFile = await open(this.#dataPath, "a+");
488
+ await dataFile.close();
489
+ const walFile = await open(this.#walPath, "a+");
490
+ await walFile.close();
491
+ await this.#recover();
492
+ await this.#startWorker();
493
+ setInterval(() => {
494
+ void this.#checkpointIfRequired();
495
+ }, this.#options.checkpointIntervalMs).unref();
496
+ }
497
+ async flush() {
498
+ await this.#enqueueWrite(async () => {
499
+ await this.#flushCurrentBatch();
500
+ });
501
+ }
502
+ async checkpoint() {
503
+ await this.#enqueueWrite(async () => {
504
+ await this.#checkpoint();
505
+ });
506
+ }
507
+ async compact() {
508
+ await this.#enqueueWrite(async () => {
509
+ await this.#flushCurrentBatch();
510
+ const compactPath = `${this.#dataPath}.compact`;
511
+ await this.#workerRequest({ kind: "compactBegin", compactPath });
512
+ const livePages = [];
513
+ let nextPage = 0;
514
+ // const oldEntries = new O2(this.entries);
515
+ // const oldValues = new O2(this.hot_cache);
516
+ const oldEntries = Object.assign(Object.create(null), this.entries);
517
+ const oldValues = Object.assign(Object.create(null), this.hot_cache);
518
+ this.entries = Object.create(null);
519
+ // this.hot_cache.clear();
520
+ this.hot_cache = Object.create(null);
521
+ this.#freePages = [];
522
+ this.dirtyPages = Object.create(null);
523
+ this.#pageCount = 0;
524
+ for (const [key, entry] of oldEntries) {
525
+ const value = oldValues.get(key);
526
+ if (!value)
527
+ continue;
528
+ // this.hot_cache.set(key, value);
529
+ this.hot_cache[key] = value;
530
+ const keyBytes = encodeUtf8(key);
531
+ const chain = encodeRecordChain(keyBytes, value, () => nextPage++);
532
+ for (const page of chain.pages) {
533
+ livePages.push({
534
+ pageNumber: chain.pageNumbers[0],
535
+ buffer: page
536
+ });
537
+ }
538
+ this.entries[key] = {
539
+ pageNumber: chain.pageNumbers[0],
540
+ pageNumbers: chain.pageNumbers
541
+ };
542
+ }
543
+ this.#pageCount = nextPage;
544
+ const manifest = encodeManifest({ checkpointSequence: this.#nextSequence, pageCount: this.#pageCount });
545
+ await this.#workerRequest({ kind: "compactWrite", pages: livePages });
546
+ await this.#workerRequest({
547
+ kind: "compactCommit",
548
+ dataPath: this.#dataPath,
549
+ compactPath,
550
+ manifest,
551
+ walPath: this.#walPath
552
+ });
553
+ this.#checkpointSequence = this.#nextSequence;
554
+ this.#walSize = 0;
555
+ });
556
+ }
557
+ async close() {
558
+ if (this.#closed)
559
+ return;
560
+ this.#closed = true;
561
+ await this.#enqueueWrite(async () => {
562
+ await this.#checkpoint();
563
+ });
564
+ await this.#workerRequest({
565
+ kind: "close"
566
+ });
567
+ await this.#worker?.terminate();
568
+ this.#worker = undefined;
569
+ }
570
+ get stats() {
571
+ return {
572
+ keys: this.entries.size,
573
+ pages: this.#pageCount,
574
+ freePages: this.#freePages.length,
575
+ dirtyPages: Object.keys(this.dirtyPages).length,
576
+ walBytes: this.#walSize,
577
+ checkpointSequence: this.#checkpointSequence,
578
+ nextSequence: this.#nextSequence,
579
+ durability: this.#options.durability
580
+ };
581
+ }
582
+ #resolveDurability(requested) {
583
+ if (requested !== undefined) {
584
+ return requested;
585
+ }
586
+ return (this.#options.durability === "group" ||
587
+ this.#options.durability === "strict");
588
+ }
589
+ #applyPut(key, keyBytes, valueBytes, replay = false) {
590
+ const previous = this.entries[key];
591
+ const chain = encodeRecordChain(keyBytes, valueBytes, () => {
592
+ const reused = this.#freePages.pop();
593
+ if (reused !== undefined) {
594
+ return reused;
595
+ }
596
+ return this.#pageCount++;
597
+ });
598
+ if (previous) {
599
+ for (const pageNumber of previous.pageNumbers) {
600
+ this.dirtyPages[pageNumber] = encodeFreePage();
601
+ this.#freePages.push(pageNumber);
602
+ }
603
+ }
604
+ for (let index = 0; index < chain.pages.length; index++) {
605
+ this.dirtyPages[chain.pageNumbers[index]] = chain.pages[index];
606
+ }
607
+ this.entries[key] = {
608
+ pageNumber: chain.pageNumbers[0],
609
+ pageNumbers: chain.pageNumbers
610
+ };
611
+ // this.hot_cache.set(key, valueBytes);
612
+ if (replay) {
613
+ this.#nextSequence = this.#nextSequence;
614
+ }
615
+ }
616
+ #applyDelete(key, replay = false) {
617
+ const previous = this.entries[key];
618
+ if (!previous)
619
+ return;
620
+ for (const pageNumber of previous.pageNumbers) {
621
+ this.dirtyPages[pageNumber] = encodeFreePage();
622
+ this.#freePages.push(pageNumber);
623
+ }
624
+ delete this.entries[key];
625
+ //this.hot_cache.delete(key);
626
+ delete this.hot_cache[key];
627
+ if (replay) {
628
+ this.#nextSequence = this.#nextSequence;
629
+ }
630
+ }
631
+ #enqueueWrite(operation) {
632
+ const result = this.#writeQueue.then(operation, operation);
633
+ this.#writeQueue = result.catch(() => undefined);
634
+ return result;
635
+ }
636
+ #appendToBatch(record, durable) {
637
+ if (!this.#batch) {
638
+ this.#batch = {
639
+ batchId: crypto.randomUUID(),
640
+ records: [],
641
+ byteLength: 0,
642
+ durable: false,
643
+ waiters: []
644
+ };
645
+ }
646
+ const batch = this.#batch;
647
+ batch.records.push(record);
648
+ batch.byteLength += record.length;
649
+ batch.durable ||= durable;
650
+ return new Promise((resolve) => {
651
+ batch.waiters.push(resolve);
652
+ if (batch.byteLength >= this.#options.walBatchBytes ||
653
+ batch.records.length >= this.#options.walBatchRecords) {
654
+ void this.#flushCurrentBatch();
655
+ return;
656
+ }
657
+ this.#batchTimer ??= setTimeout(() => {
658
+ this.#batchTimer = undefined;
659
+ void this.#flushCurrentBatch();
660
+ }, this.#options.walFlushIntervalMs);
661
+ });
662
+ }
663
+ #workerRequest(request) {
664
+ if (!this.#worker) {
665
+ return Promise.reject(new Error("FastKV is not open"));
666
+ }
667
+ const id = crypto.randomUUID();
668
+ return new Promise((resolve, reject) => {
669
+ this.pending[id] = {
670
+ resolve,
671
+ reject
672
+ };
673
+ this.#worker.postMessage({
674
+ ...request,
675
+ id
676
+ });
677
+ });
678
+ }
679
+ // pages.ts
680
+ #decodeRecordChainFromPages(pages, pageNumbers) {
681
+ const pageByNumber = new Map();
682
+ for (let index = 0; index < pageNumbers.length; index++) {
683
+ const pageNumber = pageNumbers[index];
684
+ const page = pages[index];
685
+ if (page) {
686
+ pageByNumber.set(pageNumber, page);
687
+ }
688
+ }
689
+ const firstPageNumber = pageNumbers[0];
690
+ if (firstPageNumber === undefined) {
691
+ return undefined;
692
+ }
693
+ return decodeRecordChain((pageNumber) => pageByNumber.get(pageNumber), firstPageNumber);
694
+ }
695
+ async #recover() {
696
+ const manifestBytes = await readFile(this.#manifestPath, { flag: "r" }).catch(() => undefined);
697
+ const manifest = manifestBytes ? decodeManifest(manifestBytes) : undefined;
698
+ this.#checkpointSequence = manifest?.checkpointSequence ?? 0n;
699
+ const dataFile = await open(this.#dataPath, "r");
700
+ try {
701
+ const fileSize = Number((await dataFile.stat()).size);
702
+ const pageCount = Math.floor(fileSize / PAGE_SIZE);
703
+ const pageCache = new Map();
704
+ for (let pageNumber = 0; pageNumber < pageCount; pageNumber++) {
705
+ const page = new Uint8Array(PAGE_SIZE);
706
+ const buffer = Buffer.from(page.buffer, page.byteOffset, page.byteLength);
707
+ const result = await dataFile.read(buffer, 0, PAGE_SIZE, pageNumber * PAGE_SIZE);
708
+ if (result.bytesRead !== PAGE_SIZE)
709
+ break;
710
+ pageCache.set(pageNumber, page);
711
+ }
712
+ const readPage = (pageNumber) => pageCache.get(pageNumber);
713
+ for (const pageNumber of pageCache.keys()) {
714
+ const page = pageCache.get(pageNumber);
715
+ const view = new DataView(page.buffer, page.byteOffset, page.byteLength);
716
+ const state = view.getUint32(0, true);
717
+ if (state === 0) {
718
+ this.#freePages.push(pageNumber);
719
+ continue;
720
+ }
721
+ if (state !== 1)
722
+ continue;
723
+ const decoded = decodeRecordChain(readPage, pageNumber);
724
+ if (!decoded)
725
+ continue;
726
+ const key = decodeUtf8(decoded.key);
727
+ const pageNumbers = [];
728
+ let cursor = pageNumber;
729
+ while (cursor !== undefined && cursor !== NO_PAGE) {
730
+ pageNumbers.push(cursor);
731
+ const currentPage = pageCache.get(cursor);
732
+ const currentView = new DataView(currentPage.buffer, currentPage.byteOffset, currentPage.byteLength);
733
+ const nextPage = currentView.getUint32(4, true);
734
+ cursor = nextPage === NO_PAGE ? undefined : nextPage;
735
+ }
736
+ this.entries[key] = {
737
+ pageNumber,
738
+ pageNumbers
739
+ };
740
+ //this.hot_cache.set(key, decoded.value);
741
+ this.hot_cache[key] = decoded.value;
742
+ }
743
+ this.#pageCount = pageCount;
744
+ }
745
+ finally {
746
+ await dataFile.close();
747
+ }
748
+ const walBytes = await readFile(this.#walPath)
749
+ .catch(() => new Uint8Array(0));
750
+ const decoded = decodeWalRecords(walBytes, this.#checkpointSequence);
751
+ for (const record of decoded.records) {
752
+ const key = decodeUtf8(record.key);
753
+ if (record.operation === OP_PUT) {
754
+ this.#applyPut(key, record.key, record.value, true);
755
+ }
756
+ else if (record.operation === OP_DELETE) {
757
+ this.#applyDelete(key, true);
758
+ }
759
+ this.#nextSequence = record.sequence + 1n;
760
+ }
761
+ this.#walSize = decoded.validBytes;
762
+ }
763
+ async #flushCurrentBatch() {
764
+ const batch = this.#batch;
765
+ if (!batch || batch.records.length === 0) {
766
+ return;
767
+ }
768
+ this.#batch = undefined;
769
+ if (this.#batchTimer) {
770
+ clearTimeout(this.#batchTimer);
771
+ this.#batchTimer = undefined;
772
+ }
773
+ let totalLength = 0;
774
+ for (const record of batch.records) {
775
+ totalLength += record.length;
776
+ }
777
+ const bytes = new Uint8Array(totalLength);
778
+ let offset = 0;
779
+ for (const record of batch.records) {
780
+ bytes.set(record, offset);
781
+ offset += record.length;
782
+ }
783
+ try {
784
+ const response = await this.#workerRequest({
785
+ kind: "appendWal",
786
+ batchId: batch.batchId,
787
+ bytes,
788
+ durable: batch.durable
789
+ });
790
+ if (isWorkerError(response)) {
791
+ throw new Error(`WAL append failed: ${response.error}`);
792
+ }
793
+ if (response.kind !== "walOk") {
794
+ throw new Error(`Unexpected WAL response: ${response.kind}`);
795
+ }
796
+ this.#walSize = response.walSize;
797
+ for (const resolve of batch.waiters) {
798
+ resolve();
799
+ }
800
+ }
801
+ catch (error) {
802
+ for (const waiter of batch.waiters) {
803
+ // Resolve rather than reject: durability waiters must not hang.
804
+ waiter();
805
+ }
806
+ throw error;
807
+ }
808
+ }
809
+ async #checkpointIfRequired() {
810
+ if (this.#walSize >= this.#options.walHighWaterBytes) {
811
+ await this.checkpoint();
812
+ }
813
+ }
814
+ async #checkpoint() {
815
+ if (!this.#worker) {
816
+ throw new Error("FastKV is not open");
817
+ }
818
+ await this.#flushCurrentBatch();
819
+ const pages = [];
820
+ for (const pageNumber in this.dirtyPages) {
821
+ pages.push({
822
+ pageNumber: Number(pageNumber),
823
+ buffer: this.dirtyPages[pageNumber].slice()
824
+ });
825
+ }
826
+ const manifest = encodeManifest({
827
+ checkpointSequence: this.#nextSequence - 1n,
828
+ pageCount: this.#pageCount
829
+ });
830
+ await this.#workerRequest({
831
+ kind: "checkpoint",
832
+ pages,
833
+ manifest
834
+ });
835
+ this.dirtyPages = Object.create(null);
836
+ this.#checkpointSequence = this.#nextSequence - 1n;
837
+ this.#walSize = 0;
838
+ }
839
+ async #startWorker() {
840
+ this.#worker = new Worker(workerPath);
841
+ this.#worker.on("message", (response) => {
842
+ const pending = this.pending[response.id];
843
+ if (!pending)
844
+ return;
845
+ delete this.pending[response.id];
846
+ if (isWorkerError(response)) {
847
+ pending.reject(new Error(response.error));
848
+ return;
849
+ }
850
+ pending.resolve(response);
851
+ });
852
+ this.#worker.on("error", (error) => {
853
+ for (const id in this.pending) {
854
+ this.pending[id].reject(error);
855
+ }
856
+ this.pending = Object.create(null);
857
+ });
858
+ await this.#workerRequest({
859
+ kind: "init",
860
+ dataPath: this.#dataPath,
861
+ walPath: this.#walPath
862
+ });
863
+ }
864
+ }
865
+ /**
866
+ const watchHandlers = new Map<S, Map<S, (value: A) => V>>();
867
+
868
+ case "watch": {
869
+ const watchKey = k!;
870
+ const handler = (val: any) => {
871
+ stream.send({
872
+ key: watchKey,
873
+ value: val !== undefined ? JSON.stringify(val) : null,
874
+ event: "watch",
875
+ });
876
+ };
877
+
878
+ if (!watchHandlers.has("watch")) {
879
+ watchHandlers.set("watch", new Map());
880
+ }
881
+ watchHandlers.get("watch")!.set(watchKey, handler);
882
+
883
+ await db.watch(watchKey, handler);
884
+ result = { subscribed: true, key: watchKey };
885
+ break;
886
+ }
887
+ case "unwatch": {
888
+ const watchKey = k!;
889
+ const handlers = watchHandlers.get("watch");
890
+ if (handlers && handlers.has(watchKey)) {
891
+ handlers.delete(watchKey);
892
+ result = { unsubscribed: true, key: watchKey };
893
+ } else {
894
+ result = { unsubscribed: false, error: "No such watch" };
895
+ }
896
+ break;
897
+ } */
898
+ // #endregion