tero 0.0.6 → 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,4 +1,4 @@
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";
@@ -99,10 +99,28 @@ export class Tero {
99
99
  dataRecovery;
100
100
  committedCount = 0;
101
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
+ */
102
120
  constructor(config) {
103
121
  try {
104
122
  const rawDirectory = config?.Directory || config?.directory;
105
- const { cacheSize } = config || {};
123
+ const { cacheSize, synchronous, commitIntervalMs, dataFlushIntervalMs } = config || {};
106
124
  if (typeof rawDirectory === "string" && rawDirectory.trim()) {
107
125
  // Sanitize directory path to prevent directory traversal
108
126
  this.teroDirectory = rawDirectory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
@@ -112,19 +130,130 @@ export class Tero {
112
130
  }
113
131
  // Create directories with proper error handling
114
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
+ }
115
139
  // Initialize QuickLRU cache
116
140
  this.cache = new QuickLRU({
117
141
  maxSize: this.cacheSize
118
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 });
119
146
  // Initialize ACID storage engine (primary system)
120
- 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);
121
151
  // Initialize schema validator
122
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
+ }
123
157
  }
124
158
  catch (error) {
125
159
  throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`);
126
160
  }
127
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
+ }
128
257
  initializeDirectories() {
129
258
  try {
130
259
  if (!existsSync(this.teroDirectory)) {
@@ -148,6 +277,12 @@ export class Tero {
148
277
  throw new Error('Key contains invalid characters');
149
278
  }
150
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();
151
286
  invalidateCacheKeys(keys) {
152
287
  for (const key of keys) {
153
288
  this.cache.delete(key);
@@ -159,6 +294,16 @@ export class Tero {
159
294
  lastAccessed: Date.now(),
160
295
  transactionId
161
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
+ }
162
307
  }
163
308
  // Core ACID Operations
164
309
  beginTransaction(options) {
@@ -199,9 +344,17 @@ export class Tero {
199
344
  // Use sanitized data from validation
200
345
  data = validationResult.data || data;
201
346
  }
202
- await this.acidEngine.write(txId, key, data);
203
- // Update cache with transaction context
204
- this.updateCache(key, data, txId);
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);
205
358
  if (options?.validate || options?.schemaName) {
206
359
  return { valid: true, errors: [], data };
207
360
  }
@@ -222,9 +375,10 @@ export class Tero {
222
375
  cachedEntry.lastAccessed = Date.now();
223
376
  return cachedEntry.data;
224
377
  }
225
- // Read from ACID engine
226
- const data = await this.acidEngine.read(txId, key);
227
- if (data !== null) {
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) {
228
382
  this.updateCache(key, data, txId);
229
383
  }
230
384
  return data;
@@ -236,20 +390,24 @@ export class Tero {
236
390
  async commit(transactionId) {
237
391
  try {
238
392
  const txId = this._txId(transactionId);
239
- // Get affected keys before commit
240
- const transaction = this.acidEngine.getActiveTransactions().includes(txId);
241
- if (!transaction) {
393
+ // O(1) active check — was O(N) via getActiveTransactions().includes()
394
+ if (!this.acidEngine.isTransactionActive(txId)) {
242
395
  throw new Error(`Transaction ${txId} not found or not active`);
243
396
  }
244
- await this.acidEngine.commitTransaction(txId);
245
- // Invalidate cache entries for this transaction to force fresh reads
246
- const keysToInvalidate = [];
247
- for (const [key, entry] of this.cache.entries()) {
248
- if (entry.transactionId === txId) {
249
- 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
+ }
250
408
  }
409
+ this.txTouchedKeys.delete(txId);
251
410
  }
252
- this.invalidateCacheKeys(keysToInvalidate);
253
411
  this.committedCount++;
254
412
  }
255
413
  catch (error) {
@@ -259,15 +417,16 @@ export class Tero {
259
417
  async rollback(transactionId) {
260
418
  try {
261
419
  const txId = this._txId(transactionId);
262
- await this.acidEngine.rollbackTransaction(txId);
263
- // Remove cache entries for this transaction
264
- const keysToRemove = [];
265
- for (const [key, entry] of this.cache.entries()) {
266
- if (entry.transactionId === txId) {
267
- keysToRemove.push(key);
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);
268
427
  }
428
+ this.txTouchedKeys.delete(txId);
269
429
  }
270
- this.invalidateCacheKeys(keysToRemove);
271
430
  this.rolledBackCount++;
272
431
  }
273
432
  catch (error) {
@@ -289,17 +448,16 @@ export class Tero {
289
448
  }
290
449
  // Convenience Methods (Auto-transaction)
291
450
  async create(key, initialData, options) {
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
+ }
292
456
  const transactionId = this._beginTransaction();
293
457
  try {
294
- // Check if file already exists
295
- const existing = await this.read(transactionId, key);
296
- if (existing !== null) {
297
- await this.rollback(transactionId);
298
- return false; // File already exists
299
- }
300
- // Create with initial data or empty object
301
458
  const result = await this.write(transactionId, key, initialData || {}, options);
302
459
  await this.commit(transactionId);
460
+ this.knownKeys.set(key, true);
303
461
  return result || true;
304
462
  }
305
463
  catch (error) {
@@ -319,23 +477,73 @@ export class Tero {
319
477
  throw error;
320
478
  }
321
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
+ */
322
492
  async get(key) {
323
- 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
+ }
324
517
  try {
325
- const data = await this.read(transactionId, key);
326
- await this.commit(transactionId);
327
- return data === null ? false : data;
518
+ const content = readFileSync(filePath, 'utf-8');
519
+ const data = content.trim() ? JSON.parse(content) : {};
520
+ this.updateCache(key, data, undefined);
521
+ return data;
328
522
  }
329
523
  catch (error) {
330
- await this.rollback(transactionId);
331
- throw error;
524
+ throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
525
+ }
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;
332
537
  }
538
+ const hex = h.toString(16).padStart(8, '0');
539
+ return `${this.teroDirectory}/${hex.slice(0, 2)}/${hex.slice(2, 4)}/${key}.json`;
333
540
  }
334
541
  async remove(key) {
335
542
  const transactionId = this._beginTransaction();
336
543
  try {
337
544
  await this._deleteRaw(transactionId, key);
338
545
  await this.commit(transactionId);
546
+ this.knownKeys.delete(key);
339
547
  }
340
548
  catch (error) {
341
549
  await this.rollback(transactionId);
@@ -348,7 +556,20 @@ export class Tero {
348
556
  exists(key) {
349
557
  try {
350
558
  this.validateKey(key);
351
- 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;
352
573
  }
353
574
  catch (error) {
354
575
  return false;
@@ -362,6 +583,9 @@ export class Tero {
362
583
  await this.write(transactionId, op.key, op.data, options);
363
584
  }
364
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);
365
589
  }
366
590
  catch (error) {
367
591
  await this.rollback(transactionId);
@@ -418,7 +642,9 @@ export class Tero {
418
642
  }
419
643
  // Internal raw methods for Transaction class
420
644
  async _writeRaw(transactionId, key, data) {
421
- await this.acidEngine.write(transactionId, key, data);
645
+ const result = this.acidEngine.write(transactionId, key, data);
646
+ if (result !== undefined)
647
+ await result;
422
648
  this.updateCache(key, data, transactionId);
423
649
  }
424
650
  async _readRaw(transactionId, key) {
@@ -429,18 +655,22 @@ export class Tero {
429
655
  cachedEntry.lastAccessed = Date.now();
430
656
  return cachedEntry.data;
431
657
  }
432
- const data = await this.acidEngine.read(transactionId, key);
433
- if (data !== null) {
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) {
434
661
  this.updateCache(key, data, transactionId);
435
662
  }
436
663
  return data;
437
664
  }
438
665
  async _deleteRaw(transactionId, key) {
439
- await this.acidEngine.delete(transactionId, key);
666
+ const result = this.acidEngine.delete(transactionId, key);
667
+ if (result !== undefined)
668
+ await result;
440
669
  this.cache.delete(key);
670
+ this.knownKeys.delete(key);
441
671
  }
442
672
  async _rollbackRaw(transactionId) {
443
- await this.acidEngine.rollbackTransaction(transactionId);
673
+ this.acidEngine.rollbackTransaction(transactionId);
444
674
  this.rolledBackCount++;
445
675
  }
446
676
  _getTxStatus(transactionId) {
@@ -499,7 +729,9 @@ export class Tero {
499
729
  }
500
730
  return result;
501
731
  }
732
+ // ---------------------------------------------------------------------------
502
733
  // Backup Management
734
+ // ---------------------------------------------------------------------------
503
735
  configureBackup(config) {
504
736
  try {
505
737
  this.backupManager = new BackupManager(this.teroDirectory, config);
@@ -508,13 +740,84 @@ export class Tero {
508
740
  throw new Error(`Failed to configure backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
509
741
  }
