tero 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,450 @@
1
+ import { existsSync, mkdirSync } from "fs";
2
+ import { ACIDStorageEngine } from "./acid-engine.js";
3
+ import { SchemaValidator } from "./schema.js";
4
+ import { BackupManager } from "./backup.js";
5
+ import { DataRecovery } from "./recovery.js";
6
+ export class Tero {
7
+ teroDirectory = "TeroDB";
8
+ cacheSize = 100;
9
+ cache = new Map();
10
+ cacheHits = 0;
11
+ cacheRequests = 0;
12
+ acidEngine;
13
+ schemaValidator;
14
+ backupManager;
15
+ dataRecovery;
16
+ constructor(config) {
17
+ try {
18
+ const { directory, cacheSize } = config || {};
19
+ if (typeof directory === "string" && directory.trim()) {
20
+ // Sanitize directory path to prevent directory traversal
21
+ this.teroDirectory = directory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
22
+ }
23
+ if (typeof cacheSize === "number" && cacheSize > 0) {
24
+ this.cacheSize = Math.min(cacheSize, 10000); // Cap at 10k entries
25
+ }
26
+ // Create directories with proper error handling
27
+ this.initializeDirectories();
28
+ // Initialize ACID storage engine (primary system)
29
+ this.acidEngine = new ACIDStorageEngine(this.teroDirectory);
30
+ // Initialize schema validator
31
+ this.schemaValidator = new SchemaValidator();
32
+ }
33
+ catch (error) {
34
+ throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`);
35
+ }
36
+ }
37
+ initializeDirectories() {
38
+ try {
39
+ if (!existsSync(this.teroDirectory)) {
40
+ mkdirSync(this.teroDirectory, { recursive: true });
41
+ }
42
+ const backupDir = `${this.teroDirectory}/.backup`;
43
+ if (!existsSync(backupDir)) {
44
+ mkdirSync(backupDir, { recursive: true });
45
+ }
46
+ }
47
+ catch (error) {
48
+ throw new Error(`Failed to create directories: ${error instanceof Error ? error.message : 'Unknown error'}`);
49
+ }
50
+ }
51
+ validateKey(key) {
52
+ if (!key || typeof key !== 'string') {
53
+ throw new Error('Key must be a non-empty string');
54
+ }
55
+ // Sanitize key to prevent path traversal
56
+ if (key.includes('..') || key.includes('/') || key.includes('\\')) {
57
+ throw new Error('Key contains invalid characters');
58
+ }
59
+ }
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
+ invalidateCacheKeys(keys) {
76
+ for (const key of keys) {
77
+ this.cache.delete(key);
78
+ }
79
+ }
80
+ updateCache(key, data, transactionId) {
81
+ if (this.cache.size >= this.cacheSize) {
82
+ this.evictOldestCacheEntry();
83
+ }
84
+ this.cache.set(key, {
85
+ data: { ...data },
86
+ lastAccessed: Date.now(),
87
+ transactionId
88
+ });
89
+ }
90
+ // Core ACID Operations
91
+ beginTransaction() {
92
+ try {
93
+ return this.acidEngine.beginTransaction();
94
+ }
95
+ catch (error) {
96
+ throw new Error(`Failed to begin transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
97
+ }
98
+ }
99
+ async write(transactionId, key, data, options) {
100
+ try {
101
+ this.validateKey(key);
102
+ if (data === undefined || data === null) {
103
+ throw new Error('Data cannot be null or undefined');
104
+ }
105
+ // Perform schema validation if requested
106
+ if (options?.validate || options?.schemaName) {
107
+ const schemaName = options.schemaName || key;
108
+ const validationResult = this.schemaValidator.validate(schemaName, data);
109
+ if (!validationResult.valid) {
110
+ if (options.strict) {
111
+ const errorMessages = validationResult.errors.map(e => `${e.field}: ${e.message}`).join(', ');
112
+ throw new Error(`Schema validation failed: ${errorMessages}`);
113
+ }
114
+ else {
115
+ return validationResult;
116
+ }
117
+ }
118
+ // Use sanitized data from validation
119
+ data = validationResult.data || data;
120
+ }
121
+ await this.acidEngine.write(transactionId, key, data);
122
+ // Update cache with transaction context
123
+ this.updateCache(key, data, transactionId);
124
+ if (options?.validate || options?.schemaName) {
125
+ return { valid: true, errors: [], data };
126
+ }
127
+ }
128
+ catch (error) {
129
+ throw new Error(`Write failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
130
+ }
131
+ }
132
+ async read(transactionId, key) {
133
+ try {
134
+ this.validateKey(key);
135
+ this.cacheRequests++;
136
+ // Check cache first, but only if it's from the same transaction or committed
137
+ const cachedEntry = this.cache.get(key);
138
+ if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) {
139
+ this.cacheHits++;
140
+ cachedEntry.lastAccessed = Date.now();
141
+ return cachedEntry.data;
142
+ }
143
+ // Read from ACID engine
144
+ const data = await this.acidEngine.read(transactionId, key);
145
+ if (data !== null) {
146
+ this.updateCache(key, data, transactionId);
147
+ }
148
+ return data;
149
+ }
150
+ catch (error) {
151
+ throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
152
+ }
153
+ }
154
+ async delete(transactionId, key) {
155
+ try {
156
+ this.validateKey(key);
157
+ await this.acidEngine.delete(transactionId, key);
158
+ // Remove from cache
159
+ this.cache.delete(key);
160
+ }
161
+ catch (error) {
162
+ throw new Error(`Delete failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
163
+ }
164
+ }
165
+ async commit(transactionId) {
166
+ try {
167
+ // Get affected keys before commit
168
+ const transaction = this.acidEngine.getActiveTransactions().includes(transactionId);
169
+ if (!transaction) {
170
+ throw new Error(`Transaction ${transactionId} not found or not active`);
171
+ }
172
+ await this.acidEngine.commitTransaction(transactionId);
173
+ // Clean up cache entries for this transaction
174
+ for (const [key, entry] of this.cache.entries()) {
175
+ if (entry.transactionId === transactionId) {
176
+ // Remove transaction ID to mark as committed
177
+ entry.transactionId = undefined;
178
+ }
179
+ }
180
+ }
181
+ catch (error) {
182
+ throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
183
+ }
184
+ }
185
+ async rollback(transactionId) {
186
+ try {
187
+ await this.acidEngine.rollbackTransaction(transactionId);
188
+ // Remove cache entries for this transaction
189
+ const keysToRemove = [];
190
+ for (const [key, entry] of this.cache.entries()) {
191
+ if (entry.transactionId === transactionId) {
192
+ keysToRemove.push(key);
193
+ }
194
+ }
195
+ this.invalidateCacheKeys(keysToRemove);
196
+ }
197
+ catch (error) {
198
+ throw new Error(`Failed to rollback transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
199
+ }
200
+ }
201
+ // Convenience Methods (Auto-transaction)
202
+ async create(key, initialData, options) {
203
+ const transactionId = this.beginTransaction();
204
+ try {
205
+ // Check if file already exists
206
+ const existing = await this.read(transactionId, key);
207
+ if (existing !== null) {
208
+ await this.rollback(transactionId);
209
+ return false; // File already exists
210
+ }
211
+ // Create with initial data or empty object
212
+ const result = await this.write(transactionId, key, initialData || {}, options);
213
+ await this.commit(transactionId);
214
+ return result || true;
215
+ }
216
+ catch (error) {
217
+ await this.rollback(transactionId);
218
+ throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
219
+ }
220
+ }
221
+ async update(key, data, options) {
222
+ const transactionId = this.beginTransaction();
223
+ try {
224
+ const result = await this.write(transactionId, key, data, options);
225
+ await this.commit(transactionId);
226
+ return result;
227
+ }
228
+ catch (error) {
229
+ await this.rollback(transactionId);
230
+ throw error;
231
+ }
232
+ }
233
+ async get(key) {
234
+ const transactionId = this.beginTransaction();
235
+ try {
236
+ const data = await this.read(transactionId, key);
237
+ await this.commit(transactionId);
238
+ return data;
239
+ }
240
+ catch (error) {
241
+ await this.rollback(transactionId);
242
+ throw error;
243
+ }
244
+ }
245
+ async remove(key) {
246
+ const transactionId = this.beginTransaction();
247
+ try {
248
+ await this.delete(transactionId, key);
249
+ await this.commit(transactionId);
250
+ }
251
+ catch (error) {
252
+ await this.rollback(transactionId);
253
+ throw error;
254
+ }
255
+ }
256
+ exists(key) {
257
+ try {
258
+ this.validateKey(key);
259
+ return existsSync(`${this.teroDirectory}/${key}.json`);
260
+ }
261
+ catch (error) {
262
+ return false;
263
+ }
264
+ }
265
+ // Batch Operations
266
+ async batchWrite(operations, options) {
267
+ const transactionId = this.beginTransaction();
268
+ try {
269
+ for (const op of operations) {
270
+ await this.write(transactionId, op.key, op.data, options);
271
+ }
272
+ await this.commit(transactionId);
273
+ }
274
+ catch (error) {
275
+ await this.rollback(transactionId);
276
+ throw new Error(`Batch write failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
277
+ }
278
+ }
279
+ async batchRead(keys) {
280
+ const transactionId = this.beginTransaction();
281
+ const results = {};
282
+ try {
283
+ for (const key of keys) {
284
+ results[key] = await this.read(transactionId, key);
285
+ }
286
+ await this.commit(transactionId);
287
+ return results;
288
+ }
289
+ catch (error) {
290
+ await this.rollback(transactionId);
291
+ throw new Error(`Batch read failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
292
+ }
293
+ }
294
+ // Money transfer example demonstrating ACID properties
295
+ async transferMoney(fromKey, toKey, amount) {
296
+ if (amount <= 0) {
297
+ throw new Error('Transfer amount must be positive');
298
+ }
299
+ const transactionId = this.beginTransaction();
300
+ try {
301
+ // Read current balances
302
+ const fromAccount = await this.read(transactionId, fromKey);
303
+ const toAccount = await this.read(transactionId, toKey);
304
+ if (!fromAccount || !toAccount) {
305
+ throw new Error('One or both accounts do not exist');
306
+ }
307
+ if (fromAccount.balance < amount) {
308
+ throw new Error('Insufficient funds');
309
+ }
310
+ // Update balances
311
+ await this.write(transactionId, fromKey, {
312
+ ...fromAccount,
313
+ balance: fromAccount.balance - amount
314
+ });
315
+ await this.write(transactionId, toKey, {
316
+ ...toAccount,
317
+ balance: toAccount.balance + amount
318
+ });
319
+ // Commit the transaction
320
+ await this.commit(transactionId);
321
+ }
322
+ catch (error) {
323
+ await this.rollback(transactionId);
324
+ throw new Error(`Money transfer failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
325
+ }
326
+ }
327
+ // Schema Management
328
+ setSchema(collectionName, schema) {
329
+ try {
330
+ this.schemaValidator.setSchema(collectionName, schema);
331
+ }
332
+ catch (error) {
333
+ throw new Error(`Failed to set schema: ${error instanceof Error ? error.message : 'Unknown error'}`);
334
+ }
335
+ }
336
+ getSchema(collectionName) {
337
+ return this.schemaValidator.getSchema(collectionName);
338
+ }
339
+ removeSchema(collectionName) {
340
+ return this.schemaValidator.removeSchema(collectionName);
341
+ }
342
+ validateData(collectionName, data) {
343
+ return this.schemaValidator.validate(collectionName, data);
344
+ }
345
+ // Backup Management
346
+ configureBackup(config) {
347
+ try {
348
+ this.backupManager = new BackupManager(this.teroDirectory, config);
349
+ }
350
+ catch (error) {
351
+ throw new Error(`Failed to configure backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
352
+ }
353
+ }
354
+ async performBackup() {
355
+ if (!this.backupManager) {
356
+ throw new Error('Backup not configured. Call configureBackup() first.');
357
+ }
358
+ return await this.backupManager.performBackup();
359
+ }
360
+ // Data Recovery
361
+ configureDataRecovery(config) {
362
+ try {
363
+ this.dataRecovery = new DataRecovery(config);
364
+ }
365
+ catch (error) {
366
+ throw new Error(`Failed to configure data recovery: ${error instanceof Error ? error.message : 'Unknown error'}`);
367
+ }
368
+ }
369
+ async recoverFromCloud(key) {
370
+ if (!this.dataRecovery) {
371
+ throw new Error('Data recovery not configured. Call configureDataRecovery() first.');
372
+ }
373
+ const recovered = await this.dataRecovery.recoverSingleFile(key);
374
+ if (recovered) {
375
+ this.cache.delete(key); // Invalidate cache
376
+ }
377
+ return recovered;
378
+ }
379
+ async recoverAllFromCloud() {
380
+ if (!this.dataRecovery) {
381
+ throw new Error('Data recovery not configured. Call configureDataRecovery() first.');
382
+ }
383
+ const result = await this.dataRecovery.recoverIndividualFiles();
384
+ // Clear cache for recovered files
385
+ if (result.recovered.length > 0) {
386
+ this.invalidateCacheKeys(result.recovered);
387
+ }
388
+ return result;
389
+ }
390
+ // Utility Methods
391
+ getCacheStats() {
392
+ const hitRate = this.cacheRequests > 0 ? (this.cacheHits / this.cacheRequests) * 100 : 0;
393
+ return {
394
+ size: this.cache.size,
395
+ maxSize: this.cacheSize,
396
+ hitRate: Math.round(hitRate * 100) / 100
397
+ };
398
+ }
399
+ getActiveTransactions() {
400
+ return this.acidEngine.getActiveTransactions();
401
+ }
402
+ forceCheckpoint() {
403
+ this.acidEngine.forceCheckpoint();
404
+ }
405
+ async verifyDataIntegrity() {
406
+ const result = {
407
+ totalFiles: 0,
408
+ corruptedFiles: [],
409
+ missingFiles: [],
410
+ healthy: true
411
+ };
412
+ try {
413
+ const { readdirSync } = await import('fs');
414
+ const files = readdirSync(this.teroDirectory)
415
+ .filter((file) => file.endsWith('.json'));
416
+ result.totalFiles = files.length;
417
+ for (const file of files) {
418
+ const key = file.replace('.json', '');
419
+ try {
420
+ const data = await this.get(key);
421
+ if (data === null) {
422
+ result.missingFiles.push(key);
423
+ result.healthy = false;
424
+ }
425
+ }
426
+ catch (error) {
427
+ result.corruptedFiles.push(key);
428
+ result.healthy = false;
429
+ }
430
+ }
431
+ return result;
432
+ }
433
+ catch (error) {
434
+ throw new Error(`Data integrity verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
435
+ }
436
+ }
437
+ clearCache() {
438
+ this.cache.clear();
439
+ }
440
+ // Cleanup method
441
+ destroy() {
442
+ if (this.acidEngine) {
443
+ this.acidEngine.destroy();
444
+ }
445
+ if (this.backupManager) {
446
+ this.backupManager.destroy();
447
+ }
448
+ this.clearCache();
449
+ }
450
+ }