tero 0.0.5 → 0.0.7

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 CHANGED
@@ -1,10 +1,92 @@
1
- import { existsSync, mkdirSync } from "fs";
1
+ import { existsSync, mkdirSync, openSync, writeSync, closeSync, unlinkSync, readFileSync } from "fs";
2
2
  import { ACIDStorageEngine } from "./acid-engine.js";
3
3
  import { SchemaValidator } from "./schema.js";
4
4
  import { BackupManager } from "./backup.js";
5
5
  import { DataRecovery } from "./recovery.js";
6
6
  import { randomBytes } from "node:crypto";
7
7
  import QuickLRU from "quick-lru";
8
+ export class Transaction {
9
+ id;
10
+ db;
11
+ startTime;
12
+ opCount = 0;
13
+ destroyed = false;
14
+ timeoutTimer;
15
+ constructor(id, db, options) {
16
+ this.id = id;
17
+ this.db = db;
18
+ this.startTime = Date.now();
19
+ if (options?.timeout) {
20
+ this.timeoutTimer = setTimeout(() => {
21
+ this.destroyed = true;
22
+ this.db._rollbackRaw(this.id).catch(() => { });
23
+ }, options.timeout);
24
+ }
25
+ }
26
+ getId() {
27
+ return this.id;
28
+ }
29
+ isActive() {
30
+ if (this.destroyed)
31
+ return false;
32
+ return this.db.getActiveTransactions().includes(this.id);
33
+ }
34
+ isRolledBack() {
35
+ return !this.isActive();
36
+ }
37
+ _checkActive() {
38
+ if (this.destroyed)
39
+ throw new Error('Transaction has been destroyed');
40
+ const status = this.db._getTxStatus(this.id);
41
+ if (status === 'committed')
42
+ throw new Error('Transaction has already been committed');
43
+ if (status === 'aborted')
44
+ throw new Error('Transaction has been rolled back');
45
+ if (status === 'not_found')
46
+ throw new Error('Transaction is not active');
47
+ }
48
+ async create(key, initialData) {
49
+ this._checkActive();
50
+ if (this.db.exists(key))
51
+ throw new Error(`Document '${key}' already exists`);
52
+ await this.db._writeRaw(this.id, key, initialData || {});
53
+ this.opCount++;
54
+ }
55
+ async update(key, data) {
56
+ this._checkActive();
57
+ await this.db._writeRaw(this.id, key, data);
58
+ this.opCount++;
59
+ }
60
+ async delete(key) {
61
+ this._checkActive();
62
+ await this.db._deleteRaw(this.id, key);
63
+ this.opCount++;
64
+ }
65
+ async get(key) {
66
+ this._checkActive();
67
+ return await this.db._readRaw(this.id, key);
68
+ }
69
+ getState() {
70
+ const status = this.db._getTxStatus(this.id);
71
+ return {
72
+ status: status === 'active' ? 'active' : (status === 'committed' ? 'committed' : 'rolled_back'),
73
+ operations: Array.from({ length: this.opCount }, (_, i) => ({ key: `op_${i}`, operation: 'write' })),
74
+ startTime: this.startTime
75
+ };
76
+ }
77
+ getOperationCount() {
78
+ return this.opCount;
79
+ }
80
+ getDuration() {
81
+ return Date.now() - this.startTime;
82
+ }
83
+ destroy() {
84
+ this.destroyed = true;
85
+ if (this.timeoutTimer)
86
+ clearTimeout(this.timeoutTimer);
87
+ this.db._rollbackRaw(this.id).catch(() => { });
88
+ }
89
+ }
8
90
  export class Tero {
9
91
  teroDirectory = "TeroDB";
10
92
  cacheSize = 100;
@@ -15,31 +97,163 @@ export class Tero {
15
97
  schemaValidator;
16
98
  backupManager;
17
99
  dataRecovery;
100
+ committedCount = 0;
101
+ rolledBackCount = 0;
102
+ /**
103
+ * Bounded LRU of known-existing keys. Replaces the unbounded Set<string>
104
+ * that grew linearly with key count (catastrophic memory at 1M+ keys/tenant).
105
+ * Capped at KNOWN_KEYS_MAX (10k) ~ 800KB peak vs ~80MB at 1M keys for Set.
106
+ * Falls back to disk (partitioned path existsSync) on LRU miss.
107
+ */
108
+ knownKeys;
109
+ KNOWN_KEYS_MAX = 10000;
110
+ /** Optional exclusive file-lock fd on the data directory (flock, via fs-ext). */
111
+ lockFd;
112
+ /**
113
+ * Construct an embedded Tero instance synchronously.
114
+ *
115
+ * For v2 startup hydration from a bucket, prefer `await Tero.create(config)` which
116
+ * pulls missing/all files from the client's OWN bucket before the ACID engine is
117
+ * initialized. The control plane never holds client bucket credentials; it only
118
+ * observes instances. Pass `hydrateOnStartup` in config to use this path.
119
+ */
18
120
  constructor(config) {
19
121
  try {
20
- const { directory, cacheSize } = config || {};
21
- if (typeof directory === "string" && directory.trim()) {
122
+ const rawDirectory = config?.Directory || config?.directory;
123
+ const { cacheSize, synchronous, commitIntervalMs, dataFlushIntervalMs } = config || {};
124
+ if (typeof rawDirectory === "string" && rawDirectory.trim()) {
22
125
  // Sanitize directory path to prevent directory traversal
23
- this.teroDirectory = directory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
126
+ this.teroDirectory = rawDirectory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
24
127
  }
25
128
  if (typeof cacheSize === "number" && cacheSize > 0) {
26
129
  this.cacheSize = Math.min(cacheSize, 1000); // Cap at 1k entries
27
130
  }
28
131
  // Create directories with proper error handling
29
132
  this.initializeDirectories();
133
+ // Optional cross-process file lock: prevents two processes from opening
134
+ // the same data directory concurrently (addresses Google Pillar #2 —
135
+ // zero cross-process synchronization). Uses flock via fs-ext.
136
+ if (config?.fileLock) {
137
+ this.acquireFileLock();
138
+ }
30
139
  // Initialize QuickLRU cache
31
140
  this.cache = new QuickLRU({
32
141
  maxSize: this.cacheSize
33
142
  });
143
+ // Initialize bounded LRU for known-keys (caps memory at ~800KB vs ~80MB
144
+ // for an unbounded Set at 1M keys — addresses cloud-scale heap bloat).
145
+ this.knownKeys = new QuickLRU({ maxSize: this.KNOWN_KEYS_MAX });
34
146
  // Initialize ACID storage engine (primary system)
35
- this.acidEngine = new ACIDStorageEngine(this.teroDirectory);
147
+ const syncMode = synchronous ?? 'full';
148
+ const syncInterval = commitIntervalMs ?? 10;
149
+ const dataFlushInterval = dataFlushIntervalMs ?? 50;
150
+ this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval);
36
151
  // Initialize schema validator
37
152
  this.schemaValidator = new SchemaValidator();
153
+ // v2: optionally install a backup config at construction time.
154
+ if (config?.backup) {
155
+ this.configureBackup(config.backup);
156
+ }
38
157
  }
39
158
  catch (error) {
40
159
  throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`);
41
160
  }
42
161
  }
162
+ /**
163
+ * v2 async factory. Same as `new Tero(config)` but runs hydrate-on-startup BEFORE
164
+ * the ACID engine is constructed. Use this when `config.hydrateOnStartup` is set
165
+ * so missing/all local files are restored from the client's bucket first.
166
+ */
167
+ static async create(config) {
168
+ const hydrate = config?.hydrateOnStartup;
169
+ if (!hydrate) {
170
+ return new Tero(config);
171
+ }
172
+ // Ensure directory exists first so DataRecovery can stream into it.
173
+ const rawDirectory = config?.Directory || config?.directory || 'TeroDB';
174
+ const teroDirectory = rawDirectory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
175
+ if (!existsSync(teroDirectory)) {
176
+ mkdirSync(teroDirectory, { recursive: true });
177
+ }
178
+ // Pre-engine hydration: pull files from the client's bucket before engine init,
179
+ // so crash recovery (which runs inside the ACIDStorageEngine constructor) sees
180
+ // the latest durable state instead of an empty local directory.
181
+ const recovery = new DataRecovery({
182
+ cloudStorage: hydrate.cloudStorage,
183
+ localPath: teroDirectory,
184
+ mode: hydrate.mode === 'all' ? 'all' : 'missing',
185
+ continueOnError: hydrate.continueOnError ?? true,
186
+ });
187
+ try {
188
+ const mode = hydrate.mode ?? 'missing';
189
+ if (mode === 'all') {
190
+ const r = await recovery.recoverIndividualFiles();
191
+ if (!r.success && r.failed.length > 0) { /* continue */ }
192
+ }
193
+ else if (mode === 'snapshot') {
194
+ // Snapshot-first: download the most recent tar.gz archive, extract it
195
+ // locally in bulk (one HTTP GET for potentially thousands of docs), then
196
+ // fill gaps with individual file recovery for any data written since the
197
+ // snapshot's checkpoint. This is the Google-recommended hydration pattern:
198
+ // one bulk download instead of sequential individual S3 GETs.
199
+ try {
200
+ const snapshotResult = await recovery.recoverFromArchive();
201
+ if (!snapshotResult.success) {
202
+ // Fall back to individual file recovery if no archive exists
203
+ const r = await recovery.recoverMissingFiles();
204
+ if (!r.success && r.failed.length > 0) { /* continue */ }
205
+ }
206
+ }
207
+ catch {
208
+ // Archive may not exist or may be corrupted; fall back gracefully
209
+ const r = await recovery.recoverMissingFiles();
210
+ if (!r.success && r.failed.length > 0) { /* continue */ }
211
+ }
212
+ }
213
+ else {
214
+ const r = await recovery.recoverMissingFiles();
215
+ if (!r.success && r.failed.length > 0) { /* continue */ }
216
+ }
217
+ }
218
+ catch (error) {
219
+ // Hydration errors are non-fatal; engine init proceeds with whatever local data exists.
220
+ }
221
+ // Now construct the engine in the usual way — it sees current local state and
222
+ // runs crash recovery against the WAL for any writes between the last snapshot
223
+ // and the crash.
224
+ const instance = new Tero(config);
225
+ // Keep the recovery client wired so that runtime `getWithRecovery` / `existsWithCloudCheck`
226
+ // can fall back to the same client bucket with no extra configuration.
227
+ instance.dataRecovery = recovery;
228
+ return instance;
229
+ }
230
+ /**
231
+ * v2: explicitly run hydration at any time (idempotent). Pulls missing/all files
232
+ * from the client's bucket according to the config passed. Requires either
233
+ * `configureDataRecovery(...)` to have been called, or `hydrateOnStartup` in
234
+ * the constructor config.
235
+ */
236
+ async hydrate(options) {
237
+ const recovery = this.dataRecovery;
238
+ if (!recovery) {
239
+ throw new Error('Data recovery not configured. Call configureDataRecovery() or pass hydrateOnStartup in config.');
240
+ }
241
+ const mode = options?.mode ?? 'missing';
242
+ if (mode === 'all') {
243
+ return await recovery.recoverIndividualFiles();
244
+ }
245
+ else if (mode === 'snapshot') {
246
+ try {
247
+ return await recovery.recoverFromArchive();
248
+ }
249
+ catch {
250
+ return await recovery.recoverMissingFiles();
251
+ }
252
+ }
253
+ else {
254
+ return await recovery.recoverMissingFiles();
255
+ }
256
+ }
43
257
  initializeDirectories() {
44
258
  try {
45
259
  if (!existsSync(this.teroDirectory)) {
@@ -63,6 +277,12 @@ export class Tero {
63
277
  throw new Error('Key contains invalid characters');
64
278
  }
65
279
  }
280
+ /**
281
+ * Tracks which keys each active transaction has touched (cache entries tagged
282
+ * with that txId). Used by commit()/rollback() to promote/invalidate only the
283
+ * touched keys instead of scanning the entire LRU cache. O(touched) vs O(cacheSize).
284
+ */
285
+ txTouchedKeys = new Map();
66
286
  invalidateCacheKeys(keys) {
67
287
  for (const key of keys) {
68
288
  this.cache.delete(key);
@@ -74,18 +294,36 @@ export class Tero {
74
294
  lastAccessed: Date.now(),
75
295
  transactionId
76
296
  });
297
+ // Track touched key so commit/rollback can promote/invalidate only this key
298
+ // instead of scanning the entire LRU cache (O(touched) vs O(cacheSize)).
299
+ if (transactionId) {
300
+ let touched = this.txTouchedKeys.get(transactionId);
301
+ if (!touched) {
302
+ touched = new Set();
303
+ this.txTouchedKeys.set(transactionId, touched);
304
+ }
305
+ touched.add(key);
306
+ }
77
307
  }
78
308
  // Core ACID Operations
79
- beginTransaction() {
309
+ beginTransaction(options) {
80
310
  try {
81
- return this.acidEngine.beginTransaction();
311
+ const id = this._beginTransaction();
312
+ return new Transaction(id, this, options);
82
313
  }
83
314
  catch (error) {
84
315
  throw new Error(`Failed to begin transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
85
316
  }
86
317
  }
318
+ _beginTransaction() {
319
+ return this.acidEngine.beginTransaction();
320
+ }
321
+ _txId(id) {
322
+ return typeof id === 'string' ? id : id.getId();
323
+ }
87
324
  async write(transactionId, key, data, options) {
88
325
  try {
326
+ const txId = this._txId(transactionId);
89
327
  this.validateKey(key);
90
328
  if (data === undefined || data === null) {
91
329
  throw new Error('Data cannot be null or undefined');
@@ -106,9 +344,17 @@ export class Tero {
106
344
  // Use sanitized data from validation
107
345
  data = validationResult.data || data;
108
346
  }
109
- await this.acidEngine.write(transactionId, key, data);
110
- // Update cache with transaction context
111
- this.updateCache(key, data, transactionId);
347
+ // Engine write — returns void (sync fast path) or Promise (contended lock)
348
+ const writeResult = this.acidEngine.write(txId, key, data);
349
+ if (writeResult !== undefined)
350
+ await writeResult;
351
+ // Cache the MERGED afterImage (from pendingWrites), NOT the raw user data.
352
+ // The engine deep-merges user data with existing state, so the afterImage
353
+ // has ALL fields, not just the caller's partial update. Caching the raw
354
+ // input would poison the cache with incomplete documents (sequential
355
+ // updates to the same key would lose earlier fields).
356
+ const afterImage = this.acidEngine.getPendingAfterImage(txId, key);
357
+ this.updateCache(key, afterImage !== undefined ? afterImage : data, txId);
112
358
  if (options?.validate || options?.schemaName) {
113
359
  return { valid: true, errors: [], data };
114
360
  }
@@ -119,19 +365,21 @@ export class Tero {
119
365
  }
120
366
  async read(transactionId, key) {
121
367
  try {
368
+ const txId = this._txId(transactionId);
122
369
  this.validateKey(key);
123
370
  this.cacheRequests++;
124
371
  // Check cache first, but only if it's from the same transaction or committed
125
372
  const cachedEntry = this.cache.get(key);
126
- if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) {
373
+ if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) {
127
374
  this.cacheHits++;
128
375
  cachedEntry.lastAccessed = Date.now();
129
376
  return cachedEntry.data;
130
377
  }
131
- // Read from ACID engine
132
- const data = await this.acidEngine.read(transactionId, key);
133
- if (data !== null) {
134
- this.updateCache(key, data, transactionId);
378
+ // Read from ACID engine — returns data (sync fast path) or Promise (contended lock)
379
+ const readResult = this.acidEngine.read(txId, key);
380
+ const data = (readResult !== undefined && readResult instanceof Promise) ? await readResult : readResult;
381
+ if (data !== null && data !== undefined) {
382
+ this.updateCache(key, data, txId);
135
383
  }
136
384
  return data;
137
385
  }
@@ -139,33 +387,28 @@ export class Tero {
139
387
  throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
140
388
  }
141
389
  }
142
- async delete(transactionId, key) {
143
- try {
144
- this.validateKey(key);
145
- await this.acidEngine.delete(transactionId, key);
146
- // Remove from cache
147
- this.cache.delete(key);
148
- }
149
- catch (error) {
150
- throw new Error(`Delete failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
151
- }
152
- }
153
390
  async commit(transactionId) {
154
391
  try {
155
- // Get affected keys before commit
156
- const transaction = this.acidEngine.getActiveTransactions().includes(transactionId);
157
- if (!transaction) {
158
- throw new Error(`Transaction ${transactionId} not found or not active`);
392
+ const txId = this._txId(transactionId);
393
+ // O(1) active check — was O(N) via getActiveTransactions().includes()
394
+ if (!this.acidEngine.isTransactionActive(txId)) {
395
+ throw new Error(`Transaction ${txId} not found or not active`);
159
396
  }
160
- await this.acidEngine.commitTransaction(transactionId);
161
- // Invalidate cache entries for this transaction to force fresh reads
162
- const keysToInvalidate = [];
163
- for (const [key, entry] of this.cache.entries()) {
164
- if (entry.transactionId === transactionId) {
165
- keysToInvalidate.push(key);
397
+ // Sync call — commitTransaction is now synchronous (no awaits on happy path)
398
+ this.acidEngine.commitTransaction(txId);
399
+ // PROMOTE cache entries tagged with this transaction to "committed" state.
400
+ // O(touched) via the tracked set.
401
+ const touched = this.txTouchedKeys.get(txId);
402
+ if (touched) {
403
+ for (const key of touched) {
404
+ const entry = this.cache.get(key);
405
+ if (entry && entry.transactionId === txId) {
406
+ entry.transactionId = undefined;
407
+ }
166
408
  }
409
+ this.txTouchedKeys.delete(txId);
167
410
  }
168
- this.invalidateCacheKeys(keysToInvalidate);
411
+ this.committedCount++;
169
412
  }
170
413
  catch (error) {
171
414
  throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
@@ -173,33 +416,48 @@ export class Tero {
173
416
  }
174
417
  async rollback(transactionId) {
175
418
  try {
176
- await this.acidEngine.rollbackTransaction(transactionId);
177
- // Remove cache entries for this transaction
178
- const keysToRemove = [];
179
- for (const [key, entry] of this.cache.entries()) {
180
- if (entry.transactionId === transactionId) {
181
- keysToRemove.push(key);
419
+ const txId = this._txId(transactionId);
420
+ // Sync call — rollbackTransaction is now synchronous
421
+ this.acidEngine.rollbackTransaction(txId);
422
+ // Remove cache entries for this transaction using the touched-keys set
423
+ const touched = this.txTouchedKeys.get(txId);
424
+ if (touched) {
425
+ for (const key of touched) {
426
+ this.cache.delete(key);
182
427
  }
428
+ this.txTouchedKeys.delete(txId);
183
429
  }
184
- this.invalidateCacheKeys(keysToRemove);
430
+ this.rolledBackCount++;
185
431
  }
186
432
  catch (error) {
187
433
  throw new Error(`Failed to rollback transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
188
434
  }
189
435
  }
436
+ async commitTransaction(transactionId) {
437
+ return await this.commit(transactionId);
438
+ }
439
+ async rollbackTransaction(transactionId) {
440
+ return await this.rollback(transactionId);
441
+ }
442
+ getPerformanceStats() {
443
+ const cacheStats = this.getCacheStats();
444
+ return {
445
+ cacheStats: { hitRate: cacheStats.hitRate },
446
+ totalRequests: this.cacheRequests
447
+ };
448
+ }
190
449
  // Convenience Methods (Auto-transaction)
191
450
  async create(key, initialData, options) {
192
- const transactionId = this.beginTransaction();
451
+ this.validateKey(key);
452
+ // Fast existence check via in-memory set — avoids existsSync syscall
453
+ if (this.knownKeys.has(key)) {
454
+ return false; // already exists
455
+ }
456
+ const transactionId = this._beginTransaction();
193
457
  try {
194
- // Check if file already exists
195
- const existing = await this.read(transactionId, key);
196
- if (existing !== null) {
197
- await this.rollback(transactionId);
198
- return false; // File already exists
199
- }
200
- // Create with initial data or empty object
201
458
  const result = await this.write(transactionId, key, initialData || {}, options);
202
459
  await this.commit(transactionId);
460
+ this.knownKeys.set(key, true);
203
461
  return result || true;
204
462
  }
205
463
  catch (error) {
@@ -208,7 +466,7 @@ export class Tero {
208
466
  }
209
467
  }
210
468
  async update(key, data, options) {
211
- const transactionId = this.beginTransaction();
469
+ const transactionId = this._beginTransaction();
212
470
  try {
213
471
  const result = await this.write(transactionId, key, data, options);
214
472
  await this.commit(transactionId);
@@ -219,33 +477,99 @@ export class Tero {
219
477
  throw error;
220
478
  }
221
479
  }
480
+ /**
481
+ * Read a document. Returns the document data on success, or `false` if the
482
+ * document is absent. Throws for genuine errors.
483
+ *
484
+ * Fast path (3 tiers, zero-syscall on hit):
485
+ * 1. LRU cache (committed entries) — pure memory, 900k+ ops/s
486
+ * 2. committedBuffer (committed but not yet flushed to disk) — pure memory
487
+ * 3. Read from data file via 2-level hash-prefix partitioned path (atomic
488
+ * rename guarantees valid JSON; no single dentry holds >50k files)
489
+ *
490
+ * NO transaction is created, NO WAL I/O, NO lock acquired.
491
+ */
222
492
  async get(key) {
223
- const transactionId = this.beginTransaction();
493
+ this.validateKey(key);
494
+ this.cacheRequests++;
495
+ // 1. Fast path: committed cache hit — no tx, no WAL, no lock, no syscall
496
+ const cachedEntry = this.cache.get(key);
497
+ if (cachedEntry && !cachedEntry.transactionId) {
498
+ this.cacheHits++;
499
+ cachedEntry.lastAccessed = Date.now();
500
+ return cachedEntry.data;
501
+ }
502
+ // 2. Check committedBuffer (committed but not yet flushed to data files)
503
+ const committed = this.acidEngine.getCommittedData(key);
504
+ if (committed !== undefined) {
505
+ if (committed === null)
506
+ return false;
507
+ this.updateCache(key, committed, undefined);
508
+ return committed;
509
+ }
510
+ // 3. Slow path: read directly from disk (partitioned path; atomic rename = consistent)
511
+ const { readFileSync, existsSync: existsSyncFs } = await import('fs');
512
+ const { join } = await import('path');
513
+ const filePath = this.keyToPath(key);
514
+ if (!existsSyncFs(filePath)) {
515
+ return false;
516
+ }
224
517
  try {
225
- const data = await this.read(transactionId, key);
226
- await this.commit(transactionId);
518
+ const content = readFileSync(filePath, 'utf-8');
519
+ const data = content.trim() ? JSON.parse(content) : {};
520
+ this.updateCache(key, data, undefined);
227
521
  return data;
228
522
  }
229
523
  catch (error) {
230
- await this.rollback(transactionId);
231
- throw error;
524
+ throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
232
525
  }
233
526
  }
527
+ /**
528
+ * Map a document key to its partitioned path on disk (2-level hash-prefix).
529
+ * Matches the layout used by ACIDStorageEngine — same key resolves to same path.
530
+ */
531
+ keyToPath(key) {
532
+ // FNV-1a 32-bit of the key — same dispersion as partitionedPath() in acid-engine.ts
533
+ let h = 0x811c9dc5;
534
+ for (let i = 0; i < key.length; i++) {
535
+ h ^= key.charCodeAt(i);
536
+ h = Math.imul(h, 0x01000193) >>> 0;
537
+ }
538
+ const hex = h.toString(16).padStart(8, '0');
539
+ return `${this.teroDirectory}/${hex.slice(0, 2)}/${hex.slice(2, 4)}/${key}.json`;
540
+ }
234
541
  async remove(key) {
235
- const transactionId = this.beginTransaction();
542
+ const transactionId = this._beginTransaction();
236
543
  try {
237
- await this.delete(transactionId, key);
544
+ await this._deleteRaw(transactionId, key);
238
545
  await this.commit(transactionId);
546
+ this.knownKeys.delete(key);
239
547
  }
240
548
  catch (error) {
241
549
  await this.rollback(transactionId);
242
550
  throw error;
243
551
  }
244
552
  }
553
+ async delete(key) {
554
+ return await this.remove(key);
555
+ }
245
556
  exists(key) {
246
557
  try {
247
558
  this.validateKey(key);
248
- return existsSync(`${this.teroDirectory}/${key}.json`);
559
+ // Fast path: in-memory set
560
+ if (this.knownKeys.has(key))
561
+ return true;
562
+ // Check committedBuffer for pending deletes (deferred writes may not have
563
+ // unlinked the file yet — a committed delete should appear as absent)
564
+ const committed = this.acidEngine.getCommittedData(key);
565
+ if (committed !== undefined)
566
+ return committed !== null;
567
+ // Slow path: check disk via partitioned path
568
+ if (existsSync(this.keyToPath(key))) {
569
+ this.knownKeys.set(key, true);
570
+ return true;
571
+ }
572
+ return false;
249
573
  }
250
574
  catch (error) {
251
575
  return false;
@@ -253,12 +577,15 @@ export class Tero {
253
577
  }
254
578
  // Batch Operations
255
579
  async batchWrite(operations, options) {
256
- const transactionId = this.beginTransaction();
580
+ const transactionId = this._beginTransaction();
257
581
  try {
258
582
  for (const op of operations) {
259
583
  await this.write(transactionId, op.key, op.data, options);
260
584
  }
261
585
  await this.commit(transactionId);
586
+ // Register all written keys in knownKeys so future exists() calls are O(1)
587
+ for (const op of operations)
588
+ this.knownKeys.set(op.key, true);
262
589
  }
263
590
  catch (error) {
264
591
  await this.rollback(transactionId);
@@ -266,7 +593,7 @@ export class Tero {
266
593
  }
267
594
  }
268
595
  async batchRead(keys) {
269
- const transactionId = this.beginTransaction();
596
+ const transactionId = this._beginTransaction();
270
597
  const results = {};
271
598
  try {
272
599
  for (const key of keys) {
@@ -285,7 +612,7 @@ export class Tero {
285
612
  if (amount <= 0) {
286
613
  throw new Error('Transfer amount must be positive');
287
614
  }
288
- const transactionId = this.beginTransaction();
615
+ const transactionId = this._beginTransaction();
289
616
  try {
290
617
  // Read current balances
291
618
  const fromAccount = await this.read(transactionId, fromKey);
@@ -313,6 +640,51 @@ export class Tero {
313
640
  throw new Error(`Money transfer failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
314
641
  }
315
642
  }
643
+ // Internal raw methods for Transaction class
644
+ async _writeRaw(transactionId, key, data) {
645
+ const result = this.acidEngine.write(transactionId, key, data);
646
+ if (result !== undefined)
647
+ await result;
648
+ this.updateCache(key, data, transactionId);
649
+ }
650
+ async _readRaw(transactionId, key) {
651
+ this.cacheRequests++;
652
+ const cachedEntry = this.cache.get(key);
653
+ if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) {
654
+ this.cacheHits++;
655
+ cachedEntry.lastAccessed = Date.now();
656
+ return cachedEntry.data;
657
+ }
658
+ const result = this.acidEngine.read(transactionId, key);
659
+ const data = (result !== undefined && result instanceof Promise) ? await result : result;
660
+ if (data !== null && data !== undefined) {
661
+ this.updateCache(key, data, transactionId);
662
+ }
663
+ return data;
664
+ }
665
+ async _deleteRaw(transactionId, key) {
666
+ const result = this.acidEngine.delete(transactionId, key);
667
+ if (result !== undefined)
668
+ await result;
669
+ this.cache.delete(key);
670
+ this.knownKeys.delete(key);
671
+ }
672
+ async _rollbackRaw(transactionId) {
673
+ this.acidEngine.rollbackTransaction(transactionId);
674
+ this.rolledBackCount++;
675
+ }
676
+ _getTxStatus(transactionId) {
677
+ return this.acidEngine.getTransactionStatus(transactionId);
678
+ }
679
+ getTransactionStats() {
680
+ const active = this.acidEngine.getActiveTransactions().length;
681
+ return {
682
+ active,
683
+ committed: this.committedCount,
684
+ rolledBack: this.rolledBackCount,
685
+ total: active + this.committedCount + this.rolledBackCount
686
+ };
687
+ }
316
688
  // Schema Management
317
689
  setSchema(collectionName, schema) {
318
690
  try {
@@ -331,7 +703,35 @@ export class Tero {
331
703
  validateData(collectionName, data) {
332
704
  return this.schemaValidator.validate(collectionName, data);
333
705
  }
706
+ hasSchema(collectionName) {
707
+ return this.schemaValidator.hasSchema(collectionName);
708
+ }
709
+ listSchemas() {
710
+ return this.schemaValidator.listSchemas();
711
+ }
712
+ exportSchemas() {
713
+ return this.schemaValidator.exportSchemas();
714
+ }
715
+ getSchemaStats() {
716
+ return this.schemaValidator.getSchemaStats();
717
+ }
718
+ async createWithValidation(key, initialData, options) {
719
+ const result = await this.create(key, initialData, { ...options, validate: true });
720
+ if (result === true || result === false) {
721
+ return { valid: result, errors: [], data: initialData || {} };
722
+ }
723
+ return result;
724
+ }
725
+ async updateWithValidation(key, data, options) {
726
+ const result = await this.update(key, data, { ...options, validate: true });
727
+ if (!result) {
728
+ return { valid: true, errors: [], data };
729
+ }
730
+ return result;
731
+ }
732
+ // ---------------------------------------------------------------------------
334
733
  // Backup Management
734
+ // ---------------------------------------------------------------------------
335
735
  configureBackup(config) {
336
736
  try {
337
737
  this.backupManager = new BackupManager(this.teroDirectory, config);
@@ -340,13 +740,84 @@ export class Tero {
340
740
  throw new Error(`Failed to configure backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
341
741
  }
342
742
  }
743
+ /** Alias retained for the existing test surface / older callers. */
744
+ configureAdvancedBackup(config) {
745
+ this.configureBackup(config);
746
+ }
343
747
  async performBackup() {
344
748
  if (!this.backupManager) {
345
749
  throw new Error('Backup not configured. Call configureBackup() first.');
346
750
  }
751
+ // Force-flush committedBuffer to data files so the backup sees the latest state.
752
+ this.acidEngine.flushCommittedBuffer();
753
+ this.acidEngine.forceCheckpoint();
347
754
  return await this.backupManager.performBackup();
348
755
  }
756
+ /** Alias retained for the existing test surface / older callers. */
757
+ async performAdvancedBackup() {
758
+ return this.performBackup();
759
+ }
760
+ /** Schedule a recurring backup via cron. Returns a schedule id; cancel with cancelScheduledBackup(). */
761
+ scheduleBackup(config) {
762
+ if (!this.backupManager) {
763
+ throw new Error('Backup not configured. Call configureBackup() first.');
764
+ }
765
+ return this.backupManager.scheduleBackup(config);
766
+ }
767
+ /** Cancel a previously scheduled backup by id. */
768
+ cancelScheduledBackup(scheduleId) {
769
+ if (!this.backupManager)
770
+ return false;
771
+ return this.backupManager.cancelScheduledBackup(scheduleId);
772
+ }
773
+ /** List currently scheduled backups. */
774
+ getScheduledBackups() {
775
+ if (!this.backupManager)
776
+ return [];
777
+ return this.backupManager.getScheduledBackups();
778
+ }
779
+ /** Test reachability of the configured bucket. Returns {success, message}. */
780
+ async testCloudConnection() {
781
+ if (!this.backupManager) {
782
+ return { success: false, message: 'Backup not configured' };
783
+ }
784
+ return await this.backupManager.testCloudConnection();
785
+ }
786
+ /**
787
+ * v2: One-shot bucket backup of all current data JSON files plus any WAL archive
788
+ * segments retained locally. Designed for scheduled "snapshot to bucket" runs the
789
+ * CLIENT triggers with its OWN bucket credentials — the control plane never holds
790
+ * client cloud keys, it only observes results via heartbeats.
791
+ */
792
+ async backupToBucket(options) {
793
+ if (!this.backupManager) {
794
+ throw new Error('Backup not configured. Call configureBackup() first.');
795
+ }
796
+ // Force-flush committedBuffer to data files so the backup sees the latest state.
797
+ this.acidEngine.flushCommittedBuffer();
798
+ this.acidEngine.forceCheckpoint();
799
+ const walArchivePaths = this.acidEngine.getWAL().listArchives();
800
+ return await this.backupManager.backupToBucket({
801
+ walArchivePaths,
802
+ tag: options?.tag,
803
+ });
804
+ }
805
+ /**
806
+ * v2: Emit a WAL checkpoint + immediately rotate the WAL into a new archive segment,
807
+ * then back that fresh segment up to the bucket. Useful right after high-write bursts
808
+ * to bound the recovery window (RPO) when hydrating a new instance.
809
+ */
810
+ async checkpointAndBackupToBucket(options) {
811
+ if (!this.backupManager) {
812
+ throw new Error('Backup not configured. Call configureBackup() first.');
813
+ }
814
+ this.acidEngine.forceCheckpoint();
815
+ this.acidEngine.getWAL().rotateLog();
816
+ return await this.backupToBucket(options);
817
+ }
818
+ // ---------------------------------------------------------------------------
349
819
  // Data Recovery
820
+ // ---------------------------------------------------------------------------
350
821
  configureDataRecovery(config) {
351
822
  try {
352
823
  this.dataRecovery = new DataRecovery(config);
@@ -376,7 +847,125 @@ export class Tero {
376
847
  }
377
848
  return result;
378
849
  }
850
+ /** Recovery info: how many cloud files exist, which are missing locally, which can be pulled. */
851
+ async getRecoveryInfo() {
852
+ if (!this.dataRecovery) {
853
+ throw new Error('Data recovery not configured. Call configureDataRecovery() first.');
854
+ }
855
+ return await this.dataRecovery.getRecoveryInfo();
856
+ }
857
+ /** List available backup/archived files in the client bucket. */
858
+ async listAvailableFiles() {
859
+ if (!this.dataRecovery) {
860
+ throw new Error('Data recovery not configured. Call configureDataRecovery() first.');
861
+ }
862
+ return await this.dataRecovery.listAvailableFiles();
863
+ }
864
+ /** List available tar.gz archive backups in the client bucket. */
865
+ async listAvailableArchives() {
866
+ if (!this.dataRecovery) {
867
+ throw new Error('Data recovery not configured. Call configureDataRecovery() first.');
868
+ }
869
+ return await this.dataRecovery.listAvailableArchives();
870
+ }
871
+ /** Check (HEAD) whether a single key exists in the client bucket. */
872
+ async checkFileInCloud(key) {
873
+ if (!this.dataRecovery) {
874
+ throw new Error('Data recovery not configured. Call configureDataRecovery() first.');
875
+ }
876
+ return await this.dataRecovery.checkFileInCloud(key);
877
+ }
878
+ /** Recover an entire archive backup (tar.gz) from the client bucket and extract locally. */
879
+ async recoverFromArchive(archiveName) {
880
+ if (!this.dataRecovery) {
881
+ throw new Error('Data recovery not configured. Call configureDataRecovery() first.');
882
+ }
883
+ return await this.dataRecovery.recoverFromArchive(archiveName);
884
+ }
885
+ /**
886
+ * Read a key locally; if absent locally, transparently recover it from the client's
887
+ * bucket and cache the result. Returns the data, or `false` if the key genuinely
888
+ * doesn't exist on either side. Throws for real (auth/network) errors so callers
889
+ * don't silently mistake them for "not in cloud".
890
+ *
891
+ * Options:
892
+ * - fallbackToCloud: boolean (default true) — set false to skip cloud fetch
893
+ * - mode: 'missing' (default) — only fetch if missing locally; 'all' — always overwrite from cloud
894
+ */
895
+ async getWithRecovery(key, options) {
896
+ try {
897
+ this.validateKey(key);
898
+ }
899
+ catch (error) {
900
+ throw error;
901
+ }
902
+ const fallbackToCloud = options?.fallbackToCloud ?? true;
903
+ // 1) Try local first.
904
+ const localData = await this.get(key);
905
+ if (localData !== false) {
906
+ return localData;
907
+ }
908
+ // 2) Not local. Optionally fall back to cloud.
909
+ if (!fallbackToCloud)
910
+ return false;
911
+ if (!this.dataRecovery) {
912
+ // No cloud configured — return false to keep "absent" semantics consistent with get().
913
+ return false;
914
+ }
915
+ // 3) Best-effort cloud fetch. If it fails for any reason (auth, network, timeout,
916
+ // no such key), we don't crash the local read path — `getWithRecovery` is a
917
+ // convenience GET that prefers local, falls back opportunistically. Separate
918
+ // methods (`recoverFromCloud`, `recoverAllFromCloud`) surface real cloud errors
919
+ // for the control plane / observability path to display.
920
+ try {
921
+ const recovered = await this.dataRecovery.recoverSingleFile(key);
922
+ if (!recovered) {
923
+ return false;
924
+ }
925
+ // Cache + return the freshly hydrated data.
926
+ // Re-run get() so the read goes through the cache + lint path.
927
+ this.cache.delete(key);
928
+ return await this.get(key);
929
+ }
930
+ catch (error) {
931
+ return false;
932
+ }
933
+ }
934
+ /**
935
+ * Probe local + cloud availability for a key without modifying local state.
936
+ * Returns { local, cloud, canRecover }:
937
+ * - local: true if the file exists locally
938
+ * - cloud: true if the file exists in the client bucket (HEAD)
939
+ * - canRecover: true if cloud has it but local doesn't
940
+ */
941
+ async existsWithCloudCheck(key) {
942
+ let local = false;
943
+ try {
944
+ this.validateKey(key);
945
+ local = this.exists(key);
946
+ }
947
+ catch {
948
+ return { local: false, cloud: false, canRecover: false };
949
+ }
950
+ let cloud = false;
951
+ if (this.dataRecovery) {
952
+ try {
953
+ const info = await this.dataRecovery.checkFileInCloud(key);
954
+ cloud = info.exists;
955
+ }
956
+ catch {
957
+ cloud = false; // auth/network failure → treat as not-available, but don't throw
958
+ }
959
+ }
960
+ return {
961
+ local,
962
+ cloud,
963
+ canRecover: cloud && !local,
964
+ };
965
+ }
966
+ // ---------------------------------------------------------------------------
379
967
  // Utility Methods
968
+ // ---------------------------------------------------------------------------
380
969
  getCacheStats() {
381
970
  const hitRate = this.cacheRequests > 0 ? (this.cacheHits / this.cacheRequests) * 100 : 0;
382
971
  return {
@@ -392,6 +981,8 @@ export class Tero {
392
981
  this.acidEngine.forceCheckpoint();
393
982
  }
394
983
  async verifyDataIntegrity() {
984
+ // Force-flush committedBuffer so the scan sees all committed data on disk.
985
+ this.acidEngine.flushCommittedBuffer();
395
986
  const result = {
396
987
  totalFiles: 0,
397
988
  corruptedFiles: [],
@@ -399,15 +990,18 @@ export class Tero {
399
990
  healthy: true
400
991
  };
401
992
  try {
402
- const { readdirSync } = await import('fs');
403
- const files = readdirSync(this.teroDirectory)
404
- .filter((file) => file.endsWith('.json'));
405
- result.totalFiles = files.length;
406
- for (const file of files) {
993
+ // Streaming partition walk — no readdirSync array allocation. Each leaf
994
+ // directory is visited async via fs.opendir iteration, so a 1M-key
995
+ // database doesn't allocate ~80MB of JS string objects in one tick.
996
+ const { walkPartitions } = await import('./acid-engine.js');
997
+ const { basename } = await import('path');
998
+ await walkPartitions(this.teroDirectory, async (filePath) => {
999
+ const file = basename(filePath);
407
1000
  const key = file.replace('.json', '');
1001
+ result.totalFiles++;
408
1002
  try {
409
1003
  const data = await this.get(key);
410
- if (data === null) {
1004
+ if (data === null || data === false) {
411
1005
  result.missingFiles.push(key);
412
1006
  result.healthy = false;
413
1007
  }
@@ -416,7 +1010,7 @@ export class Tero {
416
1010
  result.corruptedFiles.push(key);
417
1011
  result.healthy = false;
418
1012
  }
419
- }
1013
+ });
420
1014
  return result;
421
1015
  }
422
1016
  catch (error) {
@@ -426,6 +1020,44 @@ export class Tero {
426
1020
  clearCache() {
427
1021
  this.cache.clear();
428
1022
  }
1023
+ /**
1024
+ * Acquire an exclusive OS-level lock on the data directory via a .lock file.
1025
+ * Uses `openSync(path, 'wx')` — creates the file exclusively, failing if it
1026
+ * already exists (i.e., another process holds the lock). Cross-platform,
1027
+ * no native modules required. The fd is held open to maintain the lock;
1028
+ * destroying the Tero instance closes the fd and deletes the lock file.
1029
+ */
1030
+ acquireFileLock() {
1031
+ try {
1032
+ const lockPath = `${this.teroDirectory}/.lock`;
1033
+ this.lockFd = openSync(lockPath, 'wx'); // exclusive create — fails if exists
1034
+ writeSync(this.lockFd, String(process.pid));
1035
+ }
1036
+ catch {
1037
+ const lockPath = `${this.teroDirectory}/.lock`;
1038
+ let pid = '?';
1039
+ if (existsSync(lockPath)) {
1040
+ try {
1041
+ pid = readFileSync(lockPath, 'utf-8').trim();
1042
+ }
1043
+ catch { }
1044
+ }
1045
+ if (pid === String(process.pid)) {
1046
+ throw new Error(`Another Tero instance is already using '${this.teroDirectory}'. ` +
1047
+ 'Destroy the existing instance first, or delete the .lock file if the previous process crashed.');
1048
+ }
1049
+ throw new Error(`Data directory locked by process ${pid}. Use fileLock: true for exclusive cross-process access.`);
1050
+ }
1051
+ }
1052
+ releaseFileLock() {
1053
+ if (this.lockFd == null)
1054
+ return;
1055
+ try {
1056
+ closeSync(this.lockFd);
1057
+ unlinkSync(`${this.teroDirectory}/.lock`);
1058
+ }
1059
+ catch { /* best-effort */ }
1060
+ }
429
1061
  // Cleanup method
430
1062
  destroy() {
431
1063
  if (this.acidEngine) {
@@ -435,6 +1067,7 @@ export class Tero {
435
1067
  this.backupManager.destroy();
436
1068
  }
437
1069
  this.clearCache();
1070
+ this.releaseFileLock();
438
1071
  }
439
1072
  /**
440
1073
  * Generates a unique identifier with a custom prefix.