tero 0.0.4 → 0.0.6
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 +4 -1
- package/dist/acid-engine.js +82 -19
- package/dist/index.d.ts +79 -6
- package/dist/index.js +204 -36
- package/package.json +2 -2
package/dist/acid-engine.d.ts
CHANGED
|
@@ -23,10 +23,12 @@ export declare class WriteAheadLog {
|
|
|
23
23
|
private flushBuffer;
|
|
24
24
|
private checkLogRotation;
|
|
25
25
|
private rotateLog;
|
|
26
|
+
private cleanupOldArchives;
|
|
26
27
|
getLogEntries(fromLSN?: number): LogEntry[];
|
|
27
28
|
forceFlush(): void;
|
|
28
29
|
getCurrentLSN(): number;
|
|
29
|
-
|
|
30
|
+
clearTransaction(transactionId: string): void;
|
|
31
|
+
truncateLog(): void;
|
|
30
32
|
}
|
|
31
33
|
export declare class LockManager {
|
|
32
34
|
private locks;
|
|
@@ -57,6 +59,7 @@ export declare class ACIDStorageEngine {
|
|
|
57
59
|
commitTransaction(transactionId: string): Promise<void>;
|
|
58
60
|
rollbackTransaction(transactionId: string): Promise<void>;
|
|
59
61
|
private deepMerge;
|
|
62
|
+
getTransactionStatus(transactionId: string): 'active' | 'committed' | 'aborted' | 'not_found';
|
|
60
63
|
getActiveTransactions(): string[];
|
|
61
64
|
forceCheckpoint(): void;
|
|
62
65
|
destroy(): void;
|
package/dist/acid-engine.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync, statSync } from "fs";
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync } from "fs";
|
|
2
2
|
import { join, dirname } from "path";
|
|
3
3
|
import { randomUUID } from "crypto";
|
|
4
4
|
import { createHash } from "crypto";
|
|
@@ -8,7 +8,7 @@ export class WriteAheadLog {
|
|
|
8
8
|
currentLSN = 0;
|
|
9
9
|
logBuffer = [];
|
|
10
10
|
BUFFER_SIZE = 100;
|
|
11
|
-
LOG_FILE_SIZE_LIMIT =
|
|
11
|
+
LOG_FILE_SIZE_LIMIT = 1 * 1024 * 1024; // 1MB
|
|
12
12
|
constructor(dbPath) {
|
|
13
13
|
this.logPath = join(dbPath, '.wal');
|
|
14
14
|
this.initializeWAL();
|
|
@@ -115,6 +115,29 @@ export class WriteAheadLog {
|
|
|
115
115
|
// Start new log with checkpoint
|
|
116
116
|
writeFileSync(this.logPath, '');
|
|
117
117
|
this.writeLog({ operation: 'CHECKPOINT', transactionId: 'SYSTEM' });
|
|
118
|
+
// Clean up old archives to prevent indefinite growth
|
|
119
|
+
this.cleanupOldArchives(3);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
// Silent failure for production
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
cleanupOldArchives(keepCount) {
|
|
126
|
+
try {
|
|
127
|
+
const dir = dirname(this.logPath);
|
|
128
|
+
if (!existsSync(dir))
|
|
129
|
+
return;
|
|
130
|
+
const files = readdirSync(dir);
|
|
131
|
+
const archiveFiles = files
|
|
132
|
+
.filter(f => f.startsWith('.wal.'))
|
|
133
|
+
.map(f => join(dir, f))
|
|
134
|
+
.sort();
|
|
135
|
+
while (archiveFiles.length > keepCount) {
|
|
136
|
+
const oldestFile = archiveFiles.shift();
|
|
137
|
+
if (oldestFile && existsSync(oldestFile)) {
|
|
138
|
+
unlinkSync(oldestFile);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
118
141
|
}
|
|
119
142
|
catch (error) {
|
|
120
143
|
// Silent failure for production
|
|
@@ -158,7 +181,7 @@ export class WriteAheadLog {
|
|
|
158
181
|
getCurrentLSN() {
|
|
159
182
|
return this.currentLSN - 1;
|
|
160
183
|
}
|
|
161
|
-
|
|
184
|
+
clearTransaction(transactionId) {
|
|
162
185
|
try {
|
|
163
186
|
// First, flush any pending buffer entries to disk
|
|
164
187
|
this.flushBuffer();
|
|
@@ -168,9 +191,9 @@ export class WriteAheadLog {
|
|
|
168
191
|
// Read current log content
|
|
169
192
|
const logContent = readFileSync(this.logPath, 'utf-8');
|
|
170
193
|
const lines = logContent.trim().split('\n').filter(line => line.trim());
|
|
171
|
-
// Filter out entries for the
|
|
194
|
+
// Filter out entries for the completed transaction
|
|
172
195
|
const filteredLines = [];
|
|
173
|
-
let
|
|
196
|
+
let transactionProcessed = false;
|
|
174
197
|
for (const line of lines) {
|
|
175
198
|
try {
|
|
176
199
|
const entry = JSON.parse(line);
|
|
@@ -179,13 +202,8 @@ export class WriteAheadLog {
|
|
|
179
202
|
filteredLines.push(line);
|
|
180
203
|
}
|
|
181
204
|
else {
|
|
182
|
-
//
|
|
183
|
-
|
|
184
|
-
if (entry.operation === 'COMMIT') {
|
|
185
|
-
filteredLines.push(line);
|
|
186
|
-
transactionCompleted = true;
|
|
187
|
-
}
|
|
188
|
-
// Skip BEGIN, WRITE, DELETE entries for committed transactions
|
|
205
|
+
// Remove ALL entries for the completed transaction to compact log
|
|
206
|
+
transactionProcessed = true;
|
|
189
207
|
}
|
|
190
208
|
}
|
|
191
209
|
catch (error) {
|
|
@@ -194,14 +212,24 @@ export class WriteAheadLog {
|
|
|
194
212
|
}
|
|
195
213
|
}
|
|
196
214
|
// Only rewrite the log if we actually found and processed the transaction
|
|
197
|
-
if (
|
|
215
|
+
if (transactionProcessed) {
|
|
198
216
|
const newContent = filteredLines.length > 0 ? filteredLines.join('\n') + '\n' : '';
|
|
199
217
|
writeFileSync(this.logPath, newContent);
|
|
200
218
|
}
|
|
201
219
|
}
|
|
202
220
|
catch (error) {
|
|
203
|
-
// Silent failure for production - WAL cleanup is an optimization
|
|
204
|
-
|
|
221
|
+
// Silent failure for production - WAL cleanup is an optimization
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
truncateLog() {
|
|
225
|
+
try {
|
|
226
|
+
this.flushBuffer();
|
|
227
|
+
writeFileSync(this.logPath, '');
|
|
228
|
+
// Clean up all archives since the log is truncated and no active transactions exist
|
|
229
|
+
this.cleanupOldArchives(0);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
// Silent failure
|
|
205
233
|
}
|
|
206
234
|
}
|
|
207
235
|
}
|
|
@@ -241,6 +269,20 @@ export class LockManager {
|
|
|
241
269
|
resolve();
|
|
242
270
|
return;
|
|
243
271
|
}
|
|
272
|
+
// Handle shared-to-exclusive upgrade: release shared lock and retry
|
|
273
|
+
// This prevents deadlock when multiple shared holders attempt to upgrade
|
|
274
|
+
if (lockInfo.holders.has(transactionId) && lockInfo.type === 'shared' && lockType === 'exclusive' && lockInfo.holders.size > 1) {
|
|
275
|
+
lockInfo.holders.delete(transactionId);
|
|
276
|
+
// Retry grant after releasing shared hold
|
|
277
|
+
if (this.canGrantLock(lockInfo, lockType, transactionId)) {
|
|
278
|
+
lockInfo.type = lockType;
|
|
279
|
+
lockInfo.holders.clear();
|
|
280
|
+
lockInfo.holders.add(transactionId);
|
|
281
|
+
clearTimeout(timeout);
|
|
282
|
+
resolve();
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
244
286
|
// Add to wait queue
|
|
245
287
|
lockInfo.waitQueue.push({
|
|
246
288
|
transactionId,
|
|
@@ -257,8 +299,13 @@ export class LockManager {
|
|
|
257
299
|
});
|
|
258
300
|
}
|
|
259
301
|
canGrantLock(lockInfo, requestedType, transactionId) {
|
|
260
|
-
|
|
261
|
-
if (
|
|
302
|
+
const isHolder = lockInfo.holders.has(transactionId);
|
|
303
|
+
if (isHolder) {
|
|
304
|
+
// Upgrading from shared to exclusive is only allowed if this is the sole holder
|
|
305
|
+
if (lockInfo.type === 'shared' && requestedType === 'exclusive') {
|
|
306
|
+
return lockInfo.holders.size === 1;
|
|
307
|
+
}
|
|
308
|
+
// Same lock type or downgrade is always allowed for existing holders
|
|
262
309
|
return true;
|
|
263
310
|
}
|
|
264
311
|
// If no current holders
|
|
@@ -615,8 +662,12 @@ export class ACIDStorageEngine {
|
|
|
615
662
|
}
|
|
616
663
|
// Update transaction status
|
|
617
664
|
transaction.status = 'committed';
|
|
618
|
-
// Clear WAL entries for this
|
|
619
|
-
this.wal.
|
|
665
|
+
// Clear WAL entries for this completed transaction
|
|
666
|
+
this.wal.clearTransaction(transactionId);
|
|
667
|
+
// Truncate log completely if no more active transactions
|
|
668
|
+
if (this.getActiveTransactions().length === 0) {
|
|
669
|
+
this.wal.truncateLog();
|
|
670
|
+
}
|
|
620
671
|
// Release all locks
|
|
621
672
|
this.lockManager.releaseAllLocks(transactionId);
|
|
622
673
|
}
|
|
@@ -639,6 +690,12 @@ export class ACIDStorageEngine {
|
|
|
639
690
|
});
|
|
640
691
|
// Update transaction status
|
|
641
692
|
transaction.status = 'aborted';
|
|
693
|
+
// Clear WAL entries for this aborted transaction
|
|
694
|
+
this.wal.clearTransaction(transactionId);
|
|
695
|
+
// Truncate log completely if no more active transactions
|
|
696
|
+
if (this.getActiveTransactions().length === 0) {
|
|
697
|
+
this.wal.truncateLog();
|
|
698
|
+
}
|
|
642
699
|
// Release all locks
|
|
643
700
|
this.lockManager.releaseAllLocks(transactionId);
|
|
644
701
|
}
|
|
@@ -668,6 +725,12 @@ export class ACIDStorageEngine {
|
|
|
668
725
|
return result;
|
|
669
726
|
}
|
|
670
727
|
// Utility methods
|
|
728
|
+
getTransactionStatus(transactionId) {
|
|
729
|
+
const tx = this.activeTransactions.get(transactionId);
|
|
730
|
+
if (!tx)
|
|
731
|
+
return 'not_found';
|
|
732
|
+
return tx.status;
|
|
733
|
+
}
|
|
671
734
|
getActiveTransactions() {
|
|
672
735
|
return Array.from(this.activeTransactions.keys()).filter(id => this.activeTransactions.get(id)?.status === 'active');
|
|
673
736
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,6 +5,43 @@ interface TeroConfig {
|
|
|
5
5
|
directory?: string;
|
|
6
6
|
cacheSize?: number;
|
|
7
7
|
}
|
|
8
|
+
interface TransactionOptions {
|
|
9
|
+
timeout?: number;
|
|
10
|
+
}
|
|
11
|
+
interface TransactionStats {
|
|
12
|
+
active: number;
|
|
13
|
+
committed: number;
|
|
14
|
+
rolledBack: number;
|
|
15
|
+
total: number;
|
|
16
|
+
}
|
|
17
|
+
export declare class Transaction {
|
|
18
|
+
private id;
|
|
19
|
+
private db;
|
|
20
|
+
private startTime;
|
|
21
|
+
private opCount;
|
|
22
|
+
private destroyed;
|
|
23
|
+
private timeoutTimer?;
|
|
24
|
+
constructor(id: string, db: Tero, options?: TransactionOptions);
|
|
25
|
+
getId(): string;
|
|
26
|
+
isActive(): boolean;
|
|
27
|
+
isRolledBack(): boolean;
|
|
28
|
+
private _checkActive;
|
|
29
|
+
create(key: string, initialData?: any): Promise<void>;
|
|
30
|
+
update(key: string, data: any): Promise<void>;
|
|
31
|
+
delete(key: string): Promise<void>;
|
|
32
|
+
get(key: string): Promise<any>;
|
|
33
|
+
getState(): {
|
|
34
|
+
status: string;
|
|
35
|
+
operations: Array<{
|
|
36
|
+
key: string;
|
|
37
|
+
operation: string;
|
|
38
|
+
}>;
|
|
39
|
+
startTime: number;
|
|
40
|
+
};
|
|
41
|
+
getOperationCount(): number;
|
|
42
|
+
getDuration(): number;
|
|
43
|
+
destroy(): void;
|
|
44
|
+
}
|
|
8
45
|
export declare class Tero {
|
|
9
46
|
private teroDirectory;
|
|
10
47
|
private cacheSize;
|
|
@@ -15,21 +52,32 @@ export declare class Tero {
|
|
|
15
52
|
private schemaValidator;
|
|
16
53
|
private backupManager?;
|
|
17
54
|
private dataRecovery?;
|
|
55
|
+
private committedCount;
|
|
56
|
+
private rolledBackCount;
|
|
18
57
|
constructor(config?: TeroConfig);
|
|
19
58
|
private initializeDirectories;
|
|
20
59
|
private validateKey;
|
|
21
60
|
private invalidateCacheKeys;
|
|
22
61
|
private updateCache;
|
|
23
|
-
beginTransaction():
|
|
24
|
-
|
|
62
|
+
beginTransaction(options?: TransactionOptions): Transaction;
|
|
63
|
+
private _beginTransaction;
|
|
64
|
+
private _txId;
|
|
65
|
+
write(transactionId: string | Transaction, key: string, data: any, options?: {
|
|
25
66
|
validate?: boolean;
|
|
26
67
|
schemaName?: string;
|
|
27
68
|
strict?: boolean;
|
|
28
69
|
}): Promise<ValidationResult | void>;
|
|
29
|
-
read(transactionId: string, key: string): Promise<any>;
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
70
|
+
read(transactionId: string | Transaction, key: string): Promise<any>;
|
|
71
|
+
commit(transactionId: string | Transaction): Promise<void>;
|
|
72
|
+
rollback(transactionId: string | Transaction): Promise<void>;
|
|
73
|
+
commitTransaction(transactionId: string | Transaction): Promise<void>;
|
|
74
|
+
rollbackTransaction(transactionId: string | Transaction): Promise<void>;
|
|
75
|
+
getPerformanceStats(): {
|
|
76
|
+
cacheStats: {
|
|
77
|
+
hitRate: number;
|
|
78
|
+
};
|
|
79
|
+
totalRequests: number;
|
|
80
|
+
};
|
|
33
81
|
create(key: string, initialData?: any, options?: {
|
|
34
82
|
validate?: boolean;
|
|
35
83
|
schemaName?: string;
|
|
@@ -42,6 +90,7 @@ export declare class Tero {
|
|
|
42
90
|
}): Promise<ValidationResult | void>;
|
|
43
91
|
get(key: string): Promise<any>;
|
|
44
92
|
remove(key: string): Promise<void>;
|
|
93
|
+
delete(key: string): Promise<void>;
|
|
45
94
|
exists(key: string): boolean;
|
|
46
95
|
batchWrite(operations: Array<{
|
|
47
96
|
key: string;
|
|
@@ -55,10 +104,34 @@ export declare class Tero {
|
|
|
55
104
|
[key: string]: any;
|
|
56
105
|
}>;
|
|
57
106
|
transferMoney(fromKey: string, toKey: string, amount: number): Promise<void>;
|
|
107
|
+
_writeRaw(transactionId: string, key: string, data: any): Promise<void>;
|
|
108
|
+
_readRaw(transactionId: string, key: string): Promise<any>;
|
|
109
|
+
_deleteRaw(transactionId: string, key: string): Promise<void>;
|
|
110
|
+
_rollbackRaw(transactionId: string): Promise<void>;
|
|
111
|
+
_getTxStatus(transactionId: string): 'active' | 'committed' | 'aborted' | 'not_found';
|
|
112
|
+
getTransactionStats(): TransactionStats;
|
|
58
113
|
setSchema(collectionName: string, schema: DocumentSchema): void;
|
|
59
114
|
getSchema(collectionName: string): DocumentSchema | undefined;
|
|
60
115
|
removeSchema(collectionName: string): boolean;
|
|
61
116
|
validateData(collectionName: string, data: any): ValidationResult;
|
|
117
|
+
hasSchema(collectionName: string): boolean;
|
|
118
|
+
listSchemas(): string[];
|
|
119
|
+
exportSchemas(): Record<string, DocumentSchema>;
|
|
120
|
+
getSchemaStats(): {
|
|
121
|
+
totalSchemas: number;
|
|
122
|
+
schemaNames: string[];
|
|
123
|
+
totalFields: number;
|
|
124
|
+
};
|
|
125
|
+
createWithValidation(key: string, initialData?: any, options?: {
|
|
126
|
+
validate?: boolean;
|
|
127
|
+
schemaName?: string;
|
|
128
|
+
strict?: boolean;
|
|
129
|
+
}): Promise<ValidationResult>;
|
|
130
|
+
updateWithValidation(key: string, data: any, options?: {
|
|
131
|
+
validate?: boolean;
|
|
132
|
+
schemaName?: string;
|
|
133
|
+
strict?: boolean;
|
|
134
|
+
}): Promise<ValidationResult>;
|
|
62
135
|
configureBackup(config: BackupConfig): void;
|
|
63
136
|
performBackup(): Promise<{
|
|
64
137
|
success: boolean;
|
package/dist/index.js
CHANGED
|
@@ -5,6 +5,88 @@ import { BackupManager } from "./backup.js";
|
|
|
5
5
|
import { DataRecovery } from "./recovery.js";
|
|
6
6
|
import { randomBytes } from "node:crypto";
|
|
7
7
|
import QuickLRU from "quick-lru";
|
|
8
|
+
export class Transaction {
|
|
9
|
+
id;
|
|
10
|
+
db;
|
|
11
|
+
startTime;
|
|
12
|
+
opCount = 0;
|
|
13
|
+
destroyed = false;
|
|
14
|
+
timeoutTimer;
|
|
15
|
+
constructor(id, db, options) {
|
|
16
|
+
this.id = id;
|
|
17
|
+
this.db = db;
|
|
18
|
+
this.startTime = Date.now();
|
|
19
|
+
if (options?.timeout) {
|
|
20
|
+
this.timeoutTimer = setTimeout(() => {
|
|
21
|
+
this.destroyed = true;
|
|
22
|
+
this.db._rollbackRaw(this.id).catch(() => { });
|
|
23
|
+
}, options.timeout);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
getId() {
|
|
27
|
+
return this.id;
|
|
28
|
+
}
|
|
29
|
+
isActive() {
|
|
30
|
+
if (this.destroyed)
|
|
31
|
+
return false;
|
|
32
|
+
return this.db.getActiveTransactions().includes(this.id);
|
|
33
|
+
}
|
|
34
|
+
isRolledBack() {
|
|
35
|
+
return !this.isActive();
|
|
36
|
+
}
|
|
37
|
+
_checkActive() {
|
|
38
|
+
if (this.destroyed)
|
|
39
|
+
throw new Error('Transaction has been destroyed');
|
|
40
|
+
const status = this.db._getTxStatus(this.id);
|
|
41
|
+
if (status === 'committed')
|
|
42
|
+
throw new Error('Transaction has already been committed');
|
|
43
|
+
if (status === 'aborted')
|
|
44
|
+
throw new Error('Transaction has been rolled back');
|
|
45
|
+
if (status === 'not_found')
|
|
46
|
+
throw new Error('Transaction is not active');
|
|
47
|
+
}
|
|
48
|
+
async create(key, initialData) {
|
|
49
|
+
this._checkActive();
|
|
50
|
+
if (this.db.exists(key))
|
|
51
|
+
throw new Error(`Document '${key}' already exists`);
|
|
52
|
+
await this.db._writeRaw(this.id, key, initialData || {});
|
|
53
|
+
this.opCount++;
|
|
54
|
+
}
|
|
55
|
+
async update(key, data) {
|
|
56
|
+
this._checkActive();
|
|
57
|
+
await this.db._writeRaw(this.id, key, data);
|
|
58
|
+
this.opCount++;
|
|
59
|
+
}
|
|
60
|
+
async delete(key) {
|
|
61
|
+
this._checkActive();
|
|
62
|
+
await this.db._deleteRaw(this.id, key);
|
|
63
|
+
this.opCount++;
|
|
64
|
+
}
|
|
65
|
+
async get(key) {
|
|
66
|
+
this._checkActive();
|
|
67
|
+
return await this.db._readRaw(this.id, key);
|
|
68
|
+
}
|
|
69
|
+
getState() {
|
|
70
|
+
const status = this.db._getTxStatus(this.id);
|
|
71
|
+
return {
|
|
72
|
+
status: status === 'active' ? 'active' : (status === 'committed' ? 'committed' : 'rolled_back'),
|
|
73
|
+
operations: Array.from({ length: this.opCount }, (_, i) => ({ key: `op_${i}`, operation: 'write' })),
|
|
74
|
+
startTime: this.startTime
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
getOperationCount() {
|
|
78
|
+
return this.opCount;
|
|
79
|
+
}
|
|
80
|
+
getDuration() {
|
|
81
|
+
return Date.now() - this.startTime;
|
|
82
|
+
}
|
|
83
|
+
destroy() {
|
|
84
|
+
this.destroyed = true;
|
|
85
|
+
if (this.timeoutTimer)
|
|
86
|
+
clearTimeout(this.timeoutTimer);
|
|
87
|
+
this.db._rollbackRaw(this.id).catch(() => { });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
8
90
|
export class Tero {
|
|
9
91
|
teroDirectory = "TeroDB";
|
|
10
92
|
cacheSize = 100;
|
|
@@ -15,12 +97,15 @@ export class Tero {
|
|
|
15
97
|
schemaValidator;
|
|
16
98
|
backupManager;
|
|
17
99
|
dataRecovery;
|
|
100
|
+
committedCount = 0;
|
|
101
|
+
rolledBackCount = 0;
|
|
18
102
|
constructor(config) {
|
|
19
103
|
try {
|
|
20
|
-
const
|
|
21
|
-
|
|
104
|
+
const rawDirectory = config?.Directory || config?.directory;
|
|
105
|
+
const { cacheSize } = config || {};
|
|
106
|
+
if (typeof rawDirectory === "string" && rawDirectory.trim()) {
|
|
22
107
|
// Sanitize directory path to prevent directory traversal
|
|
23
|
-
this.teroDirectory =
|
|
108
|
+
this.teroDirectory = rawDirectory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
|
|
24
109
|
}
|
|
25
110
|
if (typeof cacheSize === "number" && cacheSize > 0) {
|
|
26
111
|
this.cacheSize = Math.min(cacheSize, 1000); // Cap at 1k entries
|
|
@@ -76,16 +161,24 @@ export class Tero {
|
|
|
76
161
|
});
|
|
77
162
|
}
|
|
78
163
|
// Core ACID Operations
|
|
79
|
-
beginTransaction() {
|
|
164
|
+
beginTransaction(options) {
|
|
80
165
|
try {
|
|
81
|
-
|
|
166
|
+
const id = this._beginTransaction();
|
|
167
|
+
return new Transaction(id, this, options);
|
|
82
168
|
}
|
|
83
169
|
catch (error) {
|
|
84
170
|
throw new Error(`Failed to begin transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
85
171
|
}
|
|
86
172
|
}
|
|
173
|
+
_beginTransaction() {
|
|
174
|
+
return this.acidEngine.beginTransaction();
|
|
175
|
+
}
|
|
176
|
+
_txId(id) {
|
|
177
|
+
return typeof id === 'string' ? id : id.getId();
|
|
178
|
+
}
|
|
87
179
|
async write(transactionId, key, data, options) {
|
|
88
180
|
try {
|
|
181
|
+
const txId = this._txId(transactionId);
|
|
89
182
|
this.validateKey(key);
|
|
90
183
|
if (data === undefined || data === null) {
|
|
91
184
|
throw new Error('Data cannot be null or undefined');
|
|
@@ -106,9 +199,9 @@ export class Tero {
|
|
|
106
199
|
// Use sanitized data from validation
|
|
107
200
|
data = validationResult.data || data;
|
|
108
201
|
}
|
|
109
|
-
await this.acidEngine.write(
|
|
202
|
+
await this.acidEngine.write(txId, key, data);
|
|
110
203
|
// Update cache with transaction context
|
|
111
|
-
this.updateCache(key, data,
|
|
204
|
+
this.updateCache(key, data, txId);
|
|
112
205
|
if (options?.validate || options?.schemaName) {
|
|
113
206
|
return { valid: true, errors: [], data };
|
|
114
207
|
}
|
|
@@ -119,19 +212,20 @@ export class Tero {
|
|
|
119
212
|
}
|
|
120
213
|
async read(transactionId, key) {
|
|
121
214
|
try {
|
|
215
|
+
const txId = this._txId(transactionId);
|
|
122
216
|
this.validateKey(key);
|
|
123
217
|
this.cacheRequests++;
|
|
124
218
|
// Check cache first, but only if it's from the same transaction or committed
|
|
125
219
|
const cachedEntry = this.cache.get(key);
|
|
126
|
-
if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId ===
|
|
220
|
+
if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) {
|
|
127
221
|
this.cacheHits++;
|
|
128
222
|
cachedEntry.lastAccessed = Date.now();
|
|
129
223
|
return cachedEntry.data;
|
|
130
224
|
}
|
|
131
225
|
// Read from ACID engine
|
|
132
|
-
const data = await this.acidEngine.read(
|
|
226
|
+
const data = await this.acidEngine.read(txId, key);
|
|
133
227
|
if (data !== null) {
|
|
134
|
-
this.updateCache(key, data,
|
|
228
|
+
this.updateCache(key, data, txId);
|
|
135
229
|
}
|
|
136
230
|
return data;
|
|
137
231
|
}
|
|
@@ -139,33 +233,24 @@ export class Tero {
|
|
|
139
233
|
throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
140
234
|
}
|
|
141
235
|
}
|
|
142
|
-
async delete(transactionId, key) {
|
|
143
|
-
try {
|
|
144
|
-
this.validateKey(key);
|
|
145
|
-
await this.acidEngine.delete(transactionId, key);
|
|
146
|
-
// Remove from cache
|
|
147
|
-
this.cache.delete(key);
|
|
148
|
-
}
|
|
149
|
-
catch (error) {
|
|
150
|
-
throw new Error(`Delete failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
236
|
async commit(transactionId) {
|
|
154
237
|
try {
|
|
238
|
+
const txId = this._txId(transactionId);
|
|
155
239
|
// Get affected keys before commit
|
|
156
|
-
const transaction = this.acidEngine.getActiveTransactions().includes(
|
|
240
|
+
const transaction = this.acidEngine.getActiveTransactions().includes(txId);
|
|
157
241
|
if (!transaction) {
|
|
158
|
-
throw new Error(`Transaction ${
|
|
242
|
+
throw new Error(`Transaction ${txId} not found or not active`);
|
|
159
243
|
}
|
|
160
|
-
await this.acidEngine.commitTransaction(
|
|
244
|
+
await this.acidEngine.commitTransaction(txId);
|
|
161
245
|
// Invalidate cache entries for this transaction to force fresh reads
|
|
162
246
|
const keysToInvalidate = [];
|
|
163
247
|
for (const [key, entry] of this.cache.entries()) {
|
|
164
|
-
if (entry.transactionId ===
|
|
248
|
+
if (entry.transactionId === txId) {
|
|
165
249
|
keysToInvalidate.push(key);
|
|
166
250
|
}
|
|
167
251
|
}
|
|
168
252
|
this.invalidateCacheKeys(keysToInvalidate);
|
|
253
|
+
this.committedCount++;
|
|
169
254
|
}
|
|
170
255
|
catch (error) {
|
|
171
256
|
throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
@@ -173,23 +258,38 @@ export class Tero {
|
|
|
173
258
|
}
|
|
174
259
|
async rollback(transactionId) {
|
|
175
260
|
try {
|
|
176
|
-
|
|
261
|
+
const txId = this._txId(transactionId);
|
|
262
|
+
await this.acidEngine.rollbackTransaction(txId);
|
|
177
263
|
// Remove cache entries for this transaction
|
|
178
264
|
const keysToRemove = [];
|
|
179
265
|
for (const [key, entry] of this.cache.entries()) {
|
|
180
|
-
if (entry.transactionId ===
|
|
266
|
+
if (entry.transactionId === txId) {
|
|
181
267
|
keysToRemove.push(key);
|
|
182
268
|
}
|
|
183
269
|
}
|
|
184
270
|
this.invalidateCacheKeys(keysToRemove);
|
|
271
|
+
this.rolledBackCount++;
|
|
185
272
|
}
|
|
186
273
|
catch (error) {
|
|
187
274
|
throw new Error(`Failed to rollback transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
188
275
|
}
|
|
189
276
|
}
|
|
277
|
+
async commitTransaction(transactionId) {
|
|
278
|
+
return await this.commit(transactionId);
|
|
279
|
+
}
|
|
280
|
+
async rollbackTransaction(transactionId) {
|
|
281
|
+
return await this.rollback(transactionId);
|
|
282
|
+
}
|
|
283
|
+
getPerformanceStats() {
|
|
284
|
+
const cacheStats = this.getCacheStats();
|
|
285
|
+
return {
|
|
286
|
+
cacheStats: { hitRate: cacheStats.hitRate },
|
|
287
|
+
totalRequests: this.cacheRequests
|
|
288
|
+
};
|
|
289
|
+
}
|
|
190
290
|
// Convenience Methods (Auto-transaction)
|
|
191
291
|
async create(key, initialData, options) {
|
|
192
|
-
const transactionId = this.
|
|
292
|
+
const transactionId = this._beginTransaction();
|
|
193
293
|
try {
|
|
194
294
|
// Check if file already exists
|
|
195
295
|
const existing = await this.read(transactionId, key);
|
|
@@ -208,7 +308,7 @@ export class Tero {
|
|
|
208
308
|
}
|
|
209
309
|
}
|
|
210
310
|
async update(key, data, options) {
|
|
211
|
-
const transactionId = this.
|
|
311
|
+
const transactionId = this._beginTransaction();
|
|
212
312
|
try {
|
|
213
313
|
const result = await this.write(transactionId, key, data, options);
|
|
214
314
|
await this.commit(transactionId);
|
|
@@ -220,11 +320,11 @@ export class Tero {
|
|
|
220
320
|
}
|
|
221
321
|
}
|
|
222
322
|
async get(key) {
|
|
223
|
-
const transactionId = this.
|
|
323
|
+
const transactionId = this._beginTransaction();
|
|
224
324
|
try {
|
|
225
325
|
const data = await this.read(transactionId, key);
|
|
226
326
|
await this.commit(transactionId);
|
|
227
|
-
return data;
|
|
327
|
+
return data === null ? false : data;
|
|
228
328
|
}
|
|
229
329
|
catch (error) {
|
|
230
330
|
await this.rollback(transactionId);
|
|
@@ -232,9 +332,9 @@ export class Tero {
|
|
|
232
332
|
}
|
|
233
333
|
}
|
|
234
334
|
async remove(key) {
|
|
235
|
-
const transactionId = this.
|
|
335
|
+
const transactionId = this._beginTransaction();
|
|
236
336
|
try {
|
|
237
|
-
await this.
|
|
337
|
+
await this._deleteRaw(transactionId, key);
|
|
238
338
|
await this.commit(transactionId);
|
|
239
339
|
}
|
|
240
340
|
catch (error) {
|
|
@@ -242,6 +342,9 @@ export class Tero {
|
|
|
242
342
|
throw error;
|
|
243
343
|
}
|
|
244
344
|
}
|
|
345
|
+
async delete(key) {
|
|
346
|
+
return await this.remove(key);
|
|
347
|
+
}
|
|
245
348
|
exists(key) {
|
|
246
349
|
try {
|
|
247
350
|
this.validateKey(key);
|
|
@@ -253,7 +356,7 @@ export class Tero {
|
|
|
253
356
|
}
|
|
254
357
|
// Batch Operations
|
|
255
358
|
async batchWrite(operations, options) {
|
|
256
|
-
const transactionId = this.
|
|
359
|
+
const transactionId = this._beginTransaction();
|
|
257
360
|
try {
|
|
258
361
|
for (const op of operations) {
|
|
259
362
|
await this.write(transactionId, op.key, op.data, options);
|
|
@@ -266,7 +369,7 @@ export class Tero {
|
|
|
266
369
|
}
|
|
267
370
|
}
|
|
268
371
|
async batchRead(keys) {
|
|
269
|
-
const transactionId = this.
|
|
372
|
+
const transactionId = this._beginTransaction();
|
|
270
373
|
const results = {};
|
|
271
374
|
try {
|
|
272
375
|
for (const key of keys) {
|
|
@@ -285,7 +388,7 @@ export class Tero {
|
|
|
285
388
|
if (amount <= 0) {
|
|
286
389
|
throw new Error('Transfer amount must be positive');
|
|
287
390
|
}
|
|
288
|
-
const transactionId = this.
|
|
391
|
+
const transactionId = this._beginTransaction();
|
|
289
392
|
try {
|
|
290
393
|
// Read current balances
|
|
291
394
|
const fromAccount = await this.read(transactionId, fromKey);
|
|
@@ -313,6 +416,45 @@ export class Tero {
|
|
|
313
416
|
throw new Error(`Money transfer failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
314
417
|
}
|
|
315
418
|
}
|
|
419
|
+
// Internal raw methods for Transaction class
|
|
420
|
+
async _writeRaw(transactionId, key, data) {
|
|
421
|
+
await this.acidEngine.write(transactionId, key, data);
|
|
422
|
+
this.updateCache(key, data, transactionId);
|
|
423
|
+
}
|
|
424
|
+
async _readRaw(transactionId, key) {
|
|
425
|
+
this.cacheRequests++;
|
|
426
|
+
const cachedEntry = this.cache.get(key);
|
|
427
|
+
if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) {
|
|
428
|
+
this.cacheHits++;
|
|
429
|
+
cachedEntry.lastAccessed = Date.now();
|
|
430
|
+
return cachedEntry.data;
|
|
431
|
+
}
|
|
432
|
+
const data = await this.acidEngine.read(transactionId, key);
|
|
433
|
+
if (data !== null) {
|
|
434
|
+
this.updateCache(key, data, transactionId);
|
|
435
|
+
}
|
|
436
|
+
return data;
|
|
437
|
+
}
|
|
438
|
+
async _deleteRaw(transactionId, key) {
|
|
439
|
+
await this.acidEngine.delete(transactionId, key);
|
|
440
|
+
this.cache.delete(key);
|
|
441
|
+
}
|
|
442
|
+
async _rollbackRaw(transactionId) {
|
|
443
|
+
await this.acidEngine.rollbackTransaction(transactionId);
|
|
444
|
+
this.rolledBackCount++;
|
|
445
|
+
}
|
|
446
|
+
_getTxStatus(transactionId) {
|
|
447
|
+
return this.acidEngine.getTransactionStatus(transactionId);
|
|
448
|
+
}
|
|
449
|
+
getTransactionStats() {
|
|
450
|
+
const active = this.acidEngine.getActiveTransactions().length;
|
|
451
|
+
return {
|
|
452
|
+
active,
|
|
453
|
+
committed: this.committedCount,
|
|
454
|
+
rolledBack: this.rolledBackCount,
|
|
455
|
+
total: active + this.committedCount + this.rolledBackCount
|
|
456
|
+
};
|
|
457
|
+
}
|
|
316
458
|
// Schema Management
|
|
317
459
|
setSchema(collectionName, schema) {
|
|
318
460
|
try {
|
|
@@ -331,6 +473,32 @@ export class Tero {
|
|
|
331
473
|
validateData(collectionName, data) {
|
|
332
474
|
return this.schemaValidator.validate(collectionName, data);
|
|
333
475
|
}
|
|
476
|
+
hasSchema(collectionName) {
|
|
477
|
+
return this.schemaValidator.hasSchema(collectionName);
|
|
478
|
+
}
|
|
479
|
+
listSchemas() {
|
|
480
|
+
return this.schemaValidator.listSchemas();
|
|
481
|
+
}
|
|
482
|
+
exportSchemas() {
|
|
483
|
+
return this.schemaValidator.exportSchemas();
|
|
484
|
+
}
|
|
485
|
+
getSchemaStats() {
|
|
486
|
+
return this.schemaValidator.getSchemaStats();
|
|
487
|
+
}
|
|
488
|
+
async createWithValidation(key, initialData, options) {
|
|
489
|
+
const result = await this.create(key, initialData, { ...options, validate: true });
|
|
490
|
+
if (result === true || result === false) {
|
|
491
|
+
return { valid: result, errors: [], data: initialData || {} };
|
|
492
|
+
}
|
|
493
|
+
return result;
|
|
494
|
+
}
|
|
495
|
+
async updateWithValidation(key, data, options) {
|
|
496
|
+
const result = await this.update(key, data, { ...options, validate: true });
|
|
497
|
+
if (!result) {
|
|
498
|
+
return { valid: true, errors: [], data };
|
|
499
|
+
}
|
|
500
|
+
return result;
|
|
501
|
+
}
|
|
334
502
|
// Backup Management
|
|
335
503
|
configureBackup(config) {
|
|
336
504
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tero",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.6",
|
|
4
4
|
"description": "Tero is a JSON database that provides ACID transactions, schema validation, automated cloud backup, and automatic cloud recovery",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
},
|
|
16
16
|
"homepage": "https://github.com/codedynasty-dev/tero.git",
|
|
17
17
|
"scripts": {
|
|
18
|
-
"build": "npm run test
|
|
18
|
+
"build": "tsc && npm run test",
|
|
19
19
|
"dev": "tsc --watch",
|
|
20
20
|
"test": "node run-tests.js",
|
|
21
21
|
"test:production": "node local_tests/production-test.js",
|