tero 0.1.2 → 0.3.1

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,6 +1,6 @@
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
5
  import { ACIDStorageEngine, partitionedPath, RecoveryCorruptionError, DataCorruptionError, sweepStaleTempFiles } from "./acid-engine.js";
6
6
  import { BackupManager } from "./backup.js";
@@ -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);
@@ -518,28 +538,13 @@ export class Tero {
518
538
  const syncMode = synchronous ?? 'full';
519
539
  const syncInterval = commitIntervalMs ?? 10;
520
540
  const dataFlushInterval = dataFlushIntervalMs ?? 50;
521
- this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval, config?.checkpointBatchSize, config?.archiveKeepCount);
522
- // Restore durable local tombstones (P0-2) — prevents resurrection after restart even if cloud tombstone not yet durable
523
- try {
524
- const tombDir = pathJoin(this.teroDirectory, '.tombstones');
525
- if (existsSync(tombDir)) {
526
- const files = readdirSync(tombDir);
527
- for (const f of files) {
528
- if (!f.endsWith('.deleted'))
529
- continue;
530
- try {
531
- const content = readFileSync(pathJoin(tombDir, f), 'utf8');
532
- const obj = JSON.parse(content);
533
- if (obj.key && typeof obj.key === 'string') {
534
- this.missingKeys.set(obj.key, true);
535
- this.bumpGeneration(obj.key);
536
- }
537
- }
538
- catch { /* approved */ }
539
- }
540
- }
541
- }
542
- 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.
543
548
  // v2: optionally install a backup config at construction time.
544
549
  if (config?.backup) {
545
550
  this.configureBackup(config.backup);
@@ -568,40 +573,14 @@ export class Tero {
568
573
  this.loadPendingCloud();
569
574
  this.loadPendingCloudDeletions();
570
575
  this.loadPendingLocalTombstoneRemovals();
571
- // Fallback: reconstruct pending from local tombstones if queue file was lost (ENOSPC case)
572
- try {
573
- const tombDir = pathJoin(this.teroDirectory, '.tombstones');
574
- if (existsSync(tombDir)) {
575
- const files = readdirSync(tombDir);
576
- for (const f of files) {
577
- if (!f.endsWith('.deleted'))
578
- continue;
579
- try {
580
- const content = readFileSync(pathJoin(tombDir, f), 'utf8');
581
- const obj = JSON.parse(content);
582
- if (obj.key && typeof obj.key === 'string' && typeof obj.lsn === 'number') {
583
- if (!this.cloudPendingTombstones.has(obj.key) && !this.cloudPendingTombstoneDeletions.has(obj.key) && !this.pendingLocalTombstoneRemovals.has(obj.key)) {
584
- if (this.dataRecovery) {
585
- this.cloudPendingTombstones.set(obj.key, obj.lsn);
586
- }
587
- }
588
- }
589
- }
590
- catch { }
591
- }
592
- if (this.cloudPendingTombstones.size > 0) {
593
- try {
594
- this.savePendingCloud();
595
- }
596
- catch { }
597
- }
598
- }
599
- }
600
- catch { }
576
+ if (this.cloudReconcileEnabled())
577
+ this.requeueTombstonesFromDisk();
601
578
  if (this.cloudPendingTombstones.size > 0 || this.cloudPendingTombstoneDeletions.size > 0 || this.pendingLocalTombstoneRemovals.size > 0)
602
579
  this.scheduleCloudRetry();
603
580
  }
604
581
  catch (error) {
582
+ // A failed open must not keep the directory locked (in this process or on disk).
583
+ this.releaseFileLock();
605
584
  if (error instanceof RecoveryCorruptionError || error instanceof DataCorruptionError) {
606
585
  throw error;
607
586
  }
@@ -697,6 +676,7 @@ export class Tero {
697
676
  const hasTomb = await this.dataRecovery.hasTombstone(key);
698
677
  if (hasTomb) {
699
678
  this.missingKeys.set(key, true);
679
+ this.knownCloudTombstones.set(key, true);
700
680
  return null;
701
681
  }
702
682
  }
@@ -818,6 +798,7 @@ export class Tero {
818
798
  }
819
799
  finally {
820
800
  this.inFlightHydrations.delete(key);
801
+ this.keyGenerations.delete(key);
821
802
  }
822
803
  })();
823
804
  this.inFlightHydrations.set(key, fetchPromise);
@@ -893,7 +874,50 @@ export class Tero {
893
874
  throw new Error('Key contains invalid characters');
894
875
  }
895
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
+ }
896
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;
897
921
  const next = (this.keyGenerations.get(key) ?? 0) + 1;
898
922
  this.keyGenerations.set(key, next);
899
923
  return next;
@@ -913,8 +937,12 @@ export class Tero {
913
937
  }
914
938
  }