510
742
  }
743
+ /** Alias retained for the existing test surface / older callers. */
744
+ configureAdvancedBackup(config) {
745
+ this.configureBackup(config);
746
+ }
511
747
  async performBackup() {
512
748
  if (!this.backupManager) {
513
749
  throw new Error('Backup not configured. Call configureBackup() first.');
514
750
  }
751
+ // Force-flush committedBuffer to data files so the backup sees the latest state.
752
+ this.acidEngine.flushCommittedBuffer();
753
+ this.acidEngine.forceCheckpoint();
515
754
  return await this.backupManager.performBackup();
516
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
+ // ---------------------------------------------------------------------------
517
819
  // Data Recovery
820
+ // ---------------------------------------------------------------------------
518
821
  configureDataRecovery(config) {
519
822
  try {
520
823
  this.dataRecovery = new DataRecovery(config);
@@ -544,7 +847,125 @@ export class Tero {
544
847
  }
545
848
  return result;
546
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
+ // ---------------------------------------------------------------------------
547
967
  // Utility Methods
968
+ // ---------------------------------------------------------------------------
548
969
  getCacheStats() {
549
970
  const hitRate = this.cacheRequests > 0 ? (this.cacheHits / this.cacheRequests) * 100 : 0;
550
971
  return {
@@ -560,6 +981,8 @@ export class Tero {
560
981
  this.acidEngine.forceCheckpoint();
561
982
  }
562
983
  async verifyDataIntegrity() {
984
+ // Force-flush committedBuffer so the scan sees all committed data on disk.
985
+ this.acidEngine.flushCommittedBuffer();
563
986
  const result = {
564
987
  totalFiles: 0,
565
988
  corruptedFiles: [],
@@ -567,15 +990,18 @@ export class Tero {
567
990
  healthy: true
568
991
  };
569
992
  try {
570
- const { readdirSync } = await import('fs');
571
- const files = readdirSync(this.teroDirectory)
572
- .filter((file) => file.endsWith('.json'));
573
- result.totalFiles = files.length;
574
- 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);
575
1000
  const key = file.replace('.json', '');
1001
+ result.totalFiles++;
576
1002
  try {
577
1003
  const data = await this.get(key);
578
- if (data === null) {
1004
+ if (data === null || data === false) {
579
1005
  result.missingFiles.push(key);
580
1006
  result.healthy = false;
581
1007
  }
@@ -584,7 +1010,7 @@ export class Tero {
584
1010
  result.corruptedFiles.push(key);
585
1011
  result.healthy = false;
586
1012
  }
587
- }
1013
+ });
588
1014
  return result;
589
1015
  }
590
1016
  catch (error) {
@@ -594,6 +1020,44 @@ export class Tero {
594
1020
  clearCache() {
595
1021
  this.cache.clear();
596
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
+ }
597
1061
  // Cleanup method
598
1062
  destroy() {
599
1063
  if (this.acidEngine) {
@@ -603,6 +1067,7 @@ export class Tero {
603
1067
  this.backupManager.destroy();
604
1068
  }
605
1069
  this.clearCache();
1070
+ this.releaseFileLock();
606
1071
  }
607
1072
  /**
608
1073
  * Generates a unique identifier with a custom prefix.