tero 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { randomBytes, createHash } from "node:crypto";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
- import { existsSync, mkdirSync, openSync, writeSync, closeSync, unlinkSync, readFileSync, writeFileSync, readdirSync, fsyncSync, renameSync } from "fs";
3
+ import { existsSync, mkdirSync, openSync, writeSync, closeSync, unlinkSync, readFileSync, writeFileSync, readdirSync, fsyncSync, renameSync, fstatSync, statSync } from "fs";
4
4
  import { resolve as pathResolve, relative as pathRelative, join as pathJoin } from "path";
5
- import { ACIDStorageEngine, partitionedPath, RecoveryCorruptionError, DataCorruptionError } from "./acid-engine.js";
5
+ import { ACIDStorageEngine, partitionedPath, RecoveryCorruptionError, DataCorruptionError, sweepStaleTempFiles } from "./acid-engine.js";
6
6
  import { BackupManager } from "./backup.js";
7
7
  import { DataRecovery, classifyRecoveryError } from "./recovery.js";
8
8
  import QuickLRU from "quick-lru";
@@ -16,6 +16,17 @@ import QuickLRU from "quick-lru";
16
16
  const PROCESS_UNIQUE = randomBytes(5);
17
17
  let idCounter = ~~(Math.random() * 0xffffff);
18
18
  const MAX_DOCUMENT_DEPTH = 32;
19
+ /** Data directories this process currently holds open (see acquireFileLock). */
20
+ const OPEN_DIRECTORIES = new Map(); // directory -> fd of its .lock
21
+ /** Changes on every boot of the machine/container; '' where unavailable (non-Linux). */
22
+ function currentBootId() {
23
+ try {
24
+ return readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
25
+ }
26
+ catch {
27
+ return '';
28
+ }
29
+ }
19
30
  const MAX_DOCUMENT_SIZE = 16 * 1024 * 1024; // 16MB max document size limit