915
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.
916
944
  this.cache.set(key, {
917
- data: deepClone(data),
945
+ data,
918
946
  lastAccessed: Date.now(),
919
947
  transactionId
920
948
  });
@@ -945,31 +973,47 @@ export class Tero {
945
973
  _txId(id) {
946
974
  return typeof id === 'string' ? id : id.getId();
947
975
  }
948
- 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) {
949
982
  try {
950
983
  const txId = this._txId(transactionId);
951
984
  this.validateKey(key);
952
985
  if (data === undefined || data === null) {
953
986
  throw new Error('Data cannot be null or undefined');
954
987
  }
955
- 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
+ }
956
999
  // Use byte length, not char length — 'é' is 1 char but 2 bytes UTF-8, emoji is 4 bytes
957
- const jsonStr = JSON.stringify(data);
958
1000
  const byteLen = Buffer.byteLength(jsonStr, 'utf8');
959
1001
  if (byteLen > MAX_DOCUMENT_SIZE) {
960
1002
  throw new Error(`Document size exceeds maximum allowed size (${MAX_DOCUMENT_SIZE / (1024 * 1024)}MB) — got ${(byteLen / (1024 * 1024)).toFixed(2)}MB`);
961
1003
  }
1004
+ if (options?.replace)
1005
+ data = JSON.parse(jsonStr);
962
1006
  // Check cache for beforeImage so engine doesn't need disk I/O on hot writes
963
1007
  const cachedEntry = this.cache.get(key);
964
1008
  let cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) ? cachedEntry.data : undefined;
965
1009
  // Lazy hydration: if updating a cold document not on disk, hydrate beforeImage from cloud
966
- if (cachedData === undefined && this.dataRecovery && this.hydrateMode === 'lazy' &&
1010
+ if (!options?.replace && cachedData === undefined && this.dataRecovery && this.hydrateMode === 'lazy' &&
967
1011
  this.acidEngine.getCommittedData(key) === undefined &&
968
1012
  !existsSync(this.keyToPath(key))) {
969
1013
  cachedData = (await this.hydrateKey(key)) ?? undefined;
970
1014
  }
971
1015
  // Engine write — returns void (sync fast path) or Promise (contended lock)
972
- 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);
973
1017
  if (writeResult !== undefined)
974
1018
  await writeResult;
975
1019
  // Cache the MERGED afterImage (from pendingWrites), NOT the raw user data.
@@ -1050,14 +1094,18 @@ export class Tero {
1050
1094
  // Bump generation for P0-1 in-flight hydration invalidation and P0-10 stale hydration
1051
1095
  this.bumpGeneration(key);
1052
1096
  }
