tero 0.0.9 → 0.0.12

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,16 +1,124 @@
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
+ const MAX_DOCUMENT_DEPTH = 32;
19
+ const MAX_DOCUMENT_SIZE = 16 * 1024 * 1024; // 16MB max document size limit
20
+ /**
21
+ * Clone for cache safety — hot-path optimized.
22
+ * Flat JSON docs (no nested objects/arrays) are shallow-copied via spread
23
+ * (~0.04µs) vs ~2.7µs for structuredClone — 60× faster. Bench tiny docs
24
+ * are flat, so hot cached `get()` stays near 500k ops/s instead of 85k.
25
+ * Nested docs are recursively cloned with depth and cycle guards.
26
+ */
27
+ function deepClone(value, depth = 0, seen = new WeakSet()) {
28
+ if (value === null || typeof value !== 'object')
29
+ return value;
30
+ if (depth > MAX_DOCUMENT_DEPTH) {
31
+ throw new Error(`Document depth exceeds maximum allowed depth (${MAX_DOCUMENT_DEPTH})`);
32
+ }
33
+ if (!Array.isArray(value)) {
34
+ let hasNested = false;
35
+ for (const k in value) {
36
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
37
+ const v = value[k];
38
+ if (v !== null && typeof v === 'object') {
39
+ hasNested = true;
40
+ break;
41
+ }
42
+ }
43
+ }
44
+ if (!hasNested)
45
+ return { ...value };
46
+ if (seen.has(value)) {
47
+ throw new Error('Circular reference detected in document');
48
+ }
49
+ seen.add(value);
50
+ const copy = {};
51
+ for (const k in value) {
52
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
53
+ const v = value[k];
54
+ copy[k] = (v !== null && typeof v === 'object') ? deepClone(v, depth + 1, seen) : v;
55
+ }
56
+ }
57
+ seen.delete(value);
58
+ return copy;
59
+ }
60
+ let hasNested = false;
61
+ const len = value.length;
62
+ for (let i = 0; i < len; i++) {
63
+ const v = value[i];
64
+ if (v !== null && typeof v === 'object') {
65
+ hasNested = true;
66
+ break;
67
+ }
68
+ }
69
+ if (!hasNested)
70
+ return [...value];
71
+ if (seen.has(value)) {
72
+ throw new Error('Circular reference detected in document');
73
+ }
74
+ seen.add(value);
75
+ const arr = new Array(len);
76
+ for (let i = 0; i < len; i++) {
77
+ const el = value[i];
78
+ arr[i] = (el !== null && typeof el === 'object') ? deepClone(el, depth + 1, seen) : el;
79
+ }
80
+ seen.delete(value);
81
+ return arr;
82
+ }
83
+ /**
84
+ * Validate a user-supplied data directory name.
85
+ */
86
+ function validateDirectory(raw) {
87
+ const dir = raw.trim();
88
+ if (!dir)
89
+ throw new Error('Directory name cannot be empty.');
90
+ if (dir === '.' || dir === './') {
91
+ throw new Error(`Invalid directory '${raw}': cannot use working directory root as database directory. Specify a named directory.`);
92
+ }
93
+ if (/[^A-Za-z0-9_\-./]/.test(dir)) {
94
+ throw new Error(`Invalid directory '${raw}': directory names may only contain letters, digits, '_', '-', '.' and '/' path separators.`);
95
+ }
96
+ const segments = dir.split('/').filter(s => s.length > 0);
97
+ if (segments.length === 0 || segments.includes('..')) {
98
+ throw new Error(`Invalid directory '${raw}': empty or contains '..' path traversal.`);
99
+ }
100
+ const resolved = pathResolve(dir);
101
+ const wasAbsolute = dir.startsWith('/');
102
+ if (!wasAbsolute) {
103
+ const rel = pathRelative(pathResolve('.'), resolved);
104
+ if (rel.startsWith('..')) {
105
+ throw new Error(`Invalid directory '${raw}': relative path escapes the working directory.`);
106
+ }
107
+ }
108
+ return resolved;
109
+ }
8
110
  export class Transaction {
9
111
  id;
10
112
  db;
11
113
  startTime;
12
114
  opCount = 0;
115
+ /** Real operation log backing getState() — the old implementation fabricated
116
+ * fake keys ('op_0', 'op_1', …) and labeled every operation 'write',
117
+ * including deletes. One array push per op: O(1), off the engine hot path. */
118
+ operationsLog = [];
13
119
  destroyed = false;
120
+ committed = false;
121
+ rolledBack = false;
14
122
  timeoutTimer;
15
123
  constructor(id, db, options) {
16
124
  this.id = id;
@@ -19,69 +127,142 @@ export class Transaction {
19
127
  if (options?.timeout) {
20
128
  this.timeoutTimer = setTimeout(() => {
21
129
  this.destroyed = true;
130
+ this.rolledBack = true;
22
131
  this.db._rollbackRaw(this.id).catch(() => { });
23
132
  }, options.timeout);
133
+ this.timeoutTimer.unref?.();
24
134
  }
25
135
  }
26
136
  getId() {
27
137
  return this.id;
28
138
  }
29
139
  isActive() {
30
- if (this.destroyed)
140
+ if (this.destroyed || this.committed || this.rolledBack)
31
141
  return false;
32
142
  return this.db.getActiveTransactions().includes(this.id);
33
143
  }
34
144
  isRolledBack() {
35
- return !this.isActive();
145
+ if (this.rolledBack)
146
+ return true;
147
+ if (this.destroyed)
148
+ return true;
149
+ const status = this.db._getTxStatus(this.id);
150
+ if (status === 'aborted') {
151
+ this.rolledBack = true;
152
+ return true;
153
+ }
154
+ return false;
155
+ }
156
+ isCommitted() {
157
+ if (this.committed)
158
+ return true;
159
+ return this.db._getTxStatus(this.id) === 'committed';
36
160
  }
37
161
  _checkActive() {
38
162
  if (this.destroyed)
39
163
  throw new Error('Transaction has been destroyed');
164
+ if (this.committed)
165
+ throw new Error('Transaction has already been committed');
166
+ if (this.rolledBack)
167
+ throw new Error('Transaction has been rolled back');
40
168
  const status = this.db._getTxStatus(this.id);
41
- if (status === 'committed')
169
+ if (status === 'committed') {
170
+ this.committed = true;
42
171
  throw new Error('Transaction has already been committed');
43
- if (status === 'aborted')
172
+ }
173
+ if (status === 'aborted') {
174
+ this.rolledBack = true;
44
175
  throw new Error('Transaction has been rolled back');
45
- if (status === 'not_found')
176
+ }
177
+ if (status === 'not_found') {
178
+ // Engine GC'd the transaction (after commit/rollback). Use local flags to give precise error
179
+ if (this.committed)
180
+ throw new Error('Transaction has already been committed');
181
+ if (this.rolledBack)
182
+ throw new Error('Transaction has been rolled back');
46
183
  throw new Error('Transaction is not active');
184
+ }
47
185
  }
48
186
  async create(key, initialData) {
49
187
  this._checkActive();
188
+ // Acquire exclusive lock BEFORE existence check to close TOCTOU
189
+ // (two concurrent create('same') both passed exists() before either held the lock)
190
+ const lockRes = this.db.acidEngine.acquireExclusiveLock(this.id, key);
191
+ if (lockRes instanceof Promise)
192
+ await lockRes;
50
193
  if (this.db.exists(key))
51
194
  throw new Error(`Document '${key}' already exists`);
52
195
  await this.db._writeRaw(this.id, key, initialData || {});
53
196
  this.opCount++;
197
+ this.operationsLog.push({ key, operation: 'create' });
54
198
  }
55
199
  async update(key, data) {
56
200
  this._checkActive();
57
201
  await this.db._writeRaw(this.id, key, data);
58
202
  this.opCount++;
203
+ this.operationsLog.push({ key, operation: 'update' });
59
204
  }
60
205
  async delete(key) {
61
206
  this._checkActive();
62
207
  await this.db._deleteRaw(this.id, key);
63
208
  this.opCount++;
209
+ this.operationsLog.push({ key, operation: 'delete' });
64
210
  }
65
- async get(key) {
211
+ /**
212
+ * Read document within this transaction.
213
+ * @param options.lock - 'shared' (default) or 'exclusive' (SELECT FOR UPDATE)
214
+ */
215
+ async get(key, options) {
66
216
  this._checkActive();
67
- return await this.db._readRaw(this.id, key);
217
+ return await this.db.read(this.id, key, options);
218
+ }
219
+ /**
220
+ * Alias for get() with explicit locking semantics.
221
+ * @param options.lock - 'shared' (default) or 'exclusive' (SELECT FOR UPDATE)
222
+ */
223
+ async read(key, options) {
224
+ this._checkActive();
225
+ return await this.db.read(this.id, key, options);
68
226
  }
69
227
  getState() {
228
+ if (this.committed)
229
+ return { status: 'committed', operations: [...this.operationsLog], startTime: this.startTime };
230
+ if (this.rolledBack || this.destroyed) {
231
+ const s = this.db._getTxStatus(this.id);
232
+ if (s === 'aborted' || this.rolledBack)
233
+ return { status: 'rolled_back', operations: [...this.operationsLog], startTime: this.startTime };
234
+ }
70
235
  const status = this.db._getTxStatus(this.id);
71
236
  return {
72
237
  status: status === 'active' ? 'active' : (status === 'committed' ? 'committed' : 'rolled_back'),
73
- operations: Array.from({ length: this.opCount }, (_, i) => ({ key: `op_${i}`, operation: 'write' })),
238
+ operations: [...this.operationsLog],
74
239
  startTime: this.startTime
75
240
  };
76
241
  }
77
242
  getOperationCount() {
78
243
  return this.opCount;
79
244
  }
80
- getDuration() {
81
- return Date.now() - this.startTime;
245
+ async commit() {
246
+ this._checkActive();
247
+ if (this.timeoutTimer)
248
+ clearTimeout(this.timeoutTimer);
249
+ await this.db.commit(this.id);
250
+ this.committed = true;
251
+ }
252
+ async abort() {
253
+ if (this.destroyed)
254
+ return;
255
+ if (this.timeoutTimer)
256
+ clearTimeout(this.timeoutTimer);
257
+ await this.db._rollbackRaw(this.id);
258
+ this.rolledBack = true;
259
+ }
260
+ async rollback() {
261
+ await this.abort();
82
262
  }
83
263
  destroy() {
84
264
  this.destroyed = true;
265
+ this.rolledBack = true;
85
266
  if (this.timeoutTimer)
86
267
  clearTimeout(this.timeoutTimer);
87
268
  this.db._rollbackRaw(this.id).catch(() => { });
@@ -107,7 +288,7 @@ export class Tero {
107
288
  */
108
289
  knownKeys;
109
290
  KNOWN_KEYS_MAX = 10000;
110
- /** Optional exclusive file-lock fd on the data directory (flock, via fs-ext). */
291
+ /** Exclusive lock fd on <dir>/.lock (lock-file based; see acquireFileLock). */
111
292
  lockFd;
112
293
  /**
113
294
  * Construct an embedded Tero instance synchronously.
@@ -119,21 +300,33 @@ export class Tero {
119
300
  */
120
301
  constructor(config) {
121
302
  try {
122
- const rawDirectory = config?.Directory || config?.directory;
303
+ // Validate live-backup requirements BEFORE creating any resources, so a
304
+ // misconfiguration can never leak a half-constructed engine or timers.
305
+ if (config?.liveBackup && !config.backup?.cloudStorage) {
306
+ throw new Error('config.liveBackup requires config.backup with cloudStorage configured — live backup needs a bucket.');
307
+ }
308
+ const rawDirectory = config?.directory;
123
309
  const { cacheSize, synchronous, commitIntervalMs, dataFlushIntervalMs } = config || {};
310
+ if (synchronous && !['full', 'normal', 'off'].includes(synchronous)) {
311
+ throw new Error(`Invalid synchronous mode '${synchronous}'. Expected 'full', 'normal', or 'off'.`);
312
+ }
313
+ if (synchronous === 'off' && (process.env.TERO_ALLOW_UNSAFE_OFF !== '1' && process.env.NODE_ENV !== 'test' && process.env.NODE_ENV !== 'development')) {
314
+ throw new Error("synchronous='off' is not allowed — it disables all fsync and will lose data on crash. Use 'full' or 'normal'. Set TERO_ALLOW_UNSAFE_OFF=1 to force in benchmarks.");
315
+ }
124
316
  if (typeof rawDirectory === "string" && rawDirectory.trim()) {
125
- // Sanitize directory path to prevent directory traversal
126
- this.teroDirectory = rawDirectory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
317
+ // Throw on illegal characters instead of silently stripping them —
318
+ // 'my db' used to quietly become 'mydb' and users wrote to the wrong
319
+ // directory. Also blocks absolute paths and traversal.
320
+ this.teroDirectory = validateDirectory(rawDirectory);
127
321
  }
128
322
  if (typeof cacheSize === "number" && cacheSize > 0) {
129
- this.cacheSize = Math.min(cacheSize, 1000); // Cap at 1k entries
323
+ this.cacheSize = cacheSize;
130
324
  }
131
325
  // Create directories with proper error handling
132
326
  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) {
327
+ // Cross-process lock enabled by default — prevents two processes from opening the
328
+ // same data directory concurrently (Google Pillar #2). Set fileLock: false to disable.
329
+ if (config?.fileLock !== false) {
137
330
  this.acquireFileLock();
138
331
  }
139
332
  // Initialize QuickLRU cache
@@ -155,12 +348,15 @@ export class Tero {
155
348
  this.configureBackup(config.backup);
156
349
  }
157
350
  // v2: enable per-second live WAL shipping if configured.
158
- if (config?.liveBackup && this.backupManager) {
351
+ if (config?.liveBackup) {
352
+ if (!this.backupManager) {
353
+ throw new Error('config.liveBackup requires config.backup with cloudStorage configured.');
354
+ }
159
355
  this.enableLiveBackup(config.liveBackup);
160
356
  }
161
357
  }
162
358
  catch (error) {
163
- throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`);
359
+ throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
164
360
  }
165
361
  }
166
362
  /**
@@ -174,8 +370,12 @@ export class Tero {
174
370
  return new Tero(config);
175
371
  }
176
372
  // Ensure directory exists first so DataRecovery can stream into it.
177
- const rawDirectory = config?.Directory || config?.directory || 'TeroDB';
178
- const teroDirectory = rawDirectory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
373
+ // MUST use validateDirectory() — the same validation the constructor
374
+ // applies. The old strip-regex diverged ('my db' hydrated into 'mydb'
375
+ // while `new Tero` resolved the real path below), causing split-brain
376
+ // directories where hydrated data became invisible to the engine.
377
+ const rawDirectory = config?.directory || 'TeroDB';
378
+ const teroDirectory = validateDirectory(rawDirectory);
179
379
  if (!existsSync(teroDirectory)) {
180
380
  mkdirSync(teroDirectory, { recursive: true });
181
381
  }
@@ -188,39 +388,55 @@ export class Tero {
188
388
  mode: hydrate.mode === 'all' ? 'all' : 'missing',
189
389
  continueOnError: hydrate.continueOnError ?? true,
190
390
  });
191
- try {
192
- const mode = hydrate.mode ?? 'missing';
193
- if (mode === 'all') {
194
- const r = await recovery.recoverIndividualFiles();
195
- if (!r.success && r.failed.length > 0) { /* continue */ }
196
- }
197
- else if (mode === 'snapshot') {
198
- // Snapshot-first: download the most recent tar.gz archive, extract it
199
- // locally in bulk (one HTTP GET for potentially thousands of docs), then
200
- // fill gaps with individual file recovery for any data written since the
201
- // snapshot's checkpoint. This is the Google-recommended hydration pattern:
202
- // one bulk download instead of sequential individual S3 GETs.
203
- try {
204
- const snapshotResult = await recovery.recoverFromArchive();
205
- if (!snapshotResult.success) {
206
- // Fall back to individual file recovery if no archive exists
207
- const r = await recovery.recoverMissingFiles();
391
+ let hydrateCancelled = false;
392
+ const hydrateWork = async () => {
393
+ try {
394
+ const mode = hydrate.mode ?? 'missing';
395
+ if (hydrateCancelled)
396
+ return;
397
+ if (mode === 'all') {
398
+ const r = await recovery.recoverIndividualFiles(undefined, () => hydrateCancelled);
399
+ if (!r.success && r.failed.length > 0) { /* continue */ }
400
+ }
401
+ else if (mode === 'snapshot') {
402
+ if (hydrateCancelled)
403
+ return;
404
+ try {
405
+ const snapshotResult = await recovery.recoverFromArchive();
406
+ if (hydrateCancelled)
407
+ return;
408
+ if (!snapshotResult.success) {
409
+ if (hydrateCancelled)
410
+ return;
411
+ const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
412
+ if (!r.success && r.failed.length > 0) { /* continue */ }
413
+ }
414
+ }
415
+ catch {
416
+ if (hydrateCancelled)
417
+ return;
418
+ const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
208
419
  if (!r.success && r.failed.length > 0) { /* continue */ }
209
420
  }
210
421
  }
211
- catch {
212
- // Archive may not exist or may be corrupted; fall back gracefully
213
- const r = await recovery.recoverMissingFiles();
422
+ else {
423
+ const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
214
424
  if (!r.success && r.failed.length > 0) { /* continue */ }
215
425
  }
216
426
  }
217
- else {
218
- const r = await recovery.recoverMissingFiles();
219
- if (!r.success && r.failed.length > 0) { /* continue */ }
427
+ catch (error) {
428
+ // Hydration errors are non-fatal; engine init proceeds with whatever local data exists.
220
429
  }
430
+ };
431
+ const timeoutMs = hydrate.timeout;
432
+ if (typeof timeoutMs === 'number' && timeoutMs > 0) {
433
+ await Promise.race([
434
+ hydrateWork(),
435
+ new Promise((resolve) => { const t = setTimeout(() => { hydrateCancelled = true; resolve(); }, timeoutMs); t.unref?.(); }),
436
+ ]);
221
437
  }
222
- catch (error) {
223
- // Hydration errors are non-fatal; engine init proceeds with whatever local data exists.
438
+ else {
439
+ await hydrateWork();
224
440
  }
225
441
  // Now construct the engine in the usual way — it sees current local state and
226
442
  // runs crash recovery against the WAL for any writes between the last snapshot
@@ -243,19 +459,39 @@ export class Tero {
243
459
  throw new Error('Data recovery not configured. Call configureDataRecovery() or pass hydrateOnStartup in config.');
244
460
  }
245
461
  const mode = options?.mode ?? 'missing';
246
- if (mode === 'all') {
247
- return await recovery.recoverIndividualFiles();
462
+ const timeoutMs = options?.timeout;
463
+ let cancelled = false;
464
+ let timeoutTimer;
465
+ if (typeof timeoutMs === 'number' && timeoutMs > 0) {
466
+ timeoutTimer = setTimeout(() => { cancelled = true; }, timeoutMs);
467
+ timeoutTimer.unref?.();
248
468
  }
249
- else if (mode === 'snapshot') {
250
- try {
251
- return await recovery.recoverFromArchive();
469
+ try {
470
+ if (cancelled)
471
+ throw new Error(`Hydrate timed out after ${timeoutMs}ms`);
472
+ if (mode === 'all') {
473
+ return await recovery.recoverIndividualFiles(undefined, () => cancelled);
252
474
  }
253
- catch {
254
- return await recovery.recoverMissingFiles();
475
+ else if (mode === 'snapshot') {
476
+ try {
477
+ const r = await recovery.recoverFromArchive();
478
+ if (cancelled)
479
+ throw new Error(`Hydrate timed out after ${timeoutMs}ms`);
480
+ return r;
481
+ }
482
+ catch (e) {
483
+ if (cancelled)
484
+ throw e;
485
+ return await recovery.recoverMissingFiles(() => cancelled);
486
+ }
487
+ }
488
+ else {
489
+ return await recovery.recoverMissingFiles(() => cancelled);
255
490
  }
256
491
  }
257
- else {
258
- return await recovery.recoverMissingFiles();
492
+ finally {
493
+ if (timeoutTimer)
494
+ clearTimeout(timeoutTimer);
259
495
  }
260
496
  }
261
497
  initializeDirectories() {
@@ -269,15 +505,19 @@ export class Tero {
269
505
  }
270
506
  }
271
507
  catch (error) {
272
- throw new Error(`Failed to create directories: ${error instanceof Error ? error.message : 'Unknown error'}`);
508
+ throw new Error(`Failed to create directories: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
273
509
  }
274
510
  }
511
+ static MAX_KEY_LENGTH = 200;
275
512
  validateKey(key) {
276
- if (!key || typeof key !== 'string') {
513
+ if (!key || typeof key !== 'string' || !key.trim()) {
277
514
  throw new Error('Key must be a non-empty string');
278
515
  }
279
- // Sanitize key to prevent path traversal
280
- if (key.includes('..') || key.includes('/') || key.includes('\\')) {
516
+ if (key.length > Tero.MAX_KEY_LENGTH) {
517
+ throw new Error(`Key exceeds maximum length of ${Tero.MAX_KEY_LENGTH} characters (got ${key.length})`);
518
+ }
519
+ // Sanitize key to prevent path traversal, hidden files, and illegal chars
520
+ if (key.includes('..') || key.includes('/') || key.includes('\\') || key.includes('\0') || key === '.' || key.startsWith('.')) {
281
521
  throw new Error('Key contains invalid characters');
282
522
  }
283
523
  }
@@ -294,7 +534,7 @@ export class Tero {
294
534
  }
295
535
  updateCache(key, data, transactionId) {
296
536
  this.cache.set(key, {
297
- data: data,
537
+ data: deepClone(data),
298
538
  lastAccessed: Date.now(),
299
539
  transactionId
300
540
  });
@@ -316,7 +556,7 @@ export class Tero {
316
556
  return new Transaction(id, this, options);
317
557
  }
318
558
  catch (error) {
319
- throw new Error(`Failed to begin transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
559
+ throw new Error(`Failed to begin transaction: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
320
560
  }
321
561
  }
322
562
  _beginTransaction() {
@@ -332,6 +572,13 @@ export class Tero {
332
572
  if (data === undefined || data === null) {
333
573
  throw new Error('Data cannot be null or undefined');
334
574
  }
575
+ data = deepClone(data);
576
+ // Use byte length, not char length — 'é' is 1 char but 2 bytes UTF-8, emoji is 4 bytes
577
+ const jsonStr = JSON.stringify(data);
578
+ const byteLen = Buffer.byteLength(jsonStr, 'utf8');
579
+ if (byteLen > MAX_DOCUMENT_SIZE) {
580
+ throw new Error(`Document size exceeds maximum allowed size (${MAX_DOCUMENT_SIZE / (1024 * 1024)}MB) — got ${(byteLen / (1024 * 1024)).toFixed(2)}MB`);
581
+ }
335
582
  // Perform schema validation if requested
336
583
  if (options?.validate || options?.schemaName) {
337
584
  const schemaName = options.schemaName || key;
@@ -348,8 +595,11 @@ export class Tero {
348
595
  // Use sanitized data from validation
349
596
  data = validationResult.data || data;
350
597
  }
598
+ // Check cache for beforeImage so engine doesn't need disk I/O on hot writes
599
+ const cachedEntry = this.cache.get(key);
600
+ const cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) ? cachedEntry.data : undefined;
351
601
  // Engine write — returns void (sync fast path) or Promise (contended lock)
352
- const writeResult = this.acidEngine.write(txId, key, data);
602
+ const writeResult = this.acidEngine.write(txId, key, data, cachedData);
353
603
  if (writeResult !== undefined)
354
604
  await writeResult;
355
605
  // Cache the MERGED afterImage (from pendingWrites), NOT the raw user data.
@@ -364,20 +614,29 @@ export class Tero {
364
614
  }
365
615
  }
366
616
  catch (error) {
367
- throw new Error(`Write failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
617
+ throw new Error(`Write failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
368
618
  }
369
619
  }
370
- async read(transactionId, key) {
620
+ async read(transactionId, key, options) {
371
621
  try {
372
622
  const txId = this._txId(transactionId);
373
623
  this.validateKey(key);
374
624
  this.cacheRequests++;
625
+ if (options?.lock === 'exclusive') {
626
+ const lockRes = this.acidEngine.acquireExclusiveLock(txId, key);
627
+ if (lockRes !== undefined && lockRes instanceof Promise)
628
+ await lockRes;
629
+ }
630
+ else {
631
+ const lockRes = this.acidEngine.acquireSharedLock(txId, key);
632
+ if (lockRes !== undefined && lockRes instanceof Promise)
633
+ await lockRes;
634
+ }
375
635
  // Check cache first, but only if it's from the same transaction or committed
376
636
  const cachedEntry = this.cache.get(key);
377
637
  if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) {
378
638
  this.cacheHits++;
379
- cachedEntry.lastAccessed = Date.now();
380
- return cachedEntry.data;
639
+ return deepClone(cachedEntry.data);
381
640
  }
382
641
  // Read from ACID engine — returns data (sync fast path) or Promise (contended lock)
383
642
  const readResult = this.acidEngine.read(txId, key);
@@ -385,10 +644,10 @@ export class Tero {
385
644
  if (data !== null && data !== undefined) {
386
645
  this.updateCache(key, data, txId);
387
646
  }
388
- return data;
647
+ return deepClone(data);
389
648
  }
390
649
  catch (error) {
391
- throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
650
+ throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
392
651
  }
393
652
  }
394
653
  async commit(transactionId) {
@@ -415,7 +674,7 @@ export class Tero {
415
674
  this.committedCount++;
416
675
  }
417
676
  catch (error) {
418
- throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
677
+ throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
419
678
  }
420
679
  }
421
680
  async rollback(transactionId) {
@@ -434,7 +693,7 @@ export class Tero {
434
693
  this.rolledBackCount++;
435
694
  }
436
695
  catch (error) {
437
- throw new Error(`Failed to rollback transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
696
+ throw new Error(`Failed to rollback transaction: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
438
697
  }
439
698
  }
440
699
  async commitTransaction(transactionId) {
@@ -453,20 +712,47 @@ export class Tero {
453
712
  // Convenience Methods (Auto-transaction)
454
713
  async create(key, initialData, options) {
455
714
  this.validateKey(key);
456
- // Fast existence check via in-memory set — avoids existsSync syscall
457
- if (this.knownKeys.has(key)) {
458
- return false; // already exists
459
- }
460
715
  const transactionId = this._beginTransaction();
461
716
  try {
717
+ // Serialize existence check under an exclusive lock — two concurrent
718
+ // create('sameKey') must not both succeed (TOCTOU). Acquire exclusive
719
+ // first, then check committed state under that lock.
720
+ const lockRes = this.acidEngine.acquireExclusiveLock(transactionId, key);
721
+ if (lockRes instanceof Promise)
722
+ await lockRes;
723
+ // Check existence while holding the lock (covers knownKeys, committedBuffer, disk)
724
+ if (this.knownKeys.has(key)) {
725
+ await this.rollback(transactionId);
726
+ return false; // already exists
727
+ }
728
+ const pending = this.acidEngine.getCommittedData(key);
729
+ if (pending !== undefined) {
730
+ if (pending !== null) {
731
+ this.knownKeys.set(key, true);
732
+ await this.rollback(transactionId);
733
+ return false; // duplicate — already committed, not yet flushed
734
+ }
735
+ // tombstone → logically absent, fall through to allow re-create
736
+ }
737
+ else if (existsSync(this.keyToPath(key))) {
738
+ this.knownKeys.set(key, true); // re-pin; existed all along
739
+ await this.rollback(transactionId);
740
+ return false;
741
+ }
742
+ // Also check pendingWrites of other active tx via reading within tx
743
+ // (write will deepMerge, but for create we need empty). The exclusive
744
+ // lock guarantees no other tx is writing this key concurrently.
462
745
  const result = await this.write(transactionId, key, initialData || {}, options);
463
746
  await this.commit(transactionId);
464
747
  this.knownKeys.set(key, true);
465
748
  return result || true;
466
749
  }
467
750
  catch (error) {
468
- await this.rollback(transactionId);
469
- throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
751
+ try {
752
+ await this.rollback(transactionId);
753
+ }
754
+ catch { }
755
+ throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
470
756
  }
471
757
  }
472
758
  async update(key, data, options) {
@@ -482,8 +768,10 @@ export class Tero {
482
768
  }
483
769
  }
484
770
  /**
485
- * Read a document. Returns the document data on success, or `false` if the
486
- * document is absent. Throws for genuine errors.
771
+ * Read a document. Returns the document data on success, or `null` if the
772
+ * document is absent (use `=== null` to check). For backwards-compat, `false`
773
+ * is still treated as "not found" by callers, but new code should check for null.
774
+ * Throws for genuine errors (invalid key, corrupt file).
487
775
  *
488
776
  * Fast path (3 tiers, zero-syscall on hit):
489
777
  * 1. LRU cache (committed entries) — pure memory, 900k+ ops/s
@@ -500,47 +788,42 @@ export class Tero {
500
788
  const cachedEntry = this.cache.get(key);
501
789
  if (cachedEntry && !cachedEntry.transactionId) {
502
790
  this.cacheHits++;
503
- cachedEntry.lastAccessed = Date.now();
504
- return cachedEntry.data;
791
+ return deepClone(cachedEntry.data);
505
792
  }
506
793
  // 2. Check committedBuffer (committed but not yet flushed to data files)
507
794
  const committed = this.acidEngine.getCommittedData(key);
508
795
  if (committed !== undefined) {
509
796
  if (committed === null)
510
- return false;
797
+ return null;
511
798
  this.updateCache(key, committed, undefined);
512
- return committed;
799
+ return deepClone(committed);
513
800
  }
514
801
  // 3. Slow path: read directly from disk (partitioned path; atomic rename = consistent)
515
- const { readFileSync, existsSync: existsSyncFs } = await import('fs');
516
- const { join } = await import('path');
517
802
  const filePath = this.keyToPath(key);
518
- if (!existsSyncFs(filePath)) {
519
- return false;
803
+ if (!existsSync(filePath)) {
804
+ return null;
520
805
  }
521
806
  try {
522
807
  const content = readFileSync(filePath, 'utf-8');
523
808
  const data = content.trim() ? JSON.parse(content) : {};
524
809
  this.updateCache(key, data, undefined);
525
- return data;
810
+ return deepClone(data);
526
811
  }
527
812
  catch (error) {
528
- throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`);
813
+ throw new Error(`Read failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
529
814
  }
530
815
  }
531
816
  /**
532
817
  * Map a document key to its partitioned path on disk (2-level hash-prefix).
533
- * Matches the layout used by ACIDStorageEngine — same key resolves to same path.
818
+ * Delegates to the ENGINE'S partitionedPath() — the single authoritative
819
+ * implementation. The previous local FNV-1a re-implementation produced the
820
+ * same paths only by convention; if the two ever drifted, get() would read a
821
+ * different file than the engine writes (silent data loss). The engine's
822
+ * hash computes a 64-bit value (2 imul/char vs 1) but this runs only on
823
+ * cache-miss reads, which are syscall-dominated — measured impact: none.
534
824
  */
535
825
  keyToPath(key) {
536
- // FNV-1a 32-bit of the key — same dispersion as partitionedPath() in acid-engine.ts
537
- let h = 0x811c9dc5;
538
- for (let i = 0; i < key.length; i++) {
539
- h ^= key.charCodeAt(i);
540
- h = Math.imul(h, 0x01000193) >>> 0;
541
- }
542
- const hex = h.toString(16).padStart(8, '0');
543
- return `${this.teroDirectory}/${hex.slice(0, 2)}/${hex.slice(2, 4)}/${key}.json`;
826
+ return partitionedPath(this.teroDirectory, key);
544
827
  }
545
828
  async remove(key) {
546
829
  const transactionId = this._beginTransaction();
@@ -558,26 +841,22 @@ export class Tero {
558
841
  return await this.remove(key);
559
842
  }
560
843
  exists(key) {
561
- try {
562
- this.validateKey(key);
563
- // Fast path: in-memory set
564
- if (this.knownKeys.has(key))
565
- return true;
566
- // Check committedBuffer for pending deletes (deferred writes may not have
567
- // unlinked the file yet — a committed delete should appear as absent)
568
- const committed = this.acidEngine.getCommittedData(key);
569
- if (committed !== undefined)
570
- return committed !== null;
571
- // Slow path: check disk via partitioned path
572
- if (existsSync(this.keyToPath(key))) {
573
- this.knownKeys.set(key, true);
574
- return true;
575
- }
576
- return false;
577
- }
578
- catch (error) {
579
- return false;
844
+ // Fail-fast on invalid keys — don't mask programming errors as "not found"
845
+ this.validateKey(key);
846
+ // Fast path: in-memory set
847
+ if (this.knownKeys.has(key))
848
+ return true;
849
+ // Check committedBuffer for pending deletes (deferred writes may not have
850
+ // unlinked the file yet — a committed delete should appear as absent)
851
+ const committed = this.acidEngine.getCommittedData(key);
852
+ if (committed !== undefined)
853
+ return committed !== null;
854
+ // Slow path: check disk via partitioned path
855
+ if (existsSync(this.keyToPath(key))) {
856
+ this.knownKeys.set(key, true);
857
+ return true;
580
858
  }
859
+ return false;
581
860
  }
582
861
  // Batch Operations
583
862
  async batchWrite(operations, options) {
@@ -593,7 +872,7 @@ export class Tero {
593
872
  }
594
873
  catch (error) {
595
874
  await this.rollback(transactionId);
596
- throw new Error(`Batch write failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
875
+ throw new Error(`Batch write failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
597
876
  }
598
877
  }
599
878
  async batchRead(keys) {
@@ -608,7 +887,7 @@ export class Tero {
608
887
  }
609
888
  catch (error) {
610
889
  await this.rollback(transactionId);
611
- throw new Error(`Batch read failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
890
+ throw new Error(`Batch read failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
612
891
  }
613
892
  }
614
893
  // Money transfer example demonstrating ACID properties
@@ -618,7 +897,22 @@ export class Tero {
618
897
  }
619
898
  const transactionId = this._beginTransaction();
620
899
  try {
621
- // Read current balances
900
+ // Acquire exclusive locks in GLOBAL SORTED ORDER *before* reading.
901
+ // Two concurrent opposite-direction transfers (A→B and B→A) that
902
+ // first take shared locks on their source then try to upgrade to
903
+ // exclusive will deadlock (both hold shared, both wait for the
904
+ // other). Sorted exclusive acquisition + SERIALIZABLE reads avoids
905
+ // both the deadlock and the read-check-write overdraft race where
906
+ // two transfers both pass the balance check under shared locks.
907
+ const [firstKey, secondKey] = [fromKey, toKey].sort();
908
+ const a1 = this.acidEngine.acquireExclusiveLock(transactionId, firstKey);
909
+ if (a1 !== undefined)
910
+ await a1;
911
+ const a2 = this.acidEngine.acquireExclusiveLock(transactionId, secondKey);
912
+ if (a2 !== undefined)
913
+ await a2;
914
+ // Now reads are performed while already holding exclusive — they
915
+ // cannot interleave with another transfer's balance check.
622
916
  const fromAccount = await this.read(transactionId, fromKey);
623
917
  const toAccount = await this.read(transactionId, toKey);
624
918
  if (!fromAccount || !toAccount) {
@@ -627,44 +921,53 @@ export class Tero {
627
921
  if (fromAccount.balance < amount) {
628
922
  throw new Error('Insufficient funds');
629
923
  }
630
- // Update balances
631
- await this.write(transactionId, fromKey, {
632
- ...fromAccount,
633
- balance: fromAccount.balance - amount
634
- });
635
- await this.write(transactionId, toKey, {
636
- ...toAccount,
637
- balance: toAccount.balance + amount
638
- });
924
+ // Update balances — writes reuse the already-held exclusive locks
925
+ // (acquired above in sorted order), so no additional ordering needed.
926
+ const balances = { [fromKey]: fromAccount, [toKey]: toAccount };
927
+ const deltas = { [fromKey]: -amount, [toKey]: +amount };
928
+ for (const key of [firstKey, secondKey]) {
929
+ await this.write(transactionId, key, {
930
+ ...balances[key],
931
+ balance: balances[key].balance + deltas[key]
932
+ });
933
+ }
639
934
  // Commit the transaction
640
935
  await this.commit(transactionId);
641
936
  }
642
937
  catch (error) {
643
938
  await this.rollback(transactionId);
644
- throw new Error(`Money transfer failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
939
+ throw new Error(`Money transfer failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
645
940
  }
646
941
  }
647
942
  // Internal raw methods for Transaction class
648
943
  async _writeRaw(transactionId, key, data) {
649
- const result = this.acidEngine.write(transactionId, key, data);
944
+ const cachedEntry = this.cache.get(key);
945
+ const cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) ? cachedEntry.data : undefined;
946
+ const result = this.acidEngine.write(transactionId, key, data, cachedData);
650
947
  if (result !== undefined)
651
948
  await result;
652
- this.updateCache(key, data, transactionId);
949
+ // Cache the MERGED afterImage, not the raw caller input. The engine
950
+ // deep-merges partial updates with existing state, so caching `data`
951
+ // would poison the cache with incomplete documents — a second tx.update
952
+ // to the same key would lose fields written by the first update until a
953
+ // disk re-read. (Tero.write() does this correctly; the Transaction path
954
+ // goes through this raw method, so it must too.)
955
+ const afterImage = this.acidEngine.getPendingAfterImage(transactionId, key);
956
+ this.updateCache(key, afterImage !== undefined ? afterImage : data, transactionId);
653
957
  }
654
958
  async _readRaw(transactionId, key) {
655
959
  this.cacheRequests++;
656
960
  const cachedEntry = this.cache.get(key);
657
961
  if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) {
658
962
  this.cacheHits++;
659
- cachedEntry.lastAccessed = Date.now();
660
- return cachedEntry.data;
963
+ return deepClone(cachedEntry.data);
661
964
  }
662
965
  const result = this.acidEngine.read(transactionId, key);
663
966
  const data = (result !== undefined && result instanceof Promise) ? await result : result;
664
967
  if (data !== null && data !== undefined) {
665
968
  this.updateCache(key, data, transactionId);
666
969
  }
667
- return data;
970
+ return deepClone(data);
668
971
  }
669
972
  async _deleteRaw(transactionId, key) {
670
973
  const result = this.acidEngine.delete(transactionId, key);
@@ -675,6 +978,16 @@ export class Tero {
675
978
  }
676
979
  async _rollbackRaw(transactionId) {
677
980
  this.acidEngine.rollbackTransaction(transactionId);
981
+ // Invalidate cache entries this transaction touched and drop the tracking
982
+ // set. Without this, the timeout rollback path (Transaction constructor
983
+ // timer) leaves stale cache entries tagged with the dead txId, and
984
+ // txTouchedKeys grows unbounded across timed-out transactions.
985
+ const touched = this.txTouchedKeys.get(transactionId);
986
+ if (touched) {
987
+ for (const k of touched)
988
+ this.cache.delete(k);
989
+ this.txTouchedKeys.delete(transactionId);
990
+ }
678
991
  this.rolledBackCount++;
679
992
  }
680
993
  _getTxStatus(transactionId) {
@@ -695,7 +1008,7 @@ export class Tero {
695
1008
  this.schemaValidator.setSchema(collectionName, schema);
696
1009
  }
697
1010
  catch (error) {
698
- throw new Error(`Failed to set schema: ${error instanceof Error ? error.message : 'Unknown error'}`);
1011
+ throw new Error(`Failed to set schema: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
699
1012
  }
700
1013
  }
701
1014
  getSchema(collectionName) {
@@ -741,7 +1054,7 @@ export class Tero {
741
1054
  this.backupManager = new BackupManager(this.teroDirectory, config);
742
1055
  }
743
1056
  catch (error) {
744
- throw new Error(`Failed to configure backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
1057
+ throw new Error(`Failed to configure backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
745
1058
  }
746
1059
  }
747
1060
  /** Alias retained for the existing test surface / older callers. */
@@ -816,6 +1129,10 @@ export class Tero {
816
1129
  throw new Error('Backup not configured. Call configureBackup() first.');
817
1130
  }
818
1131
  this.acidEngine.forceCheckpoint();
1132
+ // Flush deferred data before archiving — mirrors commitTransaction()
1133
+ // rotation guard; otherwise committedBuffer data would be lost if we
1134
+ // crashed right after rotating and truncating .wal.
1135
+ this.acidEngine.flushCommittedBuffer?.();
819
1136
  this.acidEngine.getWAL().rotateLog();
820
1137
  return await this.backupToBucket(options);
821
1138
  }
@@ -838,17 +1155,22 @@ export class Tero {
838
1155
  return { state: 'stopped', nodeId: 'unknown', intervalMs: 0, lastShippedLsn: 0, lastShipAt: 0, secondsSinceLastShip: 0, segmentsShipped: 0, checkpointsTaken: 0, errorCount: 0 };
839
1156
  return this.backupManager.getLiveBackupStatus();
840
1157
  }
841
- /** Take an incremental checkpoint (uploads only dirty docs). First call = full upload. */
1158
+ /** Take a checkpoint: FULL on the first call after enable (also taken
1159
+ * automatically), INCREMENTAL (only dirty docs) on subsequent calls. */
842
1160
  async liveCheckpointToBucket(opts) {
843
1161
  if (!this.backupManager)
844
1162
  throw new Error('Backup not configured. Call configureBackup() first.');
845
- this.acidEngine.flushCommittedBuffer();
1163
+ // No flush here on purpose: the manager captures the conservative baseLsn
1164
+ // FIRST and flushes after — flushing before capture would be the wrong order.
846
1165
  return await this.backupManager.liveCheckpointToBucket(opts);
847
1166
  }
848
1167
  /** Restore a fresh Tero instance from a live backup in the bucket. */
849
1168
  static async restoreFromLiveBackup(opts) {
850
- const sanitized = opts.directory.replace(/[^a-zA-Z0-9_\-\/]/g, '') || 'TeroDB';
851
- const tempMgr = new BackupManager(sanitized, { format: 'individual', cloudStorage: opts.cloudStorage });
1169
+ const sanitized = validateDirectory(opts.directory);
1170
+ const source = validateDirectory(opts.sourceDirectory ?? opts.directory);
1171
+ // The temp manager is built with the SOURCE name so bucket prefixes resolve;
1172
+ // files are written into the sanitized TARGET directory.
1173
+ const tempMgr = new BackupManager(source, { format: 'individual', cloudStorage: opts.cloudStorage });
852
1174
  try {
853
1175
  await tempMgr.restoreLiveToDirectory(sanitized, { nodeId: opts.nodeId, pointInTime: opts.pointInTime });
854
1176
  }
@@ -865,7 +1187,7 @@ export class Tero {
865
1187
  this.dataRecovery = new DataRecovery(config);
866
1188
  }
867
1189
  catch (error) {
868
- throw new Error(`Failed to configure data recovery: ${error instanceof Error ? error.message : 'Unknown error'}`);
1190
+ throw new Error(`Failed to configure data recovery: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
869
1191
  }
870
1192
  }
871
1193
  async recoverFromCloud(key) {
@@ -926,9 +1248,9 @@ export class Tero {
926
1248
  }
927
1249
  /**
928
1250
  * Read a key locally; if absent locally, transparently recover it from the client's
929
- * bucket and cache the result. Returns the data, or `false` if the key genuinely
930
- * doesn't exist on either side. Throws for real (auth/network) errors so callers
931
- * don't silently mistake them for "not in cloud".
1251
+ * bucket and cache the result. Returns the data, or `null` if the key genuinely
1252
+ * doesn't exist on either side (returns `false` for backwards compat — both mean "not found").
1253
+ * Throws for real (auth/network) errors so callers don't silently mistake them for "not in cloud".
932
1254
  *
933
1255
  * Options:
934
1256
  * - fallbackToCloud: boolean (default true) — set false to skip cloud fetch
@@ -942,17 +1264,17 @@ export class Tero {
942
1264
  throw error;
943
1265
  }
944
1266
  const fallbackToCloud = options?.fallbackToCloud ?? true;
945
- // 1) Try local first.
1267
+ // 1) Try local first. Handle both null (new) and false (legacy) as "not found"
946
1268
  const localData = await this.get(key);
947
- if (localData !== false) {
1269
+ if (localData !== null && localData !== false) {
948
1270
  return localData;
949
1271
  }
950
1272
  // 2) Not local. Optionally fall back to cloud.
951
1273
  if (!fallbackToCloud)
952
- return false;
1274
+ return null;
953
1275
  if (!this.dataRecovery) {
954
- // No cloud configured — return false to keep "absent" semantics consistent with get().
955
- return false;
1276
+ // No cloud configured — return null to keep "absent" semantics consistent with get().
1277
+ return null;
956
1278
  }
957
1279
  // 3) Best-effort cloud fetch. If it fails for any reason (auth, network, timeout,
958
1280
  // no such key), we don't crash the local read path — `getWithRecovery` is a
@@ -962,7 +1284,7 @@ export class Tero {
962
1284
  try {
963
1285
  const recovered = await this.dataRecovery.recoverSingleFile(key);
964
1286
  if (!recovered) {
965
- return false;
1287
+ return null;
966
1288
  }
967
1289
  // Cache + return the freshly hydrated data.
968
1290
  // Re-run get() so the read goes through the cache + lint path.
@@ -970,7 +1292,7 @@ export class Tero {
970
1292
  return await this.get(key);
971
1293
  }
972
1294
  catch (error) {
973
- return false;
1295
+ return null;
974
1296
  }
975
1297
  }
976
1298
  /**
@@ -1056,40 +1378,77 @@ export class Tero {
1056
1378
  return result;
1057
1379
  }
1058
1380
  catch (error) {
1059
- throw new Error(`Data integrity verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
1381
+ throw new Error(`Data integrity verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
1060
1382
  }
1061
1383
  }
1062
1384
  clearCache() {
1063
1385
  this.cache.clear();
1064
1386
  }
1065
1387
  /**
1066
- * Acquire an exclusive OS-level lock on the data directory via a .lock file.
1067
- * Uses `openSync(path, 'wx')` — creates the file exclusively, failing if it
1068
- * already exists (i.e., another process holds the lock). Cross-platform,
1069
- * no native modules required. The fd is held open to maintain the lock;
1070
- * destroying the Tero instance closes the fd and deletes the lock file.
1388
+ * Acquire an exclusive lock on the data directory via a `.lock` file
1389
+ * (openSync 'wx' exclusive-create — no native modules, cross-platform).
1390
+ * The holder's PID is written to the file; if acquisition fails and the
1391
+ * recorded PID is no longer alive, the stale lock from a crashed process
1392
+ * is reclaimed automatically.
1071
1393
  */
1072
1394
  acquireFileLock() {
1073
- try {
1074
- const lockPath = `${this.teroDirectory}/.lock`;
1075
- this.lockFd = openSync(lockPath, 'wx'); // exclusive create — fails if exists
1076
- writeSync(this.lockFd, String(process.pid));
1077
- }
1078
- catch {
1079
- const lockPath = `${this.teroDirectory}/.lock`;
1395
+ const lockPath = `${this.teroDirectory}/.lock`;
1396
+ const tryAcquire = () => {
1397
+ try {
1398
+ this.lockFd = openSync(lockPath, 'wx'); // exclusive create — fails if exists
1399
+ writeSync(this.lockFd, String(process.pid));
1400
+ return true;
1401
+ }
1402
+ catch {
1403
+ return false;
1404
+ }
1405
+ };
1406
+ if (tryAcquire())
1407
+ return;
1408
+ // Retry loop with bounded attempts for TOCTOU races during stale-lock reclamation
1409
+ for (let attempt = 0; attempt < 3; attempt++) {
1080
1410
  let pid = '?';
1081
1411
  if (existsSync(lockPath)) {
1082
1412
  try {
1083
1413
  pid = readFileSync(lockPath, 'utf-8').trim();
1084
1414
  }
1085
- catch { }
1415
+ catch { /* unreadable */ }
1416
+ }
1417
+ const pidNum = parseInt(pid, 10);
1418
+ if (Number.isInteger(pidNum) && pidNum > 0 && pidNum !== process.pid) {
1419
+ let alive = true;
1420
+ try {
1421
+ process.kill(pidNum, 0);
1422
+ }
1423
+ catch (e) {
1424
+ // ESRCH = no such process → stale lock from a crashed holder.
1425
+ // EPERM = process exists but is owned by another user → treat as alive.
1426
+ alive = e?.code === 'EPERM';
1427
+ }
1428
+ if (!alive) {
1429
+ // Reclaim the stale lock (crashed previous owner) and retry once.
1430
+ try {
1431
+ unlinkSync(lockPath);
1432
+ }
1433
+ catch { /* racing holder */ }
1434
+ if (tryAcquire())
1435
+ return;
1436
+ continue;
1437
+ }
1438
+ if (alive) {
1439
+ throw new Error(`Data directory '${this.teroDirectory}' is locked by live process ${pidNum}. ` +
1440
+ 'Stop that process (or use a different directory) and retry.');
1441
+ }
1086
1442
  }
1087
1443
  if (pid === String(process.pid)) {
1088
- throw new Error(`Another Tero instance is already using '${this.teroDirectory}'. ` +
1089
- 'Destroy the existing instance first, or delete the .lock file if the previous process crashed.');
1444
+ throw new Error(`Another Tero instance in THIS process is already using '${this.teroDirectory}'. ` +
1445
+ 'Destroy the existing instance before constructing a new one.');
1090
1446
  }
1091
- throw new Error(`Data directory locked by process ${pid}. Use fileLock: true for exclusive cross-process access.`);
1447
+ if (tryAcquire())
1448
+ return;
1092
1449
  }
1450
+ throw new Error(`Data directory '${this.teroDirectory}' is locked. ` +
1451
+ `If the holder crashed, delete '${lockPath}' and retry.`);
1093
1452
  }
1094
1453
  releaseFileLock() {
1095
1454
  if (this.lockFd == null)
@@ -1100,14 +1459,34 @@ export class Tero {
1100
1459
  }
1101
1460
  catch { /* best-effort */ }
1102
1461
  }
1103
- // Cleanup method
1104
- destroy() {
1462
+ // Cleanup methods
1463
+ async destroyAsync() {
1464
+ if (this.backupManager) {
1465
+ await this.backupManager.drainInFlight();
1466
+ this.backupManager.destroy();
1467
+ }
1105
1468
  if (this.acidEngine) {
1106
1469
  this.acidEngine.destroy();
1107
1470
  }
1471
+ this.clearCache();
1472
+ this.releaseFileLock();
1473
+ }
1474
+ async close() {
1475
+ await this.destroyAsync();
1476
+ }
1477
+ destroy() {
1478
+ // Sync destroy cannot drain inflight S3 uploads (that's async) — warn if live backup has in-flight work.
1479
+ // Prefer `await db.destroyAsync()` / `await db.close()` in production when live backup is enabled.
1108
1480
  if (this.backupManager) {
1481
+ const live = this.backupManager.liveCheckpointPromise;
1482
+ if (live) {
1483
+ console.warn('[Tero] destroy() called with inflight live checkpoint — use await destroyAsync() to avoid losing the last checkpoint.');
1484
+ }
1109
1485
  this.backupManager.destroy();
1110
1486
  }
1487
+ if (this.acidEngine) {
1488
+ this.acidEngine.destroy();
1489
+ }
1111
1490
  this.clearCache();
1112
1491
  this.releaseFileLock();
1113
1492
  }
@@ -1139,11 +1518,12 @@ export class Tero {
1139
1518
  * ```
1140
1519
  */
1141
1520
  getNewId(prefix) {
1142
- const PROCESS_UNIQUE = randomBytes(5);
1143
1521
  const buffer = Buffer.allocUnsafe(12);
1144
- let index = ~~(Math.random() * 0xffffff);
1145
1522
  const time = ~~(Date.now() / 1000);
1146
- const inc = (index = (index + 1) % 0xffffff);
1523
+ // Module-level monotonic counter (see PROCESS_UNIQUE above) — guarantees
1524
+ // within-process uniqueness even for ids minted in the same millisecond,
1525
+ // with zero crypto calls on this path.
1526
+ const inc = (idCounter = (idCounter + 1) % 0xffffff);
1147
1527
  // 4-byte timestamp (seconds since Unix epoch)
1148
1528
  buffer.writeUInt32BE(time, 0);
1149
1529
  // 5-byte process unique identifier