20
31
  /**
21
32
  * Clone for cache safety — hot-path optimized.
@@ -248,6 +259,8 @@ export class Transaction {
248
259
  let hasTomb = false;
249
260
  if (typeof dbAny.dataRecovery.hasTombstone === 'function') {
250
261
  hasTomb = await dbAny.dataRecovery.hasTombstone(key);
262
+ if (hasTomb)
263
+ dbAny.knownCloudTombstones.set(key, true);
251
264
  }
252
265
  if (!hasTomb) {
253
266
  const info = await dbAny.dataRecovery.checkFileInCloud(key);
@@ -283,6 +296,13 @@ export class Transaction {
283
296
  throw err;
284
297
  }
285
298
  }
299
+ /** Replace the whole document within this transaction (see Tero.set). */
300
+ async set(key, data) {
301
+ this._checkActive();
302
+ await this.db._writeRaw(this.id, key, data, true);
303
+ this.opCount++;
304
+ this.operationsLog.push({ key, operation: 'update' });
305
+ }
286
306
  async update(key, data) {
287
307
  this._checkActive();
288
308
  await this.db._writeRaw(this.id, key, data);
@@ -498,6 +518,13 @@ export class Tero {
498
518
  if (config?.fileLock !== false) {
499
519
  this.acquireFileLock();
500
520
  }
521
+ // Reap temp files orphaned by a process that died mid-atomic-write. Safe
522
+ // here and only here: the lock is held, and no writer exists yet, so any
523
+ // .tmp.* file on disk predates this instance. Never fails the boot.
524
+ try {
525
+ sweepStaleTempFiles(this.teroDirectory);
526
+ }
527
+ catch { /* approved: a leftover temp file must not block startup */ }
501
528
  // Initialize QuickLRU cache
502
529
  this.cache = new QuickLRU({
503
530
  maxSize: this.cacheSize
@@ -511,28 +538,13 @@ export class Tero {
511
538
  const syncMode = synchronous ?? 'full';
512
539
  const syncInterval = commitIntervalMs ?? 10;
513
540
  const dataFlushInterval = dataFlushIntervalMs ?? 50;
514
- this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval, config?.checkpointBatchSize);
515
- // Restore durable local tombstones (P0-2) — prevents resurrection after restart even if cloud tombstone not yet durable
516
- try {
517
- const tombDir = pathJoin(this.teroDirectory, '.tombstones');
518
- if (existsSync(tombDir)) {
519
- const files = readdirSync(tombDir);
520
- for (const f of files) {
521
- if (!f.endsWith('.deleted'))
522
- continue;
523
- try {
524
- const content = readFileSync(pathJoin(tombDir, f), 'utf8');
525
- const obj = JSON.parse(content);
526
- if (obj.key && typeof obj.key === 'string') {
527
- this.missingKeys.set(obj.key, true);
528
- this.bumpGeneration(obj.key);
529
- }
530
- }
531
- catch { /* approved */ }
532
- }
533
- }
534
- }
535
- catch { /* approved */ }
541
+ this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval, config?.checkpointBatchSize, config?.archiveKeepCount, config?.durableCheckpointIntervalMs ?? 30_000);
542
+ // Dirty-key tracking feeds live-backup checkpoints only; enableLiveBackup()
543
+ // turns it on. Left on without a consumer it clones every document forever.
544
+ this.acidEngine.setDirtyTracking(false);
545
+ // Local tombstones are NOT read at boot any more: hydrateKey() checks
546
+ // hasLocalTombstone() on demand before any cloud fetch, so resurrection is
547
+ // still impossible, and boot no longer scales with the number of deletes.
536
548
  // v2: optionally install a backup config at construction time.
537
549
  if (config?.backup) {
538
550
  this.configureBackup(config.backup);
@@ -561,40 +573,14 @@ export class Tero {
561
573
  this.loadPendingCloud();
562
574
  this.loadPendingCloudDeletions();
563
575
  this.loadPendingLocalTombstoneRemovals();
564
- // Fallback: reconstruct pending from local tombstones if queue file was lost (ENOSPC case)
565
- try {
566
- const tombDir = pathJoin(this.teroDirectory, '.tombstones');
567
- if (existsSync(tombDir)) {
568
- const files = readdirSync(tombDir);
569
- for (const f of files) {
570
- if (!f.endsWith('.deleted'))
571
- continue;
572
- try {
573
- const content = readFileSync(pathJoin(tombDir, f), 'utf8');
574
- const obj = JSON.parse(content);
575
- if (obj.key && typeof obj.key === 'string' && typeof obj.lsn === 'number') {
576
- if (!this.cloudPendingTombstones.has(obj.key) && !this.cloudPendingTombstoneDeletions.has(obj.key) && !this.pendingLocalTombstoneRemovals.has(obj.key)) {
577
- if (this.dataRecovery) {
578
- this.cloudPendingTombstones.set(obj.key, obj.lsn);
579
- }
580
- }
581
- }
582
- }
583
- catch { }
584
- }
585
- if (this.cloudPendingTombstones.size > 0) {
586
- try {
587
- this.savePendingCloud();
588
- }
589
- catch { }
590
- }
591
- }
592
- }
593
- catch { }
576
+ if (this.cloudReconcileEnabled())
577
+ this.requeueTombstonesFromDisk();
594
578
  if (this.cloudPendingTombstones.size > 0 || this.cloudPendingTombstoneDeletions.size > 0 || this.pendingLocalTombstoneRemovals.size > 0)
595
579
  this.scheduleCloudRetry();
596
580
  }
597
581
  catch (error) {
582
+ // A failed open must not keep the directory locked (in this process or on disk).
583
+ this.releaseFileLock();
598
584
  if (error instanceof RecoveryCorruptionError || error instanceof DataCorruptionError) {
599
585
  throw error;
600
586
  }
@@ -690,6 +676,7 @@ export class Tero {
690
676
  const hasTomb = await this.dataRecovery.hasTombstone(key);
691
677
  if (hasTomb) {
692
678
  this.missingKeys.set(key, true);
679
+ this.knownCloudTombstones.set(key, true);
693
680
  return null;
694
681
  }
695
682
  }
@@ -811,6 +798,7 @@ export class Tero {
811
798
  }
812
799
  finally {
813
800
  this.inFlightHydrations.delete(key);
801
+ this.keyGenerations.delete(key);
814
802
  }
815
803
  })();
816
804
  this.inFlightHydrations.set(key, fetchPromise);
@@ -886,7 +874,50 @@ export class Tero {
886
874
  throw new Error('Key contains invalid characters');
887
875
  }
888
876
  }
877
+ /** True when deletes/re-creates must be mirrored to the bucket (lazy/eager hydration). */
878
+ cloudReconcileEnabled() {
879
+ return !!this.dataRecovery && this.hydrateMode !== 'off';
880
+ }
881
+ /**
882
+ * Keys known to have a tombstone in the bucket. A commit only issues the cloud
883
+ * tombstone DELETE for keys in this set (or with a local tombstone / pending
884
+ * queue entry) — previously every single commit awaited a DeleteObject.
885
+ * Bounded; on eviction the bucket's newest-wins rule (document vs tombstone
886
+ * LastModified) still keeps a later backup authoritative.
887
+ */
888
+ knownCloudTombstones = new QuickLRU({ maxSize: 100_000 });
889
+ /** Fallback when the durable queue file was lost (ENOSPC): rebuild it from local tombstones. */
890
+ requeueTombstonesFromDisk() {
891
+ try {
892
+ const tombDir = pathJoin(this.teroDirectory, '.tombstones');
893
+ if (!existsSync(tombDir))
894
+ return;
895
+ for (const f of readdirSync(tombDir)) {
896
+ if (!f.endsWith('.deleted'))
897
+ continue;
898
+ try {
899
+ const obj = JSON.parse(readFileSync(pathJoin(tombDir, f), 'utf8'));
900
+ if (obj.key && typeof obj.key === 'string' && typeof obj.lsn === 'number' &&
901
+ !this.cloudPendingTombstones.has(obj.key) && !this.cloudPendingTombstoneDeletions.has(obj.key) && !this.pendingLocalTombstoneRemovals.has(obj.key)) {
902
+ this.cloudPendingTombstones.set(obj.key, obj.lsn);
903
+ }
904
+ }
905
+ catch { /* approved: unreadable tombstone file */ }
906
+ }
907
+ if (this.cloudPendingTombstones.size > 0) {
908
+ try {
909
+ this.savePendingCloud();
910
+ }
911
+ catch { /* approved */ }
912
+ }
913
+ }
914
+ catch { /* approved */ }
915
+ }
889
916
  bumpGeneration(key) {
917
+ // Generations only exist to invalidate an in-flight hydration. Tracking them
918
+ // for every committed key grew this map without bound.
919
+ if (!this.inFlightHydrations.has(key))
920
+ return 0;
890
921
  const next = (this.keyGenerations.get(key) ?? 0) + 1;
891
922
  this.keyGenerations.set(key, next);
892
923
  return next;
@@ -906,8 +937,12 @@ export class Tero {
906
937
  }
907
938
  }
908
939
  updateCache(key, data, transactionId) {
940
+ // Stored by reference: every value cached here is an engine-owned image that
941
+ // is never mutated after it is produced (merges build new objects), and every
942
+ // read path hands out deepClone(entry.data). Cloning here too doubled the
943
+ // cost of every write.
909
944
  this.cache.set(key, {
910
- data: deepClone(data),
945
+ data,
911
946
  lastAccessed: Date.now(),
912
947
  transactionId
913
948
  });
@@ -938,31 +973,47 @@ export class Tero {
938
973
  _txId(id) {
939
974
  return typeof id === 'string' ? id : id.getId();
940
975
  }
941
- async write(transactionId, key, data) {
976
+ /**
977
+ * Write inside a transaction. Default: deep-merge `data` into the current document.
978
+ * With `{ replace: true }` the document becomes exactly `data` — the only way to
979
+ * remove a field (a merge can add and change fields but never drop one).
980
+ */
981
+ async write(transactionId, key, data, options) {
942
982
  try {
943
983
  const txId = this._txId(transactionId);
944
984
  this.validateKey(key);
945
985
  if (data === undefined || data === null) {
946
986
  throw new Error('Data cannot be null or undefined');
947
987
  }
948
- data = deepClone(data);
988
+ // replace: the serialization done for the size check doubles as the private
989
+ // copy (JSON semantics: undefined fields dropped, exactly as stored on disk).
990
+ // One clone instead of three on the hot path. merge: validated deep clone.
991
+ let jsonStr;
992
+ if (options?.replace) {
993
+ jsonStr = JSON.stringify(data);
994
+ }
995
+ else {
996
+ data = deepClone(data);
997
+ jsonStr = JSON.stringify(data);
998
+ }
949
999
  // Use byte length, not char length — 'é' is 1 char but 2 bytes UTF-8, emoji is 4 bytes
950
- const jsonStr = JSON.stringify(data);
951
1000
  const byteLen = Buffer.byteLength(jsonStr, 'utf8');
952
1001
  if (byteLen > MAX_DOCUMENT_SIZE) {
953
1002
  throw new Error(`Document size exceeds maximum allowed size (${MAX_DOCUMENT_SIZE / (1024 * 1024)}MB) — got ${(byteLen / (1024 * 1024)).toFixed(2)}MB`);
954
1003
  }
1004
+ if (options?.replace)
1005
+ data = JSON.parse(jsonStr);
955
1006
  // Check cache for beforeImage so engine doesn't need disk I/O on hot writes
956
1007
  const cachedEntry = this.cache.get(key);
957
1008
  let cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) ? cachedEntry.data : undefined;
958
1009
  // Lazy hydration: if updating a cold document not on disk, hydrate beforeImage from cloud
959
- if (cachedData === undefined && this.dataRecovery && this.hydrateMode === 'lazy' &&
1010
+ if (!options?.replace && cachedData === undefined && this.dataRecovery && this.hydrateMode === 'lazy' &&
960
1011
  this.acidEngine.getCommittedData(key) === undefined &&
961
1012
  !existsSync(this.keyToPath(key))) {
962
1013
  cachedData = (await this.hydrateKey(key)) ?? undefined;
963
1014
  }
964
1015
  // Engine write — returns void (sync fast path) or Promise (contended lock)
965
- const writeResult = this.acidEngine.write(txId, key, data, cachedData);
1016
+ const writeResult = this.acidEngine.write(txId, key, data, cachedData, options?.replace === true, options?.replace ? jsonStr : undefined);
966
1017
  if (writeResult !== undefined)
967
1018
  await writeResult;
968
1019
  // Cache the MERGED afterImage (from pendingWrites), NOT the raw user data.
@@ -1043,14 +1094,18 @@ export class Tero {
1043
1094
  // Bump generation for P0-1 in-flight hydration invalidation and P0-10 stale hydration
1044
1095
  this.bumpGeneration(key);
1045
1096
  }
1046
- // Post-commit reconciliation — durable but best-effort, never fails the logical commit
1047
- for (const key of touched) {
1097
+ // Post-commit reconciliation — durable but best-effort, never fails the logical commit.
1098
+ // Only meaningful when deletes are mirrored to a bucket (lazy/eager hydration).
1099
+ for (const key of (this.cloudReconcileEnabled() ? touched : [])) {
1048
1100
  try {
1049
1101
  await this.withReconciliationLock(key, async () => {
1050
1102
  const committed = this.acidEngine.getCommittedData(key);
1051
1103
  if (committed !== undefined) {
1052
1104
  if (committed !== null) {
1053
- // Write/present — clear tombstones so re-create can succeed and hydration can fetch
1105
+ // Write/present — clear tombstones so re-create can succeed and hydration can fetch.
1106
+ // Only keys that may have a cloud tombstone pay for the DeleteObject below.
1107
+ const mayHaveCloudTombstone = this.hasLocalTombstone(key) || this.knownCloudTombstones.has(key) ||
1108
+ this.cloudPendingTombstones.has(key) || this.cloudPendingTombstoneDeletions.has(key);
1054
1109
  try {
1055
1110
  this.deleteLocalTombstone(key);
1056
1111
  }
@@ -1072,7 +1127,7 @@ export class Tero {
1072
1127
  }
1073
1128
  catch { }
1074
1129
  }
1075
- if (this.dataRecovery) {
1130
+ if (this.dataRecovery && mayHaveCloudTombstone) {
1076
1131
  // Re-check still present before deleting cloud tombstone
1077
1132
  const committed2 = this.acidEngine.getCommittedData(key);
1078
1133
  const hasLocal2 = this.hasLocalTombstone(key);
@@ -1085,6 +1140,7 @@ export class Tero {
1085
1140
  }
1086
1141
  try {
1087
1142
  await this.dataRecovery.deleteTombstone?.(key);
1143
+ this.knownCloudTombstones.delete(key);
1088
1144
  if (this.cloudPendingTombstoneDeletions.has(key)) {
1089
1145
  this.cloudPendingTombstoneDeletions.delete(key);
1090
1146
  try {
@@ -1137,12 +1193,22 @@ export class Tero {
1137
1193
  }
1138
1194
  if (failed)
1139
1195
  this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1140
- else if (this.cloudPendingTombstones.has(key)) {
1141
- this.cloudPendingTombstones.delete(key);
1196
+ else {
1197
+ this.knownCloudTombstones.set(key, true);
1198
+ if (this.cloudPendingTombstones.has(key)) {
1199
+ this.cloudPendingTombstones.delete(key);
1200
+ try {
1201
+ this.savePendingCloud();
1202
+ }
1203
+ catch { }
1204
+ }
1205
+ // The bucket now holds the durable tombstone and no document, so
1206
+ // hydration cannot resurrect the key: the local marker has done
1207
+ // its job. Dropping it stops .tombstones growing with every delete.
1142
1208
  try {
1143
- this.savePendingCloud();
1209
+ this.deleteLocalTombstone(key);
1144
1210
  }
1145
- catch { }
1211
+ catch { /* approved: retried on next delete/re-create */ }
1146
1212
  }
1147
1213
  }
1148
1214
  }
@@ -1197,9 +1263,10 @@ export class Tero {
1197
1263
  }
1198
1264
  catch { }
1199
1265
  }
1200
- if (this.dataRecovery) {
1266
+ if (this.dataRecovery && (this.knownCloudTombstones.has(key) || this.cloudPendingTombstoneDeletions.has(key))) {
1201
1267
  try {
1202
1268
  await this.dataRecovery.deleteTombstone?.(key);
1269
+ this.knownCloudTombstones.delete(key);
1203
1270
  if (this.cloudPendingTombstoneDeletions.has(key)) {
1204
1271
  this.cloudPendingTombstoneDeletions.delete(key);
1205
1272
  try {
@@ -1294,6 +1361,8 @@ export class Tero {
1294
1361
  let hasTomb = false;
1295
1362
  if (typeof this.dataRecovery.hasTombstone === 'function') {
1296
1363
  hasTomb = await this.dataRecovery.hasTombstone(key);
1364
+ if (hasTomb)
1365
+ this.knownCloudTombstones.set(key, true);
1297
1366
  }
1298
1367
  if (!hasTomb) {
1299
1368
  const info = await this.dataRecovery.checkFileInCloud(key);
@@ -1324,6 +1393,27 @@ export class Tero {
1324
1393
  }
1325
1394
  });
1326
1395
  }
1396
+ /**
1397
+ * Upsert that REPLACES the whole document (creates it if absent). Unlike
1398
+ * update(), fields missing from `data` are removed — use this whenever the
1399
+ * caller holds the complete document (read-modify-write).
1400
+ */
1401
+ async set(key, data) {
1402
+ this.validateKey(key);
1403
+ if (data === undefined || data === null)
1404
+ throw new Error('Data cannot be null or undefined');
1405
+ const transactionId = this._beginTransaction();
1406
+ try {
1407
+ await this.write(transactionId, key, data, { replace: true });
1408
+ await this.commit(transactionId);
1409
+ this.knownKeys.set(key, true);
1410
+ this.missingKeys.delete(key);
1411
+ }
1412
+ catch (error) {
1413
+ await this.rollback(transactionId);
1414
+ throw error;
1415
+ }
1416
+ }
1327
1417
  async update(key, data) {
1328
1418
  const transactionId = this._beginTransaction();
1329
1419
  try {
@@ -1983,39 +2073,8 @@ export class Tero {
1983
2073
  await this.commit(transactionId);
1984
2074
  this.knownKeys.delete(key);
1985
2075
  this.missingKeys.set(key, true);
1986
- this.writeLocalTombstone(key);
1987
- if (this.dataRecovery && this.hydrateMode === 'lazy') {
1988
- // Already inside outer reconciliation lock — re-check still deleted before cloud mutation
1989
- const committed = this.acidEngine.getCommittedData(key);
1990
- const hasLocal = this.hasLocalTombstone(key);
1991
- const existsLocal = existsSync(this.keyToPath(key));
1992
- const stillDeleted = hasLocal || (committed !== undefined && committed === null) || (!existsLocal && committed === undefined);
1993
- if (!stillDeleted) {
1994
- this.cloudPendingTombstones.delete(key);
1995
- this.savePendingCloud();
1996
- return;
1997
- }
1998
- const lsn = this.acidEngine.getLastCommittedLSN();
1999
- let failed = false;
2000
- try {
2001
- await this.dataRecovery.deleteFromCloud(key);
2002
- }
2003
- catch {
2004
- failed = true;
2005
- }
2006
- try {
2007
- await this.dataRecovery.putTombstone(key, lsn);
2008
- }
2009
- catch {
2010
- failed = true;
2011
- }
2012
- if (failed)
2013
- this.queueCloudTombstone(key, lsn);
2014
- else if (this.cloudPendingTombstones.has(key)) {
2015
- this.cloudPendingTombstones.delete(key);
2016
- this.savePendingCloud();
2017
- }
2018
- }
2076
+ // Cloud mirroring (local tombstone, bucket delete + tombstone, retry queue)
2077
+ // happens once, inside commit(). It used to run a second time here.
2019
2078
  }
2020
2079
  catch (error) {
2021
2080
  try {
@@ -2052,7 +2111,7 @@ export class Tero {
2052
2111
  const transactionId = this._beginTransaction();
2053
2112
  try {
2054
2113
  for (const op of operations) {
2055
- await this.write(transactionId, op.key, op.data);
2114
+ await this.write(transactionId, op.key, op.data, { replace: op.replace === true });
2056
2115
  }
2057
2116
  await this.commit(transactionId);
2058
2117
  // Register all written keys in knownKeys so future exists() calls are O(1)
@@ -2131,10 +2190,14 @@ export class Tero {
2131
2190
  }
2132
2191
  }
2133
2192
  // Internal raw methods for Transaction class
2134
- async _writeRaw(transactionId, key, data) {
2193
+ async _writeRaw(transactionId, key, data, replace = false) {
2135
2194
  const cachedEntry = this.cache.get(key);
2136
2195
  const cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) ? cachedEntry.data : undefined;
2137
- const result = this.acidEngine.write(transactionId, key, data, cachedData);
2196
+ // Engine replace adopts the object it is given — pass a private JSON copy.
2197
+ const json = replace ? JSON.stringify(data) : undefined;
2198
+ if (replace)
2199
+ data = JSON.parse(json);
2200
+ const result = this.acidEngine.write(transactionId, key, data, cachedData, replace, json);
2138
2201
  if (result !== undefined)
2139
2202
  await result;
2140
2203
  // Cache the MERGED afterImage, not the raw caller input. The engine
@@ -2345,6 +2408,19 @@ export class Tero {
2345
2408
  configureDataRecovery(config) {
2346
2409
  try {
2347
2410
  this.dataRecovery = new DataRecovery(config);
2411
+ // mode 'off': keep explicit recovery APIs (recoverFromCloud, recoverAllFromCloud…)
2412
+ // but never touch the bucket from get/create/update/delete. Use it when the
2413
+ // local disk is authoritative and restores happen explicitly at boot — it
2414
+ // keeps the bucket off the request path entirely.
2415
+ if (config.mode === 'off')
2416
+ this.hydrateMode = 'off';
2417
+ else if (this.hydrateMode === 'off')
2418
+ this.hydrateMode = 'lazy';
2419
+ if (this.cloudReconcileEnabled()) {
2420
+ this.requeueTombstonesFromDisk();
2421
+ if (this.cloudPendingTombstones.size > 0 || this.cloudPendingTombstoneDeletions.size > 0 || this.pendingLocalTombstoneRemovals.size > 0)
2422
+ this.scheduleCloudRetry();
2423
+ }
2348
2424
  }
2349
2425
  catch (error) {
2350
2426
  throw new Error(`Failed to configure data recovery: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
@@ -2570,71 +2646,127 @@ export class Tero {
2570
2646
  */
2571
2647
  acquireFileLock() {
2572
2648
  const lockPath = `${this.teroDirectory}/.lock`;
2649
+ const dir = this.teroDirectory;
2650
+ const heldFd = OPEN_DIRECTORIES.get(dir);
2651
+ if (heldFd !== undefined) {
2652
+ // Still ours only if the lock file on disk is the one that fd points at. If the
2653
+ // directory was wiped or restored underneath a leaked instance, the entry is dead.
2654
+ let same = false;
2655
+ try {
2656
+ const a = fstatSync(heldFd);
2657
+ const b = statSync(lockPath);
2658
+ same = a.ino === b.ino && a.dev === b.dev;
2659
+ }
2660
+ catch {
2661
+ same = false;
2662
+ }
2663
+ if (!same) {
2664
+ OPEN_DIRECTORIES.delete(dir);
2665
+ try {
2666
+ closeSync(heldFd);
2667
+ }
2668
+ catch { /* already closed */ }
2669
+ }
2670
+ }
2671
+ if (OPEN_DIRECTORIES.has(dir)) {
2672
+ throw new Error(`Another Tero instance in THIS process is already using '${dir}'. ` +
2673
+ 'Destroy the existing instance before constructing a new one.');
2674
+ }
2675
+ const bootId = currentBootId();
2573
2676
  const tryAcquire = () => {
2677
+ let fd;
2574
2678
  try {
2575
- this.lockFd = openSync(lockPath, 'wx'); // exclusive create — fails if exists
2576
- writeSync(this.lockFd, String(process.pid));
2577
- return true;
2679
+ fd = openSync(lockPath, 'wx'); // exclusive create — fails if exists
2578
2680
  }
2579
2681
  catch {
2580
2682
  return false;
2581
2683
  }
2684
+ try {
2685
+ writeSync(fd, `${process.pid}\n${bootId}`);
2686
+ }
2687
+ catch { /* an empty lock is reclaimed as stale */ }
2688
+ this.lockFd = fd;
2689
+ OPEN_DIRECTORIES.set(dir, fd);
2690
+ return true;
2582
2691
  };
2583
2692
  if (tryAcquire())
2584
2693
  return;
2585
- // Retry loop with bounded attempts for TOCTOU races during stale-lock reclamation
2694
+ // The lock exists. It is stale when its holder cannot be alive:
2695
+ // - it was written during a different boot of this machine/container, or
2696
+ // - it names OUR pid but this process has no open instance on the directory
2697
+ // (containers hand the app the same pid on every start, so after a crash
2698
+ // the leftover lock always "belongs" to the new process), or
2699
+ // - the pid it names no longer exists, or
2700
+ // - it is empty/garbled (holder died between creating and writing it).
2586
2701
  for (let attempt = 0; attempt < 3; attempt++) {
2587
- let pid = '?';
2588
- if (existsSync(lockPath)) {
2589
- try {
2590
- pid = readFileSync(lockPath, 'utf-8').trim();
2591
- }
2592
- catch { /* unreadable */ }
2702
+ let raw = '';
2703
+ try {
2704
+ raw = readFileSync(lockPath, 'utf-8');
2593
2705
  }
2594
- const pidNum = parseInt(pid, 10);
2595
- if (Number.isInteger(pidNum) && pidNum > 0 && pidNum !== process.pid) {
2706
+ catch { /* vanished or unreadable */ }
2707
+ const [pidStr = '', lockBoot = ''] = raw.trim().split('\n');
2708
+ const pidNum = parseInt(pidStr, 10);
2709
+ let stale;
2710
+ if (!Number.isInteger(pidNum) || pidNum <= 0) {
2711
+ stale = attempt > 0; // give a holder that is mid-write one retry
2712
+ }
2713
+ else if (lockBoot && bootId && lockBoot.trim() !== bootId) {
2714
+ stale = true;
2715
+ }
2716
+ else if (pidNum === process.pid) {
2717
+ stale = true;
2718
+ }
2719
+ else {
2596
2720
  let alive = true;
2597
2721
  try {
2598
2722
  process.kill(pidNum, 0);
2599
2723
  }
2600
2724
  catch (e) {
2601
- // ESRCH = no such process → stale lock from a crashed holder.
2602
- // EPERM = process exists but is owned by another user → treat as alive.
2725
+ // ESRCH = no such process. EPERM = exists, owned by another user → alive.
2603
2726
  alive = e?.code === 'EPERM';
2604
2727
  }
2605
- if (!alive) {
2606
- // Reclaim the stale lock (crashed previous owner) and retry once.
2607
- try {
2608
- unlinkSync(lockPath);
2609
- }
2610
- catch { /* racing holder */ }
2611
- if (tryAcquire())
2612
- return;
2613
- continue;
2614
- }
2615
2728
  if (alive) {
2616
- throw new Error(`Data directory '${this.teroDirectory}' is locked by live process ${pidNum}. ` +
2729
+ throw new Error(`Data directory '${dir}' is locked by live process ${pidNum}. ` +
2617
2730
  'Stop that process (or use a different directory) and retry.');
2618
2731
  }
2732
+ stale = true;
2619
2733
  }
2620
- if (pid === String(process.pid)) {
2621
- throw new Error(`Another Tero instance in THIS process is already using '${this.teroDirectory}'. ` +
2622
- 'Destroy the existing instance before constructing a new one.');
2734
+ if (stale) {
2735
+ try {
2736
+ unlinkSync(lockPath);
2737
+ }
2738
+ catch { /* racing holder */ }
2623
2739
  }
2624
2740
  if (tryAcquire())
2625
2741
  return;
2626
2742
  }
2627
- throw new Error(`Data directory '${this.teroDirectory}' is locked. ` +
2743
+ throw new Error(`Data directory '${dir}' is locked. ` +
2628
2744
  `If the holder crashed, delete '${lockPath}' and retry.`);
2629
2745
  }
2630
2746
  releaseFileLock() {
2631
2747
  if (this.lockFd == null)
2632
2748
  return;
2749
+ const lockPath = `${this.teroDirectory}/.lock`;
2750
+ if (OPEN_DIRECTORIES.get(this.teroDirectory) === this.lockFd)
2751
+ OPEN_DIRECTORIES.delete(this.teroDirectory);
2633
2752
  try {
2753
+ // Only remove the lock file if it is still ours (the directory may have been
2754
+ // replaced and re-opened by a newer instance).
2755
+ let ours = true;
2756
+ try {
2757
+ const a = fstatSync(this.lockFd);
2758
+ const b = statSync(lockPath);
2759
+ ours = a.ino === b.ino && a.dev === b.dev;
2760
+ }
2761
+ catch {
2762
+ ours = false;
2763
+ }
2634
2764
  closeSync(this.lockFd);
2635
- unlinkSync(`${this.teroDirectory}/.lock`);
2765
+ if (ours)
2766
+ unlinkSync(lockPath);
2636
2767
  }
2637
2768
  catch { /* best-effort */ }
2769
+ this.lockFd = undefined;
2638
2770
  }
2639
2771
  // Cleanup methods
2640
2772
  async destroyAsync() {
package/dist/recovery.js CHANGED
@@ -2,6 +2,7 @@ import { S3Client, GetObjectCommand, ListObjectsV2Command, HeadObjectCommand, De
2
2
  import { createWriteStream, existsSync, mkdirSync, openSync, fsyncSync, closeSync, renameSync, unlinkSync, writeSync } from "fs";
3
3
  import { join, dirname, resolve as pathResolve } from "path";
4
4
  import { pipeline } from "stream/promises";
5
+ import { buildS3ClientConfig } from "./s3-config.js";
5
6
  import { partitionedPath, DataCorruptionError } from "./acid-engine.js";
6
7
  export const MAX_DOCUMENT_SIZE = 10 * 1024 * 1024; // 10MB limit
7
8
  export function classifyRecoveryError(error) {
@@ -50,19 +51,7 @@ export class DataRecovery {
50
51
  this.s3Client = this.config.customS3Client;
51
52
  return;
52
53
  }
53
- const clientConfig = {
54
- region: this.config.cloudStorage.region,
55
- credentials: {
56
- accessKeyId: this.config.cloudStorage.accessKeyId,
57
- secretAccessKey: this.config.cloudStorage.secretAccessKey,
58
- },
59
- };
60
- // Configure for Cloudflare R2 or custom endpoints
61
- if (this.config.cloudStorage.endpoint) {
62
- clientConfig.endpoint = this.config.cloudStorage.endpoint;
63
- clientConfig.forcePathStyle = true; // Required for R2
64
- }
65
- this.s3Client = new S3Client(clientConfig);
54
+ this.s3Client = new S3Client(buildS3ClientConfig(this.config.cloudStorage));
66
55
  }
67
56
  catch (error) {
68
57
  throw new Error(`Failed to initialize cloud storage for recovery: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });