tero 0.0.0 → 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 +50 -24
- package/dist/acid-engine.d.ts +63 -0
- package/dist/acid-engine.js +76 -10
- package/dist/backup.d.ts +66 -0
- package/dist/backup.js +75 -22
- package/dist/index.d.ts +115 -0
- package/dist/index.js +55 -24
- package/dist/recovery.d.ts +46 -0
- package/dist/schema.d.ts +61 -0
- package/package.json +14 -11
- package/dist/fn.js +0 -192
- package/dist/transaction.js +0 -476
package/README.md
CHANGED
|
@@ -7,38 +7,36 @@
|
|
|
7
7
|
[](#)
|
|
8
8
|
[](#)
|
|
9
9
|
|
|
10
|
-
**
|
|
10
|
+
**JSON document database**
|
|
11
11
|
|
|
12
|
-
Tero is a
|
|
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
|
|
|
16
|
-
###
|
|
16
|
+
### Transactions
|
|
17
17
|
- **Atomicity**: All-or-nothing transactions ensure data consistency
|
|
18
18
|
- **Consistency**: Schema validation and business rule enforcement
|
|
19
19
|
- **Isolation**: Concurrent operations are properly isolated
|
|
20
20
|
- **Durability**: Write-ahead logging ensures data survives system crashes
|
|
21
21
|
|
|
22
|
-
###
|
|
22
|
+
### Ready-To-Use
|
|
23
23
|
- **High Performance**: Intelligent caching and batch operations
|
|
24
24
|
- **Data Integrity**: Built-in corruption detection and recovery
|
|
25
25
|
- **Schema Validation**: Flexible schema system with strict mode
|
|
26
26
|
- **Error Handling**: Comprehensive error handling and recovery
|
|
27
27
|
- **Memory Management**: Efficient memory usage with automatic cleanup
|
|
28
|
-
|
|
29
|
-
### Enterprise Features
|
|
30
28
|
- **Cloud Backup**: AWS S3 and Cloudflare R2 support
|
|
31
29
|
- **Data Recovery**: Automatic crash recovery and cloud restore
|
|
32
30
|
- **Monitoring**: Performance metrics and health checks
|
|
33
31
|
- **Security**: Path traversal protection and input validation
|
|
34
32
|
|
|
35
|
-
##
|
|
33
|
+
## Installation
|
|
36
34
|
|
|
37
35
|
```bash
|
|
38
36
|
npm install tero
|
|
39
37
|
```
|
|
40
38
|
|
|
41
|
-
##
|
|
39
|
+
## Quick Start
|
|
42
40
|
|
|
43
41
|
```javascript
|
|
44
42
|
import { Tero } from 'tero';
|
|
@@ -56,7 +54,7 @@ await db.update('user1', { age: 30 });
|
|
|
56
54
|
await db.remove('user1');
|
|
57
55
|
```
|
|
58
56
|
|
|
59
|
-
##
|
|
57
|
+
## ACID Transactions
|
|
60
58
|
|
|
61
59
|
### Automatic Transactions
|
|
62
60
|
All basic operations are automatically wrapped in ACID transactions:
|
|
@@ -95,7 +93,7 @@ Demonstrates ACID properties with business logic:
|
|
|
95
93
|
await db.transferMoney('savings', 'checking', 500);
|
|
96
94
|
```
|
|
97
95
|
|
|
98
|
-
##
|
|
96
|
+
## Schema Validation
|
|
99
97
|
|
|
100
98
|
Define and enforce data schemas:
|
|
101
99
|
|
|
@@ -122,7 +120,7 @@ await db.create('user1', userData, {
|
|
|
122
120
|
});
|
|
123
121
|
```
|
|
124
122
|
|
|
125
|
-
##
|
|
123
|
+
## Batch Operations
|
|
126
124
|
|
|
127
125
|
Efficient batch processing with ACID guarantees:
|
|
128
126
|
|
|
@@ -138,7 +136,7 @@ await db.batchWrite([
|
|
|
138
136
|
const products = await db.batchRead(['product1', 'product2', 'product3']);
|
|
139
137
|
```
|
|
140
138
|
|
|
141
|
-
##
|
|
139
|
+
## Cloud Backup
|
|
142
140
|
|
|
143
141
|
Configure automatic cloud backups:
|
|
144
142
|
|
|
@@ -159,7 +157,7 @@ db.configureBackup({
|
|
|
159
157
|
const result = await db.performBackup();
|
|
160
158
|
```
|
|
161
159
|
|
|
162
|
-
##
|
|
160
|
+
## Data Recovery
|
|
163
161
|
|
|
164
162
|
Automatic crash recovery and cloud restore:
|
|
165
163
|
|
|
@@ -177,14 +175,41 @@ await db.recoverFromCloud('important-data');
|
|
|
177
175
|
const result = await db.recoverAllFromCloud();
|
|
178
176
|
```
|
|
179
177
|
|
|
180
|
-
##
|
|
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
|
+
|
|
204
|
+
## Monitoring
|
|
181
205
|
|
|
182
206
|
Built-in performance monitoring and health checks:
|
|
183
207
|
|
|
184
208
|
```javascript
|
|
185
|
-
// Cache performance
|
|
209
|
+
// Cache performance (now using optimized QuickLRU)
|
|
186
210
|
const cacheStats = db.getCacheStats();
|
|
187
211
|
console.log(`Cache hit rate: ${cacheStats.hitRate}%`);
|
|
212
|
+
console.log(`Cache size: ${cacheStats.size}/${cacheStats.maxSize}`);
|
|
188
213
|
|
|
189
214
|
// Data integrity check
|
|
190
215
|
const integrity = await db.verifyDataIntegrity();
|
|
@@ -197,7 +222,7 @@ const activeTx = db.getActiveTransactions();
|
|
|
197
222
|
console.log(`Active transactions: ${activeTx.length}`);
|
|
198
223
|
```
|
|
199
224
|
|
|
200
|
-
##
|
|
225
|
+
## Error Handling
|
|
201
226
|
|
|
202
227
|
Comprehensive error handling with detailed messages:
|
|
203
228
|
|
|
@@ -213,7 +238,7 @@ try {
|
|
|
213
238
|
}
|
|
214
239
|
```
|
|
215
240
|
|
|
216
|
-
##
|
|
241
|
+
## Configuration
|
|
217
242
|
|
|
218
243
|
### Database Options
|
|
219
244
|
```javascript
|
|
@@ -248,14 +273,14 @@ const db = new Tero({
|
|
|
248
273
|
4. Monitor cache hit rates and adjust cache size
|
|
249
274
|
5. Use transactions for related operations
|
|
250
275
|
|
|
251
|
-
##
|
|
276
|
+
## Security
|
|
252
277
|
|
|
253
278
|
- **Path Traversal Protection**: Automatic key sanitization
|
|
254
279
|
- **Input Validation**: Comprehensive data validation
|
|
255
280
|
- **Error Handling**: No sensitive data in error messages
|
|
256
281
|
- **Access Control**: File system permissions respected
|
|
257
282
|
|
|
258
|
-
##
|
|
283
|
+
## API Reference
|
|
259
284
|
|
|
260
285
|
### Core Methods
|
|
261
286
|
- `create(key, data, options?)`: Create new document
|
|
@@ -288,9 +313,10 @@ const db = new Tero({
|
|
|
288
313
|
- `getActiveTransactions()`: List active transactions
|
|
289
314
|
- `forceCheckpoint()`: Force WAL flush
|
|
290
315
|
- `clearCache()`: Clear memory cache
|
|
316
|
+
- `getNewId(prefix)`: Generate unique identifiers with custom prefix
|
|
291
317
|
- `destroy()`: Cleanup and shutdown
|
|
292
318
|
|
|
293
|
-
##
|
|
319
|
+
## Testing
|
|
294
320
|
|
|
295
321
|
Run the production test suite:
|
|
296
322
|
|
|
@@ -298,11 +324,11 @@ Run the production test suite:
|
|
|
298
324
|
npm run test:production
|
|
299
325
|
```
|
|
300
326
|
|
|
301
|
-
##
|
|
327
|
+
## License
|
|
302
328
|
|
|
303
329
|
MIT License - see LICENSE file for details.
|
|
304
330
|
|
|
305
|
-
##
|
|
331
|
+
## Contributing
|
|
306
332
|
|
|
307
333
|
1. Fork the repository
|
|
308
334
|
2. Create a feature branch
|
|
@@ -310,7 +336,7 @@ MIT License - see LICENSE file for details.
|
|
|
310
336
|
4. Ensure all tests pass
|
|
311
337
|
5. Submit a pull request
|
|
312
338
|
|
|
313
|
-
##
|
|
339
|
+
## Support
|
|
314
340
|
|
|
315
341
|
For issues and questions:
|
|
316
342
|
- GitHub Issues: [Report bugs and request features](https://github.com/codedynasty-dev/tero/issues)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export interface LogEntry {
|
|
2
|
+
lsn: number;
|
|
3
|
+
transactionId: string;
|
|
4
|
+
operation: 'BEGIN' | 'WRITE' | 'DELETE' | 'COMMIT' | 'ROLLBACK' | 'CHECKPOINT';
|
|
5
|
+
key?: string;
|
|
6
|
+
beforeImage?: any;
|
|
7
|
+
afterImage?: any;
|
|
8
|
+
timestamp: number;
|
|
9
|
+
checksum: string;
|
|
10
|
+
}
|
|
11
|
+
export declare class WriteAheadLog {
|
|
12
|
+
private logPath;
|
|
13
|
+
private currentLSN;
|
|
14
|
+
private logBuffer;
|
|
15
|
+
private readonly BUFFER_SIZE;
|
|
16
|
+
private readonly LOG_FILE_SIZE_LIMIT;
|
|
17
|
+
constructor(dbPath: string);
|
|
18
|
+
private initializeWAL;
|
|
19
|
+
private recoverFromLog;
|
|
20
|
+
private calculateChecksum;
|
|
21
|
+
private verifyChecksum;
|
|
22
|
+
writeLog(entry: Omit<LogEntry, 'lsn' | 'checksum' | 'timestamp'>): number;
|
|
23
|
+
private flushBuffer;
|
|
24
|
+
private checkLogRotation;
|
|
25
|
+
private rotateLog;
|
|
26
|
+
getLogEntries(fromLSN?: number): LogEntry[];
|
|
27
|
+
forceFlush(): void;
|
|
28
|
+
getCurrentLSN(): number;
|
|
29
|
+
clearCommittedTransaction(transactionId: string): void;
|
|
30
|
+
}
|
|
31
|
+
export declare class LockManager {
|
|
32
|
+
private locks;
|
|
33
|
+
private readonly DEADLOCK_TIMEOUT;
|
|
34
|
+
acquireLock(key: string, transactionId: string, lockType: 'shared' | 'exclusive'): Promise<void>;
|
|
35
|
+
private canGrantLock;
|
|
36
|
+
releaseLock(key: string, transactionId: string): void;
|
|
37
|
+
private processWaitQueue;
|
|
38
|
+
private removeLockRequest;
|
|
39
|
+
releaseAllLocks(transactionId: string): void;
|
|
40
|
+
detectDeadlock(): string[];
|
|
41
|
+
}
|
|
42
|
+
export declare class ACIDStorageEngine {
|
|
43
|
+
private wal;
|
|
44
|
+
private lockManager;
|
|
45
|
+
private dbPath;
|
|
46
|
+
private activeTransactions;
|
|
47
|
+
constructor(dbPath: string);
|
|
48
|
+
private initializeStorage;
|
|
49
|
+
private performCrashRecovery;
|
|
50
|
+
private redoOperation;
|
|
51
|
+
private redoDelete;
|
|
52
|
+
private undoOperation;
|
|
53
|
+
beginTransaction(): string;
|
|
54
|
+
write(transactionId: string, key: string, data: any): Promise<void>;
|
|
55
|
+
read(transactionId: string, key: string): Promise<any>;
|
|
56
|
+
delete(transactionId: string, key: string): Promise<void>;
|
|
57
|
+
commitTransaction(transactionId: string): Promise<void>;
|
|
58
|
+
rollbackTransaction(transactionId: string): Promise<void>;
|
|
59
|
+
private deepMerge;
|
|
60
|
+
getActiveTransactions(): string[];
|
|
61
|
+
forceCheckpoint(): void;
|
|
62
|
+
destroy(): void;
|
|
63
|
+
}
|
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
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export interface CloudStorageConfig {
|
|
2
|
+
provider: 'aws-s3' | 'cloudflare-r2';
|
|
3
|
+
region: string;
|
|
4
|
+
bucket: string;
|
|
5
|
+
accessKeyId: string;
|
|
6
|
+
secretAccessKey: string;
|
|
7
|
+
endpoint?: string;
|
|
8
|
+
pathPrefix?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface BackupConfig {
|
|
11
|
+
interval?: string;
|
|
12
|
+
retention?: string;
|
|
13
|
+
format: 'individual' | 'archive';
|
|
14
|
+
cloudStorage?: CloudStorageConfig;
|
|
15
|
+
localPath?: string;
|
|
16
|
+
compression?: boolean;
|
|
17
|
+
includeMetadata?: boolean;
|
|
18
|
+
metadataUse?: 'verification' | 'audit' | 'recovery' | 'none';
|
|
19
|
+
}
|
|
20
|
+
export interface BackupMetadata {
|
|
21
|
+
timestamp: string;
|
|
22
|
+
format: 'individual' | 'archive';
|
|
23
|
+
fileCount: number;
|
|
24
|
+
totalSize: number;
|
|
25
|
+
checksum: string;
|
|
26
|
+
retention: string;
|
|
27
|
+
}
|
|
28
|
+
export declare class BackupManager {
|
|
29
|
+
private s3Client?;
|
|
30
|
+
private scheduledBackups;
|
|
31
|
+
private config;
|
|
32
|
+
private dbPath;
|
|
33
|
+
constructor(dbPath: string, config: BackupConfig);
|
|
34
|
+
private initializeCloudStorage;
|
|
35
|
+
private parseInterval;
|
|
36
|
+
private parseRetention;
|
|
37
|
+
private intervalToCron;
|
|
38
|
+
private calculateChecksum;
|
|
39
|
+
private getJsonFiles;
|
|
40
|
+
private createArchiveBackup;
|
|
41
|
+
private createIndividualBackup;
|
|
42
|
+
private uploadToCloud;
|
|
43
|
+
private uploadDirectoryToCloud;
|
|
44
|
+
private uploadIndividualFilesToCloud;
|
|
45
|
+
private getCloudKey;
|
|
46
|
+
performBackup(): Promise<{
|
|
47
|
+
success: boolean;
|
|
48
|
+
metadata: BackupMetadata;
|
|
49
|
+
cloudUploaded?: boolean;
|
|
50
|
+
}>;
|
|
51
|
+
private cleanupOldBackups;
|
|
52
|
+
scheduleBackup(config: {
|
|
53
|
+
interval: string;
|
|
54
|
+
retention?: string;
|
|
55
|
+
}): string;
|
|
56
|
+
cancelScheduledBackup(scheduleId: string): boolean;
|
|
57
|
+
getScheduledBackups(): Array<{
|
|
58
|
+
id: string;
|
|
59
|
+
active: boolean;
|
|
60
|
+
}>;
|
|
61
|
+
testCloudConnection(): Promise<{
|
|
62
|
+
success: boolean;
|
|
63
|
+
message: string;
|
|
64
|
+
}>;
|
|
65
|
+
destroy(): void;
|
|
66
|
+
}
|
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');
|