tero 0.0.9 → 0.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acid-engine.d.ts +21 -6
- package/dist/acid-engine.js +91 -33
- package/dist/backup.d.ts +26 -5
- package/dist/backup.js +302 -90
- package/dist/index.d.ts +29 -19
- package/dist/index.js +335 -112
- package/dist/recovery.js +42 -19
- package/package.json +7 -10
package/dist/acid-engine.d.ts
CHANGED
|
@@ -78,6 +78,11 @@ export declare class WriteAheadLog {
|
|
|
78
78
|
* Rotate the WAL: archive the current log to .wal.<timestamp>, start a fresh log,
|
|
79
79
|
* and write a CHECKPOINT entry at the head of the new log. Old archives beyond
|
|
80
80
|
* ARCHIVE_KEEP_COUNT are pruned locally (cloud upload in v2 retains durable copies).
|
|
81
|
+
*
|
|
82
|
+
* NOTE: ACIDStorageEngine.flushCommittedBuffer() MUST be called before
|
|
83
|
+
* rotateLog() — see commitTransaction() — otherwise deferred writes still
|
|
84
|
+
* in memory would be lost on crash after truncation. rotateLog() itself
|
|
85
|
+
* only guarantees WAL durability (forceFlush before archiving).
|
|
81
86
|
*/
|
|
82
87
|
rotateLog(): void;
|
|
83
88
|
/**
|
|
@@ -171,14 +176,17 @@ export declare class ACIDStorageEngine {
|
|
|
171
176
|
private readonly COMMIT_INTERVAL;
|
|
172
177
|
private commitCount;
|
|
173
178
|
/**
|
|
174
|
-
* Monotonic
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
179
|
+
* Monotonic counter + PID + per-process random salt. The old counter-only
|
|
180
|
+
* scheme reused IDs after a restart (txCounter resets to 0), so a WAL
|
|
181
|
+
* containing t<oldPid>_0 COMMIT and a new uncommitted t<newPid>_0 would
|
|
182
|
+
* collide — recovery treated the new writes as committed (data loss / ghost
|
|
183
|
+
* docs). Including a per-process 3-byte random + timestamp makes IDs
|
|
184
|
+
* unique across restarts with zero hot-path cost (one random draw at
|
|
185
|
+
* construction, then cheap counter).
|
|
179
186
|
*/
|
|
180
187
|
private txCounter;
|
|
181
188
|
private readonly pid;
|
|
189
|
+
private readonly txSalt;
|
|
182
190
|
/**
|
|
183
191
|
* Deferred data-file write buffer. On commit, committed data moves here instead
|
|
184
192
|
* of being written to data files immediately. A background timer flushes this
|
|
@@ -228,13 +236,20 @@ export declare class ACIDStorageEngine {
|
|
|
228
236
|
* `Promise<void>` only when the lock is contended and we must wait in queue.
|
|
229
237
|
* Callers should check: `if (result !== undefined) await result;`
|
|
230
238
|
*/
|
|
231
|
-
write(transactionId: string, key: string, data: any): void | Promise<void>;
|
|
239
|
+
write(transactionId: string, key: string, data: any, cachedBeforeImage?: any): void | Promise<void>;
|
|
232
240
|
/**
|
|
233
241
|
* Synchronous write work — called from write() after the lock is acquired.
|
|
234
242
|
* Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
|
|
235
243
|
* pendingWrites tracking. No syscalls, no Promises.
|
|
236
244
|
*/
|
|
237
245
|
private doWriteSync;
|
|
246
|
+
/**
|
|
247
|
+
* Acquire an exclusive lock without writing. Used for SELECT FOR UPDATE
|
|
248
|
+
* / transferMoney: acquire locks in global sorted order BEFORE reading
|
|
249
|
+
* so reads are serializable and the read→write upgrade never deadlocks.
|
|
250
|
+
* Same sync fast-path pattern as write/read — returns void or Promise.
|
|
251
|
+
*/
|
|
252
|
+
acquireExclusiveLock(transactionId: string, key: string): void | Promise<void>;
|
|
238
253
|
/**
|
|
239
254
|
* Read data for a transaction. Same pattern as write: returns the data
|
|
240
255
|
* synchronously when the lock is uncontended, returns a Promise only when
|
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
|
|
@@ -261,6 +262,11 @@ export class WriteAheadLog {
|
|
|
261
262
|
* Rotate the WAL: archive the current log to .wal.<timestamp>, start a fresh log,
|
|
262
263
|
* and write a CHECKPOINT entry at the head of the new log. Old archives beyond
|
|
263
264
|
* ARCHIVE_KEEP_COUNT are pruned locally (cloud upload in v2 retains durable copies).
|
|
265
|
+
*
|
|
266
|
+
* NOTE: ACIDStorageEngine.flushCommittedBuffer() MUST be called before
|
|
267
|
+
* rotateLog() — see commitTransaction() — otherwise deferred writes still
|
|
268
|
+
* in memory would be lost on crash after truncation. rotateLog() itself
|
|
269
|
+
* only guarantees WAL durability (forceFlush before archiving).
|
|
264
270
|
*/
|
|
265
271
|
rotateLog() {
|
|
266
272
|
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
@@ -415,16 +421,11 @@ export class LockManager {
|
|
|
415
421
|
}
|
|
416
422
|
return true;
|
|
417
423
|
}
|
|
418
|
-
//
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
lockInfo.holders.clear();
|
|
424
|
-
lockInfo.holders.add(transactionId);
|
|
425
|
-
return true;
|
|
426
|
-
}
|
|
427
|
-
}
|
|
424
|
+
// Shared→exclusive upgrade is handled via the wait queue. The
|
|
425
|
+
// previous fast path deleted the holder before re-checking
|
|
426
|
+
// canGrantLock and lost the shared lock when the upgrade blocked.
|
|
427
|
+
// Keep the shared lock held while waiting — processWaitQueue will
|
|
428
|
+
// promote atomically when holders drain.
|
|
428
429
|
// Slow path: lock is contended — allocate Promise + timer and wait in queue
|
|
429
430
|
return new Promise((resolve, reject) => {
|
|
430
431
|
const timeout = setTimeout(() => {
|
|
@@ -455,6 +456,20 @@ export class LockManager {
|
|
|
455
456
|
// Same lock type or downgrade is always allowed for existing holders
|
|
456
457
|
return true;
|
|
457
458
|
}
|
|
459
|
+
// Writer-starvation fairness: if an exclusive waiter is queued,
|
|
460
|
+
// new shared requests must wait behind it. Otherwise continuous
|
|
461
|
+
// readers can starve a writer indefinitely (holders drain → new
|
|
462
|
+
// reader immediately re-acquires before the waiter is dequeued).
|
|
463
|
+
if (requestedType === 'shared' && lockInfo.waitQueue.length > 0) {
|
|
464
|
+
const hasExclusiveWaiter = lockInfo.waitQueue.some((w) => w.type === 'exclusive');
|
|
465
|
+
if (hasExclusiveWaiter)
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
// FIFO for exclusive: if anyone is queued, a new exclusive must
|
|
469
|
+
// wait behind the existing queue (even if holders just drained).
|
|
470
|
+
if (requestedType === 'exclusive' && lockInfo.waitQueue.length > 0) {
|
|
471
|
+
return false;
|
|
472
|
+
}
|
|
458
473
|
// If no current holders
|
|
459
474
|
if (lockInfo.holders.size === 0) {
|
|
460
475
|
return true;
|
|
@@ -657,17 +672,20 @@ export class ACIDStorageEngine {
|
|
|
657
672
|
* transactions, we rotate the WAL into an archive and start a fresh log.
|
|
658
673
|
* This bounds WAL size without rewriting it on every commit.
|
|
659
674
|
*/
|
|
660
|
-
COMMIT_INTERVAL =
|
|
675
|
+
COMMIT_INTERVAL = 10000;
|
|
661
676
|
commitCount = 0;
|
|
662
677
|
/**
|
|
663
|
-
* Monotonic
|
|
664
|
-
*
|
|
665
|
-
*
|
|
666
|
-
*
|
|
667
|
-
*
|
|
678
|
+
* Monotonic counter + PID + per-process random salt. The old counter-only
|
|
679
|
+
* scheme reused IDs after a restart (txCounter resets to 0), so a WAL
|
|
680
|
+
* containing t<oldPid>_0 COMMIT and a new uncommitted t<newPid>_0 would
|
|
681
|
+
* collide — recovery treated the new writes as committed (data loss / ghost
|
|
682
|
+
* docs). Including a per-process 3-byte random + timestamp makes IDs
|
|
683
|
+
* unique across restarts with zero hot-path cost (one random draw at
|
|
684
|
+
* construction, then cheap counter).
|
|
668
685
|
*/
|
|
669
686
|
txCounter = 0;
|
|
670
687
|
pid = process.pid;
|
|
688
|
+
txSalt = randomBytes(3).toString('hex');
|
|
671
689
|
/**
|
|
672
690
|
* Deferred data-file write buffer. On commit, committed data moves here instead
|
|
673
691
|
* of being written to data files immediately. A background timer flushes this
|
|
@@ -757,9 +775,16 @@ export class ACIDStorageEngine {
|
|
|
757
775
|
!committedTransactions.has(entry.transactionId) &&
|
|
758
776
|
!abortedTransactions.has(entry.transactionId) &&
|
|
759
777
|
entry.key) {
|
|
760
|
-
// Uncommitted:
|
|
761
|
-
//
|
|
762
|
-
|
|
778
|
+
// Uncommitted: keep the FIRST (earliest) entry per key, whose
|
|
779
|
+
// beforeImage is the ORIGINAL pre-transaction state. The old
|
|
780
|
+
// code kept the LAST entry — for two uncommitted writes to the
|
|
781
|
+
// same key (e.g. create {a:1} then update {a:1,b:2}) that
|
|
782
|
+
// stored {a:1} as the beforeImage and undo resurrected a ghost
|
|
783
|
+
// document that never existed before the transaction. Undo
|
|
784
|
+
// must restore the state BEFORE the first uncommitted write.
|
|
785
|
+
if (!undoByKey.has(entry.key)) {
|
|
786
|
+
undoByKey.set(entry.key, entry);
|
|
787
|
+
}
|
|
763
788
|
}
|
|
764
789
|
});
|
|
765
790
|
// Phase 3: reverse undo — process buffered uncommitted ops. Order within
|
|
@@ -841,7 +866,7 @@ export class ACIDStorageEngine {
|
|
|
841
866
|
}
|
|
842
867
|
// Transaction management
|
|
843
868
|
beginTransaction() {
|
|
844
|
-
const transactionId =
|
|
869
|
+
const transactionId = `t${this.pid}_${this.txSalt}_${Date.now().toString(36)}_${this.txCounter++}`;
|
|
845
870
|
const startLSN = this.wal.writeLog({
|
|
846
871
|
operation: 'BEGIN',
|
|
847
872
|
transactionId
|
|
@@ -862,7 +887,7 @@ export class ACIDStorageEngine {
|
|
|
862
887
|
* `Promise<void>` only when the lock is contended and we must wait in queue.
|
|
863
888
|
* Callers should check: `if (result !== undefined) await result;`
|
|
864
889
|
*/
|
|
865
|
-
write(transactionId, key, data) {
|
|
890
|
+
write(transactionId, key, data, cachedBeforeImage) {
|
|
866
891
|
const transaction = this.activeTransactions.get(transactionId);
|
|
867
892
|
if (!transaction || transaction.status !== 'active') {
|
|
868
893
|
throw new Error(`Invalid transaction: ${transactionId}`);
|
|
@@ -873,22 +898,22 @@ export class ACIDStorageEngine {
|
|
|
873
898
|
// Slow path: lock is contended — return a Promise
|
|
874
899
|
return lockResult.then(() => {
|
|
875
900
|
transaction.heldLocks.add(key);
|
|
876
|
-
this.doWriteSync(transactionId, key, data, transaction);
|
|
901
|
+
this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
|
|
877
902
|
});
|
|
878
903
|
}
|
|
879
904
|
// Fast path: lock granted synchronously — do the write work sync, return void
|
|
880
905
|
transaction.heldLocks.add(key);
|
|
881
|
-
this.doWriteSync(transactionId, key, data, transaction);
|
|
906
|
+
this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
|
|
882
907
|
}
|
|
883
908
|
/**
|
|
884
909
|
* Synchronous write work — called from write() after the lock is acquired.
|
|
885
910
|
* Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
|
|
886
911
|
* pendingWrites tracking. No syscalls, no Promises.
|
|
887
912
|
*/
|
|
888
|
-
doWriteSync(transactionId, key, data, transaction) {
|
|
913
|
+
doWriteSync(transactionId, key, data, transaction, cachedBeforeImage) {
|
|
889
914
|
try {
|
|
890
915
|
const pendingTx = this.pendingWrites.get(transactionId);
|
|
891
|
-
// Determine "before image" — check pending writes, then committedBuffer, then disk
|
|
916
|
+
// Determine "before image" — check pending writes, then committedBuffer, then cached, then disk
|
|
892
917
|
let currentData = null;
|
|
893
918
|
const pending = pendingTx.get(key);
|
|
894
919
|
if (pending) {
|
|
@@ -903,6 +928,9 @@ export class ACIDStorageEngine {
|
|
|
903
928
|
const committed = this.committedBuffer.get(key);
|
|
904
929
|
currentData = committed.op === 'write' ? committed.data : null;
|
|
905
930
|
}
|
|
931
|
+
else if (cachedBeforeImage !== undefined) {
|
|
932
|
+
currentData = cachedBeforeImage;
|
|
933
|
+
}
|
|
906
934
|
else {
|
|
907
935
|
const filePath = partitionedPath(this.dbPath, key);
|
|
908
936
|
if (existsSync(filePath)) {
|
|
@@ -932,6 +960,25 @@ export class ACIDStorageEngine {
|
|
|
932
960
|
throw error;
|
|
933
961
|
}
|
|
934
962
|
}
|
|
963
|
+
/**
|
|
964
|
+
* Acquire an exclusive lock without writing. Used for SELECT FOR UPDATE
|
|
965
|
+
* / transferMoney: acquire locks in global sorted order BEFORE reading
|
|
966
|
+
* so reads are serializable and the read→write upgrade never deadlocks.
|
|
967
|
+
* Same sync fast-path pattern as write/read — returns void or Promise.
|
|
968
|
+
*/
|
|
969
|
+
acquireExclusiveLock(transactionId, key) {
|
|
970
|
+
const transaction = this.activeTransactions.get(transactionId);
|
|
971
|
+
if (!transaction || transaction.status !== 'active') {
|
|
972
|
+
throw new Error(`Invalid transaction: ${transactionId}`);
|
|
973
|
+
}
|
|
974
|
+
const lockResult = this.lockManager.acquireLock(key, transactionId, 'exclusive');
|
|
975
|
+
if (lockResult !== true) {
|
|
976
|
+
return lockResult.then(() => {
|
|
977
|
+
transaction.heldLocks.add(key);
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
transaction.heldLocks.add(key);
|
|
981
|
+
}
|
|
935
982
|
/**
|
|
936
983
|
* Read data for a transaction. Same pattern as write: returns the data
|
|
937
984
|
* synchronously when the lock is uncontended, returns a Promise only when
|
|
@@ -1083,9 +1130,14 @@ export class ACIDStorageEngine {
|
|
|
1083
1130
|
this.pendingWrites.delete(transactionId);
|
|
1084
1131
|
this.activeTransactions.delete(transactionId);
|
|
1085
1132
|
// Bound WAL growth: periodically rotate when no active transactions are left.
|
|
1133
|
+
// MUST flush committedBuffer before archiving — otherwise the
|
|
1134
|
+
// archive truncates .wal while deferred writes are still only in
|
|
1135
|
+
// memory; a crash before the 50ms timer would lose them and
|
|
1136
|
+
// recovery (which reads only .wal) would not replay them.
|
|
1086
1137
|
this.commitCount++;
|
|
1087
1138
|
if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
|
|
1088
1139
|
this.getActiveTransactions().length === 0) {
|
|
1140
|
+
this.flushCommittedBuffer();
|
|
1089
1141
|
this.wal.rotateLog();
|
|
1090
1142
|
}
|
|
1091
1143
|
}
|
|
@@ -1129,14 +1181,20 @@ export class ACIDStorageEngine {
|
|
|
1129
1181
|
}
|
|
1130
1182
|
const result = { ...target };
|
|
1131
1183
|
for (const key in source) {
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1184
|
+
// Prototype-pollution guard — attacker-controlled JSON may contain
|
|
1185
|
+
// {"__proto__": ...} or {"constructor": {"prototype": ...}} which
|
|
1186
|
+
// would pollute Object.prototype if merged naively. hasOwnProperty
|
|
1187
|
+
// alone does NOT block __proto__ from JSON.parse.
|
|
1188
|
+
if (key === '__proto__' || key === 'constructor' || key === 'prototype')
|
|
1189
|
+
continue;
|
|
1190
|
+
if (!Object.prototype.hasOwnProperty.call(source, key))
|
|
1191
|
+
continue;
|
|
1192
|
+
if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key]) &&
|
|
1193
|
+
typeof target[key] === 'object' && target[key] !== null && !Array.isArray(target[key])) {
|
|
1194
|
+
result[key] = this.deepMerge(target[key], source[key]);
|
|
1195
|
+
}
|
|
1196
|
+
else {
|
|
1197
|
+
result[key] = source[key];
|
|
1140
1198
|
}
|
|
1141
1199
|
}
|
|
1142
1200
|
return result;
|
package/dist/backup.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ export interface LiveBackupStatus {
|
|
|
10
10
|
checkpointsTaken: number;
|
|
11
11
|
errorCount: number;
|
|
12
12
|
lastError?: string;
|
|
13
|
+
/** Last error from liveCheckpointToBucket (initial or manual). Cleared on success. */
|
|
14
|
+
lastCheckpointError?: string;
|
|
13
15
|
}
|
|
14
16
|
export interface LiveBackupOptions {
|
|
15
17
|
/** The only consistency level live backup offers: RPO ≤ 1 second of committed writes. */
|
|
@@ -19,6 +21,12 @@ export interface LiveBackupOptions {
|
|
|
19
21
|
/** Stable identity for this node in the bucket. Persisted to <dbPath>/.tero-node-id. */
|
|
20
22
|
nodeId?: string;
|
|
21
23
|
}
|
|
24
|
+
export interface LiveCheckpointResult {
|
|
25
|
+
uploadedDocs: number;
|
|
26
|
+
tombstonedDocs: number;
|
|
27
|
+
fullUpload: boolean;
|
|
28
|
+
duration: number;
|
|
29
|
+
}
|
|
22
30
|
export interface RestoreLiveResult {
|
|
23
31
|
nodeId: string;
|
|
24
32
|
docsRestored: number;
|
|
@@ -35,6 +43,14 @@ export interface CloudStorageConfig {
|
|
|
35
43
|
endpoint?: string;
|
|
36
44
|
pathPrefix?: string;
|
|
37
45
|
}
|
|
46
|
+
/** Injectable logger for BackupManager. Pass your own to route backup logs into
|
|
47
|
+
* your observability stack; pass 'silent' to disable them entirely. Default
|
|
48
|
+
* (undefined) keeps console output for backwards compatibility. */
|
|
49
|
+
export type BackupLogger = {
|
|
50
|
+
info: (...args: any[]) => void;
|
|
51
|
+
warn: (...args: any[]) => void;
|
|
52
|
+
error: (...args: any[]) => void;
|
|
53
|
+
};
|
|
38
54
|
export interface BackupConfig {
|
|
39
55
|
interval?: string;
|
|
40
56
|
retention?: string;
|
|
@@ -44,6 +60,7 @@ export interface BackupConfig {
|
|
|
44
60
|
compression?: boolean;
|
|
45
61
|
includeMetadata?: boolean;
|
|
46
62
|
metadataUse?: 'verification' | 'audit' | 'recovery' | 'none';
|
|
63
|
+
logger?: 'silent' | BackupLogger;
|
|
47
64
|
}
|
|
48
65
|
export interface BackupMetadata {
|
|
49
66
|
timestamp: string;
|
|
@@ -65,6 +82,8 @@ export declare class BackupManager {
|
|
|
65
82
|
private scheduledBackups;
|
|
66
83
|
private config;
|
|
67
84
|
private dbPath;
|
|
85
|
+
/** Injected or default logger (see BackupConfig.logger). */
|
|
86
|
+
private log;
|
|
68
87
|
constructor(dbPath: string, config: BackupConfig);
|
|
69
88
|
private initializeCloudStorage;
|
|
70
89
|
private parseInterval;
|
|
@@ -126,6 +145,9 @@ export declare class BackupManager {
|
|
|
126
145
|
private liveEngine?;
|
|
127
146
|
private livePrefix?;
|
|
128
147
|
private liveCheckpoints;
|
|
148
|
+
/** In-flight checkpoint (shared promise: concurrent callers await the same run). */
|
|
149
|
+
private liveCheckpointPromise?;
|
|
150
|
+
private lastCheckpointError?;
|
|
129
151
|
destroy(): void;
|
|
130
152
|
private liveCloudPrefix;
|
|
131
153
|
private uploadBytes;
|
|
@@ -133,15 +155,14 @@ export declare class BackupManager {
|
|
|
133
155
|
private readJsonOrDefault;
|
|
134
156
|
private listPrefix;
|
|
135
157
|
enableLiveBackup(engine: ACIDStorageEngine, opts: LiveBackupOptions): void;
|
|
158
|
+
/** Initial full checkpoint with bounded retry. Stops on success or disable. */
|
|
159
|
+
private runInitialCheckpoint;
|
|
136
160
|
disableLiveBackup(): void;
|
|
137
161
|
getLiveBackupStatus(): LiveBackupStatus;
|
|
138
162
|
liveCheckpointToBucket(_opts?: {
|
|
139
163
|
tag?: string;
|
|
140
|
-
}): Promise<
|
|
141
|
-
|
|
142
|
-
fullUpload: boolean;
|
|
143
|
-
duration: number;
|
|
144
|
-
}>;
|
|
164
|
+
}): Promise<LiveCheckpointResult>;
|
|
165
|
+
private doLiveCheckpoint;
|
|
145
166
|
restoreLiveToDirectory(targetDir: string, opts?: {
|
|
146
167
|
nodeId?: string;
|
|
147
168
|
pointInTime?: number;
|