tero 0.0.1 → 0.0.3
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/README.md +30 -2
- package/dist/acid-engine.d.ts +1 -0
- package/dist/acid-engine.js +76 -10
- package/dist/backup.d.ts +2 -0
- package/dist/backup.js +75 -22
- package/dist/index.d.ts +28 -1
- package/dist/index.js +55 -24
- package/package.json +14 -11
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
**JSON document database**
|
|
11
11
|
|
|
12
|
-
Tero is a JSON database that provides ACID transactions, schema validation, cloud backup, and automatic recovery.
|
|
12
|
+
Tero is a JSON database that provides ACID transactions, schema validation, automated cloud backup, and automatic cloud recovery.
|
|
13
13
|
|
|
14
14
|
## Key Features
|
|
15
15
|
|
|
@@ -175,14 +175,41 @@ await db.recoverFromCloud('important-data');
|
|
|
175
175
|
const result = await db.recoverAllFromCloud();
|
|
176
176
|
```
|
|
177
177
|
|
|
178
|
+
## Unique ID Generation
|
|
179
|
+
|
|
180
|
+
Generate MongoDB ObjectId-like unique identifiers:
|
|
181
|
+
|
|
182
|
+
```javascript
|
|
183
|
+
// Generate unique IDs for different purposes
|
|
184
|
+
const userId = db.getNewId('user'); // e.g., "user-507f1f77bcf86cd799439011"
|
|
185
|
+
const sessionId = db.getNewId('session'); // e.g., "session-507f1f77bcf86cd799439012"
|
|
186
|
+
const orderId = db.getNewId('order'); // e.g., "order-507f1f77bcf86cd799439013"
|
|
187
|
+
|
|
188
|
+
// Use as document keys
|
|
189
|
+
await db.create(userId, {
|
|
190
|
+
name: 'Alice',
|
|
191
|
+
email: 'alice@example.com',
|
|
192
|
+
createdAt: new Date()
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// IDs are guaranteed unique across processes and time
|
|
196
|
+
const logId = db.getNewId('log');
|
|
197
|
+
await db.create(logId, {
|
|
198
|
+
level: 'info',
|
|
199
|
+
message: 'User created',
|
|
200
|
+
userId: userId
|
|
201
|
+
});
|
|
202
|
+
```
|
|
203
|
+
|
|
178
204
|
## Monitoring
|
|
179
205
|
|
|
180
206
|
Built-in performance monitoring and health checks:
|
|
181
207
|
|
|
182
208
|
```javascript
|
|
183
|
-
// Cache performance
|
|
209
|
+
// Cache performance (now using optimized QuickLRU)
|
|
184
210
|
const cacheStats = db.getCacheStats();
|
|
185
211
|
console.log(`Cache hit rate: ${cacheStats.hitRate}%`);
|
|
212
|
+
console.log(`Cache size: ${cacheStats.size}/${cacheStats.maxSize}`);
|
|
186
213
|
|
|
187
214
|
// Data integrity check
|
|
188
215
|
const integrity = await db.verifyDataIntegrity();
|
|
@@ -286,6 +313,7 @@ const db = new Tero({
|
|
|
286
313
|
- `getActiveTransactions()`: List active transactions
|
|
287
314
|
- `forceCheckpoint()`: Force WAL flush
|
|
288
315
|
- `clearCache()`: Clear memory cache
|
|
316
|
+
- `getNewId(prefix)`: Generate unique identifiers with custom prefix
|
|
289
317
|
- `destroy()`: Cleanup and shutdown
|
|
290
318
|
|
|
291
319
|
## Testing
|
package/dist/acid-engine.d.ts
CHANGED
package/dist/acid-engine.js
CHANGED
|
@@ -158,6 +158,52 @@ export class WriteAheadLog {
|
|
|
158
158
|
getCurrentLSN() {
|
|
159
159
|
return this.currentLSN - 1;
|
|
160
160
|
}
|
|
161
|
+
clearCommittedTransaction(transactionId) {
|
|
162
|
+
try {
|
|
163
|
+
// First, flush any pending buffer entries to disk
|
|
164
|
+
this.flushBuffer();
|
|
165
|
+
if (!existsSync(this.logPath)) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
// Read current log content
|
|
169
|
+
const logContent = readFileSync(this.logPath, 'utf-8');
|
|
170
|
+
const lines = logContent.trim().split('\n').filter(line => line.trim());
|
|
171
|
+
// Filter out entries for the committed transaction
|
|
172
|
+
const filteredLines = [];
|
|
173
|
+
let transactionCompleted = false;
|
|
174
|
+
for (const line of lines) {
|
|
175
|
+
try {
|
|
176
|
+
const entry = JSON.parse(line);
|
|
177
|
+
// Keep entries that don't belong to this transaction
|
|
178
|
+
if (entry.transactionId !== transactionId) {
|
|
179
|
+
filteredLines.push(line);
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
// For the committed transaction, only keep the COMMIT entry as a marker
|
|
183
|
+
// This preserves the fact that the transaction was committed for recovery purposes
|
|
184
|
+
if (entry.operation === 'COMMIT') {
|
|
185
|
+
filteredLines.push(line);
|
|
186
|
+
transactionCompleted = true;
|
|
187
|
+
}
|
|
188
|
+
// Skip BEGIN, WRITE, DELETE entries for committed transactions
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
// Keep corrupted entries as-is to avoid data loss
|
|
193
|
+
filteredLines.push(line);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// Only rewrite the log if we actually found and processed the transaction
|
|
197
|
+
if (transactionCompleted) {
|
|
198
|
+
const newContent = filteredLines.length > 0 ? filteredLines.join('\n') + '\n' : '';
|
|
199
|
+
writeFileSync(this.logPath, newContent);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
// Silent failure for production - WAL cleanup is an optimization, not critical
|
|
204
|
+
// The system will still work correctly even if cleanup fails
|
|
205
|
+
}
|
|
206
|
+
}
|
|
161
207
|
}
|
|
162
208
|
// Lock Manager for proper concurrency control
|
|
163
209
|
export class LockManager {
|
|
@@ -418,20 +464,38 @@ export class ACIDStorageEngine {
|
|
|
418
464
|
// Acquire exclusive lock
|
|
419
465
|
await this.lockManager.acquireLock(key, transactionId, 'exclusive');
|
|
420
466
|
try {
|
|
421
|
-
// Read current data for before image
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
467
|
+
// Read current data for before image - check pending writes in this transaction first
|
|
468
|
+
let currentData = null;
|
|
469
|
+
const logEntries = this.wal.getLogEntries(transaction.startLSN);
|
|
470
|
+
const transactionEntries = logEntries.filter(entry => entry.transactionId === transactionId &&
|
|
471
|
+
entry.key === key &&
|
|
472
|
+
(entry.operation === 'WRITE' || entry.operation === 'DELETE'));
|
|
473
|
+
if (transactionEntries.length > 0) {
|
|
474
|
+
// Use the most recent transaction state
|
|
475
|
+
const lastEntry = transactionEntries[transactionEntries.length - 1];
|
|
476
|
+
if (lastEntry.operation === 'DELETE') {
|
|
477
|
+
currentData = null;
|
|
428
478
|
}
|
|
429
|
-
|
|
430
|
-
|
|
479
|
+
else {
|
|
480
|
+
currentData = lastEntry.afterImage || {};
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
else {
|
|
484
|
+
// Read from disk
|
|
485
|
+
const filePath = join(this.dbPath, `${key}.json`);
|
|
486
|
+
if (existsSync(filePath)) {
|
|
487
|
+
try {
|
|
488
|
+
const content = readFileSync(filePath, 'utf-8');
|
|
489
|
+
currentData = content.trim() ? JSON.parse(content) : {};
|
|
490
|
+
}
|
|
491
|
+
catch (error) {
|
|
492
|
+
currentData = {};
|
|
493
|
+
}
|
|
431
494
|
}
|
|
432
495
|
}
|
|
496
|
+
const beforeImage = currentData;
|
|
433
497
|
// Deep merge for proper data integrity
|
|
434
|
-
const afterImage = this.deepMerge(
|
|
498
|
+
const afterImage = this.deepMerge(currentData || {}, data);
|
|
435
499
|
// Write to WAL first (Write-Ahead Logging)
|
|
436
500
|
this.wal.writeLog({
|
|
437
501
|
operation: 'WRITE',
|
|
@@ -551,6 +615,8 @@ export class ACIDStorageEngine {
|
|
|
551
615
|
}
|
|
552
616
|
// Update transaction status
|
|
553
617
|
transaction.status = 'committed';
|
|
618
|
+
// Clear WAL entries for this committed transaction
|
|
619
|
+
this.wal.clearCommittedTransaction(transactionId);
|
|
554
620
|
// Release all locks
|
|
555
621
|
this.lockManager.releaseAllLocks(transactionId);
|
|
556
622
|
}
|
package/dist/backup.d.ts
CHANGED
|
@@ -34,12 +34,14 @@ export declare class BackupManager {
|
|
|
34
34
|
private initializeCloudStorage;
|
|
35
35
|
private parseInterval;
|
|
36
36
|
private parseRetention;
|
|
37
|
+
private intervalToCron;
|
|
37
38
|
private calculateChecksum;
|
|
38
39
|
private getJsonFiles;
|
|
39
40
|
private createArchiveBackup;
|
|
40
41
|
private createIndividualBackup;
|
|
41
42
|
private uploadToCloud;
|
|
42
43
|
private uploadDirectoryToCloud;
|
|
44
|
+
private uploadIndividualFilesToCloud;
|
|
43
45
|
private getCloudKey;
|
|
44
46
|
performBackup(): Promise<{
|
|
45
47
|
success: boolean;
|
package/dist/backup.js
CHANGED
|
@@ -3,6 +3,7 @@ import { join, basename } from "path";
|
|
|
3
3
|
import tar from "tar";
|
|
4
4
|
import { S3Client, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
|
|
5
5
|
import { Upload } from "@aws-sdk/lib-storage";
|
|
6
|
+
import { CronJob } from "cron";
|
|
6
7
|
export class BackupManager {
|
|
7
8
|
s3Client;
|
|
8
9
|
scheduledBackups = new Map();
|
|
@@ -61,6 +62,39 @@ export class BackupManager {
|
|
|
61
62
|
default: throw new Error(`Unsupported retention unit: ${unit}`);
|
|
62
63
|
}
|
|
63
64
|
}
|
|
65
|
+
intervalToCron(interval) {
|
|
66
|
+
const match = interval.match(/^(\d+)([hdw])$/);
|
|
67
|
+
if (!match)
|
|
68
|
+
throw new Error(`Invalid interval format: ${interval}`);
|
|
69
|
+
const [, num, unit] = match;
|
|
70
|
+
const value = parseInt(num);
|
|
71
|
+
switch (unit) {
|
|
72
|
+
case 'h': // Every N hours
|
|
73
|
+
if (value === 1)
|
|
74
|
+
return '0 * * * *'; // Every hour
|
|
75
|
+
if (value === 6)
|
|
76
|
+
return '0 */6 * * *'; // Every 6 hours
|
|
77
|
+
if (value === 12)
|
|
78
|
+
return '0 */12 * * *'; // Every 12 hours
|
|
79
|
+
if (24 % value === 0)
|
|
80
|
+
return `0 */${value} * * *`; // Every N hours if divisible
|
|
81
|
+
throw new Error(`Unsupported hour interval: ${value}h`);
|
|
82
|
+
case 'd': // Every N days
|
|
83
|
+
if (value === 1)
|
|
84
|
+
return '0 0 * * *'; // Daily at midnight
|
|
85
|
+
if (value === 7)
|
|
86
|
+
return '0 0 * * 0'; // Weekly on Sunday
|
|
87
|
+
return `0 0 */${value} * *`; // Every N days
|
|
88
|
+
case 'w': // Every N weeks
|
|
89
|
+
if (value === 1)
|
|
90
|
+
return '0 0 * * 0'; // Weekly on Sunday
|
|
91
|
+
if (value === 2)
|
|
92
|
+
return '0 0 * * 0/2'; // Bi-weekly
|
|
93
|
+
throw new Error(`Unsupported week interval: ${value}w`);
|
|
94
|
+
default:
|
|
95
|
+
throw new Error(`Unsupported time unit: ${unit}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
64
98
|
async calculateChecksum(filePath) {
|
|
65
99
|
const crypto = await import('crypto');
|
|
66
100
|
const hash = crypto.createHash('sha256');
|
|
@@ -134,10 +168,8 @@ export class BackupManager {
|
|
|
134
168
|
}
|
|
135
169
|
}
|
|
136
170
|
async createIndividualBackup() {
|
|
137
|
-
|
|
138
|
-
const backupDir = this.config.localPath
|
|
139
|
-
? join(this.config.localPath, `tero-backup-${timestamp}`)
|
|
140
|
-
: join(this.dbPath, `.backup-${timestamp}`);
|
|
171
|
+
// Use key-based backup instead of timestamp-based directories
|
|
172
|
+
const backupDir = this.config.localPath || join(this.dbPath, '.backup');
|
|
141
173
|
try {
|
|
142
174
|
const jsonFiles = await this.getJsonFiles();
|
|
143
175
|
if (jsonFiles.length === 0) {
|
|
@@ -148,7 +180,7 @@ export class BackupManager {
|
|
|
148
180
|
await fs.mkdir(backupDir, { recursive: true });
|
|
149
181
|
const backedUpFiles = [];
|
|
150
182
|
let totalSize = 0;
|
|
151
|
-
// Copy each JSON file
|
|
183
|
+
// Copy each JSON file using its key as the filename (no timestamp directories)
|
|
152
184
|
for (const file of jsonFiles) {
|
|
153
185
|
const destPath = join(backupDir, file.name);
|
|
154
186
|
await fs.copyFile(file.path, destPath);
|
|
@@ -250,6 +282,27 @@ export class BackupManager {
|
|
|
250
282
|
throw new Error(`Failed to upload directory to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
251
283
|
}
|
|
252
284
|
}
|
|
285
|
+
async uploadIndividualFilesToCloud(localDir) {
|
|
286
|
+
if (!this.s3Client || !this.config.cloudStorage) {
|
|
287
|
+
throw new Error('Cloud storage not configured');
|
|
288
|
+
}
|
|
289
|
+
try {
|
|
290
|
+
const fs = await import('fs/promises');
|
|
291
|
+
const files = await fs.readdir(localDir);
|
|
292
|
+
const uploadPromises = files
|
|
293
|
+
.filter(file => file.endsWith('.json')) // Only upload JSON files, skip metadata
|
|
294
|
+
.map(async (file) => {
|
|
295
|
+
const localFilePath = join(localDir, file);
|
|
296
|
+
// Use direct key-based cloud storage: each JSON file is stored with its key as the cloud key
|
|
297
|
+
const cloudKey = this.getCloudKey(file);
|
|
298
|
+
await this.uploadToCloud(localFilePath, cloudKey);
|
|
299
|
+
});
|
|
300
|
+
await Promise.all(uploadPromises);
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
throw new Error(`Failed to upload individual files to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
253
306
|
getCloudKey(filename) {
|
|
254
307
|
const prefix = this.config.cloudStorage?.pathPrefix || 'tero-backups';
|
|
255
308
|
const dbName = basename(this.dbPath);
|
|
@@ -275,13 +328,11 @@ export class BackupManager {
|
|
|
275
328
|
else {
|
|
276
329
|
const { files, metadata: backupMetadata } = await this.createIndividualBackup();
|
|
277
330
|
metadata = backupMetadata;
|
|
278
|
-
// Upload to cloud if configured
|
|
331
|
+
// Upload to cloud if configured - use key-based storage for direct recovery
|
|
279
332
|
if (this.config.cloudStorage && this.s3Client) {
|
|
280
|
-
|
|
281
|
-
const cloudPrefix = this.getCloudKey(`individual-${timestamp}`);
|
|
282
|
-
await this.uploadDirectoryToCloud(files[0].split('/').slice(0, -1).join('/'), cloudPrefix);
|
|
333
|
+
await this.uploadIndividualFilesToCloud(files[0].split('/').slice(0, -1).join('/'));
|
|
283
334
|
cloudUploaded = true;
|
|
284
|
-
console.log(`☁️ Uploaded individual backup to cloud
|
|
335
|
+
console.log(`☁️ Uploaded individual backup to cloud using key-based storage`);
|
|
285
336
|
}
|
|
286
337
|
console.log(`✅ Individual backup completed: ${files.length} files`);
|
|
287
338
|
}
|
|
@@ -343,7 +394,8 @@ export class BackupManager {
|
|
|
343
394
|
scheduleBackup(config) {
|
|
344
395
|
const scheduleId = `backup-${Date.now()}`;
|
|
345
396
|
try {
|
|
346
|
-
|
|
397
|
+
// Convert interval to cron expression
|
|
398
|
+
const cronExpression = this.intervalToCron(config.interval);
|
|
347
399
|
// Update config with new retention if provided
|
|
348
400
|
if (config.retention) {
|
|
349
401
|
this.config.retention = config.retention;
|
|
@@ -352,12 +404,13 @@ export class BackupManager {
|
|
|
352
404
|
console.log(`⏰ Scheduled backup triggered (${config.interval} interval)`);
|
|
353
405
|
await this.performBackup();
|
|
354
406
|
};
|
|
355
|
-
//
|
|
356
|
-
performScheduledBackup
|
|
357
|
-
//
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
407
|
+
// Create cron job for recurring backups
|
|
408
|
+
const cronJob = new CronJob(cronExpression, performScheduledBackup, null, // onComplete
|
|
409
|
+
true, // start immediately
|
|
410
|
+
'UTC' // timezone
|
|
411
|
+
);
|
|
412
|
+
this.scheduledBackups.set(scheduleId, cronJob);
|
|
413
|
+
console.log(`📅 Backup scheduled with cron: ${cronExpression} (${config.interval} interval), ${config.retention || this.config.retention} retention`);
|
|
361
414
|
return scheduleId;
|
|
362
415
|
}
|
|
363
416
|
catch (error) {
|
|
@@ -365,9 +418,9 @@ export class BackupManager {
|
|
|
365
418
|
}
|
|
366
419
|
}
|
|
367
420
|
cancelScheduledBackup(scheduleId) {
|
|
368
|
-
const
|
|
369
|
-
if (
|
|
370
|
-
|
|
421
|
+
const cronJob = this.scheduledBackups.get(scheduleId);
|
|
422
|
+
if (cronJob) {
|
|
423
|
+
cronJob.stop();
|
|
371
424
|
this.scheduledBackups.delete(scheduleId);
|
|
372
425
|
console.log(`❌ Cancelled scheduled backup: ${scheduleId}`);
|
|
373
426
|
return true;
|
|
@@ -402,8 +455,8 @@ export class BackupManager {
|
|
|
402
455
|
}
|
|
403
456
|
destroy() {
|
|
404
457
|
// Cancel all scheduled backups
|
|
405
|
-
for (const [id,
|
|
406
|
-
|
|
458
|
+
for (const [id, cronJob] of this.scheduledBackups) {
|
|
459
|
+
cronJob.stop();
|
|
407
460
|
}
|
|
408
461
|
this.scheduledBackups.clear();
|
|
409
462
|
console.log('🛑 BackupManager destroyed, all scheduled backups cancelled');
|
package/dist/index.d.ts
CHANGED
|
@@ -18,7 +18,6 @@ export declare class Tero {
|
|
|
18
18
|
constructor(config?: TeroConfig);
|
|
19
19
|
private initializeDirectories;
|
|
20
20
|
private validateKey;
|
|
21
|
-
private evictOldestCacheEntry;
|
|
22
21
|
private invalidateCacheKeys;
|
|
23
22
|
private updateCache;
|
|
24
23
|
beginTransaction(): string;
|
|
@@ -84,5 +83,33 @@ export declare class Tero {
|
|
|
84
83
|
}>;
|
|
85
84
|
clearCache(): void;
|
|
86
85
|
destroy(): void;
|
|
86
|
+
/**
|
|
87
|
+
* Generates a unique identifier with a custom prefix.
|
|
88
|
+
*
|
|
89
|
+
* This method creates MongoDB ObjectId-like unique identifiers that consist of:
|
|
90
|
+
* - 4-byte timestamp (seconds since Unix epoch)
|
|
91
|
+
* - 5-byte process-unique random value
|
|
92
|
+
* - 3-byte incrementing counter
|
|
93
|
+
*
|
|
94
|
+
* The generated ID is guaranteed to be unique across processes and time,
|
|
95
|
+
* making it suitable for distributed systems and concurrent operations.
|
|
96
|
+
*
|
|
97
|
+
* @param prefix - A string prefix to prepend to the generated ID
|
|
98
|
+
* @returns A unique identifier string in the format: `${prefix}-${hexString}`
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```typescript
|
|
102
|
+
* const db = new Tero();
|
|
103
|
+
*
|
|
104
|
+
* // Generate unique IDs for different purposes
|
|
105
|
+
* const userId = db.getNewId('user'); // e.g., "user-507f1f77bcf86cd799439011"
|
|
106
|
+
* const sessionId = db.getNewId('session'); // e.g., "session-507f1f77bcf86cd799439012"
|
|
107
|
+
* const logId = db.getNewId('log'); // e.g., "log-507f1f77bcf86cd799439013"
|
|
108
|
+
*
|
|
109
|
+
* // Use as document keys
|
|
110
|
+
* await db.create(userId, { name: 'Alice', email: 'alice@example.com' });
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
getNewId(prefix: string): string;
|
|
87
114
|
}
|
|
88
115
|
export { DocumentSchema, ValidationResult, BackupConfig, BackupMetadata, RecoveryConfig, RecoveryResult, FileRecoveryInfo };
|
package/dist/index.js
CHANGED
|
@@ -3,10 +3,12 @@ import { ACIDStorageEngine } from "./acid-engine.js";
|
|
|
3
3
|
import { SchemaValidator } from "./schema.js";
|
|
4
4
|
import { BackupManager } from "./backup.js";
|
|
5
5
|
import { DataRecovery } from "./recovery.js";
|
|
6
|
+
import { randomBytes } from "node:crypto";
|
|
7
|
+
import QuickLRU from "quick-lru";
|
|
6
8
|
export class Tero {
|
|
7
9
|
teroDirectory = "TeroDB";
|
|
8
10
|
cacheSize = 100;
|
|
9
|
-
cache
|
|
11
|
+
cache;
|
|
10
12
|
cacheHits = 0;
|
|
11
13
|
cacheRequests = 0;
|
|
12
14
|
acidEngine;
|
|
@@ -21,10 +23,14 @@ export class Tero {
|
|
|
21
23
|
this.teroDirectory = directory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
|
|
22
24
|
}
|
|
23
25
|
if (typeof cacheSize === "number" && cacheSize > 0) {
|
|
24
|
-
this.cacheSize = Math.min(cacheSize,
|
|
26
|
+
this.cacheSize = Math.min(cacheSize, 1000); // Cap at 1k entries
|
|
25
27
|
}
|
|
26
28
|
// Create directories with proper error handling
|
|
27
29
|
this.initializeDirectories();
|
|
30
|
+
// Initialize QuickLRU cache
|
|
31
|
+
this.cache = new QuickLRU({
|
|
32
|
+
maxSize: this.cacheSize
|
|
33
|
+
});
|
|
28
34
|
// Initialize ACID storage engine (primary system)
|
|
29
35
|
this.acidEngine = new ACIDStorageEngine(this.teroDirectory);
|
|
30
36
|
// Initialize schema validator
|
|
@@ -57,32 +63,14 @@ export class Tero {
|
|
|
57
63
|
throw new Error('Key contains invalid characters');
|
|
58
64
|
}
|
|
59
65
|
}
|
|
60
|
-
evictOldestCacheEntry() {
|
|
61
|
-
if (this.cache.size === 0)
|
|
62
|
-
return;
|
|
63
|
-
let oldestKey = '';
|
|
64
|
-
let oldestTime = Date.now();
|
|
65
|
-
for (const [key, entry] of this.cache.entries()) {
|
|
66
|
-
if (entry.lastAccessed < oldestTime) {
|
|
67
|
-
oldestTime = entry.lastAccessed;
|
|
68
|
-
oldestKey = key;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
if (oldestKey) {
|
|
72
|
-
this.cache.delete(oldestKey);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
66
|
invalidateCacheKeys(keys) {
|
|
76
67
|
for (const key of keys) {
|
|
77
68
|
this.cache.delete(key);
|
|
78
69
|
}
|
|
79
70
|
}
|
|
80
71
|
updateCache(key, data, transactionId) {
|
|
81
|
-
if (this.cache.size >= this.cacheSize) {
|
|
82
|
-
this.evictOldestCacheEntry();
|
|
83
|
-
}
|
|
84
72
|
this.cache.set(key, {
|
|
85
|
-
data:
|
|
73
|
+
data: data,
|
|
86
74
|
lastAccessed: Date.now(),
|
|
87
75
|
transactionId
|
|
88
76
|
});
|
|
@@ -170,13 +158,14 @@ export class Tero {
|
|
|
170
158
|
throw new Error(`Transaction ${transactionId} not found or not active`);
|
|
171
159
|
}
|
|
172
160
|
await this.acidEngine.commitTransaction(transactionId);
|
|
173
|
-
//
|
|
161
|
+
// Invalidate cache entries for this transaction to force fresh reads
|
|
162
|
+
const keysToInvalidate = [];
|
|
174
163
|
for (const [key, entry] of this.cache.entries()) {
|
|
175
164
|
if (entry.transactionId === transactionId) {
|
|
176
|
-
|
|
177
|
-
entry.transactionId = undefined;
|
|
165
|
+
keysToInvalidate.push(key);
|
|
178
166
|
}
|
|
179
167
|
}
|
|
168
|
+
this.invalidateCacheKeys(keysToInvalidate);
|
|
180
169
|
}
|
|
181
170
|
catch (error) {
|
|
182
171
|
throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
@@ -447,4 +436,46 @@ export class Tero {
|
|
|
447
436
|
}
|
|
448
437
|
this.clearCache();
|
|
449
438
|
}
|
|
439
|
+
/**
|
|
440
|
+
* Generates a unique identifier with a custom prefix.
|
|
441
|
+
*
|
|
442
|
+
* This method creates MongoDB ObjectId-like unique identifiers that consist of:
|
|
443
|
+
* - 4-byte timestamp (seconds since Unix epoch)
|
|
444
|
+
* - 5-byte process-unique random value
|
|
445
|
+
* - 3-byte incrementing counter
|
|
446
|
+
*
|
|
447
|
+
* The generated ID is guaranteed to be unique across processes and time,
|
|
448
|
+
* making it suitable for distributed systems and concurrent operations.
|
|
449
|
+
*
|
|
450
|
+
* @param prefix - A string prefix to prepend to the generated ID
|
|
451
|
+
* @returns A unique identifier string in the format: `${prefix}-${hexString}`
|
|
452
|
+
*
|
|
453
|
+
* @example
|
|
454
|
+
* ```typescript
|
|
455
|
+
* const db = new Tero();
|
|
456
|
+
*
|
|
457
|
+
* // Generate unique IDs for different purposes
|
|
458
|
+
* const userId = db.getNewId('user'); // e.g., "user-507f1f77bcf86cd799439011"
|
|
459
|
+
* const sessionId = db.getNewId('session'); // e.g., "session-507f1f77bcf86cd799439012"
|
|
460
|
+
* const logId = db.getNewId('log'); // e.g., "log-507f1f77bcf86cd799439013"
|
|
461
|
+
*
|
|
462
|
+
* // Use as document keys
|
|
463
|
+
* await db.create(userId, { name: 'Alice', email: 'alice@example.com' });
|
|
464
|
+
* ```
|
|
465
|
+
*/
|
|
466
|
+
getNewId(prefix) {
|
|
467
|
+
const PROCESS_UNIQUE = randomBytes(5);
|
|
468
|
+
const buffer = Buffer.allocUnsafe(12);
|
|
469
|
+
let index = ~~(Math.random() * 0xffffff);
|
|
470
|
+
const time = ~~(Date.now() / 1000);
|
|
471
|
+
const inc = (index = (index + 1) % 0xffffff);
|
|
472
|
+
// 4-byte timestamp (seconds since Unix epoch)
|
|
473
|
+
buffer.writeUInt32BE(time, 0);
|
|
474
|
+
// 5-byte process unique identifier
|
|
475
|
+
buffer.set(PROCESS_UNIQUE, 4);
|
|
476
|
+
// 3-byte incrementing counter
|
|
477
|
+
buffer.writeUIntBE(inc, 9, 3);
|
|
478
|
+
// Convert to hexadecimal string and prepend prefix
|
|
479
|
+
return prefix + "-" + buffer.toString("hex");
|
|
480
|
+
}
|
|
450
481
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tero",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.0.3",
|
|
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",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
@@ -15,20 +15,19 @@
|
|
|
15
15
|
},
|
|
16
16
|
"homepage": "https://github.com/codedynasty-dev/tero.git",
|
|
17
17
|
"scripts": {
|
|
18
|
-
"build": "tsc",
|
|
18
|
+
"build": "npm run test && tsc",
|
|
19
19
|
"dev": "tsc --watch",
|
|
20
20
|
"test": "node run-tests.js",
|
|
21
|
-
"test:production": "node
|
|
22
|
-
"test:legacy": "node
|
|
23
|
-
"test:backup": "node
|
|
24
|
-
"test:schema": "node
|
|
21
|
+
"test:production": "node local_tests/production-test.js",
|
|
22
|
+
"test:legacy": "node local_tests/test.js",
|
|
23
|
+
"test:backup": "node local_tests/backup-test.js",
|
|
24
|
+
"test:schema": "node local_tests/schema-test.js",
|
|
25
25
|
"test:all": "npm run test",
|
|
26
26
|
"test:watch": "npm run test",
|
|
27
27
|
"prebuild": "echo 'Building Tero...'",
|
|
28
28
|
"postbuild": "echo 'Build completed successfully!'",
|
|
29
29
|
"pretest": "echo 'Running Tero test suite...'",
|
|
30
30
|
"posttest": "echo 'Test suite completed!'",
|
|
31
|
-
"prepublishOnly": "npm run test",
|
|
32
31
|
"verify": "node verify-build.js && npm run test",
|
|
33
32
|
"ci": "npm run verify"
|
|
34
33
|
},
|
|
@@ -42,16 +41,20 @@
|
|
|
42
41
|
],
|
|
43
42
|
"license": "MIT",
|
|
44
43
|
"dependencies": {
|
|
44
|
+
"@aws-sdk/client-s3": "^3.0.0",
|
|
45
|
+
"@aws-sdk/lib-storage": "^3.0.0",
|
|
46
|
+
"cron": "^4.3.2",
|
|
45
47
|
"fs-ext": "^2.0.0",
|
|
46
48
|
"glob": "^9.3.4",
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
"@aws-sdk/lib-storage": "^3.0.0"
|
|
49
|
+
"quick-lru": "^7.0.1",
|
|
50
|
+
"tar": "^6.1.13"
|
|
50
51
|
},
|
|
51
52
|
"devDependencies": {
|
|
53
|
+
"@types/cron": "^2.0.1",
|
|
52
54
|
"@types/fs-ext": "^2.0.3",
|
|
53
55
|
"@types/glob": "^8.1.0",
|
|
54
56
|
"@types/node": "^24.0.14",
|
|
57
|
+
"@types/quick-lru": "^2.0.0",
|
|
55
58
|
"@types/tar": "^6.1.13",
|
|
56
59
|
"typescript": "^5.8.3"
|
|
57
60
|
}
|