tero 0.0.0 â 0.0.1
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 +21 -23
- package/dist/acid-engine.d.ts +62 -0
- package/dist/backup.d.ts +64 -0
- package/dist/index.d.ts +88 -0
- package/dist/recovery.d.ts +46 -0
- package/dist/schema.d.ts +61 -0
- package/package.json +1 -1
- 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, cloud backup, and automatic recovery. Built for production environments requiring json data integrity and reliability.
|
|
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,7 +175,7 @@ await db.recoverFromCloud('important-data');
|
|
|
177
175
|
const result = await db.recoverAllFromCloud();
|
|
178
176
|
```
|
|
179
177
|
|
|
180
|
-
##
|
|
178
|
+
## Monitoring
|
|
181
179
|
|
|
182
180
|
Built-in performance monitoring and health checks:
|
|
183
181
|
|
|
@@ -197,7 +195,7 @@ const activeTx = db.getActiveTransactions();
|
|
|
197
195
|
console.log(`Active transactions: ${activeTx.length}`);
|
|
198
196
|
```
|
|
199
197
|
|
|
200
|
-
##
|
|
198
|
+
## Error Handling
|
|
201
199
|
|
|
202
200
|
Comprehensive error handling with detailed messages:
|
|
203
201
|
|
|
@@ -213,7 +211,7 @@ try {
|
|
|
213
211
|
}
|
|
214
212
|
```
|
|
215
213
|
|
|
216
|
-
##
|
|
214
|
+
## Configuration
|
|
217
215
|
|
|
218
216
|
### Database Options
|
|
219
217
|
```javascript
|
|
@@ -248,14 +246,14 @@ const db = new Tero({
|
|
|
248
246
|
4. Monitor cache hit rates and adjust cache size
|
|
249
247
|
5. Use transactions for related operations
|
|
250
248
|
|
|
251
|
-
##
|
|
249
|
+
## Security
|
|
252
250
|
|
|
253
251
|
- **Path Traversal Protection**: Automatic key sanitization
|
|
254
252
|
- **Input Validation**: Comprehensive data validation
|
|
255
253
|
- **Error Handling**: No sensitive data in error messages
|
|
256
254
|
- **Access Control**: File system permissions respected
|
|
257
255
|
|
|
258
|
-
##
|
|
256
|
+
## API Reference
|
|
259
257
|
|
|
260
258
|
### Core Methods
|
|
261
259
|
- `create(key, data, options?)`: Create new document
|
|
@@ -290,7 +288,7 @@ const db = new Tero({
|
|
|
290
288
|
- `clearCache()`: Clear memory cache
|
|
291
289
|
- `destroy()`: Cleanup and shutdown
|
|
292
290
|
|
|
293
|
-
##
|
|
291
|
+
## Testing
|
|
294
292
|
|
|
295
293
|
Run the production test suite:
|
|
296
294
|
|
|
@@ -298,11 +296,11 @@ Run the production test suite:
|
|
|
298
296
|
npm run test:production
|
|
299
297
|
```
|
|
300
298
|
|
|
301
|
-
##
|
|
299
|
+
## License
|
|
302
300
|
|
|
303
301
|
MIT License - see LICENSE file for details.
|
|
304
302
|
|
|
305
|
-
##
|
|
303
|
+
## Contributing
|
|
306
304
|
|
|
307
305
|
1. Fork the repository
|
|
308
306
|
2. Create a feature branch
|
|
@@ -310,7 +308,7 @@ MIT License - see LICENSE file for details.
|
|
|
310
308
|
4. Ensure all tests pass
|
|
311
309
|
5. Submit a pull request
|
|
312
310
|
|
|
313
|
-
##
|
|
311
|
+
## Support
|
|
314
312
|
|
|
315
313
|
For issues and questions:
|
|
316
314
|
- GitHub Issues: [Report bugs and request features](https://github.com/codedynasty-dev/tero/issues)
|
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
}
|
|
30
|
+
export declare class LockManager {
|
|
31
|
+
private locks;
|
|
32
|
+
private readonly DEADLOCK_TIMEOUT;
|
|
33
|
+
acquireLock(key: string, transactionId: string, lockType: 'shared' | 'exclusive'): Promise<void>;
|
|
34
|
+
private canGrantLock;
|
|
35
|
+
releaseLock(key: string, transactionId: string): void;
|
|
36
|
+
private processWaitQueue;
|
|
37
|
+
private removeLockRequest;
|
|
38
|
+
releaseAllLocks(transactionId: string): void;
|
|
39
|
+
detectDeadlock(): string[];
|
|
40
|
+
}
|
|
41
|
+
export declare class ACIDStorageEngine {
|
|
42
|
+
private wal;
|
|
43
|
+
private lockManager;
|
|
44
|
+
private dbPath;
|
|
45
|
+
private activeTransactions;
|
|
46
|
+
constructor(dbPath: string);
|
|
47
|
+
private initializeStorage;
|
|
48
|
+
private performCrashRecovery;
|
|
49
|
+
private redoOperation;
|
|
50
|
+
private redoDelete;
|
|
51
|
+
private undoOperation;
|
|
52
|
+
beginTransaction(): string;
|
|
53
|
+
write(transactionId: string, key: string, data: any): Promise<void>;
|
|
54
|
+
read(transactionId: string, key: string): Promise<any>;
|
|
55
|
+
delete(transactionId: string, key: string): Promise<void>;
|
|
56
|
+
commitTransaction(transactionId: string): Promise<void>;
|
|
57
|
+
rollbackTransaction(transactionId: string): Promise<void>;
|
|
58
|
+
private deepMerge;
|
|
59
|
+
getActiveTransactions(): string[];
|
|
60
|
+
forceCheckpoint(): void;
|
|
61
|
+
destroy(): void;
|
|
62
|
+
}
|
package/dist/backup.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
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 calculateChecksum;
|
|
38
|
+
private getJsonFiles;
|
|
39
|
+
private createArchiveBackup;
|
|
40
|
+
private createIndividualBackup;
|
|
41
|
+
private uploadToCloud;
|
|
42
|
+
private uploadDirectoryToCloud;
|
|
43
|
+
private getCloudKey;
|
|
44
|
+
performBackup(): Promise<{
|
|
45
|
+
success: boolean;
|
|
46
|
+
metadata: BackupMetadata;
|
|
47
|
+
cloudUploaded?: boolean;
|
|
48
|
+
}>;
|
|
49
|
+
private cleanupOldBackups;
|
|
50
|
+
scheduleBackup(config: {
|
|
51
|
+
interval: string;
|
|
52
|
+
retention?: string;
|
|
53
|
+
}): string;
|
|
54
|
+
cancelScheduledBackup(scheduleId: string): boolean;
|
|
55
|
+
getScheduledBackups(): Array<{
|
|
56
|
+
id: string;
|
|
57
|
+
active: boolean;
|
|
58
|
+
}>;
|
|
59
|
+
testCloudConnection(): Promise<{
|
|
60
|
+
success: boolean;
|
|
61
|
+
message: string;
|
|
62
|
+
}>;
|
|
63
|
+
destroy(): void;
|
|
64
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { DocumentSchema, ValidationResult } from "./schema.js";
|
|
2
|
+
import { BackupConfig, BackupMetadata } from "./backup.js";
|
|
3
|
+
import { RecoveryConfig, RecoveryResult, FileRecoveryInfo } from "./recovery.js";
|
|
4
|
+
interface TeroConfig {
|
|
5
|
+
directory?: string;
|
|
6
|
+
cacheSize?: number;
|
|
7
|
+
}
|
|
8
|
+
export declare class Tero {
|
|
9
|
+
private teroDirectory;
|
|
10
|
+
private cacheSize;
|
|
11
|
+
private cache;
|
|
12
|
+
private cacheHits;
|
|
13
|
+
private cacheRequests;
|
|
14
|
+
private acidEngine;
|
|
15
|
+
private schemaValidator;
|
|
16
|
+
private backupManager?;
|
|
17
|
+
private dataRecovery?;
|
|
18
|
+
constructor(config?: TeroConfig);
|
|
19
|
+
private initializeDirectories;
|
|
20
|
+
private validateKey;
|
|
21
|
+
private evictOldestCacheEntry;
|
|
22
|
+
private invalidateCacheKeys;
|
|
23
|
+
private updateCache;
|
|
24
|
+
beginTransaction(): string;
|
|
25
|
+
write(transactionId: string, key: string, data: any, options?: {
|
|
26
|
+
validate?: boolean;
|
|
27
|
+
schemaName?: string;
|
|
28
|
+
strict?: boolean;
|
|
29
|
+
}): Promise<ValidationResult | void>;
|
|
30
|
+
read(transactionId: string, key: string): Promise<any>;
|
|
31
|
+
delete(transactionId: string, key: string): Promise<void>;
|
|
32
|
+
commit(transactionId: string): Promise<void>;
|
|
33
|
+
rollback(transactionId: string): Promise<void>;
|
|
34
|
+
create(key: string, initialData?: any, options?: {
|
|
35
|
+
validate?: boolean;
|
|
36
|
+
schemaName?: string;
|
|
37
|
+
strict?: boolean;
|
|
38
|
+
}): Promise<ValidationResult | boolean>;
|
|
39
|
+
update(key: string, data: any, options?: {
|
|
40
|
+
validate?: boolean;
|
|
41
|
+
schemaName?: string;
|
|
42
|
+
strict?: boolean;
|
|
43
|
+
}): Promise<ValidationResult | void>;
|
|
44
|
+
get(key: string): Promise<any>;
|
|
45
|
+
remove(key: string): Promise<void>;
|
|
46
|
+
exists(key: string): boolean;
|
|
47
|
+
batchWrite(operations: Array<{
|
|
48
|
+
key: string;
|
|
49
|
+
data: any;
|
|
50
|
+
}>, options?: {
|
|
51
|
+
validate?: boolean;
|
|
52
|
+
schemaName?: string;
|
|
53
|
+
strict?: boolean;
|
|
54
|
+
}): Promise<void>;
|
|
55
|
+
batchRead(keys: string[]): Promise<{
|
|
56
|
+
[key: string]: any;
|
|
57
|
+
}>;
|
|
58
|
+
transferMoney(fromKey: string, toKey: string, amount: number): Promise<void>;
|
|
59
|
+
setSchema(collectionName: string, schema: DocumentSchema): void;
|
|
60
|
+
getSchema(collectionName: string): DocumentSchema | undefined;
|
|
61
|
+
removeSchema(collectionName: string): boolean;
|
|
62
|
+
validateData(collectionName: string, data: any): ValidationResult;
|
|
63
|
+
configureBackup(config: BackupConfig): void;
|
|
64
|
+
performBackup(): Promise<{
|
|
65
|
+
success: boolean;
|
|
66
|
+
metadata: BackupMetadata;
|
|
67
|
+
cloudUploaded?: boolean;
|
|
68
|
+
}>;
|
|
69
|
+
configureDataRecovery(config: RecoveryConfig): void;
|
|
70
|
+
recoverFromCloud(key: string): Promise<boolean>;
|
|
71
|
+
recoverAllFromCloud(): Promise<RecoveryResult>;
|
|
72
|
+
getCacheStats(): {
|
|
73
|
+
size: number;
|
|
74
|
+
maxSize: number;
|
|
75
|
+
hitRate: number;
|
|
76
|
+
};
|
|
77
|
+
getActiveTransactions(): string[];
|
|
78
|
+
forceCheckpoint(): void;
|
|
79
|
+
verifyDataIntegrity(): Promise<{
|
|
80
|
+
totalFiles: number;
|
|
81
|
+
corruptedFiles: string[];
|
|
82
|
+
missingFiles: string[];
|
|
83
|
+
healthy: boolean;
|
|
84
|
+
}>;
|
|
85
|
+
clearCache(): void;
|
|
86
|
+
destroy(): void;
|
|
87
|
+
}
|
|
88
|
+
export { DocumentSchema, ValidationResult, BackupConfig, BackupMetadata, RecoveryConfig, RecoveryResult, FileRecoveryInfo };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { CloudStorageConfig } from "./backup.js";
|
|
2
|
+
export interface RecoveryConfig {
|
|
3
|
+
cloudStorage: CloudStorageConfig;
|
|
4
|
+
localPath: string;
|
|
5
|
+
autoRecover?: boolean;
|
|
6
|
+
recoveryTimeout?: number;
|
|
7
|
+
}
|
|
8
|
+
export interface RecoveryResult {
|
|
9
|
+
success: boolean;
|
|
10
|
+
recovered: string[];
|
|
11
|
+
failed: string[];
|
|
12
|
+
totalFiles: number;
|
|
13
|
+
duration: number;
|
|
14
|
+
}
|
|
15
|
+
export interface FileRecoveryInfo {
|
|
16
|
+
key: string;
|
|
17
|
+
exists: boolean;
|
|
18
|
+
size?: number;
|
|
19
|
+
lastModified?: Date;
|
|
20
|
+
recovered?: boolean;
|
|
21
|
+
}
|
|
22
|
+
export declare class DataRecovery {
|
|
23
|
+
private s3Client;
|
|
24
|
+
private config;
|
|
25
|
+
constructor(config: RecoveryConfig);
|
|
26
|
+
private initializeCloudStorage;
|
|
27
|
+
private getCloudKey;
|
|
28
|
+
checkFileInCloud(key: string): Promise<FileRecoveryInfo>;
|
|
29
|
+
recoverSingleFile(key: string): Promise<boolean>;
|
|
30
|
+
recoverFromArchive(archiveName?: string): Promise<RecoveryResult>;
|
|
31
|
+
recoverIndividualFiles(keys?: string[]): Promise<RecoveryResult>;
|
|
32
|
+
listAvailableArchives(): Promise<string[]>;
|
|
33
|
+
listAvailableFiles(): Promise<string[]>;
|
|
34
|
+
private downloadFile;
|
|
35
|
+
private extractArchive;
|
|
36
|
+
testCloudConnection(): Promise<{
|
|
37
|
+
success: boolean;
|
|
38
|
+
message: string;
|
|
39
|
+
}>;
|
|
40
|
+
getRecoveryInfo(): Promise<{
|
|
41
|
+
cloudFiles: number;
|
|
42
|
+
localFiles: number;
|
|
43
|
+
missingLocally: string[];
|
|
44
|
+
availableForRecovery: string[];
|
|
45
|
+
}>;
|
|
46
|
+
}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export interface SchemaField {
|
|
2
|
+
type: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'date' | 'any';
|
|
3
|
+
required?: boolean;
|
|
4
|
+
min?: number;
|
|
5
|
+
max?: number;
|
|
6
|
+
format?: 'email' | 'url' | 'uuid' | 'date' | 'time' | 'datetime' | 'phone' | 'ip';
|
|
7
|
+
pattern?: string;
|
|
8
|
+
enum?: any[];
|
|
9
|
+
default?: any;
|
|
10
|
+
properties?: {
|
|
11
|
+
[key: string]: SchemaField;
|
|
12
|
+
};
|
|
13
|
+
items?: SchemaField;
|
|
14
|
+
custom?: (value: any) => boolean | string;
|
|
15
|
+
}
|
|
16
|
+
export interface DocumentSchema {
|
|
17
|
+
[fieldName: string]: SchemaField;
|
|
18
|
+
}
|
|
19
|
+
export interface ValidationError {
|
|
20
|
+
field: string;
|
|
21
|
+
message: string;
|
|
22
|
+
value?: any;
|
|
23
|
+
expected?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface ValidationResult {
|
|
26
|
+
valid: boolean;
|
|
27
|
+
errors: ValidationError[];
|
|
28
|
+
data?: any;
|
|
29
|
+
}
|
|
30
|
+
export declare class SchemaValidator {
|
|
31
|
+
private schemas;
|
|
32
|
+
setSchema(collectionName: string, schema: DocumentSchema): void;
|
|
33
|
+
getSchema(collectionName: string): DocumentSchema | undefined;
|
|
34
|
+
removeSchema(collectionName: string): boolean;
|
|
35
|
+
hasSchema(collectionName: string): boolean;
|
|
36
|
+
listSchemas(): string[];
|
|
37
|
+
private validateSchemaDefinition;
|
|
38
|
+
validate(collectionName: string, data: any): ValidationResult;
|
|
39
|
+
private validateAndSanitizeData;
|
|
40
|
+
private validateField;
|
|
41
|
+
private validateType;
|
|
42
|
+
private validateString;
|
|
43
|
+
private validateNumber;
|
|
44
|
+
private validateBoolean;
|
|
45
|
+
private validateDate;
|
|
46
|
+
private validateArray;
|
|
47
|
+
private validateObject;
|
|
48
|
+
private validateFormat;
|
|
49
|
+
getSchemaStats(): {
|
|
50
|
+
totalSchemas: number;
|
|
51
|
+
schemaNames: string[];
|
|
52
|
+
totalFields: number;
|
|
53
|
+
};
|
|
54
|
+
exportSchemas(): {
|
|
55
|
+
[collectionName: string]: DocumentSchema;
|
|
56
|
+
};
|
|
57
|
+
importSchemas(schemas: {
|
|
58
|
+
[collectionName: string]: DocumentSchema;
|
|
59
|
+
}): void;
|
|
60
|
+
clearAllSchemas(): void;
|
|
61
|
+
}
|
package/package.json
CHANGED
package/dist/fn.js
DELETED
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import tar from "tar";
|
|
2
|
-
import glob from "glob";
|
|
3
|
-
import { openSync, readFileSync, writeFileSync, unlinkSync, closeSync, ftruncateSync, readdirSync, copyFileSync, mkdirSync, rmSync, existsSync, } from "fs";
|
|
4
|
-
import pkg from "fs-ext";
|
|
5
|
-
const { flockSync } = pkg;
|
|
6
|
-
export async function createFile(file) {
|
|
7
|
-
try {
|
|
8
|
-
if (!file || typeof file !== 'string') {
|
|
9
|
-
throw new Error('File path must be a non-empty string');
|
|
10
|
-
}
|
|
11
|
-
if (!existsSync(file)) {
|
|
12
|
-
writeFileSync(file, "{}", { flag: "w", encoding: "utf8" });
|
|
13
|
-
return true;
|
|
14
|
-
}
|
|
15
|
-
return false;
|
|
16
|
-
}
|
|
17
|
-
catch (error) {
|
|
18
|
-
throw new Error(`Failed to create file '${file}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
export async function backupFiles(source) {
|
|
22
|
-
try {
|
|
23
|
-
if (!source || typeof source !== 'string') {
|
|
24
|
-
throw new Error('Source path must be a non-empty string');
|
|
25
|
-
}
|
|
26
|
-
if (!existsSync(source)) {
|
|
27
|
-
throw new Error(`Source directory '${source}' does not exist`);
|
|
28
|
-
}
|
|
29
|
-
const backup = source + "/.backup";
|
|
30
|
-
// Ensure backup directory exists
|
|
31
|
-
if (!existsSync(backup)) {
|
|
32
|
-
mkdirSync(backup, { recursive: true });
|
|
33
|
-
}
|
|
34
|
-
// Copy files to backup directory
|
|
35
|
-
const files = readdirSync(source);
|
|
36
|
-
for (const file of files) {
|
|
37
|
-
if (file !== ".backup") {
|
|
38
|
-
try {
|
|
39
|
-
copyFileSync(`${source}/${file}`, `${backup}/${file}`);
|
|
40
|
-
}
|
|
41
|
-
catch (copyError) {
|
|
42
|
-
console.warn(`Warning: Could not backup file '${file}': ${copyError instanceof Error ? copyError.message : 'Unknown error'}`);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
// Create tar.gz backup
|
|
47
|
-
const filePattern = `${source}/*.json`;
|
|
48
|
-
const backupFile = `${source}/backup.tar.gz`;
|
|
49
|
-
try {
|
|
50
|
-
const matchedFiles = await glob(filePattern);
|
|
51
|
-
if (matchedFiles.length > 0) {
|
|
52
|
-
await tar.create({
|
|
53
|
-
file: backupFile,
|
|
54
|
-
cwd: source,
|
|
55
|
-
gzip: true
|
|
56
|
-
}, matchedFiles.map(f => f.replace(`${source}/`, '')));
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
catch (tarError) {
|
|
60
|
-
console.warn(`Warning: Could not create tar backup: ${tarError instanceof Error ? tarError.message : 'Unknown error'}`);
|
|
61
|
-
}
|
|
62
|
-
// Clean up copied files in backup directory
|
|
63
|
-
try {
|
|
64
|
-
rmSync(backup, { recursive: true, force: true });
|
|
65
|
-
mkdirSync(backup, { recursive: true });
|
|
66
|
-
}
|
|
67
|
-
catch (cleanupError) {
|
|
68
|
-
console.warn(`Warning: Could not clean backup directory: ${cleanupError instanceof Error ? cleanupError.message : 'Unknown error'}`);
|
|
69
|
-
}
|
|
70
|
-
return true;
|
|
71
|
-
}
|
|
72
|
-
catch (error) {
|
|
73
|
-
throw new Error(`Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
export async function getFile(filename) {
|
|
77
|
-
try {
|
|
78
|
-
if (!filename || typeof filename !== 'string') {
|
|
79
|
-
throw new Error('Filename must be a non-empty string');
|
|
80
|
-
}
|
|
81
|
-
if (!existsSync(filename)) {
|
|
82
|
-
return false;
|
|
83
|
-
}
|
|
84
|
-
const fileContents = readFileSync(filename, "utf-8");
|
|
85
|
-
if (!fileContents.trim()) {
|
|
86
|
-
return {};
|
|
87
|
-
}
|
|
88
|
-
return JSON.parse(fileContents);
|
|
89
|
-
}
|
|
90
|
-
catch (error) {
|
|
91
|
-
if (error instanceof SyntaxError) {
|
|
92
|
-
throw new Error(`Invalid JSON in file '${filename}': ${error.message}`);
|
|
93
|
-
}
|
|
94
|
-
throw new Error(`Failed to read file '${filename}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
export async function updateFile(filename, data) {
|
|
98
|
-
let fd = null;
|
|
99
|
-
try {
|
|
100
|
-
if (!filename || typeof filename !== 'string') {
|
|
101
|
-
throw new Error('Filename must be a non-empty string');
|
|
102
|
-
}
|
|
103
|
-
if (data === undefined || data === null) {
|
|
104
|
-
throw new Error('Data cannot be null or undefined');
|
|
105
|
-
}
|
|
106
|
-
// Ensure file exists
|
|
107
|
-
if (!existsSync(filename)) {
|
|
108
|
-
writeFileSync(filename, "{}", { encoding: "utf8" });
|
|
109
|
-
}
|
|
110
|
-
// Acquire an exclusive lock on the file
|
|
111
|
-
fd = openSync(filename, "r+");
|
|
112
|
-
flockSync(fd, "ex");
|
|
113
|
-
// Read existing data with better error handling
|
|
114
|
-
let existingData = {};
|
|
115
|
-
try {
|
|
116
|
-
const fileContents = readFileSync(filename, "utf-8");
|
|
117
|
-
if (fileContents.trim()) {
|
|
118
|
-
// Validate JSON before parsing
|
|
119
|
-
const trimmedContent = fileContents.trim();
|
|
120
|
-
if (!trimmedContent.startsWith('{') && !trimmedContent.startsWith('[')) {
|
|
121
|
-
throw new Error('Invalid JSON format');
|
|
122
|
-
}
|
|
123
|
-
existingData = JSON.parse(trimmedContent);
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
catch (parseError) {
|
|
127
|
-
console.warn(`Warning: Could not parse existing data in '${filename}', starting with empty object`);
|
|
128
|
-
existingData = {};
|
|
129
|
-
}
|
|
130
|
-
// Deep merge data instead of shallow merge
|
|
131
|
-
const updatedData = deepMerge(existingData, data);
|
|
132
|
-
// Validate the merged data
|
|
133
|
-
const jsonString = JSON.stringify(updatedData, null, 2);
|
|
134
|
-
if (!jsonString || jsonString === 'undefined') {
|
|
135
|
-
throw new Error('Failed to serialize updated data');
|
|
136
|
-
}
|
|
137
|
-
// Write to temporary file first with atomic rename
|
|
138
|
-
const tmpFilename = `${filename}.tmp.${Date.now()}.${Math.random().toString(36).substr(2, 9)}`;
|
|
139
|
-
writeFileSync(tmpFilename, jsonString, { encoding: "utf8" });
|
|
140
|
-
// Verify the temporary file was written correctly
|
|
141
|
-
const verifyContent = readFileSync(tmpFilename, "utf-8");
|
|
142
|
-
if (verifyContent !== jsonString) {
|
|
143
|
-
unlinkSync(tmpFilename);
|
|
144
|
-
throw new Error('Temporary file verification failed');
|
|
145
|
-
}
|
|
146
|
-
// Atomic replace: truncate and write to original file
|
|
147
|
-
ftruncateSync(fd, 0);
|
|
148
|
-
writeFileSync(fd, jsonString, { encoding: "utf8" });
|
|
149
|
-
// Clean up temporary file
|
|
150
|
-
unlinkSync(tmpFilename);
|
|
151
|
-
}
|
|
152
|
-
catch (error) {
|
|
153
|
-
throw new Error(`Failed to update file '${filename}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
154
|
-
}
|
|
155
|
-
finally {
|
|
156
|
-
// Always release the file lock and close file descriptor
|
|
157
|
-
if (fd !== null) {
|
|
158
|
-
try {
|
|
159
|
-
flockSync(fd, "un");
|
|
160
|
-
closeSync(fd);
|
|
161
|
-
}
|
|
162
|
-
catch (closeError) {
|
|
163
|
-
console.warn(`Warning: Could not properly close file descriptor: ${closeError instanceof Error ? closeError.message : 'Unknown error'}`);
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
// Deep merge function to properly handle nested objects
|
|
169
|
-
function deepMerge(target, source) {
|
|
170
|
-
if (source === null || source === undefined) {
|
|
171
|
-
return target;
|
|
172
|
-
}
|
|
173
|
-
if (typeof source !== 'object' || Array.isArray(source)) {
|
|
174
|
-
return source;
|
|
175
|
-
}
|
|
176
|
-
if (typeof target !== 'object' || target === null || Array.isArray(target)) {
|
|
177
|
-
return source;
|
|
178
|
-
}
|
|
179
|
-
const result = { ...target };
|
|
180
|
-
for (const key in source) {
|
|
181
|
-
if (source.hasOwnProperty(key)) {
|
|
182
|
-
if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key]) &&
|
|
183
|
-
typeof target[key] === 'object' && target[key] !== null && !Array.isArray(target[key])) {
|
|
184
|
-
result[key] = deepMerge(target[key], source[key]);
|
|
185
|
-
}
|
|
186
|
-
else {
|
|
187
|
-
result[key] = source[key];
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
return result;
|
|
192
|
-
}
|
package/dist/transaction.js
DELETED
|
@@ -1,476 +0,0 @@
|
|
|
1
|
-
import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync } from "fs";
|
|
2
|
-
import { join } from "path";
|
|
3
|
-
import { randomUUID } from "crypto";
|
|
4
|
-
export class Transaction {
|
|
5
|
-
state;
|
|
6
|
-
config;
|
|
7
|
-
lockFiles = new Set();
|
|
8
|
-
timeoutHandle;
|
|
9
|
-
transactionDir;
|
|
10
|
-
committed = false;
|
|
11
|
-
rolledBack = false;
|
|
12
|
-
constructor(dbPath, config = {}) {
|
|
13
|
-
this.state = {
|
|
14
|
-
id: randomUUID(),
|
|
15
|
-
operations: [],
|
|
16
|
-
status: 'active',
|
|
17
|
-
startTime: Date.now(),
|
|
18
|
-
dbPath
|
|
19
|
-
};
|
|
20
|
-
this.config = {
|
|
21
|
-
timeout: config.timeout || 30000, // 30 seconds default
|
|
22
|
-
isolationLevel: config.isolationLevel || 'read_committed',
|
|
23
|
-
autoCommit: config.autoCommit || false
|
|
24
|
-
};
|
|
25
|
-
this.transactionDir = join(dbPath, '.transactions');
|
|
26
|
-
this.initializeTransaction();
|
|
27
|
-
}
|
|
28
|
-
initializeTransaction() {
|
|
29
|
-
try {
|
|
30
|
-
// Create transactions directory if it doesn't exist
|
|
31
|
-
if (!existsSync(this.transactionDir)) {
|
|
32
|
-
mkdirSync(this.transactionDir, { recursive: true });
|
|
33
|
-
}
|
|
34
|
-
// Set up transaction timeout
|
|
35
|
-
if (this.config.timeout && this.config.timeout > 0) {
|
|
36
|
-
this.timeoutHandle = setTimeout(() => {
|
|
37
|
-
this.handleTimeout();
|
|
38
|
-
}, this.config.timeout);
|
|
39
|
-
}
|
|
40
|
-
// Save initial transaction state
|
|
41
|
-
this.saveTransactionState();
|
|
42
|
-
console.log(`đ Transaction ${this.state.id} started`);
|
|
43
|
-
}
|
|
44
|
-
catch (error) {
|
|
45
|
-
throw new Error(`Failed to initialize transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
async handleTimeout() {
|
|
49
|
-
console.warn(`â° Transaction ${this.state.id} timed out after ${this.config.timeout}ms`);
|
|
50
|
-
try {
|
|
51
|
-
await this.rollback();
|
|
52
|
-
}
|
|
53
|
-
catch (error) {
|
|
54
|
-
console.error(`Failed to rollback timed out transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
saveTransactionState() {
|
|
58
|
-
try {
|
|
59
|
-
const statePath = join(this.transactionDir, `${this.state.id}.json`);
|
|
60
|
-
writeFileSync(statePath, JSON.stringify(this.state, null, 2));
|
|
61
|
-
}
|
|
62
|
-
catch (error) {
|
|
63
|
-
console.warn(`Failed to save transaction state: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
validateKey(key) {
|
|
67
|
-
if (!key || typeof key !== 'string') {
|
|
68
|
-
throw new Error('Key must be a non-empty string');
|
|
69
|
-
}
|
|
70
|
-
if (key.includes('..') || key.includes('/') || key.includes('\\')) {
|
|
71
|
-
throw new Error('Key contains invalid characters');
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
getFilePath(key) {
|
|
75
|
-
return join(this.state.dbPath, `${key}.json`);
|
|
76
|
-
}
|
|
77
|
-
getLockFilePath(key) {
|
|
78
|
-
return join(this.transactionDir, `${key}.lock`);
|
|
79
|
-
}
|
|
80
|
-
acquireLock(key) {
|
|
81
|
-
try {
|
|
82
|
-
const lockPath = this.getLockFilePath(key);
|
|
83
|
-
// Check if already locked by another transaction
|
|
84
|
-
if (existsSync(lockPath)) {
|
|
85
|
-
const lockData = JSON.parse(readFileSync(lockPath, 'utf-8'));
|
|
86
|
-
if (lockData.transactionId !== this.state.id) {
|
|
87
|
-
return false; // Lock held by another transaction
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
// Acquire lock
|
|
91
|
-
const lockData = {
|
|
92
|
-
transactionId: this.state.id,
|
|
93
|
-
timestamp: Date.now(),
|
|
94
|
-
key
|
|
95
|
-
};
|
|
96
|
-
writeFileSync(lockPath, JSON.stringify(lockData));
|
|
97
|
-
this.lockFiles.add(key);
|
|
98
|
-
return true;
|
|
99
|
-
}
|
|
100
|
-
catch (error) {
|
|
101
|
-
return false;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
releaseLock(key) {
|
|
105
|
-
try {
|
|
106
|
-
const lockPath = this.getLockFilePath(key);
|
|
107
|
-
if (existsSync(lockPath)) {
|
|
108
|
-
unlinkSync(lockPath);
|
|
109
|
-
}
|
|
110
|
-
this.lockFiles.delete(key);
|
|
111
|
-
}
|
|
112
|
-
catch (error) {
|
|
113
|
-
console.warn(`Failed to release lock for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
releaseAllLocks() {
|
|
117
|
-
for (const key of this.lockFiles) {
|
|
118
|
-
this.releaseLock(key);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
readCurrentData(key) {
|
|
122
|
-
try {
|
|
123
|
-
const filePath = this.getFilePath(key);
|
|
124
|
-
if (!existsSync(filePath)) {
|
|
125
|
-
return null;
|
|
126
|
-
}
|
|
127
|
-
const content = readFileSync(filePath, 'utf-8');
|
|
128
|
-
return content.trim() ? JSON.parse(content) : {};
|
|
129
|
-
}
|
|
130
|
-
catch (error) {
|
|
131
|
-
return null;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
ensureNotFinalized() {
|
|
135
|
-
if (this.committed) {
|
|
136
|
-
throw new Error('Transaction has already been committed');
|
|
137
|
-
}
|
|
138
|
-
if (this.rolledBack) {
|
|
139
|
-
throw new Error('Transaction has already been rolled back');
|
|
140
|
-
}
|
|
141
|
-
if (this.state.status !== 'active') {
|
|
142
|
-
throw new Error(`Transaction is not active (status: ${this.state.status})`);
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
async create(key) {
|
|
146
|
-
try {
|
|
147
|
-
this.ensureNotFinalized();
|
|
148
|
-
this.validateKey(key);
|
|
149
|
-
// Acquire lock
|
|
150
|
-
if (!this.acquireLock(key)) {
|
|
151
|
-
throw new Error(`Cannot acquire lock for key '${key}' - may be locked by another transaction`);
|
|
152
|
-
}
|
|
153
|
-
// Check if file already exists
|
|
154
|
-
const filePath = this.getFilePath(key);
|
|
155
|
-
if (existsSync(filePath)) {
|
|
156
|
-
throw new Error(`Document '${key}' already exists`);
|
|
157
|
-
}
|
|
158
|
-
// Record operation
|
|
159
|
-
const operation = {
|
|
160
|
-
type: 'create',
|
|
161
|
-
key,
|
|
162
|
-
data: {},
|
|
163
|
-
timestamp: Date.now()
|
|
164
|
-
};
|
|
165
|
-
this.state.operations.push(operation);
|
|
166
|
-
this.saveTransactionState();
|
|
167
|
-
console.log(`đ Transaction ${this.state.id}: Queued create operation for '${key}'`);
|
|
168
|
-
}
|
|
169
|
-
catch (error) {
|
|
170
|
-
throw new Error(`Transaction create failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
async update(key, data) {
|
|
174
|
-
try {
|
|
175
|
-
this.ensureNotFinalized();
|
|
176
|
-
this.validateKey(key);
|
|
177
|
-
if (data === undefined || data === null) {
|
|
178
|
-
throw new Error('Data cannot be null or undefined');
|
|
179
|
-
}
|
|
180
|
-
// Acquire lock
|
|
181
|
-
if (!this.acquireLock(key)) {
|
|
182
|
-
throw new Error(`Cannot acquire lock for key '${key}' - may be locked by another transaction`);
|
|
183
|
-
}
|
|
184
|
-
// Read current data for rollback
|
|
185
|
-
const originalData = this.readCurrentData(key);
|
|
186
|
-
// Record operation
|
|
187
|
-
const operation = {
|
|
188
|
-
type: 'update',
|
|
189
|
-
key,
|
|
190
|
-
data,
|
|
191
|
-
originalData,
|
|
192
|
-
timestamp: Date.now()
|
|
193
|
-
};
|
|
194
|
-
this.state.operations.push(operation);
|
|
195
|
-
this.saveTransactionState();
|
|
196
|
-
console.log(`âī¸ Transaction ${this.state.id}: Queued update operation for '${key}'`);
|
|
197
|
-
}
|
|
198
|
-
catch (error) {
|
|
199
|
-
throw new Error(`Transaction update failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
async delete(key) {
|
|
203
|
-
try {
|
|
204
|
-
this.ensureNotFinalized();
|
|
205
|
-
this.validateKey(key);
|
|
206
|
-
// Acquire lock
|
|
207
|
-
if (!this.acquireLock(key)) {
|
|
208
|
-
throw new Error(`Cannot acquire lock for key '${key}' - may be locked by another transaction`);
|
|
209
|
-
}
|
|
210
|
-
// Read current data for rollback
|
|
211
|
-
const originalData = this.readCurrentData(key);
|
|
212
|
-
if (originalData === null) {
|
|
213
|
-
throw new Error(`Document '${key}' does not exist`);
|
|
214
|
-
}
|
|
215
|
-
// Record operation
|
|
216
|
-
const operation = {
|
|
217
|
-
type: 'delete',
|
|
218
|
-
key,
|
|
219
|
-
originalData,
|
|
220
|
-
timestamp: Date.now()
|
|
221
|
-
};
|
|
222
|
-
this.state.operations.push(operation);
|
|
223
|
-
this.saveTransactionState();
|
|
224
|
-
console.log(`đī¸ Transaction ${this.state.id}: Queued delete operation for '${key}'`);
|
|
225
|
-
}
|
|
226
|
-
catch (error) {
|
|
227
|
-
throw new Error(`Transaction delete failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
async get(key) {
|
|
231
|
-
try {
|
|
232
|
-
this.ensureNotFinalized();
|
|
233
|
-
this.validateKey(key);
|
|
234
|
-
// Check if there's a pending operation for this key in the transaction
|
|
235
|
-
const pendingOps = this.state.operations.filter(op => op.key === key);
|
|
236
|
-
if (pendingOps.length > 0) {
|
|
237
|
-
const lastOp = pendingOps[pendingOps.length - 1];
|
|
238
|
-
switch (lastOp.type) {
|
|
239
|
-
case 'create':
|
|
240
|
-
return lastOp.data || {};
|
|
241
|
-
case 'update':
|
|
242
|
-
// Merge original data with updates
|
|
243
|
-
const original = lastOp.originalData || {};
|
|
244
|
-
return { ...original, ...lastOp.data };
|
|
245
|
-
case 'delete':
|
|
246
|
-
return null; // Document will be deleted
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
// Read from disk (current committed state)
|
|
250
|
-
return this.readCurrentData(key);
|
|
251
|
-
}
|
|
252
|
-
catch (error) {
|
|
253
|
-
throw new Error(`Transaction get failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
async commit() {
|
|
257
|
-
try {
|
|
258
|
-
this.ensureNotFinalized();
|
|
259
|
-
if (this.timeoutHandle) {
|
|
260
|
-
clearTimeout(this.timeoutHandle);
|
|
261
|
-
}
|
|
262
|
-
console.log(`đž Committing transaction ${this.state.id} with ${this.state.operations.length} operations...`);
|
|
263
|
-
// Apply all operations atomically
|
|
264
|
-
const appliedOperations = [];
|
|
265
|
-
try {
|
|
266
|
-
for (const operation of this.state.operations) {
|
|
267
|
-
const filePath = this.getFilePath(operation.key);
|
|
268
|
-
switch (operation.type) {
|
|
269
|
-
case 'create':
|
|
270
|
-
writeFileSync(filePath, JSON.stringify(operation.data || {}, null, 2));
|
|
271
|
-
appliedOperations.push(`create:${operation.key}`);
|
|
272
|
-
break;
|
|
273
|
-
case 'update':
|
|
274
|
-
// Use the original data that was captured when the operation was queued
|
|
275
|
-
const baseData = operation.originalData || {};
|
|
276
|
-
const updatedData = { ...baseData, ...operation.data };
|
|
277
|
-
writeFileSync(filePath, JSON.stringify(updatedData, null, 2));
|
|
278
|
-
appliedOperations.push(`update:${operation.key}`);
|
|
279
|
-
break;
|
|
280
|
-
case 'delete':
|
|
281
|
-
if (existsSync(filePath)) {
|
|
282
|
-
unlinkSync(filePath);
|
|
283
|
-
}
|
|
284
|
-
appliedOperations.push(`delete:${operation.key}`);
|
|
285
|
-
break;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
// Mark as committed
|
|
289
|
-
this.state.status = 'committed';
|
|
290
|
-
this.state.endTime = Date.now();
|
|
291
|
-
this.committed = true;
|
|
292
|
-
this.saveTransactionState();
|
|
293
|
-
this.releaseAllLocks();
|
|
294
|
-
const duration = this.state.endTime - this.state.startTime;
|
|
295
|
-
console.log(`â
Transaction ${this.state.id} committed successfully in ${duration}ms`);
|
|
296
|
-
}
|
|
297
|
-
catch (error) {
|
|
298
|
-
// Rollback applied operations
|
|
299
|
-
console.error(`â Error during commit, rolling back applied operations...`);
|
|
300
|
-
await this.rollbackAppliedOperations(appliedOperations);
|
|
301
|
-
throw error;
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
catch (error) {
|
|
305
|
-
this.state.status = 'failed';
|
|
306
|
-
this.state.endTime = Date.now();
|
|
307
|
-
this.saveTransactionState();
|
|
308
|
-
this.releaseAllLocks();
|
|
309
|
-
throw new Error(`Transaction commit failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
async rollbackAppliedOperations(appliedOperations) {
|
|
313
|
-
for (const opString of appliedOperations.reverse()) {
|
|
314
|
-
try {
|
|
315
|
-
const [type, key] = opString.split(':');
|
|
316
|
-
const operation = this.state.operations.find(op => op.key === key && op.type === type);
|
|
317
|
-
if (!operation)
|
|
318
|
-
continue;
|
|
319
|
-
const filePath = this.getFilePath(key);
|
|
320
|
-
switch (type) {
|
|
321
|
-
case 'create':
|
|
322
|
-
if (existsSync(filePath)) {
|
|
323
|
-
unlinkSync(filePath);
|
|
324
|
-
}
|
|
325
|
-
break;
|
|
326
|
-
case 'update':
|
|
327
|
-
if (operation.originalData !== null) {
|
|
328
|
-
writeFileSync(filePath, JSON.stringify(operation.originalData, null, 2));
|
|
329
|
-
}
|
|
330
|
-
else if (existsSync(filePath)) {
|
|
331
|
-
unlinkSync(filePath);
|
|
332
|
-
}
|
|
333
|
-
break;
|
|
334
|
-
case 'delete':
|
|
335
|
-
if (operation.originalData) {
|
|
336
|
-
writeFileSync(filePath, JSON.stringify(operation.originalData, null, 2));
|
|
337
|
-
}
|
|
338
|
-
break;
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
catch (error) {
|
|
342
|
-
console.warn(`Failed to rollback operation ${opString}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
async rollback() {
|
|
347
|
-
try {
|
|
348
|
-
if (this.committed) {
|
|
349
|
-
throw new Error('Cannot rollback a committed transaction');
|
|
350
|
-
}
|
|
351
|
-
if (this.timeoutHandle) {
|
|
352
|
-
clearTimeout(this.timeoutHandle);
|
|
353
|
-
}
|
|
354
|
-
console.log(`đ Rolling back transaction ${this.state.id}...`);
|
|
355
|
-
this.state.status = 'rolled_back';
|
|
356
|
-
this.state.endTime = Date.now();
|
|
357
|
-
this.rolledBack = true;
|
|
358
|
-
this.saveTransactionState();
|
|
359
|
-
this.releaseAllLocks();
|
|
360
|
-
const duration = this.state.endTime - this.state.startTime;
|
|
361
|
-
console.log(`âŠī¸ Transaction ${this.state.id} rolled back in ${duration}ms`);
|
|
362
|
-
}
|
|
363
|
-
catch (error) {
|
|
364
|
-
this.state.status = 'failed';
|
|
365
|
-
this.state.endTime = Date.now();
|
|
366
|
-
this.saveTransactionState();
|
|
367
|
-
this.releaseAllLocks();
|
|
368
|
-
throw new Error(`Transaction rollback failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
getState() {
|
|
372
|
-
return { ...this.state };
|
|
373
|
-
}
|
|
374
|
-
getId() {
|
|
375
|
-
return this.state.id;
|
|
376
|
-
}
|
|
377
|
-
getOperationCount() {
|
|
378
|
-
return this.state.operations.length;
|
|
379
|
-
}
|
|
380
|
-
isActive() {
|
|
381
|
-
return this.state.status === 'active' && !this.committed && !this.rolledBack;
|
|
382
|
-
}
|
|
383
|
-
isCommitted() {
|
|
384
|
-
return this.committed;
|
|
385
|
-
}
|
|
386
|
-
isRolledBack() {
|
|
387
|
-
return this.rolledBack;
|
|
388
|
-
}
|
|
389
|
-
getDuration() {
|
|
390
|
-
const endTime = this.state.endTime || Date.now();
|
|
391
|
-
return endTime - this.state.startTime;
|
|
392
|
-
}
|
|
393
|
-
// Cleanup method
|
|
394
|
-
destroy() {
|
|
395
|
-
if (this.timeoutHandle) {
|
|
396
|
-
clearTimeout(this.timeoutHandle);
|
|
397
|
-
}
|
|
398
|
-
if (this.isActive()) {
|
|
399
|
-
console.warn(`â ī¸ Destroying active transaction ${this.state.id}, performing rollback...`);
|
|
400
|
-
this.rollback().catch(error => {
|
|
401
|
-
console.error(`Failed to rollback during destroy: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
402
|
-
});
|
|
403
|
-
}
|
|
404
|
-
this.releaseAllLocks();
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
export class TransactionManager {
|
|
408
|
-
activeTransactions = new Map();
|
|
409
|
-
dbPath;
|
|
410
|
-
constructor(dbPath) {
|
|
411
|
-
this.dbPath = dbPath;
|
|
412
|
-
}
|
|
413
|
-
beginTransaction(config) {
|
|
414
|
-
try {
|
|
415
|
-
const transaction = new Transaction(this.dbPath, config);
|
|
416
|
-
this.activeTransactions.set(transaction.getId(), transaction);
|
|
417
|
-
console.log(`đ Started transaction ${transaction.getId()}`);
|
|
418
|
-
return transaction;
|
|
419
|
-
}
|
|
420
|
-
catch (error) {
|
|
421
|
-
throw new Error(`Failed to begin transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
getTransaction(id) {
|
|
425
|
-
return this.activeTransactions.get(id);
|
|
426
|
-
}
|
|
427
|
-
getActiveTransactions() {
|
|
428
|
-
return Array.from(this.activeTransactions.values()).filter(tx => tx.isActive());
|
|
429
|
-
}
|
|
430
|
-
async commitTransaction(id) {
|
|
431
|
-
const transaction = this.activeTransactions.get(id);
|
|
432
|
-
if (!transaction) {
|
|
433
|
-
throw new Error(`Transaction ${id} not found`);
|
|
434
|
-
}
|
|
435
|
-
await transaction.commit();
|
|
436
|
-
this.activeTransactions.delete(id);
|
|
437
|
-
}
|
|
438
|
-
async rollbackTransaction(id) {
|
|
439
|
-
const transaction = this.activeTransactions.get(id);
|
|
440
|
-
if (!transaction) {
|
|
441
|
-
throw new Error(`Transaction ${id} not found`);
|
|
442
|
-
}
|
|
443
|
-
await transaction.rollback();
|
|
444
|
-
this.activeTransactions.delete(id);
|
|
445
|
-
}
|
|
446
|
-
async rollbackAllTransactions() {
|
|
447
|
-
const rollbackPromises = Array.from(this.activeTransactions.values()).map(async (tx) => {
|
|
448
|
-
try {
|
|
449
|
-
if (tx.isActive()) {
|
|
450
|
-
await tx.rollback();
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
catch (error) {
|
|
454
|
-
console.error(`Failed to rollback transaction ${tx.getId()}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
455
|
-
}
|
|
456
|
-
});
|
|
457
|
-
await Promise.all(rollbackPromises);
|
|
458
|
-
this.activeTransactions.clear();
|
|
459
|
-
}
|
|
460
|
-
getStats() {
|
|
461
|
-
const transactions = Array.from(this.activeTransactions.values());
|
|
462
|
-
return {
|
|
463
|
-
active: transactions.filter(tx => tx.isActive()).length,
|
|
464
|
-
total: transactions.length,
|
|
465
|
-
committed: transactions.filter(tx => tx.isCommitted()).length,
|
|
466
|
-
rolledBack: transactions.filter(tx => tx.isRolledBack()).length
|
|
467
|
-
};
|
|
468
|
-
}
|
|
469
|
-
// Cleanup method
|
|
470
|
-
destroy() {
|
|
471
|
-
console.log('đ Destroying TransactionManager, rolling back all active transactions...');
|
|
472
|
-
this.rollbackAllTransactions().catch(error => {
|
|
473
|
-
console.error(`Failed to rollback all transactions during destroy: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
474
|
-
});
|
|
475
|
-
}
|
|
476
|
-
}
|