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.
@@ -0,0 +1,628 @@
1
+ import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync, statSync } from "fs";
2
+ import { join, dirname } from "path";
3
+ import { randomUUID } from "crypto";
4
+ import { createHash } from "crypto";
5
+ // Write-Ahead Log (WAL) implementation
6
+ export class WriteAheadLog {
7
+ logPath;
8
+ currentLSN = 0;
9
+ logBuffer = [];
10
+ BUFFER_SIZE = 100;
11
+ LOG_FILE_SIZE_LIMIT = 10 * 1024 * 1024; // 10MB
12
+ constructor(dbPath) {
13
+ this.logPath = join(dbPath, '.wal');
14
+ this.initializeWAL();
15
+ }
16
+ initializeWAL() {
17
+ if (!existsSync(dirname(this.logPath))) {
18
+ mkdirSync(dirname(this.logPath), { recursive: true });
19
+ }
20
+ // Recovery: read existing log and determine next LSN
21
+ if (existsSync(this.logPath)) {
22
+ this.recoverFromLog();
23
+ }
24
+ }
25
+ recoverFromLog() {
26
+ try {
27
+ const logContent = readFileSync(this.logPath, 'utf-8');
28
+ const lines = logContent.trim().split('\n').filter(line => line.trim());
29
+ for (const line of lines) {
30
+ try {
31
+ const entry = JSON.parse(line);
32
+ if (this.verifyChecksum(entry)) {
33
+ this.currentLSN = Math.max(this.currentLSN, entry.lsn);
34
+ }
35
+ }
36
+ catch (error) {
37
+ // Skip corrupted entries silently
38
+ continue;
39
+ }
40
+ }
41
+ this.currentLSN++; // Next LSN
42
+ }
43
+ catch (error) {
44
+ this.currentLSN = 1;
45
+ }
46
+ }
47
+ calculateChecksum(entry) {
48
+ const data = JSON.stringify(entry);
49
+ return createHash('sha256').update(data).digest('hex');
50
+ }
51
+ verifyChecksum(entry) {
52
+ const { checksum, ...entryWithoutChecksum } = entry;
53
+ const calculatedChecksum = this.calculateChecksum(entryWithoutChecksum);
54
+ return calculatedChecksum === checksum;
55
+ }
56
+ writeLog(entry) {
57
+ const lsn = this.currentLSN++;
58
+ const entryWithoutChecksum = {
59
+ ...entry,
60
+ lsn,
61
+ timestamp: Date.now()
62
+ };
63
+ const checksum = this.calculateChecksum(entryWithoutChecksum);
64
+ const logEntry = {
65
+ ...entryWithoutChecksum,
66
+ checksum
67
+ };
68
+ this.logBuffer.push(logEntry);
69
+ // Force flush for critical operations
70
+ if (entry.operation === 'COMMIT' || entry.operation === 'ROLLBACK' ||
71
+ this.logBuffer.length >= this.BUFFER_SIZE) {
72
+ this.flushBuffer();
73
+ }
74
+ return lsn;
75
+ }
76
+ flushBuffer() {
77
+ if (this.logBuffer.length === 0)
78
+ return;
79
+ try {
80
+ const logEntries = this.logBuffer.map(entry => JSON.stringify(entry)).join('\n') + '\n';
81
+ // Atomic append to log file
82
+ if (existsSync(this.logPath)) {
83
+ const currentContent = readFileSync(this.logPath, 'utf-8');
84
+ writeFileSync(this.logPath, currentContent + logEntries);
85
+ }
86
+ else {
87
+ writeFileSync(this.logPath, logEntries);
88
+ }
89
+ this.logBuffer = [];
90
+ // Check if log rotation is needed
91
+ this.checkLogRotation();
92
+ }
93
+ catch (error) {
94
+ throw new Error(`Failed to flush WAL: ${error instanceof Error ? error.message : 'Unknown error'}`);
95
+ }
96
+ }
97
+ checkLogRotation() {
98
+ try {
99
+ const stats = statSync(this.logPath);
100
+ if (stats.size > this.LOG_FILE_SIZE_LIMIT) {
101
+ this.rotateLog();
102
+ }
103
+ }
104
+ catch (error) {
105
+ // Silent failure for production
106
+ }
107
+ }
108
+ rotateLog() {
109
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
110
+ const archivePath = `${this.logPath}.${timestamp}`;
111
+ try {
112
+ // Archive current log
113
+ const currentContent = readFileSync(this.logPath, 'utf-8');
114
+ writeFileSync(archivePath, currentContent);
115
+ // Start new log with checkpoint
116
+ writeFileSync(this.logPath, '');
117
+ this.writeLog({ operation: 'CHECKPOINT', transactionId: 'SYSTEM' });
118
+ }
119
+ catch (error) {
120
+ // Silent failure for production
121
+ }
122
+ }
123
+ getLogEntries(fromLSN) {
124
+ try {
125
+ const entries = [];
126
+ // First, add entries from the buffer (not yet flushed to disk)
127
+ for (const bufferedEntry of this.logBuffer) {
128
+ if (!fromLSN || bufferedEntry.lsn >= fromLSN) {
129
+ entries.push(bufferedEntry);
130
+ }
131
+ }
132
+ // Then, add entries from the log file
133
+ if (existsSync(this.logPath)) {
134
+ const logContent = readFileSync(this.logPath, 'utf-8');
135
+ const lines = logContent.trim().split('\n').filter(line => line.trim());
136
+ for (const line of lines) {
137
+ try {
138
+ const entry = JSON.parse(line);
139
+ if (this.verifyChecksum(entry) && (!fromLSN || entry.lsn >= fromLSN)) {
140
+ entries.push(entry);
141
+ }
142
+ }
143
+ catch (error) {
144
+ // Skip corrupted entries silently in production
145
+ continue;
146
+ }
147
+ }
148
+ }
149
+ return entries.sort((a, b) => a.lsn - b.lsn);
150
+ }
151
+ catch (error) {
152
+ return [];
153
+ }
154
+ }
155
+ forceFlush() {
156
+ this.flushBuffer();
157
+ }
158
+ getCurrentLSN() {
159
+ return this.currentLSN - 1;
160
+ }
161
+ }
162
+ // Lock Manager for proper concurrency control
163
+ export class LockManager {
164
+ locks = new Map();
165
+ DEADLOCK_TIMEOUT = 30000; // 30 seconds
166
+ async acquireLock(key, transactionId, lockType) {
167
+ return new Promise((resolve, reject) => {
168
+ const timeout = setTimeout(() => {
169
+ this.removeLockRequest(key, transactionId);
170
+ reject(new Error(`Lock acquisition timeout for key '${key}' in transaction '${transactionId}'`));
171
+ }, this.DEADLOCK_TIMEOUT);
172
+ const lockInfo = this.locks.get(key);
173
+ if (!lockInfo) {
174
+ // No existing lock, grant immediately
175
+ this.locks.set(key, {
176
+ type: lockType,
177
+ holders: new Set([transactionId]),
178
+ waitQueue: []
179
+ });
180
+ clearTimeout(timeout);
181
+ resolve();
182
+ return;
183
+ }
184
+ // Check if lock can be granted immediately
185
+ if (this.canGrantLock(lockInfo, lockType, transactionId)) {
186
+ if (lockType === 'shared' && lockInfo.type === 'shared') {
187
+ lockInfo.holders.add(transactionId);
188
+ }
189
+ else {
190
+ lockInfo.type = lockType;
191
+ lockInfo.holders.clear();
192
+ lockInfo.holders.add(transactionId);
193
+ }
194
+ clearTimeout(timeout);
195
+ resolve();
196
+ return;
197
+ }
198
+ // Add to wait queue
199
+ lockInfo.waitQueue.push({
200
+ transactionId,
201
+ type: lockType,
202
+ resolve: () => {
203
+ clearTimeout(timeout);
204
+ resolve();
205
+ },
206
+ reject: (error) => {
207
+ clearTimeout(timeout);
208
+ reject(error);
209
+ }
210
+ });
211
+ });
212
+ }
213
+ canGrantLock(lockInfo, requestedType, transactionId) {
214
+ // If transaction already holds the lock
215
+ if (lockInfo.holders.has(transactionId)) {
216
+ return true;
217
+ }
218
+ // If no current holders
219
+ if (lockInfo.holders.size === 0) {
220
+ return true;
221
+ }
222
+ // Shared locks can coexist
223
+ if (lockInfo.type === 'shared' && requestedType === 'shared') {
224
+ return true;
225
+ }
226
+ return false;
227
+ }
228
+ releaseLock(key, transactionId) {
229
+ const lockInfo = this.locks.get(key);
230
+ if (!lockInfo || !lockInfo.holders.has(transactionId)) {
231
+ return;
232
+ }
233
+ lockInfo.holders.delete(transactionId);
234
+ // Process wait queue if no more holders
235
+ if (lockInfo.holders.size === 0 && lockInfo.waitQueue.length > 0) {
236
+ this.processWaitQueue(key, lockInfo);
237
+ }
238
+ // Clean up empty lock
239
+ if (lockInfo.holders.size === 0 && lockInfo.waitQueue.length === 0) {
240
+ this.locks.delete(key);
241
+ }
242
+ }
243
+ processWaitQueue(key, lockInfo) {
244
+ if (lockInfo.waitQueue.length === 0)
245
+ return;
246
+ const firstRequest = lockInfo.waitQueue[0];
247
+ if (firstRequest.type === 'shared') {
248
+ // Grant all consecutive shared locks
249
+ const sharedRequests = [];
250
+ while (lockInfo.waitQueue.length > 0 && lockInfo.waitQueue[0].type === 'shared') {
251
+ sharedRequests.push(lockInfo.waitQueue.shift());
252
+ }
253
+ lockInfo.type = 'shared';
254
+ for (const request of sharedRequests) {
255
+ lockInfo.holders.add(request.transactionId);
256
+ request.resolve();
257
+ }
258
+ }
259
+ else {
260
+ // Grant single exclusive lock
261
+ const request = lockInfo.waitQueue.shift();
262
+ lockInfo.type = 'exclusive';
263
+ lockInfo.holders.add(request.transactionId);
264
+ request.resolve();
265
+ }
266
+ }
267
+ removeLockRequest(key, transactionId) {
268
+ const lockInfo = this.locks.get(key);
269
+ if (!lockInfo)
270
+ return;
271
+ lockInfo.waitQueue = lockInfo.waitQueue.filter(req => req.transactionId !== transactionId);
272
+ }
273
+ releaseAllLocks(transactionId) {
274
+ for (const [key, lockInfo] of this.locks.entries()) {
275
+ if (lockInfo.holders.has(transactionId)) {
276
+ this.releaseLock(key, transactionId);
277
+ }
278
+ // Remove from wait queue
279
+ lockInfo.waitQueue = lockInfo.waitQueue.filter(req => {
280
+ if (req.transactionId === transactionId) {
281
+ req.reject(new Error('Transaction aborted'));
282
+ return false;
283
+ }
284
+ return true;
285
+ });
286
+ }
287
+ }
288
+ detectDeadlock() {
289
+ // Simple deadlock detection - can be enhanced with wait-for graph
290
+ const suspiciousTransactions = [];
291
+ for (const [key, lockInfo] of this.locks.entries()) {
292
+ if (lockInfo.waitQueue.length > 5) { // Arbitrary threshold
293
+ suspiciousTransactions.push(...lockInfo.waitQueue.map(req => req.transactionId));
294
+ }
295
+ }
296
+ return [...new Set(suspiciousTransactions)];
297
+ }
298
+ }
299
+ // ACID-compliant storage engine
300
+ export class ACIDStorageEngine {
301
+ wal;
302
+ lockManager;
303
+ dbPath;
304
+ activeTransactions = new Map();
305
+ constructor(dbPath) {
306
+ this.dbPath = dbPath;
307
+ this.wal = new WriteAheadLog(dbPath);
308
+ this.lockManager = new LockManager();
309
+ this.initializeStorage();
310
+ }
311
+ initializeStorage() {
312
+ if (!existsSync(this.dbPath)) {
313
+ mkdirSync(this.dbPath, { recursive: true });
314
+ }
315
+ // Perform crash recovery
316
+ this.performCrashRecovery();
317
+ }
318
+ performCrashRecovery() {
319
+ const logEntries = this.wal.getLogEntries();
320
+ const committedTransactions = new Set();
321
+ const abortedTransactions = new Set();
322
+ // Phase 1: Analysis - determine transaction status
323
+ for (const entry of logEntries) {
324
+ if (entry.operation === 'COMMIT') {
325
+ committedTransactions.add(entry.transactionId);
326
+ }
327
+ else if (entry.operation === 'ROLLBACK') {
328
+ abortedTransactions.add(entry.transactionId);
329
+ }
330
+ }
331
+ // Phase 2: Redo - replay committed transactions
332
+ for (const entry of logEntries) {
333
+ if (entry.operation === 'WRITE' && committedTransactions.has(entry.transactionId)) {
334
+ this.redoOperation(entry);
335
+ }
336
+ else if (entry.operation === 'DELETE' && committedTransactions.has(entry.transactionId)) {
337
+ this.redoDelete(entry);
338
+ }
339
+ }
340
+ // Phase 3: Undo - rollback uncommitted transactions
341
+ const uncommittedOps = logEntries.filter(entry => (entry.operation === 'WRITE' || entry.operation === 'DELETE') &&
342
+ !committedTransactions.has(entry.transactionId) &&
343
+ !abortedTransactions.has(entry.transactionId)).reverse();
344
+ for (const entry of uncommittedOps) {
345
+ this.undoOperation(entry);
346
+ }
347
+ }
348
+ redoOperation(entry) {
349
+ if (!entry.key || !entry.afterImage)
350
+ return;
351
+ try {
352
+ const filePath = join(this.dbPath, `${entry.key}.json`);
353
+ writeFileSync(filePath, JSON.stringify(entry.afterImage, null, 2));
354
+ }
355
+ catch (error) {
356
+ // Silent failure for production
357
+ }
358
+ }
359
+ redoDelete(entry) {
360
+ if (!entry.key)
361
+ return;
362
+ try {
363
+ const filePath = join(this.dbPath, `${entry.key}.json`);
364
+ if (existsSync(filePath)) {
365
+ unlinkSync(filePath);
366
+ }
367
+ }
368
+ catch (error) {
369
+ // Silent failure for production
370
+ }
371
+ }
372
+ undoOperation(entry) {
373
+ if (!entry.key)
374
+ return;
375
+ try {
376
+ const filePath = join(this.dbPath, `${entry.key}.json`);
377
+ if (entry.operation === 'WRITE') {
378
+ if (entry.beforeImage === null) {
379
+ // File didn't exist before, delete it
380
+ if (existsSync(filePath)) {
381
+ unlinkSync(filePath);
382
+ }
383
+ }
384
+ else {
385
+ // Restore previous content
386
+ writeFileSync(filePath, JSON.stringify(entry.beforeImage, null, 2));
387
+ }
388
+ }
389
+ else if (entry.operation === 'DELETE' && entry.beforeImage) {
390
+ // Restore deleted file
391
+ writeFileSync(filePath, JSON.stringify(entry.beforeImage, null, 2));
392
+ }
393
+ }
394
+ catch (error) {
395
+ // Silent failure for production
396
+ }
397
+ }
398
+ // Transaction management
399
+ beginTransaction() {
400
+ const transactionId = randomUUID();
401
+ const startLSN = this.wal.writeLog({
402
+ operation: 'BEGIN',
403
+ transactionId
404
+ });
405
+ this.activeTransactions.set(transactionId, {
406
+ id: transactionId,
407
+ startLSN,
408
+ operations: [],
409
+ status: 'active'
410
+ });
411
+ return transactionId;
412
+ }
413
+ async write(transactionId, key, data) {
414
+ const transaction = this.activeTransactions.get(transactionId);
415
+ if (!transaction || transaction.status !== 'active') {
416
+ throw new Error(`Invalid transaction: ${transactionId}`);
417
+ }
418
+ // Acquire exclusive lock
419
+ await this.lockManager.acquireLock(key, transactionId, 'exclusive');
420
+ try {
421
+ // Read current data for before image
422
+ const filePath = join(this.dbPath, `${key}.json`);
423
+ let beforeImage = null;
424
+ if (existsSync(filePath)) {
425
+ try {
426
+ const content = readFileSync(filePath, 'utf-8');
427
+ beforeImage = content.trim() ? JSON.parse(content) : {};
428
+ }
429
+ catch (error) {
430
+ beforeImage = {};
431
+ }
432
+ }
433
+ // Deep merge for proper data integrity
434
+ const afterImage = this.deepMerge(beforeImage || {}, data);
435
+ // Write to WAL first (Write-Ahead Logging)
436
+ this.wal.writeLog({
437
+ operation: 'WRITE',
438
+ transactionId,
439
+ key,
440
+ beforeImage,
441
+ afterImage
442
+ });
443
+ // Track operation
444
+ transaction.operations.push({ key, operation: 'write' });
445
+ }
446
+ catch (error) {
447
+ this.lockManager.releaseLock(key, transactionId);
448
+ throw error;
449
+ }
450
+ }
451
+ async read(transactionId, key) {
452
+ const transaction = this.activeTransactions.get(transactionId);
453
+ if (!transaction || transaction.status !== 'active') {
454
+ throw new Error(`Invalid transaction: ${transactionId}`);
455
+ }
456
+ // Acquire shared lock for consistent read
457
+ await this.lockManager.acquireLock(key, transactionId, 'shared');
458
+ try {
459
+ // Check if there are pending writes in this transaction first
460
+ const logEntries = this.wal.getLogEntries(transaction.startLSN);
461
+ const transactionEntries = logEntries.filter(entry => entry.transactionId === transactionId &&
462
+ entry.key === key &&
463
+ (entry.operation === 'WRITE' || entry.operation === 'DELETE'));
464
+ if (transactionEntries.length > 0) {
465
+ // Return the most recent transaction state
466
+ const lastEntry = transactionEntries[transactionEntries.length - 1];
467
+ if (lastEntry.operation === 'DELETE') {
468
+ return null;
469
+ }
470
+ return lastEntry.afterImage || {};
471
+ }
472
+ // Read from disk
473
+ const filePath = join(this.dbPath, `${key}.json`);
474
+ if (!existsSync(filePath)) {
475
+ return null;
476
+ }
477
+ const content = readFileSync(filePath, 'utf-8');
478
+ return content.trim() ? JSON.parse(content) : {};
479
+ }
480
+ catch (error) {
481
+ this.lockManager.releaseLock(key, transactionId);
482
+ throw new Error(`Read failed for ${key}: ${error instanceof Error ? error.message : 'Unknown error'}`);
483
+ }
484
+ }
485
+ async delete(transactionId, key) {
486
+ const transaction = this.activeTransactions.get(transactionId);
487
+ if (!transaction || transaction.status !== 'active') {
488
+ throw new Error(`Invalid transaction: ${transactionId}`);
489
+ }
490
+ // Acquire exclusive lock
491
+ await this.lockManager.acquireLock(key, transactionId, 'exclusive');
492
+ try {
493
+ const filePath = join(this.dbPath, `${key}.json`);
494
+ let beforeImage = null;
495
+ if (existsSync(filePath)) {
496
+ try {
497
+ const content = readFileSync(filePath, 'utf-8');
498
+ beforeImage = content.trim() ? JSON.parse(content) : {};
499
+ }
500
+ catch (error) {
501
+ // Silent failure for production
502
+ }
503
+ }
504
+ // Write to WAL
505
+ this.wal.writeLog({
506
+ operation: 'DELETE',
507
+ transactionId,
508
+ key,
509
+ beforeImage,
510
+ afterImage: null
511
+ });
512
+ // Track operation
513
+ transaction.operations.push({ key, operation: 'delete' });
514
+ }
515
+ catch (error) {
516
+ this.lockManager.releaseLock(key, transactionId);
517
+ throw error;
518
+ }
519
+ }
520
+ async commitTransaction(transactionId) {
521
+ const transaction = this.activeTransactions.get(transactionId);
522
+ if (!transaction || transaction.status !== 'active') {
523
+ throw new Error(`Invalid transaction: ${transactionId}`);
524
+ }
525
+ try {
526
+ // Write commit log entry
527
+ this.wal.writeLog({
528
+ operation: 'COMMIT',
529
+ transactionId
530
+ });
531
+ // Force WAL to disk
532
+ this.wal.forceFlush();
533
+ // Apply changes to data files
534
+ const logEntries = this.wal.getLogEntries(transaction.startLSN);
535
+ const transactionEntries = logEntries.filter(entry => entry.transactionId === transactionId);
536
+ for (const entry of transactionEntries) {
537
+ if (entry.operation === 'WRITE' && entry.key && entry.afterImage !== undefined) {
538
+ const filePath = join(this.dbPath, `${entry.key}.json`);
539
+ // Ensure directory exists
540
+ if (!existsSync(dirname(filePath))) {
541
+ mkdirSync(dirname(filePath), { recursive: true });
542
+ }
543
+ writeFileSync(filePath, JSON.stringify(entry.afterImage, null, 2));
544
+ }
545
+ else if (entry.operation === 'DELETE' && entry.key) {
546
+ const filePath = join(this.dbPath, `${entry.key}.json`);
547
+ if (existsSync(filePath)) {
548
+ unlinkSync(filePath);
549
+ }
550
+ }
551
+ }
552
+ // Update transaction status
553
+ transaction.status = 'committed';
554
+ // Release all locks
555
+ this.lockManager.releaseAllLocks(transactionId);
556
+ }
557
+ catch (error) {
558
+ // Rollback on commit failure
559
+ await this.rollbackTransaction(transactionId);
560
+ throw new Error(`Commit failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
561
+ }
562
+ }
563
+ async rollbackTransaction(transactionId) {
564
+ const transaction = this.activeTransactions.get(transactionId);
565
+ if (!transaction) {
566
+ throw new Error(`Transaction not found: ${transactionId}`);
567
+ }
568
+ try {
569
+ // Write rollback log entry
570
+ this.wal.writeLog({
571
+ operation: 'ROLLBACK',
572
+ transactionId
573
+ });
574
+ // Update transaction status
575
+ transaction.status = 'aborted';
576
+ // Release all locks
577
+ this.lockManager.releaseAllLocks(transactionId);
578
+ }
579
+ catch (error) {
580
+ throw error;
581
+ }
582
+ }
583
+ deepMerge(target, source) {
584
+ if (source === null || source === undefined) {
585
+ return target;
586
+ }
587
+ if (typeof source !== 'object' || Array.isArray(source)) {
588
+ return source;
589
+ }
590
+ const result = { ...target };
591
+ for (const key in source) {
592
+ if (source.hasOwnProperty(key)) {
593
+ if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key]) &&
594
+ typeof target[key] === 'object' && target[key] !== null && !Array.isArray(target[key])) {
595
+ result[key] = this.deepMerge(target[key], source[key]);
596
+ }
597
+ else {
598
+ result[key] = source[key];
599
+ }
600
+ }
601
+ }
602
+ return result;
603
+ }
604
+ // Utility methods
605
+ getActiveTransactions() {
606
+ return Array.from(this.activeTransactions.keys()).filter(id => this.activeTransactions.get(id)?.status === 'active');
607
+ }
608
+ forceCheckpoint() {
609
+ this.wal.writeLog({
610
+ operation: 'CHECKPOINT',
611
+ transactionId: 'SYSTEM'
612
+ });
613
+ this.wal.forceFlush();
614
+ }
615
+ destroy() {
616
+ // Rollback all active transactions
617
+ for (const [transactionId, transaction] of this.activeTransactions.entries()) {
618
+ if (transaction.status === 'active') {
619
+ this.rollbackTransaction(transactionId).catch(() => {
620
+ // Silent failure for production
621
+ });
622
+ }
623
+ }
624
+ // Clean up memory
625
+ this.activeTransactions.clear();
626
+ this.wal.forceFlush();
627
+ }
628
+ }