tero 0.0.8 → 0.0.10

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,15 +1,113 @@
1
1
  import { existsSync, mkdirSync, openSync, writeSync, closeSync, unlinkSync, readFileSync } from "fs";
2
- import { ACIDStorageEngine } from "./acid-engine.js";
2
+ import { resolve as pathResolve, relative as pathRelative } from "path";
3
+ import { ACIDStorageEngine, partitionedPath } from "./acid-engine.js";
3
4
  import { SchemaValidator } from "./schema.js";
4
5
  import { BackupManager } from "./backup.js";
5
6
  import { DataRecovery } from "./recovery.js";
6
7
  import { randomBytes } from "node:crypto";
7
8
  import QuickLRU from "quick-lru";
9
+ /**
10
+ * ObjectId-style ID generation state (getNewId). The 5-byte process-unique salt
11
+ * is drawn ONCE per process and the counter is a module-level monotonic value —
12
+ * regenerating either per call (the old behavior) made the documented uniqueness
13
+ * guarantee false: two IDs minted in the same second could collide, and every
14
+ * call paid a crypto entropy draw. This is both correct and faster.
15
+ */
16
+ const PROCESS_UNIQUE = randomBytes(5);
17
+ let idCounter = ~~(Math.random() * 0xffffff);
18
+ /**
19
+ * Clone for cache safety — hot-path optimized.
20
+ * Flat JSON docs (no nested objects/arrays) are shallow-copied via spread
21
+ * (~0.04µs) vs ~2.7µs for structuredClone — 60× faster. Bench tiny docs
22
+ * are flat, so hot cached `get()` stays near 500k ops/s instead of 85k.
23
+ * Nested docs fall through to structuredClone (preserves Dates, Arrays).
24
+ * Cloning on store *and* on return guarantees `doc = await get(k); doc.x=evil`
25
+ * cannot poison the LRU, and `data = {nested:{a:1}}; create(k,data); data.nested.a=2`
26
+ * cannot poison pendingWrites.
27
+ */
28
+ function deepClone(value) {
29
+ if (value === null || typeof value !== 'object')
30
+ return value;
31
+ if (!Array.isArray(value)) {
32
+ let hasNested = false;
33
+ for (const k in value) {
34
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
35
+ const v = value[k];
36
+ if (v !== null && typeof v === 'object') {
37
+ hasNested = true;
38
+ break;
39
+ }
40
+ }
41
+ }
42
+ if (!hasNested)
43
+ return { ...value };
44
+ const copy = {};
45
+ for (const k in value) {
46
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
47
+ const v = value[k];
48
+ copy[k] = (v !== null && typeof v === 'object') ? deepClone(v) : v;
49
+ }
50
+ }
51
+ return copy;
52
+ }
53
+ let hasNested = false;
54
+ const len = value.length;
55
+ for (let i = 0; i < len; i++) {
56
+ const v = value[i];
57
+ if (v !== null && typeof v === 'object') {
58
+ hasNested = true;
59
+ break;
60
+ }
61
+ }
62
+ if (!hasNested)
63
+ return [...value];
64
+ const arr = new Array(len);
65
+ for (let i = 0; i < len; i++) {
66
+ const el = value[i];
67
+ arr[i] = (el !== null && typeof el === 'object') ? deepClone(el) : el;
68
+ }
69
+ return arr;
70
+ }
71
+ /**
72
+ * Validate a user-supplied data directory name. Previously illegal characters
73
+ * were silently stripped ('my db' quietly became 'mydb' — users wrote to the
74
+ * wrong directory without knowing). Now: throw with an actionable message.
75
+ * Allowed: letters, digits, '_', '-', '/' separators; absolute paths are
76
+ * accepted as an explicit user choice; '..' segments always rejected; a
77
+ * RELATIVE path must resolve inside the process working directory.
78
+ * Called once at construction — zero hot-path cost. Returns the resolved
79
+ * absolute path so all downstream joins are unambiguous.
80
+ */
81
+ function validateDirectory(raw) {
82
+ const dir = raw.trim();
83
+ if (!dir)
84
+ throw new Error('Directory name cannot be empty.');
85
+ if (/[^A-Za-z0-9_\-./]/.test(dir)) {
86
+ throw new Error(`Invalid directory '${raw}': directory names may only contain letters, digits, '_', '-', '.' and '/' path separators.`);
87
+ }
88
+ const segments = dir.split('/').filter(s => s.length > 0);
89
+ if (segments.length === 0 || segments.includes('..')) {
90
+ throw new Error(`Invalid directory '${raw}': empty or contains '..' path traversal.`);
91
+ }
92
+ const resolved = pathResolve(dir);
93
+ const wasAbsolute = dir.startsWith('/');
94
+ if (!wasAbsolute) {
95
+ const rel = pathRelative(pathResolve('.'), resolved);
96
+ if (rel.startsWith('..')) {
97
+ throw new Error(`Invalid directory '${raw}': relative path escapes the working directory.`);
98
+ }
99
+ }
100
+ return resolved;
101
+ }
8
102
  export class Transaction {
9
103
  id;
10
104
  db;
11
105
  startTime;
12
106
  opCount = 0;
107
+ /** Real operation log backing getState() — the old implementation fabricated
108
+ * fake keys ('op_0', 'op_1', …) and labeled every operation 'write',
109
+ * including deletes. One array push per op: O(1), off the engine hot path. */
110
+ operationsLog = [];
13
111
  destroyed = false;
14
112
  timeoutTimer;
15
113
  constructor(id, db, options) {
@@ -51,16 +149,19 @@ export class Transaction {
51
149
  throw new Error(`Document '${key}' already exists`);
52
150
  await this.db._writeRaw(this.id, key, initialData || {});
53
151
  this.opCount++;
152
+ this.operationsLog.push({ key, operation: 'create' });
54
153
  }
55
154
  async update(key, data) {
56
155
  this._checkActive();
57
156
  await this.db._writeRaw(this.id, key, data);
58
157
  this.opCount++;
158
+ this.operationsLog.push({ key, operation: 'update' });
59
159
  }
60
160
  async delete(key) {
61
161
  this._checkActive();
62
162
  await this.db._deleteRaw(this.id, key);
63
163
  this.opCount++;
164
+ this.operationsLog.push({ key, operation: 'delete' });
64
165
  }
65
166
  async get(key) {
66
167
  this._checkActive();
@@ -70,7 +171,7 @@ export class Transaction {
70
171
  const status = this.db._getTxStatus(this.id);
71
172
  return {
72
173
  status: status === 'active' ? 'active' : (status === 'committed' ? 'committed' : 'rolled_back'),
73
- operations: Array.from({ length: this.opCount }, (_, i) => ({ key: `op_${i}`, operation: 'write' })),
174
+ operations: [...this.operationsLog],
74
175
  startTime: this.startTime
75
176
  };
76
177
  }
@@ -107,7 +208,7 @@ export class Tero {
107
208
  */
108
209
  knownKeys;
109
210
  KNOWN_KEYS_MAX = 10000;
110
- /** Optional exclusive file-lock fd on the data directory (flock, via fs-ext). */
211
+ /** Exclusive lock fd on <dir>/.lock (lock-file based; see acquireFileLock). */
111
212
  lockFd;
112
213
  /**
113
214
  * Construct an embedded Tero instance synchronously.
@@ -119,20 +220,27 @@ export class Tero {
119
220
  */
120
221
  constructor(config) {
121
222
  try {
223
+ // Validate live-backup requirements BEFORE creating any resources, so a
224
+ // misconfiguration can never leak a half-constructed engine or timers.
225
+ if (config?.liveBackup && !config.backup?.cloudStorage) {
226
+ throw new Error('config.liveBackup requires config.backup with cloudStorage configured — live backup needs a bucket.');
227
+ }
122
228
  const rawDirectory = config?.Directory || config?.directory;
123
229
  const { cacheSize, synchronous, commitIntervalMs, dataFlushIntervalMs } = config || {};
124
230
  if (typeof rawDirectory === "string" && rawDirectory.trim()) {
125
- // Sanitize directory path to prevent directory traversal
126
- this.teroDirectory = rawDirectory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
231
+ // Throw on illegal characters instead of silently stripping them —
232
+ // 'my db' used to quietly become 'mydb' and users wrote to the wrong
233
+ // directory. Also blocks absolute paths and traversal.
234
+ this.teroDirectory = validateDirectory(rawDirectory);
127
235
  }
128
236
  if (typeof cacheSize === "number" && cacheSize > 0) {
129
237
  this.cacheSize = Math.min(cacheSize, 1000); // Cap at 1k entries
130
238
  }
131
239
  // Create directories with proper error handling
132
240
  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.
241
+ // Optional cross-process lock: prevents two processes from opening the
242
+ // same data directory concurrently (addresses Google Pillar #2 —
243
+ // zero cross-process synchronization). Lock-file based, no native deps.
136
244
  if (config?.fileLock) {
137
245
  this.acquireFileLock();
138
246
  }
@@ -154,9 +262,16 @@ export class Tero {
154
262
  if (config?.backup) {
155
263
  this.configureBackup(config.backup);
156
264
  }
265
+ // v2: enable per-second live WAL shipping if configured.
266
+ if (config?.liveBackup) {
267
+ if (!this.backupManager) {
268
+ throw new Error('config.liveBackup requires config.backup with cloudStorage configured.');
269
+ }
270
+ this.enableLiveBackup(config.liveBackup);
271
+ }
157
272
  }
158
273
  catch (error) {
159
- throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`);
274
+ throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
160
275
  }
161
276
  }
162
277
  /**
@@ -170,8 +285,12 @@ export class Tero {
170
285
  return new Tero(config);
171
286
  }
172
287
  // Ensure directory exists first so DataRecovery can stream into it.
288
+ // MUST use validateDirectory() — the same validation the constructor
289
+ // applies. The old strip-regex diverged ('my db' hydrated into 'mydb'
290
+ // while `new Tero` resolved the real path below), causing split-brain
291
+ // directories where hydrated data became invisible to the engine.
173
292
  const rawDirectory = config?.Directory || config?.directory || 'TeroDB';
174
- const teroDirectory = rawDirectory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
293
+ const teroDirectory = validateDirectory(rawDirectory);
175
294
  if (!existsSync(teroDirectory)) {
176
295
  mkdirSync(teroDirectory, { recursive: true });
177
296
  }
@@ -184,39 +303,55 @@ export class Tero {
184
303
  mode: hydrate.mode === 'all' ? 'all' : 'missing',
185
304
  continueOnError: hydrate.continueOnError ?? true,
186
305
  });
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
306
+ const hydrateWork = async () => {
307
+ try {
308
+ const mode = hydrate.mode ?? 'missing';
309
+ if (mode === 'all') {
310
+ const r = await recovery.recoverIndividualFiles();
311
+ if (!r.success && r.failed.length > 0) { /* continue */ }
312
+ }
313
+ else if (mode === 'snapshot') {
314
+ // Snapshot-first: download the most recent tar.gz archive, extract it
315
+ // locally in bulk (one HTTP GET for potentially thousands of docs), then
316
+ // fill gaps with individual file recovery for any data written since the
317
+ // snapshot's checkpoint. This is the Google-recommended hydration pattern:
318
+ // one bulk download instead of sequential individual S3 GETs.
319
+ try {
320
+ const snapshotResult = await recovery.recoverFromArchive();
321
+ if (!snapshotResult.success) {
322
+ // Fall back to individual file recovery if no archive exists
323
+ const r = await recovery.recoverMissingFiles();
324
+ if (!r.success && r.failed.length > 0) { /* continue */ }
325
+ }
326
+ }
327
+ catch {
328
+ // Archive may not exist or may be corrupted; fall back gracefully
203
329
  const r = await recovery.recoverMissingFiles();
204
330
  if (!r.success && r.failed.length > 0) { /* continue */ }
205
331
  }
206
332
  }
207
- catch {
208
- // Archive may not exist or may be corrupted; fall back gracefully
333
+ else {
209
334
  const r = await recovery.recoverMissingFiles();
210
335
  if (!r.success && r.failed.length > 0) { /* continue */ }
211
336
  }
212
337
  }
213
- else {
214
- const r = await recovery.recoverMissingFiles();
215
- if (!r.success && r.failed.length > 0) { /* continue */ }
338
+ catch (error) {
339
+ // Hydration errors are non-fatal; engine init proceeds with whatever local data exists.
216
340
  }
341
+ };
342
+ // HydrateConfig.timeout was declared but never enforced — a hung bucket GET
343
+ // could block engine construction forever. Race the hydration against the
344
+ // deadline; on expiry the engine proceeds with whatever local state exists
345
+ // (same non-fatal contract as a hydration failure).
346
+ const timeoutMs = hydrate.timeout;
347
+ if (typeof timeoutMs === 'number' && timeoutMs > 0) {
348
+ await Promise.race([
349
+ hydrateWork(),
350
+ new Promise((resolve) => { const t = setTimeout(resolve, timeoutMs); t.unref?.(); }),
351
+ ]);
217
352
  }
218
- catch (error) {
219
- // Hydration errors are non-fatal; engine init proceeds with whatever local data exists.
353
+ else {
354
+ await hydrateWork();
220
355
  }
221
356
  // Now construct the engine in the usual way — it sees current local state and
222
357
  // runs crash recovery against the WAL for any writes between the last snapshot
@@ -265,7 +400,7 @@ export class Tero {
265
400
  }
266
401
  }
267
402
  catch (error) {
268
- throw new Error(`Failed to create directories: ${error instanceof Error ? error.message : 'Unknown error'}`);
403
+ throw new Error(`Failed to create directories: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
269
404
  }
270
405
  }
271
406
  validateKey(key) {
@@ -290,7 +425,7 @@ export class Tero {
290
425
  }
291
426
  updateCache(key, data, transactionId) {
292
427
  this.cache.set(key, {
293
- data: data,
428
+ data: deepClone(data),
294
429
  lastAccessed: Date.now(),
295
430
  transactionId
296
431
  });
@@ -312,7 +447,7 @@ export class Tero {
312
447
  return new Transaction(id, this, options);
313
448
  }
314
449
  catch (error) {
315
- throw new Error(`Failed to begin transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
450
+ throw new Error(`Failed to begin transaction: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
316
451
  }
317
452
  }
318
453
  _beginTransaction() {
@@ -344,8 +479,11 @@ export class Tero {
344
479
  // Use sanitized data from validation
345
480
  data = validationResult.data || data;
346
481
  }
482
+ // Check cache for beforeImage so engine doesn't need disk I/O on hot writes
483
+ const cachedEntry = this.cache.get(key);
484
+ const cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) ? cachedEntry.data : undefined;
347
485
  // Engine write — returns void (sync fast path) or Promise (contended lock)
348
- const writeResult = this.acidEngine.write(txId, key, data);
486
+ const writeResult = this.acidEngine.write(txId, key, data, cachedData);
349
487
  if (writeResult !== undefined)
350
488
  await writeResult;
351
489
  // Cache the MERGED afterImage (from pendingWrites), NOT the raw user data.
@@ -360,7 +498,7 @@ export class Tero {
360
498
  }
361
499
  }
362
500
  catch (error) {
363
- throw new Error(`Write failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
501
+ throw new Error(`Write failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
364
502
  }
365
503
  }
366
504
  async read(transactionId, key) {
@@ -372,8 +510,7 @@ export class Tero {
372
510
  const cachedEntry = this.cache.get(key);
373
511
  if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) {
374
512
  this.cacheHits++;
375
- cachedEntry.lastAccessed = Date.now();
376
- return cachedEntry.data;
513
+ return deepClone(cachedEntry.data);
377
514
  }
378
515
  // Read from ACID engine — returns data (sync fast path) or Promise (contended lock)
379
516
  const readResult = this.acidEngine.read(txId, key);
@@ -381,10 +518,10 @@ export class Tero {
381
518
  if (data !== null && data !== undefined) {
382
519
  this.updateCache(key, data, txId);
383
520
  }
384
- return data;
521
+ return deepClone(data);
385
522
  }
386
523
  catch (error) {
387
- throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
524
+ throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
388
525
  }
389
526
  }
390
527
  async commit(transactionId) {
@@ -411,7 +548,7 @@ export class Tero {
411
548
  this.committedCount++;
412
549
  }
413
550
  catch (error) {
414
- throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
551
+ throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
415
552
  }
416
553
  }
417
554
  async rollback(transactionId) {
@@ -430,7 +567,7 @@ export class Tero {
430
567
  this.rolledBackCount++;
431
568
  }
432
569
  catch (error) {
433
- throw new Error(`Failed to rollback transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
570
+ throw new Error(`Failed to rollback transaction: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
434
571
  }
435
572
  }
436
573
  async commitTransaction(transactionId) {
@@ -449,10 +586,29 @@ export class Tero {
449
586
  // Convenience Methods (Auto-transaction)
450
587
  async create(key, initialData, options) {
451
588
  this.validateKey(key);
452
- // Fast existence check via in-memory set — avoids existsSync syscall
589
+ // Fast existence check: LRU hit → known exists. On LRU miss we MUST
590
+ // verify on disk — a miss means either "new key" OR "evicted / cold-boot
591
+ // / restarted node". The previous `size >= MAX` guard only checked at
592
+ // capacity, so a cold boot with 1 existing doc would never hit the
593
+ // fallback and would silently overwrite via merge.
453
594
  if (this.knownKeys.has(key)) {
454
595
  return false; // already exists
455
596
  }
597
+ // Check committedBuffer before disk — a just-committed doc may not be
598
+ // flushed to its data file yet (deferred via committedBuffer, 50ms).
599
+ const pending = this.acidEngine.getCommittedData(key);
600
+ if (pending !== undefined) {
601
+ // committedBuffer says "exists" (write) or "deleted" (null tombstone)
602
+ if (pending !== null) {
603
+ this.knownKeys.set(key, true);
604
+ return false; // duplicate — already committed, not yet flushed
605
+ }
606
+ // tombstone → logically absent, fall through to allow re-create
607
+ }
608
+ else if (existsSync(this.keyToPath(key))) {
609
+ this.knownKeys.set(key, true); // re-pin; existed all along
610
+ return false;
611
+ }
456
612
  const transactionId = this._beginTransaction();
457
613
  try {
458
614
  const result = await this.write(transactionId, key, initialData || {}, options);
@@ -462,7 +618,7 @@ export class Tero {
462
618
  }
463
619
  catch (error) {
464
620
  await this.rollback(transactionId);
465
- throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
621
+ throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
466
622
  }
467
623
  }
468
624
  async update(key, data, options) {
@@ -496,8 +652,7 @@ export class Tero {
496
652
  const cachedEntry = this.cache.get(key);
497
653
  if (cachedEntry && !cachedEntry.transactionId) {
498
654
  this.cacheHits++;
499
- cachedEntry.lastAccessed = Date.now();
500
- return cachedEntry.data;
655
+ return deepClone(cachedEntry.data);
501
656
  }
502
657
  // 2. Check committedBuffer (committed but not yet flushed to data files)
503
658
  const committed = this.acidEngine.getCommittedData(key);
@@ -505,38 +660,34 @@ export class Tero {
505
660
  if (committed === null)
506
661
  return false;
507
662
  this.updateCache(key, committed, undefined);
508
- return committed;
663
+ return deepClone(committed);
509
664
  }
510
665
  // 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
666
  const filePath = this.keyToPath(key);
514
- if (!existsSyncFs(filePath)) {
667
+ if (!existsSync(filePath)) {
515
668
  return false;
516
669
  }
517
670
  try {
518
671
  const content = readFileSync(filePath, 'utf-8');
519
672
  const data = content.trim() ? JSON.parse(content) : {};
520
673
  this.updateCache(key, data, undefined);
521
- return data;
674
+ return deepClone(data);
522
675
  }
523
676
  catch (error) {
524
- throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
677
+ throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
525
678
  }
526
679
  }
527
680
  /**
528
681
  * 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.
682
+ * Delegates to the ENGINE'S partitionedPath() — the single authoritative
683
+ * implementation. The previous local FNV-1a re-implementation produced the
684
+ * same paths only by convention; if the two ever drifted, get() would read a
685
+ * different file than the engine writes (silent data loss). The engine's
686
+ * hash computes a 64-bit value (2 imul/char vs 1) but this runs only on
687
+ * cache-miss reads, which are syscall-dominated — measured impact: none.
530
688
  */
531
689
  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`;
690
+ return partitionedPath(this.teroDirectory, key);
540
691
  }
541
692
  async remove(key) {
542
693
  const transactionId = this._beginTransaction();
@@ -589,7 +740,7 @@ export class Tero {
589
740
  }
590
741
  catch (error) {
591
742
  await this.rollback(transactionId);
592
- throw new Error(`Batch write failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
743
+ throw new Error(`Batch write failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
593
744
  }
594
745
  }
595
746
  async batchRead(keys) {
@@ -604,7 +755,7 @@ export class Tero {
604
755
  }
605
756
  catch (error) {
606
757
  await this.rollback(transactionId);
607
- throw new Error(`Batch read failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
758
+ throw new Error(`Batch read failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
608
759
  }
609
760
  }
610
761
  // Money transfer example demonstrating ACID properties
@@ -614,7 +765,22 @@ export class Tero {
614
765
  }
615
766
  const transactionId = this._beginTransaction();
616
767
  try {
617
- // Read current balances
768
+ // Acquire exclusive locks in GLOBAL SORTED ORDER *before* reading.
769
+ // Two concurrent opposite-direction transfers (A→B and B→A) that
770
+ // first take shared locks on their source then try to upgrade to
771
+ // exclusive will deadlock (both hold shared, both wait for the
772
+ // other). Sorted exclusive acquisition + SERIALIZABLE reads avoids
773
+ // both the deadlock and the read-check-write overdraft race where
774
+ // two transfers both pass the balance check under shared locks.
775
+ const [firstKey, secondKey] = [fromKey, toKey].sort();
776
+ const a1 = this.acidEngine.acquireExclusiveLock(transactionId, firstKey);
777
+ if (a1 !== undefined)
778
+ await a1;
779
+ const a2 = this.acidEngine.acquireExclusiveLock(transactionId, secondKey);
780
+ if (a2 !== undefined)
781
+ await a2;
782
+ // Now reads are performed while already holding exclusive — they
783
+ // cannot interleave with another transfer's balance check.
618
784
  const fromAccount = await this.read(transactionId, fromKey);
619
785
  const toAccount = await this.read(transactionId, toKey);
620
786
  if (!fromAccount || !toAccount) {
@@ -623,44 +789,53 @@ export class Tero {
623
789
  if (fromAccount.balance < amount) {
624
790
  throw new Error('Insufficient funds');
625
791
  }
626
- // Update balances
627
- await this.write(transactionId, fromKey, {
628
- ...fromAccount,
629
- balance: fromAccount.balance - amount
630
- });
631
- await this.write(transactionId, toKey, {
632
- ...toAccount,
633
- balance: toAccount.balance + amount
634
- });
792
+ // Update balances — writes reuse the already-held exclusive locks
793
+ // (acquired above in sorted order), so no additional ordering needed.
794
+ const balances = { [fromKey]: fromAccount, [toKey]: toAccount };
795
+ const deltas = { [fromKey]: -amount, [toKey]: +amount };
796
+ for (const key of [firstKey, secondKey]) {
797
+ await this.write(transactionId, key, {
798
+ ...balances[key],
799
+ balance: balances[key].balance + deltas[key]
800
+ });
801
+ }
635
802
  // Commit the transaction
636
803
  await this.commit(transactionId);
637
804
  }
638
805
  catch (error) {
639
806
  await this.rollback(transactionId);
640
- throw new Error(`Money transfer failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
807
+ throw new Error(`Money transfer failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
641
808
  }
642
809
  }
643
810
  // Internal raw methods for Transaction class
644
811
  async _writeRaw(transactionId, key, data) {
645
- const result = this.acidEngine.write(transactionId, key, data);
812
+ const cachedEntry = this.cache.get(key);
813
+ const cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) ? cachedEntry.data : undefined;
814
+ const result = this.acidEngine.write(transactionId, key, data, cachedData);
646
815
  if (result !== undefined)
647
816
  await result;
648
- this.updateCache(key, data, transactionId);
817
+ // Cache the MERGED afterImage, not the raw caller input. The engine
818
+ // deep-merges partial updates with existing state, so caching `data`
819
+ // would poison the cache with incomplete documents — a second tx.update
820
+ // to the same key would lose fields written by the first update until a
821
+ // disk re-read. (Tero.write() does this correctly; the Transaction path
822
+ // goes through this raw method, so it must too.)
823
+ const afterImage = this.acidEngine.getPendingAfterImage(transactionId, key);
824
+ this.updateCache(key, afterImage !== undefined ? afterImage : data, transactionId);
649
825
  }
650
826
  async _readRaw(transactionId, key) {
651
827
  this.cacheRequests++;
652
828
  const cachedEntry = this.cache.get(key);
653
829
  if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) {
654
830
  this.cacheHits++;
655
- cachedEntry.lastAccessed = Date.now();
656
- return cachedEntry.data;
831
+ return deepClone(cachedEntry.data);
657
832
  }
658
833
  const result = this.acidEngine.read(transactionId, key);
659
834
  const data = (result !== undefined && result instanceof Promise) ? await result : result;
660
835
  if (data !== null && data !== undefined) {
661
836
  this.updateCache(key, data, transactionId);
662
837
  }
663
- return data;
838
+ return deepClone(data);
664
839
  }
665
840
  async _deleteRaw(transactionId, key) {
666
841
  const result = this.acidEngine.delete(transactionId, key);
@@ -671,6 +846,16 @@ export class Tero {
671
846
  }
672
847
  async _rollbackRaw(transactionId) {
673
848
  this.acidEngine.rollbackTransaction(transactionId);
849
+ // Invalidate cache entries this transaction touched and drop the tracking
850
+ // set. Without this, the timeout rollback path (Transaction constructor
851
+ // timer) leaves stale cache entries tagged with the dead txId, and
852
+ // txTouchedKeys grows unbounded across timed-out transactions.
853
+ const touched = this.txTouchedKeys.get(transactionId);
854
+ if (touched) {
855
+ for (const k of touched)
856
+ this.cache.delete(k);
857
+ this.txTouchedKeys.delete(transactionId);
858
+ }
674
859
  this.rolledBackCount++;
675
860
  }
676
861
  _getTxStatus(transactionId) {
@@ -691,7 +876,7 @@ export class Tero {
691
876
  this.schemaValidator.setSchema(collectionName, schema);
692
877
  }
693
878
  catch (error) {
694
- throw new Error(`Failed to set schema: ${error instanceof Error ? error.message : 'Unknown error'}`);
879
+ throw new Error(`Failed to set schema: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
695
880
  }
696
881
  }
697
882
  getSchema(collectionName) {
@@ -737,7 +922,7 @@ export class Tero {
737
922
  this.backupManager = new BackupManager(this.teroDirectory, config);
738
923
  }
739
924
  catch (error) {
740
- throw new Error(`Failed to configure backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
925
+ throw new Error(`Failed to configure backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
741
926
  }
742
927
  }
743
928
  /** Alias retained for the existing test surface / older callers. */
@@ -812,10 +997,57 @@ export class Tero {
812
997
  throw new Error('Backup not configured. Call configureBackup() first.');
813
998
  }
814
999
  this.acidEngine.forceCheckpoint();
1000
+ // Flush deferred data before archiving — mirrors commitTransaction()
1001
+ // rotation guard; otherwise committedBuffer data would be lost if we
1002
+ // crashed right after rotating and truncating .wal.
1003
+ this.acidEngine.flushCommittedBuffer?.();
815
1004
  this.acidEngine.getWAL().rotateLog();
816
1005
  return await this.backupToBucket(options);
817
1006
  }
818
1007
  // ---------------------------------------------------------------------------
1008
+ // Live Backup (per-second WAL shipping — RPO ≤ 1s)
1009
+ // ---------------------------------------------------------------------------
1010
+ /** Enable per-second live WAL shipping to the bucket. Only consistency: 'per-second'. */
1011
+ enableLiveBackup(opts) {
1012
+ if (!this.backupManager)
1013
+ throw new Error('Backup not configured. Call configureBackup() first.');
1014
+ this.backupManager.enableLiveBackup(this.acidEngine, opts);
1015
+ }
1016
+ /** Stop live WAL shipping. */
1017
+ disableLiveBackup() {
1018
+ this.backupManager?.disableLiveBackup();
1019
+ }
1020
+ /** Current live-backup health and counters. */
1021
+ getLiveBackupStatus() {
1022
+ if (!this.backupManager)
1023
+ return { state: 'stopped', nodeId: 'unknown', intervalMs: 0, lastShippedLsn: 0, lastShipAt: 0, secondsSinceLastShip: 0, segmentsShipped: 0, checkpointsTaken: 0, errorCount: 0 };
1024
+ return this.backupManager.getLiveBackupStatus();
1025
+ }
1026
+ /** Take a checkpoint: FULL on the first call after enable (also taken
1027
+ * automatically), INCREMENTAL (only dirty docs) on subsequent calls. */
1028
+ async liveCheckpointToBucket(opts) {
1029
+ if (!this.backupManager)
1030
+ throw new Error('Backup not configured. Call configureBackup() first.');
1031
+ // No flush here on purpose: the manager captures the conservative baseLsn
1032
+ // FIRST and flushes after — flushing before capture would be the wrong order.
1033
+ return await this.backupManager.liveCheckpointToBucket(opts);
1034
+ }
1035
+ /** Restore a fresh Tero instance from a live backup in the bucket. */
1036
+ static async restoreFromLiveBackup(opts) {
1037
+ const sanitized = validateDirectory(opts.directory);
1038
+ const source = validateDirectory(opts.sourceDirectory ?? opts.directory);
1039
+ // The temp manager is built with the SOURCE name so bucket prefixes resolve;
1040
+ // files are written into the sanitized TARGET directory.
1041
+ const tempMgr = new BackupManager(source, { format: 'individual', cloudStorage: opts.cloudStorage });
1042
+ try {
1043
+ await tempMgr.restoreLiveToDirectory(sanitized, { nodeId: opts.nodeId, pointInTime: opts.pointInTime });
1044
+ }
1045
+ finally {
1046
+ tempMgr.destroy();
1047
+ }
1048
+ return new Tero({ directory: opts.directory });
1049
+ }
1050
+ // ---------------------------------------------------------------------------
819
1051
  // Data Recovery
820
1052
  // ---------------------------------------------------------------------------
821
1053
  configureDataRecovery(config) {
@@ -823,7 +1055,7 @@ export class Tero {
823
1055
  this.dataRecovery = new DataRecovery(config);
824
1056
  }
825
1057
  catch (error) {
826
- throw new Error(`Failed to configure data recovery: ${error instanceof Error ? error.message : 'Unknown error'}`);
1058
+ throw new Error(`Failed to configure data recovery: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
827
1059
  }
828
1060
  }
829
1061
  async recoverFromCloud(key) {
@@ -1014,40 +1246,72 @@ export class Tero {
1014
1246
  return result;
1015
1247
  }
1016
1248
  catch (error) {
1017
- throw new Error(`Data integrity verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
1249
+ throw new Error(`Data integrity verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
1018
1250
  }
1019
1251
  }
1020
1252
  clearCache() {
1021
1253
  this.cache.clear();
1022
1254
  }
1023
1255
  /**
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.
1256
+ * Acquire an exclusive lock on the data directory via a `.lock` file
1257
+ * (openSync 'wx' exclusive-create — no native modules, cross-platform).
1258
+ * The holder's PID is written to the file; if acquisition fails and the
1259
+ * recorded PID is no longer alive, the stale lock from a crashed process
1260
+ * is reclaimed automatically.
1029
1261
  */
1030
1262
  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));
1263
+ const lockPath = `${this.teroDirectory}/.lock`;
1264
+ const tryAcquire = () => {
1265
+ try {
1266
+ this.lockFd = openSync(lockPath, 'wx'); // exclusive create — fails if exists
1267
+ writeSync(this.lockFd, String(process.pid));
1268
+ return true;
1269
+ }
1270
+ catch {
1271
+ return false;
1272
+ }
1273
+ };
1274
+ if (tryAcquire())
1275
+ return;
1276
+ // Held by someone (or stale). Read the holder PID and check liveness.
1277
+ let pid = '?';
1278
+ if (existsSync(lockPath)) {
1279
+ try {
1280
+ pid = readFileSync(lockPath, 'utf-8').trim();
1281
+ }
1282
+ catch { /* unreadable */ }
1035
1283
  }
1036
- catch {
1037
- const lockPath = `${this.teroDirectory}/.lock`;
1038
- let pid = '?';
1039
- if (existsSync(lockPath)) {
1284
+ const pidNum = parseInt(pid, 10);
1285
+ if (Number.isInteger(pidNum) && pidNum > 0 && pidNum !== process.pid) {
1286
+ let alive = true;
1287
+ try {
1288
+ process.kill(pidNum, 0);
1289
+ }
1290
+ catch (e) {
1291
+ // ESRCH = no such process → stale lock from a crashed holder.
1292
+ // EPERM = process exists but is owned by another user → treat as alive.
1293
+ alive = e?.code === 'EPERM';
1294
+ }
1295
+ if (!alive) {
1296
+ // Reclaim the stale lock (crashed previous owner) and retry once.
1040
1297
  try {
1041
- pid = readFileSync(lockPath, 'utf-8').trim();
1298
+ unlinkSync(lockPath);
1042
1299
  }
1043
- catch { }
1300
+ catch { /* racing holder */ }
1301
+ if (tryAcquire())
1302
+ return;
1044
1303
  }
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.');
1304
+ if (alive) {
1305
+ throw new Error(`Data directory '${this.teroDirectory}' is locked by live process ${pidNum}. ` +
1306
+ 'Stop that process (or use a different directory) and retry.');
1048
1307
  }
1049
- throw new Error(`Data directory locked by process ${pid}. Use fileLock: true for exclusive cross-process access.`);
1050
1308
  }
1309
+ if (pid === String(process.pid)) {
1310
+ throw new Error(`Another Tero instance in THIS process is already using '${this.teroDirectory}'. ` +
1311
+ 'Destroy the existing instance before constructing a new one.');
1312
+ }
1313
+ throw new Error(`Data directory '${this.teroDirectory}' is locked (holder PID: ${pid}). ` +
1314
+ `If the holder crashed, delete '${lockPath}' and retry.`);
1051
1315
  }
1052
1316
  releaseFileLock() {
1053
1317
  if (this.lockFd == null)
@@ -1097,11 +1361,12 @@ export class Tero {
1097
1361
  * ```
1098
1362
  */
1099
1363
  getNewId(prefix) {
1100
- const PROCESS_UNIQUE = randomBytes(5);
1101
1364
  const buffer = Buffer.allocUnsafe(12);
1102
- let index = ~~(Math.random() * 0xffffff);
1103
1365
  const time = ~~(Date.now() / 1000);
1104
- const inc = (index = (index + 1) % 0xffffff);
1366
+ // Module-level monotonic counter (see PROCESS_UNIQUE above) — guarantees
1367
+ // within-process uniqueness even for ids minted in the same millisecond,
1368
+ // with zero crypto calls on this path.
1369
+ const inc = (idCounter = (idCounter + 1) % 0xffffff);
1105
1370
  // 4-byte timestamp (seconds since Unix epoch)
1106
1371
  buffer.writeUInt32BE(time, 0);
1107
1372
  // 5-byte process unique identifier