1053
- // Post-commit reconciliation — durable but best-effort, never fails the logical commit
1054
- 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 : [])) {
1055
1100
  try {
1056
1101
  await this.withReconciliationLock(key, async () => {
1057
1102
  const committed = this.acidEngine.getCommittedData(key);
1058
1103
  if (committed !== undefined) {
1059
1104
  if (committed !== null) {
1060
- // 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);
1061
1109
  try {
1062
1110
  this.deleteLocalTombstone(key);
1063
1111
  }
@@ -1079,7 +1127,7 @@ export class Tero {
1079
1127
  }
1080
1128
  catch { }
1081
1129
  }
1082
- if (this.dataRecovery) {
1130
+ if (this.dataRecovery && mayHaveCloudTombstone) {
1083
1131
  // Re-check still present before deleting cloud tombstone
1084
1132
  const committed2 = this.acidEngine.getCommittedData(key);
1085
1133
  const hasLocal2 = this.hasLocalTombstone(key);
@@ -1092,6 +1140,7 @@ export class Tero {
1092
1140
  }
1093
1141
  try {
1094
1142
  await this.dataRecovery.deleteTombstone?.(key);
1143
+ this.knownCloudTombstones.delete(key);
1095
1144
  if (this.cloudPendingTombstoneDeletions.has(key)) {
1096
1145
  this.cloudPendingTombstoneDeletions.delete(key);
1097
1146
  try {
@@ -1144,12 +1193,22 @@ export class Tero {
1144
1193
  }
1145
1194
  if (failed)
1146
1195
  this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1147
- else if (this.cloudPendingTombstones.has(key)) {
1148
- 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.
1149
1208
  try {
1150
- this.savePendingCloud();
1209
+ this.deleteLocalTombstone(key);
1151
1210
  }
1152
- catch { }
1211
+ catch { /* approved: retried on next delete/re-create */ }
1153
1212
  }
1154
1213
  }
1155
1214
  }
@@ -1204,9 +1263,10 @@ export class Tero {
1204
1263
  }
1205
1264
  catch { }
1206
1265
  }
1207
- if (this.dataRecovery) {
1266
+ if (this.dataRecovery && (this.knownCloudTombstones.has(key) || this.cloudPendingTombstoneDeletions.has(key))) {
1208
1267
  try {
1209
1268
  await this.dataRecovery.deleteTombstone?.(key);
1269
+ this.knownCloudTombstones.delete(key);
1210
1270
  if (this.cloudPendingTombstoneDeletions.has(key)) {
1211
1271
  this.cloudPendingTombstoneDeletions.delete(key);
1212
1272
  try {
@@ -1301,6 +1361,8 @@ export class Tero {
1301
1361
  let hasTomb = false;
1302
1362
  if (typeof this.dataRecovery.hasTombstone === 'function') {
1303
1363
  hasTomb = await this.dataRecovery.hasTombstone(key);
1364
+ if (hasTomb)
1365
+ this.knownCloudTombstones.set(key, true);
1304
1366
  }
1305
1367
  if (!hasTomb) {
1306
1368
  const info = await this.dataRecovery.checkFileInCloud(key);
@@ -1331,6 +1393,27 @@ export class Tero {
1331
1393
  }
1332
1394
  });
1333
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
+ }
1334
1417
  async update(key, data) {
1335
1418
  const transactionId = this._beginTransaction();
1336
1419
  try {
@@ -1990,39 +2073,8 @@ export class Tero {
1990
2073
  await this.commit(transactionId);
1991
2074
  this.knownKeys.delete(key);
1992
2075
  this.missingKeys.set(key, true);
1993
- this.writeLocalTombstone(key);
1994
- if (this.dataRecovery && this.hydrateMode === 'lazy') {
1995
- // Already inside outer reconciliation lock — re-check still deleted before cloud mutation
1996
- const committed = this.acidEngine.getCommittedData(key);
1997
- const hasLocal = this.hasLocalTombstone(key);
1998
- const existsLocal = existsSync(this.keyToPath(key));
1999
- const stillDeleted = hasLocal || (committed !== undefined && committed === null) || (!existsLocal && committed === undefined);
2000
- if (!stillDeleted) {
2001
- this.cloudPendingTombstones.delete(key);
2002
- this.savePendingCloud();
2003
- return;
2004
- }
2005
- const lsn = this.acidEngine.getLastCommittedLSN();
2006
- let failed = false;
2007
- try {
2008
- await this.dataRecovery.deleteFromCloud(key);
2009
- }
2010
- catch {
2011
- failed = true;
2012
- }
2013
- try {
2014
- await this.dataRecovery.putTombstone(key, lsn);
2015
- }
2016
- catch {
2017
- failed = true;
2018
- }
2019
- if (failed)
2020
- this.queueCloudTombstone(key, lsn);
2021
- else if (this.cloudPendingTombstones.has(key)) {
2022
- this.cloudPendingTombstones.delete(key);
2023
- this.savePendingCloud();
2024
- }
2025
- }
2076
+ // Cloud mirroring (local tombstone, bucket delete + tombstone, retry queue)
2077
+ // happens once, inside commit(). It used to run a second time here.
2026
2078
  }
2027
2079
  catch (error) {
2028
2080
  try {
@@ -2059,7 +2111,7 @@ export class Tero {
2059
2111
  const transactionId = this._beginTransaction();
2060
2112
  try {
2061
2113
  for (const op of operations) {
2062
- await this.write(transactionId, op.key, op.data);
2114
+ await this.write(transactionId, op.key, op.data, { replace: op.replace === true });
2063
2115
  }
2064
2116
  await this.commit(transactionId);
2065
2117
  // Register all written keys in knownKeys so future exists() calls are O(1)
@@ -2138,10 +2190,14 @@ export class Tero {
2138
2190
  }
2139
2191
  }
2140
2192
  // Internal raw methods for Transaction class
2141
- async _writeRaw(transactionId, key, data) {
2193
+ async _writeRaw(transactionId, key, data, replace = false) {
2142
2194
  const cachedEntry = this.cache.get(key);
2143
2195
  const cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === transactionId)) ? cachedEntry.data : undefined;
2144
- 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);
2145
2201
  if (result !== undefined)
2146
2202
  await result;
2147
2203
  // Cache the MERGED afterImage, not the raw caller input. The engine
@@ -2352,6 +2408,19 @@ export class Tero {
2352
2408
  configureDataRecovery(config) {
2353
2409
  try {
2354
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
+ }
2355
2424
  }
2356
2425
  catch (error) {
2357
2426
  throw new Error(`Failed to configure data recovery: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
@@ -2577,71 +2646,127 @@ export class Tero {
2577
2646
  */
2578
2647
  acquireFileLock() {
2579
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();
2580
2676
  const tryAcquire = () => {
2677
+ let fd;
2581
2678
  try {
2582
- this.lockFd = openSync(lockPath, 'wx'); // exclusive create — fails if exists
2583
- writeSync(this.lockFd, String(process.pid));
2584
- return true;
2679
+ fd = openSync(lockPath, 'wx'); // exclusive create — fails if exists
2585
2680
  }
2586
2681
  catch {
2587
2682
  return false;
2588
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;
2589
2691
  };
2590
2692
  if (tryAcquire())
2591
2693
  return;
2592
- // 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).
2593
2701
  for (let attempt = 0; attempt < 3; attempt++) {
2594
- let pid = '?';
2595
- if (existsSync(lockPath)) {
2596
- try {
2597
- pid = readFileSync(lockPath, 'utf-8').trim();
2598
- }
2599
- catch { /* unreadable */ }
2702
+ let raw = '';
2703
+ try {
2704
+ raw = readFileSync(lockPath, 'utf-8');
2705
+ }
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;
2600
2715
  }
2601
- const pidNum = parseInt(pid, 10);
2602
- if (Number.isInteger(pidNum) && pidNum > 0 && pidNum !== process.pid) {
2716
+ else if (pidNum === process.pid) {
2717
+ stale = true;
2718
+ }
2719
+ else {
2603
2720
  let alive = true;
2604
2721
  try {
2605
2722
  process.kill(pidNum, 0);
2606
2723
  }
2607
2724
  catch (e) {
2608
- // ESRCH = no such process → stale lock from a crashed holder.
2609
- // EPERM = process exists but is owned by another user → treat as alive.
2725
+ // ESRCH = no such process. EPERM = exists, owned by another user → alive.
2610
2726
  alive = e?.code === 'EPERM';
2611
2727
  }
2612
- if (!alive) {
2613
- // Reclaim the stale lock (crashed previous owner) and retry once.
2614
- try {
2615
- unlinkSync(lockPath);
2616
- }
2617
- catch { /* racing holder */ }
2618
- if (tryAcquire())
2619
- return;
2620
- continue;
2621
- }
2622
2728
  if (alive) {
2623
- 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}. ` +
2624
2730
  'Stop that process (or use a different directory) and retry.');
2625
2731
  }
2732
+ stale = true;
2626
2733
  }
2627
- if (pid === String(process.pid)) {
2628
- throw new Error(`Another Tero instance in THIS process is already using '${this.teroDirectory}'. ` +
2629
- 'Destroy the existing instance before constructing a new one.');
2734
+ if (stale) {
2735
+ try {
2736
+ unlinkSync(lockPath);
2737
+ }
2738
+ catch { /* racing holder */ }
2630
2739
  }
2631
2740
  if (tryAcquire())
2632
2741
  return;
2633
2742
  }
2634
- throw new Error(`Data directory '${this.teroDirectory}' is locked. ` +
2743
+ throw new Error(`Data directory '${dir}' is locked. ` +
2635
2744
  `If the holder crashed, delete '${lockPath}' and retry.`);
2636
2745
  }
2637
2746
  releaseFileLock() {
2638
2747
  if (this.lockFd == null)
2639
2748
  return;
2749
+ const lockPath = `${this.teroDirectory}/.lock`;
2750
+ if (OPEN_DIRECTORIES.get(this.teroDirectory) === this.lockFd)
2751
+ OPEN_DIRECTORIES.delete(this.teroDirectory);
2640
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
+ }
2641
2764
  closeSync(this.lockFd);
2642
- unlinkSync(`${this.teroDirectory}/.lock`);
2765
+ if (ours)
2766
+ unlinkSync(lockPath);
2643
2767
  }
2644
2768
  catch { /* best-effort */ }
2769
+ this.lockFd = undefined;
2645
2770
  }
2646
2771
  // Cleanup methods
2647
2772
  async destroyAsync() {
@@ -2661,6 +2786,14 @@ export class Tero {
2661
2786
  this.backupManager.destroy();
2662
2787
  }
2663
2788
  if (this.acidEngine) {
2789
+ // Make the data durable with parallel fsyncs on the libuv pool first; the
2790
+ // synchronous final checkpoint in destroy() then has nothing left to sync.
2791
+ // One fsync per dirty file on the event loop made shutdown take minutes
2792
+ // with many pending documents (past a platform's kill timeout).
2793
+ try {
2794
+ await this.acidEngine.forceCheckpointAsync();
2795
+ }
2796
+ catch { /* destroy() retries synchronously */ }
2664
2797
  this.acidEngine.destroy();
2665
2798
  }
2666
2799
  this.inFlightHydrations.clear();
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 });
@@ -0,0 +1,3 @@
1
+ import type { CloudStorageConfig } from './backup.js';
2
+ /** Shared S3 client options: endpoint/path-style for R2 and custom endpoints, and request timeouts. */
3
+ export declare function buildS3ClientConfig(cloudConfig: CloudStorageConfig): any;