tero 0.0.9 → 0.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.
- package/LICENSE +21 -0
- package/README.md +19 -17
- package/dist/acid-engine.d.ts +32 -16
- package/dist/acid-engine.js +259 -80
- package/dist/backup.d.ts +42 -5
- package/dist/backup.js +451 -104
- package/dist/index.d.ts +64 -29
- package/dist/index.js +556 -176
- package/dist/recovery.d.ts +3 -2
- package/dist/recovery.js +103 -28
- package/package.json +37 -22
package/dist/acid-engine.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { existsSync, readFileSync, readSync, appendFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, openSync, closeSync, fsyncSync, renameSync } from "fs";
|
|
2
2
|
import { join, dirname } from "path";
|
|
3
|
+
import { randomBytes } from "crypto";
|
|
3
4
|
/**
|
|
4
5
|
* 64-bit hash via two independent FNV-1a passes with different offset basis
|
|
5
6
|
* and prime, combined into a 16-char hex string. ~2x the cost of a single
|
|
@@ -71,15 +72,14 @@ export class WriteAheadLog {
|
|
|
71
72
|
try {
|
|
72
73
|
fd = openSync(path, 'r');
|
|
73
74
|
}
|
|
74
|
-
catch {
|
|
75
|
-
|
|
75
|
+
catch (error) {
|
|
76
|
+
if (error?.code === 'ENOENT')
|
|
77
|
+
return; // file may not exist during rotation edge cases
|
|
78
|
+
throw error;
|
|
76
79
|
}
|
|
77
80
|
try {
|
|
78
81
|
fsyncSync(fd);
|
|
79
82
|
}
|
|
80
|
-
catch {
|
|
81
|
-
// fsync may fail on some filesystems; we still proceed since the data write already happened
|
|
82
|
-
}
|
|
83
83
|
finally {
|
|
84
84
|
closeSync(fd);
|
|
85
85
|
}
|
|
@@ -89,14 +89,14 @@ export class WriteAheadLog {
|
|
|
89
89
|
try {
|
|
90
90
|
fd = openSync(dirPath, 'r');
|
|
91
91
|
}
|
|
92
|
-
catch {
|
|
93
|
-
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error?.code === 'ENOENT')
|
|
94
|
+
return;
|
|
95
|
+
throw error;
|
|
94
96
|
}
|
|
95
97
|
try {
|
|
96
98
|
fsyncSync(fd);
|
|
97
99
|
}
|
|
98
|
-
catch {
|
|
99
|
-
}
|
|
100
100
|
finally {
|
|
101
101
|
closeSync(fd);
|
|
102
102
|
}
|
|
@@ -254,13 +254,20 @@ export class WriteAheadLog {
|
|
|
254
254
|
}
|
|
255
255
|
}
|
|
256
256
|
catch (error) {
|
|
257
|
-
//
|
|
257
|
+
// Surface disk-full errors — silent rotation failure masks durability loss
|
|
258
|
+
if (error?.code === 'ENOSPC')
|
|
259
|
+
throw error;
|
|
258
260
|
}
|
|
259
261
|
}
|
|
260
262
|
/**
|
|
261
263
|
* Rotate the WAL: archive the current log to .wal.<timestamp>, start a fresh log,
|
|
262
264
|
* and write a CHECKPOINT entry at the head of the new log. Old archives beyond
|
|
263
265
|
* ARCHIVE_KEEP_COUNT are pruned locally (cloud upload in v2 retains durable copies).
|
|
266
|
+
*
|
|
267
|
+
* NOTE: ACIDStorageEngine.flushCommittedBuffer() MUST be called before
|
|
268
|
+
* rotateLog() — see commitTransaction() — otherwise deferred writes still
|
|
269
|
+
* in memory would be lost on crash after truncation. rotateLog() itself
|
|
270
|
+
* only guarantees WAL durability (forceFlush before archiving).
|
|
264
271
|
*/
|
|
265
272
|
rotateLog() {
|
|
266
273
|
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
@@ -284,7 +291,9 @@ export class WriteAheadLog {
|
|
|
284
291
|
this.cleanupOldArchives(this.ARCHIVE_KEEP_COUNT);
|
|
285
292
|
}
|
|
286
293
|
catch (error) {
|
|
287
|
-
|
|
294
|
+
if (error?.code === 'ENOSPC')
|
|
295
|
+
throw error;
|
|
296
|
+
// Other rotation errors are best-effort; WAL remains usable
|
|
288
297
|
}
|
|
289
298
|
}
|
|
290
299
|
/**
|
|
@@ -373,7 +382,8 @@ export class WriteAheadLog {
|
|
|
373
382
|
this.cleanupOldArchives(0);
|
|
374
383
|
}
|
|
375
384
|
catch (error) {
|
|
376
|
-
|
|
385
|
+
if (error?.code === 'ENOSPC')
|
|
386
|
+
throw error;
|
|
377
387
|
}
|
|
378
388
|
}
|
|
379
389
|
destroy() {
|
|
@@ -403,8 +413,25 @@ export class LockManager {
|
|
|
403
413
|
});
|
|
404
414
|
return true;
|
|
405
415
|
}
|
|
406
|
-
// Fast path 2:
|
|
407
|
-
|
|
416
|
+
// Fast path 2: existing holder requesting lock — never downgrade exclusive
|
|
417
|
+
const isHolder = lockInfo.holders.has(transactionId);
|
|
418
|
+
if (isHolder) {
|
|
419
|
+
// Already holding exclusive — strongest lock, never downgrade
|
|
420
|
+
if (lockInfo.type === 'exclusive') {
|
|
421
|
+
return true;
|
|
422
|
+
}
|
|
423
|
+
// Already holding shared and requesting shared — no-op
|
|
424
|
+
if (lockType === 'shared') {
|
|
425
|
+
return true;
|
|
426
|
+
}
|
|
427
|
+
// Upgrading from shared to exclusive — grant if sole holder
|
|
428
|
+
if (lockInfo.holders.size === 1) {
|
|
429
|
+
lockInfo.type = 'exclusive';
|
|
430
|
+
return true;
|
|
431
|
+
}
|
|
432
|
+
// Multiple shared holders: must wait in queue for upgrade
|
|
433
|
+
}
|
|
434
|
+
else if (this.canGrantLock(lockInfo, lockType, transactionId)) {
|
|
408
435
|
if (lockType === 'shared' && lockInfo.type === 'shared') {
|
|
409
436
|
lockInfo.holders.add(transactionId);
|
|
410
437
|
}
|
|
@@ -415,16 +442,11 @@ export class LockManager {
|
|
|
415
442
|
}
|
|
416
443
|
return true;
|
|
417
444
|
}
|
|
418
|
-
//
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
lockInfo.holders.clear();
|
|
424
|
-
lockInfo.holders.add(transactionId);
|
|
425
|
-
return true;
|
|
426
|
-
}
|
|
427
|
-
}
|
|
445
|
+
// Shared→exclusive upgrade is handled via the wait queue. The
|
|
446
|
+
// previous fast path deleted the holder before re-checking
|
|
447
|
+
// canGrantLock and lost the shared lock when the upgrade blocked.
|
|
448
|
+
// Keep the shared lock held while waiting — processWaitQueue will
|
|
449
|
+
// promote atomically when holders drain.
|
|
428
450
|
// Slow path: lock is contended — allocate Promise + timer and wait in queue
|
|
429
451
|
return new Promise((resolve, reject) => {
|
|
430
452
|
const timeout = setTimeout(() => {
|
|
@@ -448,13 +470,27 @@ export class LockManager {
|
|
|
448
470
|
canGrantLock(lockInfo, requestedType, transactionId) {
|
|
449
471
|
const isHolder = lockInfo.holders.has(transactionId);
|
|
450
472
|
if (isHolder) {
|
|
451
|
-
|
|
473
|
+
if (lockInfo.type === 'exclusive')
|
|
474
|
+
return true;
|
|
452
475
|
if (lockInfo.type === 'shared' && requestedType === 'exclusive') {
|
|
453
476
|
return lockInfo.holders.size === 1;
|
|
454
477
|
}
|
|
455
|
-
// Same lock type or downgrade is always allowed for existing holders
|
|
456
478
|
return true;
|
|
457
479
|
}
|
|
480
|
+
// Writer-starvation fairness: if an exclusive waiter is queued,
|
|
481
|
+
// new shared requests must wait behind it. Otherwise continuous
|
|
482
|
+
// readers can starve a writer indefinitely (holders drain → new
|
|
483
|
+
// reader immediately re-acquires before the waiter is dequeued).
|
|
484
|
+
if (requestedType === 'shared' && lockInfo.waitQueue.length > 0) {
|
|
485
|
+
const hasExclusiveWaiter = lockInfo.waitQueue.some((w) => w.type === 'exclusive');
|
|
486
|
+
if (hasExclusiveWaiter)
|
|
487
|
+
return false;
|
|
488
|
+
}
|
|
489
|
+
// FIFO for exclusive: if anyone is queued, a new exclusive must
|
|
490
|
+
// wait behind the existing queue (even if holders just drained).
|
|
491
|
+
if (requestedType === 'exclusive' && lockInfo.waitQueue.length > 0) {
|
|
492
|
+
return false;
|
|
493
|
+
}
|
|
458
494
|
// If no current holders
|
|
459
495
|
if (lockInfo.holders.size === 0) {
|
|
460
496
|
return true;
|
|
@@ -471,9 +507,16 @@ export class LockManager {
|
|
|
471
507
|
return;
|
|
472
508
|
}
|
|
473
509
|
lockInfo.holders.delete(transactionId);
|
|
474
|
-
// Process wait queue if
|
|
475
|
-
|
|
476
|
-
|
|
510
|
+
// Process wait queue if:
|
|
511
|
+
// 1. All holders drained (holders.size === 0)
|
|
512
|
+
// 2. OR sole remaining holder is waiting for an exclusive upgrade!
|
|
513
|
+
if (lockInfo.waitQueue.length > 0) {
|
|
514
|
+
if (lockInfo.holders.size === 0) {
|
|
515
|
+
this.processWaitQueue(key, lockInfo);
|
|
516
|
+
}
|
|
517
|
+
else if (lockInfo.holders.size === 1 && lockInfo.waitQueue[0].type === 'exclusive' && lockInfo.holders.has(lockInfo.waitQueue[0].transactionId)) {
|
|
518
|
+
this.processWaitQueue(key, lockInfo);
|
|
519
|
+
}
|
|
477
520
|
}
|
|
478
521
|
// Clean up empty lock
|
|
479
522
|
if (lockInfo.holders.size === 0 && lockInfo.waitQueue.length === 0) {
|
|
@@ -500,6 +543,7 @@ export class LockManager {
|
|
|
500
543
|
// Grant single exclusive lock
|
|
501
544
|
const request = lockInfo.waitQueue.shift();
|
|
502
545
|
lockInfo.type = 'exclusive';
|
|
546
|
+
lockInfo.holders.clear();
|
|
503
547
|
lockInfo.holders.add(request.transactionId);
|
|
504
548
|
request.resolve();
|
|
505
549
|
}
|
|
@@ -511,20 +555,14 @@ export class LockManager {
|
|
|
511
555
|
lockInfo.waitQueue = lockInfo.waitQueue.filter(req => req.transactionId !== transactionId);
|
|
512
556
|
}
|
|
513
557
|
/**
|
|
514
|
-
* Release
|
|
515
|
-
* of O(allLocks) — the previous releaseAllLocks iterated every lock in the system
|
|
516
|
-
* on every commit, which dominated commit latency at scale.
|
|
558
|
+
* Release locks and remove pending wait-queue requests for a transaction.
|
|
517
559
|
*/
|
|
518
|
-
releaseLocksForTx(transactionId, heldKeys) {
|
|
560
|
+
releaseLocksForTx(transactionId, heldKeys, waitingKeys) {
|
|
519
561
|
for (const key of heldKeys) {
|
|
520
562
|
this.releaseLock(key, transactionId);
|
|
521
563
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
// correctness — we scan only the keys this tx was waiting on, which we can
|
|
525
|
-
// approximate by checking the locks it held (close enough for the common case
|
|
526
|
-
// where a tx never waits).
|
|
527
|
-
for (const key of heldKeys) {
|
|
564
|
+
const keysToClean = waitingKeys ? new Set([...heldKeys, ...waitingKeys]) : heldKeys;
|
|
565
|
+
for (const key of keysToClean) {
|
|
528
566
|
const lockInfo = this.locks.get(key);
|
|
529
567
|
if (lockInfo) {
|
|
530
568
|
lockInfo.waitQueue = lockInfo.waitQueue.filter(req => {
|
|
@@ -534,6 +572,9 @@ export class LockManager {
|
|
|
534
572
|
}
|
|
535
573
|
return true;
|
|
536
574
|
});
|
|
575
|
+
if (lockInfo.holders.size === 0 && lockInfo.waitQueue.length === 0) {
|
|
576
|
+
this.locks.delete(key);
|
|
577
|
+
}
|
|
537
578
|
}
|
|
538
579
|
}
|
|
539
580
|
}
|
|
@@ -657,17 +698,20 @@ export class ACIDStorageEngine {
|
|
|
657
698
|
* transactions, we rotate the WAL into an archive and start a fresh log.
|
|
658
699
|
* This bounds WAL size without rewriting it on every commit.
|
|
659
700
|
*/
|
|
660
|
-
COMMIT_INTERVAL =
|
|
701
|
+
COMMIT_INTERVAL = 10000;
|
|
661
702
|
commitCount = 0;
|
|
662
703
|
/**
|
|
663
|
-
* Monotonic
|
|
664
|
-
*
|
|
665
|
-
*
|
|
666
|
-
*
|
|
667
|
-
*
|
|
704
|
+
* Monotonic counter + PID + per-process random salt. The old counter-only
|
|
705
|
+
* scheme reused IDs after a restart (txCounter resets to 0), so a WAL
|
|
706
|
+
* containing t<oldPid>_0 COMMIT and a new uncommitted t<newPid>_0 would
|
|
707
|
+
* collide — recovery treated the new writes as committed (data loss / ghost
|
|
708
|
+
* docs). Including a per-process 3-byte random + timestamp makes IDs
|
|
709
|
+
* unique across restarts with zero hot-path cost (one random draw at
|
|
710
|
+
* construction, then cheap counter).
|
|
668
711
|
*/
|
|
669
712
|
txCounter = 0;
|
|
670
713
|
pid = process.pid;
|
|
714
|
+
txSalt = randomBytes(3).toString('hex');
|
|
671
715
|
/**
|
|
672
716
|
* Deferred data-file write buffer. On commit, committed data moves here instead
|
|
673
717
|
* of being written to data files immediately. A background timer flushes this
|
|
@@ -701,8 +745,10 @@ export class ACIDStorageEngine {
|
|
|
701
745
|
getDirtyKeyCount() {
|
|
702
746
|
return this.dirtyKeys.size;
|
|
703
747
|
}
|
|
748
|
+
synchronous;
|
|
704
749
|
constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50) {
|
|
705
750
|
this.dbPath = dbPath;
|
|
751
|
+
this.synchronous = synchronous;
|
|
706
752
|
this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
|
|
707
753
|
this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs);
|
|
708
754
|
this.lockManager = new LockManager();
|
|
@@ -712,6 +758,40 @@ export class ACIDStorageEngine {
|
|
|
712
758
|
if (this.dataFlushTimer.unref)
|
|
713
759
|
this.dataFlushTimer.unref();
|
|
714
760
|
}
|
|
761
|
+
fsyncFile(path) {
|
|
762
|
+
let fd;
|
|
763
|
+
try {
|
|
764
|
+
fd = openSync(path, 'r');
|
|
765
|
+
}
|
|
766
|
+
catch (error) {
|
|
767
|
+
if (error?.code === 'ENOENT')
|
|
768
|
+
return;
|
|
769
|
+
throw error;
|
|
770
|
+
}
|
|
771
|
+
try {
|
|
772
|
+
fsyncSync(fd);
|
|
773
|
+
}
|
|
774
|
+
finally {
|
|
775
|
+
closeSync(fd);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
fsyncDir(dirPath) {
|
|
779
|
+
let fd;
|
|
780
|
+
try {
|
|
781
|
+
fd = openSync(dirPath, 'r');
|
|
782
|
+
}
|
|
783
|
+
catch (error) {
|
|
784
|
+
if (error?.code === 'ENOENT')
|
|
785
|
+
return;
|
|
786
|
+
throw error;
|
|
787
|
+
}
|
|
788
|
+
try {
|
|
789
|
+
fsyncSync(fd);
|
|
790
|
+
}
|
|
791
|
+
finally {
|
|
792
|
+
closeSync(fd);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
715
795
|
initializeStorage() {
|
|
716
796
|
if (!existsSync(this.dbPath)) {
|
|
717
797
|
mkdirSync(this.dbPath, { recursive: true });
|
|
@@ -757,9 +837,16 @@ export class ACIDStorageEngine {
|
|
|
757
837
|
!committedTransactions.has(entry.transactionId) &&
|
|
758
838
|
!abortedTransactions.has(entry.transactionId) &&
|
|
759
839
|
entry.key) {
|
|
760
|
-
// Uncommitted:
|
|
761
|
-
//
|
|
762
|
-
|
|
840
|
+
// Uncommitted: keep the FIRST (earliest) entry per key, whose
|
|
841
|
+
// beforeImage is the ORIGINAL pre-transaction state. The old
|
|
842
|
+
// code kept the LAST entry — for two uncommitted writes to the
|
|
843
|
+
// same key (e.g. create {a:1} then update {a:1,b:2}) that
|
|
844
|
+
// stored {a:1} as the beforeImage and undo resurrected a ghost
|
|
845
|
+
// document that never existed before the transaction. Undo
|
|
846
|
+
// must restore the state BEFORE the first uncommitted write.
|
|
847
|
+
if (!undoByKey.has(entry.key)) {
|
|
848
|
+
undoByKey.set(entry.key, entry);
|
|
849
|
+
}
|
|
763
850
|
}
|
|
764
851
|
});
|
|
765
852
|
// Phase 3: reverse undo — process buffered uncommitted ops. Order within
|
|
@@ -777,7 +864,8 @@ export class ACIDStorageEngine {
|
|
|
777
864
|
this.atomicWriteFile(filePath, JSON.stringify(entry.afterImage, null, 2));
|
|
778
865
|
}
|
|
779
866
|
catch (error) {
|
|
780
|
-
|
|
867
|
+
if (error?.code === 'ENOSPC')
|
|
868
|
+
throw error;
|
|
781
869
|
}
|
|
782
870
|
}
|
|
783
871
|
redoDelete(entry) {
|
|
@@ -790,7 +878,8 @@ export class ACIDStorageEngine {
|
|
|
790
878
|
}
|
|
791
879
|
}
|
|
792
880
|
catch (error) {
|
|
793
|
-
|
|
881
|
+
if (error?.code === 'ENOSPC')
|
|
882
|
+
throw error;
|
|
794
883
|
}
|
|
795
884
|
}
|
|
796
885
|
undoOperation(entry) {
|
|
@@ -816,7 +905,8 @@ export class ACIDStorageEngine {
|
|
|
816
905
|
}
|
|
817
906
|
}
|
|
818
907
|
catch (error) {
|
|
819
|
-
|
|
908
|
+
if (error?.code === 'ENOSPC')
|
|
909
|
+
throw error;
|
|
820
910
|
}
|
|
821
911
|
}
|
|
822
912
|
/**
|
|
@@ -827,21 +917,29 @@ export class ACIDStorageEngine {
|
|
|
827
917
|
* phase rebuilds data files from the WAL. This eliminates 2 of the 3 fsyncs
|
|
828
918
|
* per commit, leaving only the WAL fsync as the single durability barrier.
|
|
829
919
|
*/
|
|
830
|
-
atomicWriteFile(filePath, content) {
|
|
920
|
+
atomicWriteFile(filePath, content, forceFsync = false) {
|
|
831
921
|
const dir = dirname(filePath);
|
|
832
922
|
if (!existsSync(dir)) {
|
|
833
923
|
mkdirSync(dir, { recursive: true });
|
|
834
924
|
}
|
|
835
925
|
const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
|
|
836
926
|
writeFileSync(tmpPath, content);
|
|
927
|
+
if (forceFsync || this.synchronous === 'full') {
|
|
928
|
+
this.fsyncFile(tmpPath);
|
|
929
|
+
}
|
|
837
930
|
// atomic rename — readers see old or new, never partial
|
|
838
931
|
renameSync(tmpPath, filePath);
|
|
839
|
-
|
|
840
|
-
|
|
932
|
+
if (forceFsync || this.synchronous === 'full') {
|
|
933
|
+
this.fsyncDir(dir);
|
|
934
|
+
}
|
|
841
935
|
}
|
|
936
|
+
static MAX_ACTIVE_TXNS = 10000;
|
|
842
937
|
// Transaction management
|
|
843
938
|
beginTransaction() {
|
|
844
|
-
|
|
939
|
+
if (this.activeTransactions.size >= ACIDStorageEngine.MAX_ACTIVE_TXNS) {
|
|
940
|
+
throw new Error(`Too many active transactions (${this.activeTransactions.size} >= ${ACIDStorageEngine.MAX_ACTIVE_TXNS}) — commit or rollback before starting more`);
|
|
941
|
+
}
|
|
942
|
+
const transactionId = `t${this.pid}_${this.txSalt}_${Date.now().toString(36)}_${this.txCounter++}`;
|
|
845
943
|
const startLSN = this.wal.writeLog({
|
|
846
944
|
operation: 'BEGIN',
|
|
847
945
|
transactionId
|
|
@@ -852,6 +950,7 @@ export class ACIDStorageEngine {
|
|
|
852
950
|
operations: [],
|
|
853
951
|
status: 'active',
|
|
854
952
|
heldLocks: new Set(),
|
|
953
|
+
waitingLocks: new Set(),
|
|
855
954
|
});
|
|
856
955
|
this.pendingWrites.set(transactionId, new Map());
|
|
857
956
|
return transactionId;
|
|
@@ -862,7 +961,7 @@ export class ACIDStorageEngine {
|
|
|
862
961
|
* `Promise<void>` only when the lock is contended and we must wait in queue.
|
|
863
962
|
* Callers should check: `if (result !== undefined) await result;`
|
|
864
963
|
*/
|
|
865
|
-
write(transactionId, key, data) {
|
|
964
|
+
write(transactionId, key, data, cachedBeforeImage) {
|
|
866
965
|
const transaction = this.activeTransactions.get(transactionId);
|
|
867
966
|
if (!transaction || transaction.status !== 'active') {
|
|
868
967
|
throw new Error(`Invalid transaction: ${transactionId}`);
|
|
@@ -871,24 +970,29 @@ export class ACIDStorageEngine {
|
|
|
871
970
|
const lockResult = this.lockManager.acquireLock(key, transactionId, 'exclusive');
|
|
872
971
|
if (lockResult !== true) {
|
|
873
972
|
// Slow path: lock is contended — return a Promise
|
|
973
|
+
transaction.waitingLocks.add(key);
|
|
874
974
|
return lockResult.then(() => {
|
|
975
|
+
transaction.waitingLocks.delete(key);
|
|
875
976
|
transaction.heldLocks.add(key);
|
|
876
|
-
this.doWriteSync(transactionId, key, data, transaction);
|
|
977
|
+
this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
|
|
978
|
+
}).catch((err) => {
|
|
979
|
+
transaction.waitingLocks.delete(key);
|
|
980
|
+
throw err;
|
|
877
981
|
});
|
|
878
982
|
}
|
|
879
983
|
// Fast path: lock granted synchronously — do the write work sync, return void
|
|
880
984
|
transaction.heldLocks.add(key);
|
|
881
|
-
this.doWriteSync(transactionId, key, data, transaction);
|
|
985
|
+
this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
|
|
882
986
|
}
|
|
883
987
|
/**
|
|
884
988
|
* Synchronous write work — called from write() after the lock is acquired.
|
|
885
989
|
* Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
|
|
886
990
|
* pendingWrites tracking. No syscalls, no Promises.
|
|
887
991
|
*/
|
|
888
|
-
doWriteSync(transactionId, key, data, transaction) {
|
|
992
|
+
doWriteSync(transactionId, key, data, transaction, cachedBeforeImage) {
|
|
889
993
|
try {
|
|
890
994
|
const pendingTx = this.pendingWrites.get(transactionId);
|
|
891
|
-
// Determine "before image" — check pending writes, then committedBuffer, then disk
|
|
995
|
+
// Determine "before image" — check pending writes, then committedBuffer, then cached, then disk
|
|
892
996
|
let currentData = null;
|
|
893
997
|
const pending = pendingTx.get(key);
|
|
894
998
|
if (pending) {
|
|
@@ -903,6 +1007,9 @@ export class ACIDStorageEngine {
|
|
|
903
1007
|
const committed = this.committedBuffer.get(key);
|
|
904
1008
|
currentData = committed.op === 'write' ? committed.data : null;
|
|
905
1009
|
}
|
|
1010
|
+
else if (cachedBeforeImage !== undefined) {
|
|
1011
|
+
currentData = cachedBeforeImage;
|
|
1012
|
+
}
|
|
906
1013
|
else {
|
|
907
1014
|
const filePath = partitionedPath(this.dbPath, key);
|
|
908
1015
|
if (existsSync(filePath)) {
|
|
@@ -932,6 +1039,51 @@ export class ACIDStorageEngine {
|
|
|
932
1039
|
throw error;
|
|
933
1040
|
}
|
|
934
1041
|
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Acquire an exclusive lock without writing. Used for SELECT FOR UPDATE
|
|
1044
|
+
* / transferMoney: acquire locks in global sorted order BEFORE reading
|
|
1045
|
+
* so reads are serializable and the read→write upgrade never deadlocks.
|
|
1046
|
+
* Same sync fast-path pattern as write/read — returns void or Promise.
|
|
1047
|
+
*/
|
|
1048
|
+
acquireExclusiveLock(transactionId, key) {
|
|
1049
|
+
const transaction = this.activeTransactions.get(transactionId);
|
|
1050
|
+
if (!transaction || transaction.status !== 'active') {
|
|
1051
|
+
throw new Error(`Invalid transaction: ${transactionId}`);
|
|
1052
|
+
}
|
|
1053
|
+
const lockResult = this.lockManager.acquireLock(key, transactionId, 'exclusive');
|
|
1054
|
+
if (lockResult !== true) {
|
|
1055
|
+
transaction.waitingLocks.add(key);
|
|
1056
|
+
return lockResult.then(() => {
|
|
1057
|
+
transaction.waitingLocks.delete(key);
|
|
1058
|
+
transaction.heldLocks.add(key);
|
|
1059
|
+
}).catch((err) => {
|
|
1060
|
+
transaction.waitingLocks.delete(key);
|
|
1061
|
+
throw err;
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
transaction.heldLocks.add(key);
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* Acquire a shared lock for a transaction.
|
|
1068
|
+
*/
|
|
1069
|
+
acquireSharedLock(transactionId, key) {
|
|
1070
|
+
const transaction = this.activeTransactions.get(transactionId);
|
|
1071
|
+
if (!transaction || transaction.status !== 'active') {
|
|
1072
|
+
throw new Error(`Invalid transaction: ${transactionId}`);
|
|
1073
|
+
}
|
|
1074
|
+
const lockResult = this.lockManager.acquireLock(key, transactionId, 'shared');
|
|
1075
|
+
if (lockResult !== true) {
|
|
1076
|
+
transaction.waitingLocks.add(key);
|
|
1077
|
+
return lockResult.then(() => {
|
|
1078
|
+
transaction.waitingLocks.delete(key);
|
|
1079
|
+
transaction.heldLocks.add(key);
|
|
1080
|
+
}).catch((err) => {
|
|
1081
|
+
transaction.waitingLocks.delete(key);
|
|
1082
|
+
throw err;
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
transaction.heldLocks.add(key);
|
|
1086
|
+
}
|
|
935
1087
|
/**
|
|
936
1088
|
* Read data for a transaction. Same pattern as write: returns the data
|
|
937
1089
|
* synchronously when the lock is uncontended, returns a Promise only when
|
|
@@ -945,9 +1097,14 @@ export class ACIDStorageEngine {
|
|
|
945
1097
|
const lockResult = this.lockManager.acquireLock(key, transactionId, 'shared');
|
|
946
1098
|
if (lockResult !== true) {
|
|
947
1099
|
// Slow path: lock is contended
|
|
1100
|
+
transaction.waitingLocks.add(key);
|
|
948
1101
|
return lockResult.then(() => {
|
|
1102
|
+
transaction.waitingLocks.delete(key);
|
|
949
1103
|
transaction.heldLocks.add(key);
|
|
950
1104
|
return this.doReadSync(transactionId, key);
|
|
1105
|
+
}).catch((err) => {
|
|
1106
|
+
transaction.waitingLocks.delete(key);
|
|
1107
|
+
throw err;
|
|
951
1108
|
});
|
|
952
1109
|
}
|
|
953
1110
|
// Fast path: lock granted synchronously
|
|
@@ -992,9 +1149,14 @@ export class ACIDStorageEngine {
|
|
|
992
1149
|
}
|
|
993
1150
|
const lockResult = this.lockManager.acquireLock(key, transactionId, 'exclusive');
|
|
994
1151
|
if (lockResult !== true) {
|
|
1152
|
+
transaction.waitingLocks.add(key);
|
|
995
1153
|
return lockResult.then(() => {
|
|
1154
|
+
transaction.waitingLocks.delete(key);
|
|
996
1155
|
transaction.heldLocks.add(key);
|
|
997
1156
|
this.doDeleteSync(transactionId, key, transaction);
|
|
1157
|
+
}).catch((err) => {
|
|
1158
|
+
transaction.waitingLocks.delete(key);
|
|
1159
|
+
throw err;
|
|
998
1160
|
});
|
|
999
1161
|
}
|
|
1000
1162
|
transaction.heldLocks.add(key);
|
|
@@ -1077,15 +1239,20 @@ export class ACIDStorageEngine {
|
|
|
1077
1239
|
}
|
|
1078
1240
|
// Update transaction status
|
|
1079
1241
|
transaction.status = 'committed';
|
|
1080
|
-
// Release only the locks this tx held
|
|
1081
|
-
this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks);
|
|
1242
|
+
// Release only the locks this tx held or was waiting on
|
|
1243
|
+
this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks, transaction.waitingLocks);
|
|
1082
1244
|
// Cleanup in-memory state
|
|
1083
1245
|
this.pendingWrites.delete(transactionId);
|
|
1084
1246
|
this.activeTransactions.delete(transactionId);
|
|
1085
1247
|
// Bound WAL growth: periodically rotate when no active transactions are left.
|
|
1248
|
+
// MUST flush committedBuffer before archiving — otherwise the
|
|
1249
|
+
// archive truncates .wal while deferred writes are still only in
|
|
1250
|
+
// memory; a crash before the 50ms timer would lose them and
|
|
1251
|
+
// recovery (which reads only .wal) would not replay them.
|
|
1086
1252
|
this.commitCount++;
|
|
1087
1253
|
if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
|
|
1088
1254
|
this.getActiveTransactions().length === 0) {
|
|
1255
|
+
this.flushCommittedBuffer(true);
|
|
1089
1256
|
this.wal.rotateLog();
|
|
1090
1257
|
}
|
|
1091
1258
|
}
|
|
@@ -1114,8 +1281,8 @@ export class ACIDStorageEngine {
|
|
|
1114
1281
|
});
|
|
1115
1282
|
// Update transaction status
|
|
1116
1283
|
transaction.status = 'aborted';
|
|
1117
|
-
// Release only the locks this tx held
|
|
1118
|
-
this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks);
|
|
1284
|
+
// Release only the locks this tx held or was waiting on
|
|
1285
|
+
this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks, transaction.waitingLocks);
|
|
1119
1286
|
// Cleanup in-memory state
|
|
1120
1287
|
this.pendingWrites.delete(transactionId);
|
|
1121
1288
|
this.activeTransactions.delete(transactionId);
|
|
@@ -1129,14 +1296,20 @@ export class ACIDStorageEngine {
|
|
|
1129
1296
|
}
|
|
1130
1297
|
const result = { ...target };
|
|
1131
1298
|
for (const key in source) {
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1299
|
+
// Prototype-pollution guard — attacker-controlled JSON may contain
|
|
1300
|
+
// {"__proto__": ...} or {"constructor": {"prototype": ...}} which
|
|
1301
|
+
// would pollute Object.prototype if merged naively. hasOwnProperty
|
|
1302
|
+
// alone does NOT block __proto__ from JSON.parse.
|
|
1303
|
+
if (key === '__proto__' || key === 'constructor' || key === 'prototype')
|
|
1304
|
+
continue;
|
|
1305
|
+
if (!Object.prototype.hasOwnProperty.call(source, key))
|
|
1306
|
+
continue;
|
|
1307
|
+
if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key]) &&
|
|
1308
|
+
typeof target[key] === 'object' && target[key] !== null && !Array.isArray(target[key])) {
|
|
1309
|
+
result[key] = this.deepMerge(target[key], source[key]);
|
|
1310
|
+
}
|
|
1311
|
+
else {
|
|
1312
|
+
result[key] = source[key];
|
|
1140
1313
|
}
|
|
1141
1314
|
}
|
|
1142
1315
|
return result;
|
|
@@ -1160,7 +1333,7 @@ export class ACIDStorageEngine {
|
|
|
1160
1333
|
return Array.from(this.activeTransactions.keys()).filter(id => this.activeTransactions.get(id)?.status === 'active');
|
|
1161
1334
|
}
|
|
1162
1335
|
forceCheckpoint() {
|
|
1163
|
-
this.flushCommittedBuffer();
|
|
1336
|
+
this.flushCommittedBuffer(true);
|
|
1164
1337
|
this.wal.writeLog({
|
|
1165
1338
|
operation: 'CHECKPOINT',
|
|
1166
1339
|
transactionId: 'SYSTEM'
|
|
@@ -1174,11 +1347,6 @@ export class ACIDStorageEngine {
|
|
|
1174
1347
|
getWAL() {
|
|
1175
1348
|
return this.wal;
|
|
1176
1349
|
}
|
|
1177
|
-
/**
|
|
1178
|
-
* Check if a key has committed-but-unflushed data. Returns the data if present
|
|
1179
|
-
* in committedBuffer, or `undefined` if not in the buffer (caller should check
|
|
1180
|
-
* disk). Used by the get() fast path in index.ts.
|
|
1181
|
-
*/
|
|
1182
1350
|
/**
|
|
1183
1351
|
* Return the pending afterImage for a key in an active transaction's pendingWrites.
|
|
1184
1352
|
* Used by index.ts write() to cache the MERGED result, not the raw user data.
|
|
@@ -1208,14 +1376,17 @@ export class ACIDStorageEngine {
|
|
|
1208
1376
|
* and by forceCheckpoint(). Writes each buffered entry to its data file using
|
|
1209
1377
|
* the atomic temp→rename pattern, then clears the buffer.
|
|
1210
1378
|
*/
|
|
1211
|
-
flushCommittedBuffer() {
|
|
1379
|
+
flushCommittedBuffer(forceFsync = false) {
|
|
1212
1380
|
if (this.committedBuffer.size === 0)
|
|
1213
1381
|
return;
|
|
1382
|
+
const syncNeeded = forceFsync || this.synchronous === 'full';
|
|
1383
|
+
const touchedDirs = new Set();
|
|
1214
1384
|
for (const [key, entry] of this.committedBuffer) {
|
|
1215
1385
|
const filePath = partitionedPath(this.dbPath, key);
|
|
1386
|
+
touchedDirs.add(dirname(filePath));
|
|
1216
1387
|
if (entry.op === 'write') {
|
|
1217
1388
|
try {
|
|
1218
|
-
this.atomicWriteFile(filePath, JSON.stringify(entry.data, null, 2));
|
|
1389
|
+
this.atomicWriteFile(filePath, JSON.stringify(entry.data, null, 2), syncNeeded);
|
|
1219
1390
|
}
|
|
1220
1391
|
catch {
|
|
1221
1392
|
// best-effort — WAL redo will handle on crash
|
|
@@ -1231,6 +1402,14 @@ export class ACIDStorageEngine {
|
|
|
1231
1402
|
}
|
|
1232
1403
|
}
|
|
1233
1404
|
}
|
|
1405
|
+
if (syncNeeded) {
|
|
1406
|
+
for (const dir of touchedDirs) {
|
|
1407
|
+
try {
|
|
1408
|
+
this.fsyncDir(dir);
|
|
1409
|
+
}
|
|
1410
|
+
catch { }
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1234
1413
|
this.committedBuffer.clear();
|
|
1235
1414
|
}
|
|
1236
1415
|
destroy() {
|