zen-fs-config 0.6.2 → 0.6.4

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.d.mts CHANGED
@@ -952,6 +952,22 @@ declare class ConfigRepo implements IConfigRepo {
952
952
  private readonly pollIntervalMs?;
953
953
  /** Tombstone cache — avoids redundant reads within a single flush() cycle. */
954
954
  private tombstoneCache;
955
+ /**
956
+ * 墓碑存在期间被排除在同步之外的路径。
957
+ *
958
+ * 远端副本可能仍残留被删路径(哪怕只剩 `.keep` / `.keep.mtime` 占位)。
959
+ * 若同步照常进行,这类残留会被当成"远端新增"再拉回本地,造成空壳复活。
960
+ * 这些路径改由 processTombstones 主动删除,直到所有副本确认不存在、
961
+ * 墓碑被 GC 之后才恢复同步。
962
+ */
963
+ private readonly tombstoneExcludePrefixes;
964
+ private readonly syncFilter;
965
+ /**
966
+ * 本轮 processTombstones 中,各副本对墓碑路径"已确认不存在"的结果。
967
+ * 目录类路径用 exists() 复核;`.mtime` 侧车对部分后端不可见,只能用
968
+ * unlink() 是否成功来判定。
969
+ */
970
+ private readonly tombstoneConfirmations;
955
971
  /** Per-backend sync state (successful pairs + connect failures). */
956
972
  private backendStates;
957
973
  /** Last known backend descriptors, for the synchronous unified handle API. */
@@ -1000,6 +1016,13 @@ declare class ConfigRepo implements IConfigRepo {
1000
1016
  * Results are cached within a flush() cycle to avoid redundant reads.
1001
1017
  */
1002
1018
  private readTombstones;
1019
+ /**
1020
+ * 把当前墓碑路径同步到同步排除表。
1021
+ *
1022
+ * 排除表与各同步对共享同一个数组实例(zen-fs-sync 在每次检测时实时读取
1023
+ * `filter.excludePrefixes`),所以这里原地更新即可生效。
1024
+ */
1025
+ private refreshSyncExclusions;
1003
1026
  /** Invalidate the tombstone cache — call after tombstones are modified. */
1004
1027
  private invalidateTombstoneCache;
1005
1028
  /**
@@ -1013,6 +1036,24 @@ declare class ConfigRepo implements IConfigRepo {
1013
1036
  * effectively free for them.
1014
1037
  */
1015
1038
  private processTombstones;
1039
+ /**
1040
+ * 删除墓碑目标在某个后端上的全部残留。
1041
+ *
1042
+ * 目录不能直接 unlink(会抛 EISDIR)。旧实现把这个异常当成"已被并发删除"
1043
+ * 而继续推进确认,墓碑随后被 GC;但副本上的占位目录仍然存在,下一次同步
1044
+ * 就把它当作远端内容拉回本地,形成空壳复活。
1045
+ *
1046
+ * 这里按树清理:
1047
+ * 1. 强制删掉 `.keep` / `.keep.mtime` 占位(部分后端把 `.keep` 隐藏在索引里,
1048
+ * readdir 看不到,只能按路径直接删);
1049
+ * 2. 递归清理可见子项;
1050
+ * 3. rmdir(后端不支持目录时退回 unlink)。
1051
+ *
1052
+ * @returns 是否确认该路径已不存在;清理失败返回 false,墓碑必须保留。
1053
+ */
1054
+ private purgePathOnBackend;
1055
+ /** 后端无关的存在性判断:优先 exists(),否则退化为 stat()。 */
1056
+ private pathExistsOnBackend;
1016
1057
  /**
1017
1058
  * Safe existence check — returns false on any error instead of throwing.
1018
1059
  * Used by processTombstones to avoid unnecessary unlink() calls.
@@ -1071,9 +1112,25 @@ declare class ConfigRepo implements IConfigRepo {
1071
1112
  */
1072
1113
  startBackgroundSync(): void;
1073
1114
  /**
1074
- * After sync: mark each tombstone as confirmed by all replica backends.
1115
+ * After sync: mark each tombstone as confirmed by replicas where the target
1116
+ * path was actually verified absent.
1117
+ *
1118
+ * 旧实现把所有副本无条件写进 confirmedBy,只要有一轮同步跑过就认为
1119
+ * "所有副本都删干净了"。但副本可能因为网络/后端限制删除失败,或只剩
1120
+ * `.keep` / `.keep.mtime` 占位目录;墓碑一旦被 GC,下一轮同步就把残留
1121
+ * 当作远端内容拉回本地。现在只确认 processTombstones 本轮真正清干净的副本。
1075
1122
  */
1076
1123
  private updateTombstoneConfirmations;
1124
+ /**
1125
+ * 墓碑路径是否已在所有副本上确认不存在。
1126
+ *
1127
+ * `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),
1128
+ * 因此只能相信本轮 `processTombstones` 的 unlink 结果;其余路径在 GC 前
1129
+ * 现场复核一次,避免"确认之后副本又把残留带了回来"。
1130
+ *
1131
+ * 任一位置仍存在就返回 false —— 墓碑必须保留,直到真正删干净。
1132
+ */
1133
+ private allReplicasConfirmAbsent;
1077
1134
  /**
1078
1135
  * GC: remove tombstones where all backends in backends.json have confirmed.
1079
1136
  *
package/dist/index.d.ts CHANGED
@@ -952,6 +952,22 @@ declare class ConfigRepo implements IConfigRepo {
952
952
  private readonly pollIntervalMs?;
953
953
  /** Tombstone cache — avoids redundant reads within a single flush() cycle. */
954
954
  private tombstoneCache;
955
+ /**
956
+ * 墓碑存在期间被排除在同步之外的路径。
957
+ *
958
+ * 远端副本可能仍残留被删路径(哪怕只剩 `.keep` / `.keep.mtime` 占位)。
959
+ * 若同步照常进行,这类残留会被当成"远端新增"再拉回本地,造成空壳复活。
960
+ * 这些路径改由 processTombstones 主动删除,直到所有副本确认不存在、
961
+ * 墓碑被 GC 之后才恢复同步。
962
+ */
963
+ private readonly tombstoneExcludePrefixes;
964
+ private readonly syncFilter;
965
+ /**
966
+ * 本轮 processTombstones 中,各副本对墓碑路径"已确认不存在"的结果。
967
+ * 目录类路径用 exists() 复核;`.mtime` 侧车对部分后端不可见,只能用
968
+ * unlink() 是否成功来判定。
969
+ */
970
+ private readonly tombstoneConfirmations;
955
971
  /** Per-backend sync state (successful pairs + connect failures). */
956
972
  private backendStates;
957
973
  /** Last known backend descriptors, for the synchronous unified handle API. */
@@ -1000,6 +1016,13 @@ declare class ConfigRepo implements IConfigRepo {
1000
1016
  * Results are cached within a flush() cycle to avoid redundant reads.
1001
1017
  */
1002
1018
  private readTombstones;
1019
+ /**
1020
+ * 把当前墓碑路径同步到同步排除表。
1021
+ *
1022
+ * 排除表与各同步对共享同一个数组实例(zen-fs-sync 在每次检测时实时读取
1023
+ * `filter.excludePrefixes`),所以这里原地更新即可生效。
1024
+ */
1025
+ private refreshSyncExclusions;
1003
1026
  /** Invalidate the tombstone cache — call after tombstones are modified. */
1004
1027
  private invalidateTombstoneCache;
1005
1028
  /**
@@ -1013,6 +1036,24 @@ declare class ConfigRepo implements IConfigRepo {
1013
1036
  * effectively free for them.
1014
1037
  */
1015
1038
  private processTombstones;
1039
+ /**
1040
+ * 删除墓碑目标在某个后端上的全部残留。
1041
+ *
1042
+ * 目录不能直接 unlink(会抛 EISDIR)。旧实现把这个异常当成"已被并发删除"
1043
+ * 而继续推进确认,墓碑随后被 GC;但副本上的占位目录仍然存在,下一次同步
1044
+ * 就把它当作远端内容拉回本地,形成空壳复活。
1045
+ *
1046
+ * 这里按树清理:
1047
+ * 1. 强制删掉 `.keep` / `.keep.mtime` 占位(部分后端把 `.keep` 隐藏在索引里,
1048
+ * readdir 看不到,只能按路径直接删);
1049
+ * 2. 递归清理可见子项;
1050
+ * 3. rmdir(后端不支持目录时退回 unlink)。
1051
+ *
1052
+ * @returns 是否确认该路径已不存在;清理失败返回 false,墓碑必须保留。
1053
+ */
1054
+ private purgePathOnBackend;
1055
+ /** 后端无关的存在性判断:优先 exists(),否则退化为 stat()。 */
1056
+ private pathExistsOnBackend;
1016
1057
  /**
1017
1058
  * Safe existence check — returns false on any error instead of throwing.
1018
1059
  * Used by processTombstones to avoid unnecessary unlink() calls.
@@ -1071,9 +1112,25 @@ declare class ConfigRepo implements IConfigRepo {
1071
1112
  */
1072
1113
  startBackgroundSync(): void;
1073
1114
  /**
1074
- * After sync: mark each tombstone as confirmed by all replica backends.
1115
+ * After sync: mark each tombstone as confirmed by replicas where the target
1116
+ * path was actually verified absent.
1117
+ *
1118
+ * 旧实现把所有副本无条件写进 confirmedBy,只要有一轮同步跑过就认为
1119
+ * "所有副本都删干净了"。但副本可能因为网络/后端限制删除失败,或只剩
1120
+ * `.keep` / `.keep.mtime` 占位目录;墓碑一旦被 GC,下一轮同步就把残留
1121
+ * 当作远端内容拉回本地。现在只确认 processTombstones 本轮真正清干净的副本。
1075
1122
  */
1076
1123
  private updateTombstoneConfirmations;
1124
+ /**
1125
+ * 墓碑路径是否已在所有副本上确认不存在。
1126
+ *
1127
+ * `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),
1128
+ * 因此只能相信本轮 `processTombstones` 的 unlink 结果;其余路径在 GC 前
1129
+ * 现场复核一次,避免"确认之后副本又把残留带了回来"。
1130
+ *
1131
+ * 任一位置仍存在就返回 false —— 墓碑必须保留,直到真正删干净。
1132
+ */
1133
+ private allReplicasConfirmAbsent;
1077
1134
  /**
1078
1135
  * GC: remove tombstones where all backends in backends.json have confirmed.
1079
1136
  *
package/dist/index.js CHANGED
@@ -2130,6 +2130,12 @@ async function removeDirectoryTree(fs, dir) {
2130
2130
  } catch {
2131
2131
  }
2132
2132
  }
2133
+ function isNotFoundError(err) {
2134
+ const code = err?.code;
2135
+ if (code === "ENOENT" || code === "ENOTDIR") return true;
2136
+ const message = String(err?.message ?? err);
2137
+ return /ENOENT|not found|does not exist|\b404\b/i.test(message);
2138
+ }
2133
2139
  function normalizeGroupName(value) {
2134
2140
  if (typeof value !== "string") {
2135
2141
  throw new Error("Group name must be a string");
@@ -2235,6 +2241,22 @@ var ConfigRepo = class {
2235
2241
  pollIntervalMs;
2236
2242
  /** Tombstone cache — avoids redundant reads within a single flush() cycle. */
2237
2243
  tombstoneCache = null;
2244
+ /**
2245
+ * 墓碑存在期间被排除在同步之外的路径。
2246
+ *
2247
+ * 远端副本可能仍残留被删路径(哪怕只剩 `.keep` / `.keep.mtime` 占位)。
2248
+ * 若同步照常进行,这类残留会被当成"远端新增"再拉回本地,造成空壳复活。
2249
+ * 这些路径改由 processTombstones 主动删除,直到所有副本确认不存在、
2250
+ * 墓碑被 GC 之后才恢复同步。
2251
+ */
2252
+ tombstoneExcludePrefixes = [];
2253
+ syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
2254
+ /**
2255
+ * 本轮 processTombstones 中,各副本对墓碑路径"已确认不存在"的结果。
2256
+ * 目录类路径用 exists() 复核;`.mtime` 侧车对部分后端不可见,只能用
2257
+ * unlink() 是否成功来判定。
2258
+ */
2259
+ tombstoneConfirmations = /* @__PURE__ */ new Map();
2238
2260
  /** Per-backend sync state (successful pairs + connect failures). */
2239
2261
  backendStates = /* @__PURE__ */ new Map();
2240
2262
  /** Last known backend descriptors, for the synchronous unified handle API. */
@@ -2514,8 +2536,29 @@ var ConfigRepo = class {
2514
2536
  return this.tombstoneCache;
2515
2537
  }
2516
2538
  this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log3.warn(message));
2539
+ this.refreshSyncExclusions(this.tombstoneCache);
2517
2540
  return this.tombstoneCache;
2518
2541
  }
2542
+ /**
2543
+ * 把当前墓碑路径同步到同步排除表。
2544
+ *
2545
+ * 排除表与各同步对共享同一个数组实例(zen-fs-sync 在每次检测时实时读取
2546
+ * `filter.excludePrefixes`),所以这里原地更新即可生效。
2547
+ */
2548
+ refreshSyncExclusions(tombstones) {
2549
+ this.tombstoneExcludePrefixes.length = 0;
2550
+ const add = (target) => {
2551
+ this.tombstoneExcludePrefixes.push(target, `${target}/`);
2552
+ };
2553
+ for (const tombstone of tombstones) {
2554
+ if (!tombstone.path) continue;
2555
+ add(tombstone.path);
2556
+ if (tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep") || tombstone.path.endsWith("/.keep.mtime")) {
2557
+ const dir = tombstone.path.slice(0, tombstone.path.lastIndexOf("/")) || "/";
2558
+ if (dir !== "/") add(dir);
2559
+ }
2560
+ }
2561
+ }
2519
2562
  /** Invalidate the tombstone cache — call after tombstones are modified. */
2520
2563
  invalidateTombstoneCache() {
2521
2564
  this.tombstoneCache = null;
@@ -2532,70 +2575,161 @@ var ConfigRepo = class {
2532
2575
  */
2533
2576
  async processTombstones() {
2534
2577
  const tombstones = await this.readTombstones();
2578
+ this.tombstoneConfirmations.clear();
2535
2579
  if (tombstones.length === 0) return;
2536
2580
  let processed = 0;
2537
2581
  let alreadyDeleted = 0;
2582
+ let unresolved = 0;
2538
2583
  for (const tombstone of tombstones) {
2539
- const forceDelete = isMtimeSidecar(tombstone.path);
2584
+ const isKeepPlaceholder = tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep");
2585
+ const forceDelete = isMtimeSidecar(tombstone.path) || isKeepPlaceholder;
2540
2586
  const tVersionPath = forceDelete ? null : versionPathFor(tombstone.path);
2541
- log3.log(`[TOMB-TRACE] processing tombstone: path=${tombstone.path} versionPath=${tVersionPath ?? "null"} forceDelete=${forceDelete}`);
2542
- const existedOnPrimary = forceDelete || await this.safeExists(this.cachedFS, tombstone.path);
2543
- log3.log(`[TOMB-TRACE] primary safeExists(${tombstone.path}) \u2192 ${existedOnPrimary}`);
2544
- if (existedOnPrimary) {
2545
- log3.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on primary \u2192 EXISTS`);
2546
- }
2547
- if (existedOnPrimary) {
2548
- try {
2549
- await this.cachedFS.unlink(tombstone.path);
2550
- processed++;
2551
- } catch {
2552
- }
2553
- }
2554
- if (tVersionPath) {
2555
- const vExistedOnPrimary = await this.safeExists(this.cachedFS, tVersionPath);
2556
- log3.log(`[TOMB-TRACE] primary safeExists(${tVersionPath}) \u2192 ${vExistedOnPrimary}`);
2557
- if (vExistedOnPrimary) {
2587
+ const sidecarOwner = sidecarOwnerPath(tombstone.path);
2588
+ const isKeepSidecar = sidecarOwner === "/.keep" || (sidecarOwner?.endsWith("/.keep") ?? false);
2589
+ const liveSidecarCandidate = sidecarOwner !== null && !isKeepSidecar;
2590
+ if (forceDelete) {
2591
+ if (!(liveSidecarCandidate && await this.pathExistsOnBackend(this.cachedFS, sidecarOwner))) {
2558
2592
  try {
2559
- await this.cachedFS.unlink(tVersionPath);
2593
+ await this.cachedFS.unlink(tombstone.path);
2594
+ processed++;
2560
2595
  } catch {
2561
2596
  }
2562
2597
  }
2598
+ } else {
2599
+ const existedOnPrimary = await this.pathExistsOnBackend(this.cachedFS, tombstone.path);
2600
+ const gone = await this.purgePathOnBackend(this.cachedFS, tombstone.path);
2601
+ if (gone) {
2602
+ if (existedOnPrimary) processed++;
2603
+ else alreadyDeleted++;
2604
+ } else unresolved++;
2605
+ if (tVersionPath) await this.purgePathOnBackend(this.cachedFS, tVersionPath);
2563
2606
  }
2564
2607
  for (const [replicaId, replica] of this.replicaBackends) {
2565
- log3.log(`[TOMB-TRACE] checking replica: ${replicaId} for ${tombstone.path}`);
2566
- const existed = forceDelete || await this.safeExists(replica.instance, tombstone.path);
2567
- log3.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tombstone.path}) \u2192 ${existed}`);
2568
- if (existed) {
2569
- log3.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on ${replicaId} \u2192 EXISTS`);
2570
- try {
2571
- log3.log(`[TOMB-TRACE] calling unlink(${tombstone.path}) on ${replicaId}`);
2572
- await replica.instance.unlink(tombstone.path);
2573
- log3.log(`[TOMB-TRACE] tombstone ${tombstone.path}: deleted on ${replicaId}`);
2574
- processed++;
2575
- } catch (err) {
2576
- log3.log(`[TOMB-TRACE] unlink(${tombstone.path}) on ${replicaId} FAILED: ${err}`);
2608
+ let gone;
2609
+ if (forceDelete) {
2610
+ if (liveSidecarCandidate && await this.pathExistsOnBackend(replica.instance, sidecarOwner)) {
2611
+ gone = true;
2577
2612
  alreadyDeleted++;
2578
- }
2579
- } else {
2580
- log3.log(`[TOMB-TRACE] replica ${replicaId}: already gone, skipping unlink`);
2581
- alreadyDeleted++;
2582
- }
2583
- if (tVersionPath) {
2584
- const vExisted = await this.safeExists(replica.instance, tVersionPath);
2585
- log3.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tVersionPath}) \u2192 ${vExisted}`);
2586
- if (vExisted) {
2613
+ } else {
2587
2614
  try {
2588
- log3.log(`[TOMB-TRACE] calling unlink(${tVersionPath}) on ${replicaId}`);
2589
- await replica.instance.unlink(tVersionPath);
2615
+ await replica.instance.unlink(tombstone.path);
2616
+ gone = true;
2590
2617
  } catch (err) {
2591
- log3.log(`[TOMB-TRACE] unlink(${tVersionPath}) on ${replicaId} FAILED: ${err}`);
2618
+ gone = isNotFoundError(err);
2592
2619
  }
2620
+ if (gone) processed++;
2593
2621
  }
2622
+ } else {
2623
+ const existed = await this.pathExistsOnBackend(replica.instance, tombstone.path);
2624
+ gone = await this.purgePathOnBackend(replica.instance, tombstone.path);
2625
+ if (gone) {
2626
+ if (existed) processed++;
2627
+ else alreadyDeleted++;
2628
+ }
2629
+ if (tVersionPath) await this.purgePathOnBackend(replica.instance, tVersionPath);
2630
+ }
2631
+ if (gone) {
2632
+ let confirmed = this.tombstoneConfirmations.get(tombstone.path);
2633
+ if (!confirmed) {
2634
+ confirmed = /* @__PURE__ */ new Set();
2635
+ this.tombstoneConfirmations.set(tombstone.path, confirmed);
2636
+ }
2637
+ confirmed.add(replicaId);
2638
+ } else {
2639
+ unresolved++;
2640
+ log3.warn(
2641
+ `[ConfigRepo] tombstone kept: ${tombstone.path} still present on replica ${replicaId}`
2642
+ );
2594
2643
  }
2595
2644
  }
2596
2645
  }
2597
- if (processed > 0 || alreadyDeleted > 0) {
2598
- log3.log(`[TOMB-TRACE] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone`);
2646
+ if (processed > 0 || alreadyDeleted > 0 || unresolved > 0) {
2647
+ log3.log(
2648
+ `[ConfigRepo] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone, ${unresolved} unresolved`
2649
+ );
2650
+ }
2651
+ }
2652
+ /**
2653
+ * 删除墓碑目标在某个后端上的全部残留。
2654
+ *
2655
+ * 目录不能直接 unlink(会抛 EISDIR)。旧实现把这个异常当成"已被并发删除"
2656
+ * 而继续推进确认,墓碑随后被 GC;但副本上的占位目录仍然存在,下一次同步
2657
+ * 就把它当作远端内容拉回本地,形成空壳复活。
2658
+ *
2659
+ * 这里按树清理:
2660
+ * 1. 强制删掉 `.keep` / `.keep.mtime` 占位(部分后端把 `.keep` 隐藏在索引里,
2661
+ * readdir 看不到,只能按路径直接删);
2662
+ * 2. 递归清理可见子项;
2663
+ * 3. rmdir(后端不支持目录时退回 unlink)。
2664
+ *
2665
+ * @returns 是否确认该路径已不存在;清理失败返回 false,墓碑必须保留。
2666
+ */
2667
+ async purgePathOnBackend(fs, targetPath) {
2668
+ let isDir2 = false;
2669
+ try {
2670
+ const stat = await fs.stat(targetPath);
2671
+ isDir2 = typeof stat?.isDirectory === "function" ? stat.isDirectory() : !!(stat && ((stat.mode ?? 0) & 61440) === 16384);
2672
+ } catch {
2673
+ if (!await this.pathExistsOnBackend(fs, targetPath)) return true;
2674
+ }
2675
+ if (!isDir2) {
2676
+ try {
2677
+ await fs.unlink(targetPath);
2678
+ } catch {
2679
+ }
2680
+ return !await this.pathExistsOnBackend(fs, targetPath);
2681
+ }
2682
+ for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
2683
+ try {
2684
+ await fs.unlink(placeholder);
2685
+ } catch {
2686
+ }
2687
+ }
2688
+ let children = [];
2689
+ try {
2690
+ children = await fs.readdir(targetPath);
2691
+ } catch {
2692
+ }
2693
+ for (const child of children) {
2694
+ await this.purgePathOnBackend(fs, `${targetPath}/${child}`);
2695
+ }
2696
+ try {
2697
+ await fs.rmdir(targetPath);
2698
+ } catch {
2699
+ try {
2700
+ await fs.unlink(targetPath);
2701
+ } catch {
2702
+ }
2703
+ }
2704
+ if (await this.pathExistsOnBackend(fs, targetPath)) {
2705
+ for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
2706
+ try {
2707
+ await fs.unlink(placeholder);
2708
+ } catch {
2709
+ }
2710
+ }
2711
+ try {
2712
+ await fs.rmdir(targetPath);
2713
+ } catch {
2714
+ }
2715
+ return !await this.pathExistsOnBackend(fs, targetPath);
2716
+ }
2717
+ return true;
2718
+ }
2719
+ /** 后端无关的存在性判断:优先 exists(),否则退化为 stat()。 */
2720
+ async pathExistsOnBackend(fs, path) {
2721
+ if (typeof fs?.exists === "function") {
2722
+ try {
2723
+ return !!await fs.exists(path);
2724
+ } catch {
2725
+ return false;
2726
+ }
2727
+ }
2728
+ try {
2729
+ await fs.stat(path);
2730
+ return true;
2731
+ } catch {
2732
+ return false;
2599
2733
  }
2600
2734
  }
2601
2735
  /**
@@ -2751,7 +2885,13 @@ var ConfigRepo = class {
2751
2885
  });
2752
2886
  }
2753
2887
  /**
2754
- * After sync: mark each tombstone as confirmed by all replica backends.
2888
+ * After sync: mark each tombstone as confirmed by replicas where the target
2889
+ * path was actually verified absent.
2890
+ *
2891
+ * 旧实现把所有副本无条件写进 confirmedBy,只要有一轮同步跑过就认为
2892
+ * "所有副本都删干净了"。但副本可能因为网络/后端限制删除失败,或只剩
2893
+ * `.keep` / `.keep.mtime` 占位目录;墓碑一旦被 GC,下一轮同步就把残留
2894
+ * 当作远端内容拉回本地。现在只确认 processTombstones 本轮真正清干净的副本。
2755
2895
  */
2756
2896
  async updateTombstoneConfirmations() {
2757
2897
  const tombstones = await this.readTombstones();
@@ -2759,11 +2899,12 @@ var ConfigRepo = class {
2759
2899
  let modified = 0;
2760
2900
  for (const tombstone of tombstones) {
2761
2901
  let changed = false;
2902
+ const confirmedReplicas = this.tombstoneConfirmations.get(tombstone.path);
2762
2903
  for (const replicaId of this.replicaBackends.keys()) {
2763
- if (!tombstone.confirmedBy.includes(replicaId)) {
2764
- tombstone.confirmedBy.push(replicaId);
2765
- changed = true;
2766
- }
2904
+ if (tombstone.confirmedBy.includes(replicaId)) continue;
2905
+ if (!confirmedReplicas?.has(replicaId)) continue;
2906
+ tombstone.confirmedBy.push(replicaId);
2907
+ changed = true;
2767
2908
  }
2768
2909
  if (changed) {
2769
2910
  try {
@@ -2782,6 +2923,29 @@ var ConfigRepo = class {
2782
2923
  log3.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
2783
2924
  if (modified > 0) this.invalidateTombstoneCache();
2784
2925
  }
2926
+ /**
2927
+ * 墓碑路径是否已在所有副本上确认不存在。
2928
+ *
2929
+ * `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),
2930
+ * 因此只能相信本轮 `processTombstones` 的 unlink 结果;其余路径在 GC 前
2931
+ * 现场复核一次,避免"确认之后副本又把残留带了回来"。
2932
+ *
2933
+ * 任一位置仍存在就返回 false —— 墓碑必须保留,直到真正删干净。
2934
+ */
2935
+ async allReplicasConfirmAbsent(path) {
2936
+ const confirmed = this.tombstoneConfirmations.get(path);
2937
+ const hiddenPlaceholder = isMtimeSidecar(path) || path === "/.keep" || path.endsWith("/.keep");
2938
+ if (hiddenPlaceholder) {
2939
+ for (const replicaId of this.replicaBackends.keys()) {
2940
+ if (!confirmed?.has(replicaId)) return false;
2941
+ }
2942
+ return true;
2943
+ }
2944
+ for (const [, replica] of this.replicaBackends) {
2945
+ if (await this.pathExistsOnBackend(replica.instance, path)) return false;
2946
+ }
2947
+ return true;
2948
+ }
2785
2949
  /**
2786
2950
  * GC: remove tombstones where all backends in backends.json have confirmed.
2787
2951
  *
@@ -2795,7 +2959,7 @@ var ConfigRepo = class {
2795
2959
  if (tombstones.length === 0) return;
2796
2960
  const allBackendIds = [...this.replicaBackends.keys()];
2797
2961
  for (const tombstone of tombstones) {
2798
- const allConfirmed = allBackendIds.every((id) => tombstone.confirmedBy.includes(id));
2962
+ const allConfirmed = await this.allReplicasConfirmAbsent(tombstone.path);
2799
2963
  if (allConfirmed) {
2800
2964
  for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
2801
2965
  const tombstonePath = tombstonePathFor(tombstone.path, dir);
@@ -3025,6 +3189,9 @@ var ConfigRepo = class {
3025
3189
  direction: import_zen_fs_sync.SyncDirection.BiDirectional,
3026
3190
  conflictStrategy: "source-wins",
3027
3191
  pollIntervalMs,
3192
+ // 墓碑未清理前排除被删路径:副本残留(含 `.keep` 占位)不会被当成
3193
+ // "远端新增"再拉回本地。
3194
+ filter: this.syncFilter,
3028
3195
  preSyncHook: async () => {
3029
3196
  try {
3030
3197
  this.invalidateTombstoneCache();
@@ -3515,6 +3682,8 @@ var ConfigRepo = class {
3515
3682
  {
3516
3683
  direction: import_zen_fs_sync.SyncDirection.BiDirectional,
3517
3684
  conflictStrategy: "source-wins",
3685
+ // 墓碑未清理前排除被删路径,避免副本残留复活到本地。
3686
+ filter: this.syncFilter,
3518
3687
  preSyncHook: async () => {
3519
3688
  try {
3520
3689
  this.invalidateTombstoneCache();
@@ -4791,6 +4960,13 @@ async function createConfigRepo(appId, options = {}) {
4791
4960
  });
4792
4961
  return repo;
4793
4962
  }
4963
+ function sidecarOwnerPath(path) {
4964
+ let owner = null;
4965
+ if (path.endsWith(".mtime")) owner = path.slice(0, -".mtime".length);
4966
+ else if (path.endsWith(".version")) owner = path.slice(0, -".version".length);
4967
+ if (owner && owner.endsWith(".version")) owner = owner.slice(0, -".version".length);
4968
+ return owner === "" ? null : owner;
4969
+ }
4794
4970
 
4795
4971
  // src/connect.ts
4796
4972
  init_backend_registry();
package/dist/index.mjs CHANGED
@@ -1575,6 +1575,12 @@ async function removeDirectoryTree(fs, dir) {
1575
1575
  } catch {
1576
1576
  }
1577
1577
  }
1578
+ function isNotFoundError(err) {
1579
+ const code = err?.code;
1580
+ if (code === "ENOENT" || code === "ENOTDIR") return true;
1581
+ const message = String(err?.message ?? err);
1582
+ return /ENOENT|not found|does not exist|\b404\b/i.test(message);
1583
+ }
1578
1584
  function normalizeGroupName(value) {
1579
1585
  if (typeof value !== "string") {
1580
1586
  throw new Error("Group name must be a string");
@@ -1680,6 +1686,22 @@ var ConfigRepo = class {
1680
1686
  pollIntervalMs;
1681
1687
  /** Tombstone cache — avoids redundant reads within a single flush() cycle. */
1682
1688
  tombstoneCache = null;
1689
+ /**
1690
+ * 墓碑存在期间被排除在同步之外的路径。
1691
+ *
1692
+ * 远端副本可能仍残留被删路径(哪怕只剩 `.keep` / `.keep.mtime` 占位)。
1693
+ * 若同步照常进行,这类残留会被当成"远端新增"再拉回本地,造成空壳复活。
1694
+ * 这些路径改由 processTombstones 主动删除,直到所有副本确认不存在、
1695
+ * 墓碑被 GC 之后才恢复同步。
1696
+ */
1697
+ tombstoneExcludePrefixes = [];
1698
+ syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
1699
+ /**
1700
+ * 本轮 processTombstones 中,各副本对墓碑路径"已确认不存在"的结果。
1701
+ * 目录类路径用 exists() 复核;`.mtime` 侧车对部分后端不可见,只能用
1702
+ * unlink() 是否成功来判定。
1703
+ */
1704
+ tombstoneConfirmations = /* @__PURE__ */ new Map();
1683
1705
  /** Per-backend sync state (successful pairs + connect failures). */
1684
1706
  backendStates = /* @__PURE__ */ new Map();
1685
1707
  /** Last known backend descriptors, for the synchronous unified handle API. */
@@ -1959,8 +1981,29 @@ var ConfigRepo = class {
1959
1981
  return this.tombstoneCache;
1960
1982
  }
1961
1983
  this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log3.warn(message));
1984
+ this.refreshSyncExclusions(this.tombstoneCache);
1962
1985
  return this.tombstoneCache;
1963
1986
  }
1987
+ /**
1988
+ * 把当前墓碑路径同步到同步排除表。
1989
+ *
1990
+ * 排除表与各同步对共享同一个数组实例(zen-fs-sync 在每次检测时实时读取
1991
+ * `filter.excludePrefixes`),所以这里原地更新即可生效。
1992
+ */
1993
+ refreshSyncExclusions(tombstones) {
1994
+ this.tombstoneExcludePrefixes.length = 0;
1995
+ const add = (target) => {
1996
+ this.tombstoneExcludePrefixes.push(target, `${target}/`);
1997
+ };
1998
+ for (const tombstone of tombstones) {
1999
+ if (!tombstone.path) continue;
2000
+ add(tombstone.path);
2001
+ if (tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep") || tombstone.path.endsWith("/.keep.mtime")) {
2002
+ const dir = tombstone.path.slice(0, tombstone.path.lastIndexOf("/")) || "/";
2003
+ if (dir !== "/") add(dir);
2004
+ }
2005
+ }
2006
+ }
1964
2007
  /** Invalidate the tombstone cache — call after tombstones are modified. */
1965
2008
  invalidateTombstoneCache() {
1966
2009
  this.tombstoneCache = null;
@@ -1977,70 +2020,161 @@ var ConfigRepo = class {
1977
2020
  */
1978
2021
  async processTombstones() {
1979
2022
  const tombstones = await this.readTombstones();
2023
+ this.tombstoneConfirmations.clear();
1980
2024
  if (tombstones.length === 0) return;
1981
2025
  let processed = 0;
1982
2026
  let alreadyDeleted = 0;
2027
+ let unresolved = 0;
1983
2028
  for (const tombstone of tombstones) {
1984
- const forceDelete = isMtimeSidecar(tombstone.path);
2029
+ const isKeepPlaceholder = tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep");
2030
+ const forceDelete = isMtimeSidecar(tombstone.path) || isKeepPlaceholder;
1985
2031
  const tVersionPath = forceDelete ? null : versionPathFor(tombstone.path);
1986
- log3.log(`[TOMB-TRACE] processing tombstone: path=${tombstone.path} versionPath=${tVersionPath ?? "null"} forceDelete=${forceDelete}`);
1987
- const existedOnPrimary = forceDelete || await this.safeExists(this.cachedFS, tombstone.path);
1988
- log3.log(`[TOMB-TRACE] primary safeExists(${tombstone.path}) \u2192 ${existedOnPrimary}`);
1989
- if (existedOnPrimary) {
1990
- log3.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on primary \u2192 EXISTS`);
1991
- }
1992
- if (existedOnPrimary) {
1993
- try {
1994
- await this.cachedFS.unlink(tombstone.path);
1995
- processed++;
1996
- } catch {
1997
- }
1998
- }
1999
- if (tVersionPath) {
2000
- const vExistedOnPrimary = await this.safeExists(this.cachedFS, tVersionPath);
2001
- log3.log(`[TOMB-TRACE] primary safeExists(${tVersionPath}) \u2192 ${vExistedOnPrimary}`);
2002
- if (vExistedOnPrimary) {
2032
+ const sidecarOwner = sidecarOwnerPath(tombstone.path);
2033
+ const isKeepSidecar = sidecarOwner === "/.keep" || (sidecarOwner?.endsWith("/.keep") ?? false);
2034
+ const liveSidecarCandidate = sidecarOwner !== null && !isKeepSidecar;
2035
+ if (forceDelete) {
2036
+ if (!(liveSidecarCandidate && await this.pathExistsOnBackend(this.cachedFS, sidecarOwner))) {
2003
2037
  try {
2004
- await this.cachedFS.unlink(tVersionPath);
2038
+ await this.cachedFS.unlink(tombstone.path);
2039
+ processed++;
2005
2040
  } catch {
2006
2041
  }
2007
2042
  }
2043
+ } else {
2044
+ const existedOnPrimary = await this.pathExistsOnBackend(this.cachedFS, tombstone.path);
2045
+ const gone = await this.purgePathOnBackend(this.cachedFS, tombstone.path);
2046
+ if (gone) {
2047
+ if (existedOnPrimary) processed++;
2048
+ else alreadyDeleted++;
2049
+ } else unresolved++;
2050
+ if (tVersionPath) await this.purgePathOnBackend(this.cachedFS, tVersionPath);
2008
2051
  }
2009
2052
  for (const [replicaId, replica] of this.replicaBackends) {
2010
- log3.log(`[TOMB-TRACE] checking replica: ${replicaId} for ${tombstone.path}`);
2011
- const existed = forceDelete || await this.safeExists(replica.instance, tombstone.path);
2012
- log3.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tombstone.path}) \u2192 ${existed}`);
2013
- if (existed) {
2014
- log3.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on ${replicaId} \u2192 EXISTS`);
2015
- try {
2016
- log3.log(`[TOMB-TRACE] calling unlink(${tombstone.path}) on ${replicaId}`);
2017
- await replica.instance.unlink(tombstone.path);
2018
- log3.log(`[TOMB-TRACE] tombstone ${tombstone.path}: deleted on ${replicaId}`);
2019
- processed++;
2020
- } catch (err) {
2021
- log3.log(`[TOMB-TRACE] unlink(${tombstone.path}) on ${replicaId} FAILED: ${err}`);
2053
+ let gone;
2054
+ if (forceDelete) {
2055
+ if (liveSidecarCandidate && await this.pathExistsOnBackend(replica.instance, sidecarOwner)) {
2056
+ gone = true;
2022
2057
  alreadyDeleted++;
2023
- }
2024
- } else {
2025
- log3.log(`[TOMB-TRACE] replica ${replicaId}: already gone, skipping unlink`);
2026
- alreadyDeleted++;
2027
- }
2028
- if (tVersionPath) {
2029
- const vExisted = await this.safeExists(replica.instance, tVersionPath);
2030
- log3.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tVersionPath}) \u2192 ${vExisted}`);
2031
- if (vExisted) {
2058
+ } else {
2032
2059
  try {
2033
- log3.log(`[TOMB-TRACE] calling unlink(${tVersionPath}) on ${replicaId}`);
2034
- await replica.instance.unlink(tVersionPath);
2060
+ await replica.instance.unlink(tombstone.path);
2061
+ gone = true;
2035
2062
  } catch (err) {
2036
- log3.log(`[TOMB-TRACE] unlink(${tVersionPath}) on ${replicaId} FAILED: ${err}`);
2063
+ gone = isNotFoundError(err);
2037
2064
  }
2065
+ if (gone) processed++;
2038
2066
  }
2067
+ } else {
2068
+ const existed = await this.pathExistsOnBackend(replica.instance, tombstone.path);
2069
+ gone = await this.purgePathOnBackend(replica.instance, tombstone.path);
2070
+ if (gone) {
2071
+ if (existed) processed++;
2072
+ else alreadyDeleted++;
2073
+ }
2074
+ if (tVersionPath) await this.purgePathOnBackend(replica.instance, tVersionPath);
2075
+ }
2076
+ if (gone) {
2077
+ let confirmed = this.tombstoneConfirmations.get(tombstone.path);
2078
+ if (!confirmed) {
2079
+ confirmed = /* @__PURE__ */ new Set();
2080
+ this.tombstoneConfirmations.set(tombstone.path, confirmed);
2081
+ }
2082
+ confirmed.add(replicaId);
2083
+ } else {
2084
+ unresolved++;
2085
+ log3.warn(
2086
+ `[ConfigRepo] tombstone kept: ${tombstone.path} still present on replica ${replicaId}`
2087
+ );
2039
2088
  }
2040
2089
  }
2041
2090
  }
2042
- if (processed > 0 || alreadyDeleted > 0) {
2043
- log3.log(`[TOMB-TRACE] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone`);
2091
+ if (processed > 0 || alreadyDeleted > 0 || unresolved > 0) {
2092
+ log3.log(
2093
+ `[ConfigRepo] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone, ${unresolved} unresolved`
2094
+ );
2095
+ }
2096
+ }
2097
+ /**
2098
+ * 删除墓碑目标在某个后端上的全部残留。
2099
+ *
2100
+ * 目录不能直接 unlink(会抛 EISDIR)。旧实现把这个异常当成"已被并发删除"
2101
+ * 而继续推进确认,墓碑随后被 GC;但副本上的占位目录仍然存在,下一次同步
2102
+ * 就把它当作远端内容拉回本地,形成空壳复活。
2103
+ *
2104
+ * 这里按树清理:
2105
+ * 1. 强制删掉 `.keep` / `.keep.mtime` 占位(部分后端把 `.keep` 隐藏在索引里,
2106
+ * readdir 看不到,只能按路径直接删);
2107
+ * 2. 递归清理可见子项;
2108
+ * 3. rmdir(后端不支持目录时退回 unlink)。
2109
+ *
2110
+ * @returns 是否确认该路径已不存在;清理失败返回 false,墓碑必须保留。
2111
+ */
2112
+ async purgePathOnBackend(fs, targetPath) {
2113
+ let isDir2 = false;
2114
+ try {
2115
+ const stat = await fs.stat(targetPath);
2116
+ isDir2 = typeof stat?.isDirectory === "function" ? stat.isDirectory() : !!(stat && ((stat.mode ?? 0) & 61440) === 16384);
2117
+ } catch {
2118
+ if (!await this.pathExistsOnBackend(fs, targetPath)) return true;
2119
+ }
2120
+ if (!isDir2) {
2121
+ try {
2122
+ await fs.unlink(targetPath);
2123
+ } catch {
2124
+ }
2125
+ return !await this.pathExistsOnBackend(fs, targetPath);
2126
+ }
2127
+ for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
2128
+ try {
2129
+ await fs.unlink(placeholder);
2130
+ } catch {
2131
+ }
2132
+ }
2133
+ let children = [];
2134
+ try {
2135
+ children = await fs.readdir(targetPath);
2136
+ } catch {
2137
+ }
2138
+ for (const child of children) {
2139
+ await this.purgePathOnBackend(fs, `${targetPath}/${child}`);
2140
+ }
2141
+ try {
2142
+ await fs.rmdir(targetPath);
2143
+ } catch {
2144
+ try {
2145
+ await fs.unlink(targetPath);
2146
+ } catch {
2147
+ }
2148
+ }
2149
+ if (await this.pathExistsOnBackend(fs, targetPath)) {
2150
+ for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
2151
+ try {
2152
+ await fs.unlink(placeholder);
2153
+ } catch {
2154
+ }
2155
+ }
2156
+ try {
2157
+ await fs.rmdir(targetPath);
2158
+ } catch {
2159
+ }
2160
+ return !await this.pathExistsOnBackend(fs, targetPath);
2161
+ }
2162
+ return true;
2163
+ }
2164
+ /** 后端无关的存在性判断:优先 exists(),否则退化为 stat()。 */
2165
+ async pathExistsOnBackend(fs, path) {
2166
+ if (typeof fs?.exists === "function") {
2167
+ try {
2168
+ return !!await fs.exists(path);
2169
+ } catch {
2170
+ return false;
2171
+ }
2172
+ }
2173
+ try {
2174
+ await fs.stat(path);
2175
+ return true;
2176
+ } catch {
2177
+ return false;
2044
2178
  }
2045
2179
  }
2046
2180
  /**
@@ -2196,7 +2330,13 @@ var ConfigRepo = class {
2196
2330
  });
2197
2331
  }
2198
2332
  /**
2199
- * After sync: mark each tombstone as confirmed by all replica backends.
2333
+ * After sync: mark each tombstone as confirmed by replicas where the target
2334
+ * path was actually verified absent.
2335
+ *
2336
+ * 旧实现把所有副本无条件写进 confirmedBy,只要有一轮同步跑过就认为
2337
+ * "所有副本都删干净了"。但副本可能因为网络/后端限制删除失败,或只剩
2338
+ * `.keep` / `.keep.mtime` 占位目录;墓碑一旦被 GC,下一轮同步就把残留
2339
+ * 当作远端内容拉回本地。现在只确认 processTombstones 本轮真正清干净的副本。
2200
2340
  */
2201
2341
  async updateTombstoneConfirmations() {
2202
2342
  const tombstones = await this.readTombstones();
@@ -2204,11 +2344,12 @@ var ConfigRepo = class {
2204
2344
  let modified = 0;
2205
2345
  for (const tombstone of tombstones) {
2206
2346
  let changed = false;
2347
+ const confirmedReplicas = this.tombstoneConfirmations.get(tombstone.path);
2207
2348
  for (const replicaId of this.replicaBackends.keys()) {
2208
- if (!tombstone.confirmedBy.includes(replicaId)) {
2209
- tombstone.confirmedBy.push(replicaId);
2210
- changed = true;
2211
- }
2349
+ if (tombstone.confirmedBy.includes(replicaId)) continue;
2350
+ if (!confirmedReplicas?.has(replicaId)) continue;
2351
+ tombstone.confirmedBy.push(replicaId);
2352
+ changed = true;
2212
2353
  }
2213
2354
  if (changed) {
2214
2355
  try {
@@ -2227,6 +2368,29 @@ var ConfigRepo = class {
2227
2368
  log3.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
2228
2369
  if (modified > 0) this.invalidateTombstoneCache();
2229
2370
  }
2371
+ /**
2372
+ * 墓碑路径是否已在所有副本上确认不存在。
2373
+ *
2374
+ * `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),
2375
+ * 因此只能相信本轮 `processTombstones` 的 unlink 结果;其余路径在 GC 前
2376
+ * 现场复核一次,避免"确认之后副本又把残留带了回来"。
2377
+ *
2378
+ * 任一位置仍存在就返回 false —— 墓碑必须保留,直到真正删干净。
2379
+ */
2380
+ async allReplicasConfirmAbsent(path) {
2381
+ const confirmed = this.tombstoneConfirmations.get(path);
2382
+ const hiddenPlaceholder = isMtimeSidecar(path) || path === "/.keep" || path.endsWith("/.keep");
2383
+ if (hiddenPlaceholder) {
2384
+ for (const replicaId of this.replicaBackends.keys()) {
2385
+ if (!confirmed?.has(replicaId)) return false;
2386
+ }
2387
+ return true;
2388
+ }
2389
+ for (const [, replica] of this.replicaBackends) {
2390
+ if (await this.pathExistsOnBackend(replica.instance, path)) return false;
2391
+ }
2392
+ return true;
2393
+ }
2230
2394
  /**
2231
2395
  * GC: remove tombstones where all backends in backends.json have confirmed.
2232
2396
  *
@@ -2240,7 +2404,7 @@ var ConfigRepo = class {
2240
2404
  if (tombstones.length === 0) return;
2241
2405
  const allBackendIds = [...this.replicaBackends.keys()];
2242
2406
  for (const tombstone of tombstones) {
2243
- const allConfirmed = allBackendIds.every((id) => tombstone.confirmedBy.includes(id));
2407
+ const allConfirmed = await this.allReplicasConfirmAbsent(tombstone.path);
2244
2408
  if (allConfirmed) {
2245
2409
  for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
2246
2410
  const tombstonePath = tombstonePathFor(tombstone.path, dir);
@@ -2470,6 +2634,9 @@ var ConfigRepo = class {
2470
2634
  direction: SyncDirection.BiDirectional,
2471
2635
  conflictStrategy: "source-wins",
2472
2636
  pollIntervalMs,
2637
+ // 墓碑未清理前排除被删路径:副本残留(含 `.keep` 占位)不会被当成
2638
+ // "远端新增"再拉回本地。
2639
+ filter: this.syncFilter,
2473
2640
  preSyncHook: async () => {
2474
2641
  try {
2475
2642
  this.invalidateTombstoneCache();
@@ -2960,6 +3127,8 @@ var ConfigRepo = class {
2960
3127
  {
2961
3128
  direction: SyncDirection.BiDirectional,
2962
3129
  conflictStrategy: "source-wins",
3130
+ // 墓碑未清理前排除被删路径,避免副本残留复活到本地。
3131
+ filter: this.syncFilter,
2963
3132
  preSyncHook: async () => {
2964
3133
  try {
2965
3134
  this.invalidateTombstoneCache();
@@ -4236,6 +4405,13 @@ async function createConfigRepo(appId, options = {}) {
4236
4405
  });
4237
4406
  return repo;
4238
4407
  }
4408
+ function sidecarOwnerPath(path) {
4409
+ let owner = null;
4410
+ if (path.endsWith(".mtime")) owner = path.slice(0, -".mtime".length);
4411
+ else if (path.endsWith(".version")) owner = path.slice(0, -".version".length);
4412
+ if (owner && owner.endsWith(".version")) owner = owner.slice(0, -".version".length);
4413
+ return owner === "" ? null : owner;
4414
+ }
4239
4415
 
4240
4416
  // src/connect.ts
4241
4417
  var log4 = createLogger("connect");
@@ -28144,6 +28144,12 @@ var ZenFSConfig = (() => {
28144
28144
  } catch {
28145
28145
  }
28146
28146
  }
28147
+ function isNotFoundError(err2) {
28148
+ const code = err2?.code;
28149
+ if (code === "ENOENT" || code === "ENOTDIR") return true;
28150
+ const message = String(err2?.message ?? err2);
28151
+ return /ENOENT|not found|does not exist|\b404\b/i.test(message);
28152
+ }
28147
28153
  function normalizeGroupName(value) {
28148
28154
  if (typeof value !== "string") {
28149
28155
  throw new Error("Group name must be a string");
@@ -28250,6 +28256,22 @@ var ZenFSConfig = (() => {
28250
28256
  __publicField(this, "pollIntervalMs");
28251
28257
  /** Tombstone cache — avoids redundant reads within a single flush() cycle. */
28252
28258
  __publicField(this, "tombstoneCache", null);
28259
+ /**
28260
+ * 墓碑存在期间被排除在同步之外的路径。
28261
+ *
28262
+ * 远端副本可能仍残留被删路径(哪怕只剩 `.keep` / `.keep.mtime` 占位)。
28263
+ * 若同步照常进行,这类残留会被当成"远端新增"再拉回本地,造成空壳复活。
28264
+ * 这些路径改由 processTombstones 主动删除,直到所有副本确认不存在、
28265
+ * 墓碑被 GC 之后才恢复同步。
28266
+ */
28267
+ __publicField(this, "tombstoneExcludePrefixes", []);
28268
+ __publicField(this, "syncFilter", { excludePrefixes: this.tombstoneExcludePrefixes });
28269
+ /**
28270
+ * 本轮 processTombstones 中,各副本对墓碑路径"已确认不存在"的结果。
28271
+ * 目录类路径用 exists() 复核;`.mtime` 侧车对部分后端不可见,只能用
28272
+ * unlink() 是否成功来判定。
28273
+ */
28274
+ __publicField(this, "tombstoneConfirmations", /* @__PURE__ */ new Map());
28253
28275
  /** Per-backend sync state (successful pairs + connect failures). */
28254
28276
  __publicField(this, "backendStates", /* @__PURE__ */ new Map());
28255
28277
  /** Last known backend descriptors, for the synchronous unified handle API. */
@@ -28528,8 +28550,29 @@ var ZenFSConfig = (() => {
28528
28550
  return this.tombstoneCache;
28529
28551
  }
28530
28552
  this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log7.warn(message));
28553
+ this.refreshSyncExclusions(this.tombstoneCache);
28531
28554
  return this.tombstoneCache;
28532
28555
  }
28556
+ /**
28557
+ * 把当前墓碑路径同步到同步排除表。
28558
+ *
28559
+ * 排除表与各同步对共享同一个数组实例(zen-fs-sync 在每次检测时实时读取
28560
+ * `filter.excludePrefixes`),所以这里原地更新即可生效。
28561
+ */
28562
+ refreshSyncExclusions(tombstones) {
28563
+ this.tombstoneExcludePrefixes.length = 0;
28564
+ const add = (target) => {
28565
+ this.tombstoneExcludePrefixes.push(target, `${target}/`);
28566
+ };
28567
+ for (const tombstone of tombstones) {
28568
+ if (!tombstone.path) continue;
28569
+ add(tombstone.path);
28570
+ if (tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep") || tombstone.path.endsWith("/.keep.mtime")) {
28571
+ const dir = tombstone.path.slice(0, tombstone.path.lastIndexOf("/")) || "/";
28572
+ if (dir !== "/") add(dir);
28573
+ }
28574
+ }
28575
+ }
28533
28576
  /** Invalidate the tombstone cache — call after tombstones are modified. */
28534
28577
  invalidateTombstoneCache() {
28535
28578
  this.tombstoneCache = null;
@@ -28546,70 +28589,161 @@ var ZenFSConfig = (() => {
28546
28589
  */
28547
28590
  async processTombstones() {
28548
28591
  const tombstones = await this.readTombstones();
28592
+ this.tombstoneConfirmations.clear();
28549
28593
  if (tombstones.length === 0) return;
28550
28594
  let processed = 0;
28551
28595
  let alreadyDeleted = 0;
28596
+ let unresolved = 0;
28552
28597
  for (const tombstone of tombstones) {
28553
- const forceDelete = isMtimeSidecar(tombstone.path);
28598
+ const isKeepPlaceholder = tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep");
28599
+ const forceDelete = isMtimeSidecar(tombstone.path) || isKeepPlaceholder;
28554
28600
  const tVersionPath = forceDelete ? null : versionPathFor(tombstone.path);
28555
- log7.log(`[TOMB-TRACE] processing tombstone: path=${tombstone.path} versionPath=${tVersionPath ?? "null"} forceDelete=${forceDelete}`);
28556
- const existedOnPrimary = forceDelete || await this.safeExists(this.cachedFS, tombstone.path);
28557
- log7.log(`[TOMB-TRACE] primary safeExists(${tombstone.path}) \u2192 ${existedOnPrimary}`);
28558
- if (existedOnPrimary) {
28559
- log7.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on primary \u2192 EXISTS`);
28560
- }
28561
- if (existedOnPrimary) {
28562
- try {
28563
- await this.cachedFS.unlink(tombstone.path);
28564
- processed++;
28565
- } catch {
28566
- }
28567
- }
28568
- if (tVersionPath) {
28569
- const vExistedOnPrimary = await this.safeExists(this.cachedFS, tVersionPath);
28570
- log7.log(`[TOMB-TRACE] primary safeExists(${tVersionPath}) \u2192 ${vExistedOnPrimary}`);
28571
- if (vExistedOnPrimary) {
28601
+ const sidecarOwner = sidecarOwnerPath(tombstone.path);
28602
+ const isKeepSidecar = sidecarOwner === "/.keep" || (sidecarOwner?.endsWith("/.keep") ?? false);
28603
+ const liveSidecarCandidate = sidecarOwner !== null && !isKeepSidecar;
28604
+ if (forceDelete) {
28605
+ if (!(liveSidecarCandidate && await this.pathExistsOnBackend(this.cachedFS, sidecarOwner))) {
28572
28606
  try {
28573
- await this.cachedFS.unlink(tVersionPath);
28607
+ await this.cachedFS.unlink(tombstone.path);
28608
+ processed++;
28574
28609
  } catch {
28575
28610
  }
28576
28611
  }
28612
+ } else {
28613
+ const existedOnPrimary = await this.pathExistsOnBackend(this.cachedFS, tombstone.path);
28614
+ const gone = await this.purgePathOnBackend(this.cachedFS, tombstone.path);
28615
+ if (gone) {
28616
+ if (existedOnPrimary) processed++;
28617
+ else alreadyDeleted++;
28618
+ } else unresolved++;
28619
+ if (tVersionPath) await this.purgePathOnBackend(this.cachedFS, tVersionPath);
28577
28620
  }
28578
28621
  for (const [replicaId, replica] of this.replicaBackends) {
28579
- log7.log(`[TOMB-TRACE] checking replica: ${replicaId} for ${tombstone.path}`);
28580
- const existed = forceDelete || await this.safeExists(replica.instance, tombstone.path);
28581
- log7.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tombstone.path}) \u2192 ${existed}`);
28582
- if (existed) {
28583
- log7.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on ${replicaId} \u2192 EXISTS`);
28584
- try {
28585
- log7.log(`[TOMB-TRACE] calling unlink(${tombstone.path}) on ${replicaId}`);
28586
- await replica.instance.unlink(tombstone.path);
28587
- log7.log(`[TOMB-TRACE] tombstone ${tombstone.path}: deleted on ${replicaId}`);
28588
- processed++;
28589
- } catch (err2) {
28590
- log7.log(`[TOMB-TRACE] unlink(${tombstone.path}) on ${replicaId} FAILED: ${err2}`);
28622
+ let gone;
28623
+ if (forceDelete) {
28624
+ if (liveSidecarCandidate && await this.pathExistsOnBackend(replica.instance, sidecarOwner)) {
28625
+ gone = true;
28591
28626
  alreadyDeleted++;
28592
- }
28593
- } else {
28594
- log7.log(`[TOMB-TRACE] replica ${replicaId}: already gone, skipping unlink`);
28595
- alreadyDeleted++;
28596
- }
28597
- if (tVersionPath) {
28598
- const vExisted = await this.safeExists(replica.instance, tVersionPath);
28599
- log7.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tVersionPath}) \u2192 ${vExisted}`);
28600
- if (vExisted) {
28627
+ } else {
28601
28628
  try {
28602
- log7.log(`[TOMB-TRACE] calling unlink(${tVersionPath}) on ${replicaId}`);
28603
- await replica.instance.unlink(tVersionPath);
28629
+ await replica.instance.unlink(tombstone.path);
28630
+ gone = true;
28604
28631
  } catch (err2) {
28605
- log7.log(`[TOMB-TRACE] unlink(${tVersionPath}) on ${replicaId} FAILED: ${err2}`);
28632
+ gone = isNotFoundError(err2);
28606
28633
  }
28634
+ if (gone) processed++;
28635
+ }
28636
+ } else {
28637
+ const existed = await this.pathExistsOnBackend(replica.instance, tombstone.path);
28638
+ gone = await this.purgePathOnBackend(replica.instance, tombstone.path);
28639
+ if (gone) {
28640
+ if (existed) processed++;
28641
+ else alreadyDeleted++;
28607
28642
  }
28643
+ if (tVersionPath) await this.purgePathOnBackend(replica.instance, tVersionPath);
28644
+ }
28645
+ if (gone) {
28646
+ let confirmed = this.tombstoneConfirmations.get(tombstone.path);
28647
+ if (!confirmed) {
28648
+ confirmed = /* @__PURE__ */ new Set();
28649
+ this.tombstoneConfirmations.set(tombstone.path, confirmed);
28650
+ }
28651
+ confirmed.add(replicaId);
28652
+ } else {
28653
+ unresolved++;
28654
+ log7.warn(
28655
+ `[ConfigRepo] tombstone kept: ${tombstone.path} still present on replica ${replicaId}`
28656
+ );
28608
28657
  }
28609
28658
  }
28610
28659
  }
28611
- if (processed > 0 || alreadyDeleted > 0) {
28612
- log7.log(`[TOMB-TRACE] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone`);
28660
+ if (processed > 0 || alreadyDeleted > 0 || unresolved > 0) {
28661
+ log7.log(
28662
+ `[ConfigRepo] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone, ${unresolved} unresolved`
28663
+ );
28664
+ }
28665
+ }
28666
+ /**
28667
+ * 删除墓碑目标在某个后端上的全部残留。
28668
+ *
28669
+ * 目录不能直接 unlink(会抛 EISDIR)。旧实现把这个异常当成"已被并发删除"
28670
+ * 而继续推进确认,墓碑随后被 GC;但副本上的占位目录仍然存在,下一次同步
28671
+ * 就把它当作远端内容拉回本地,形成空壳复活。
28672
+ *
28673
+ * 这里按树清理:
28674
+ * 1. 强制删掉 `.keep` / `.keep.mtime` 占位(部分后端把 `.keep` 隐藏在索引里,
28675
+ * readdir 看不到,只能按路径直接删);
28676
+ * 2. 递归清理可见子项;
28677
+ * 3. rmdir(后端不支持目录时退回 unlink)。
28678
+ *
28679
+ * @returns 是否确认该路径已不存在;清理失败返回 false,墓碑必须保留。
28680
+ */
28681
+ async purgePathOnBackend(fs, targetPath) {
28682
+ let isDir2 = false;
28683
+ try {
28684
+ const stat5 = await fs.stat(targetPath);
28685
+ isDir2 = typeof stat5?.isDirectory === "function" ? stat5.isDirectory() : !!(stat5 && ((stat5.mode ?? 0) & 61440) === 16384);
28686
+ } catch {
28687
+ if (!await this.pathExistsOnBackend(fs, targetPath)) return true;
28688
+ }
28689
+ if (!isDir2) {
28690
+ try {
28691
+ await fs.unlink(targetPath);
28692
+ } catch {
28693
+ }
28694
+ return !await this.pathExistsOnBackend(fs, targetPath);
28695
+ }
28696
+ for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
28697
+ try {
28698
+ await fs.unlink(placeholder);
28699
+ } catch {
28700
+ }
28701
+ }
28702
+ let children = [];
28703
+ try {
28704
+ children = await fs.readdir(targetPath);
28705
+ } catch {
28706
+ }
28707
+ for (const child of children) {
28708
+ await this.purgePathOnBackend(fs, `${targetPath}/${child}`);
28709
+ }
28710
+ try {
28711
+ await fs.rmdir(targetPath);
28712
+ } catch {
28713
+ try {
28714
+ await fs.unlink(targetPath);
28715
+ } catch {
28716
+ }
28717
+ }
28718
+ if (await this.pathExistsOnBackend(fs, targetPath)) {
28719
+ for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
28720
+ try {
28721
+ await fs.unlink(placeholder);
28722
+ } catch {
28723
+ }
28724
+ }
28725
+ try {
28726
+ await fs.rmdir(targetPath);
28727
+ } catch {
28728
+ }
28729
+ return !await this.pathExistsOnBackend(fs, targetPath);
28730
+ }
28731
+ return true;
28732
+ }
28733
+ /** 后端无关的存在性判断:优先 exists(),否则退化为 stat()。 */
28734
+ async pathExistsOnBackend(fs, path) {
28735
+ if (typeof fs?.exists === "function") {
28736
+ try {
28737
+ return !!await fs.exists(path);
28738
+ } catch {
28739
+ return false;
28740
+ }
28741
+ }
28742
+ try {
28743
+ await fs.stat(path);
28744
+ return true;
28745
+ } catch {
28746
+ return false;
28613
28747
  }
28614
28748
  }
28615
28749
  /**
@@ -28765,7 +28899,13 @@ var ZenFSConfig = (() => {
28765
28899
  });
28766
28900
  }
28767
28901
  /**
28768
- * After sync: mark each tombstone as confirmed by all replica backends.
28902
+ * After sync: mark each tombstone as confirmed by replicas where the target
28903
+ * path was actually verified absent.
28904
+ *
28905
+ * 旧实现把所有副本无条件写进 confirmedBy,只要有一轮同步跑过就认为
28906
+ * "所有副本都删干净了"。但副本可能因为网络/后端限制删除失败,或只剩
28907
+ * `.keep` / `.keep.mtime` 占位目录;墓碑一旦被 GC,下一轮同步就把残留
28908
+ * 当作远端内容拉回本地。现在只确认 processTombstones 本轮真正清干净的副本。
28769
28909
  */
28770
28910
  async updateTombstoneConfirmations() {
28771
28911
  const tombstones = await this.readTombstones();
@@ -28773,11 +28913,12 @@ var ZenFSConfig = (() => {
28773
28913
  let modified = 0;
28774
28914
  for (const tombstone of tombstones) {
28775
28915
  let changed = false;
28916
+ const confirmedReplicas = this.tombstoneConfirmations.get(tombstone.path);
28776
28917
  for (const replicaId of this.replicaBackends.keys()) {
28777
- if (!tombstone.confirmedBy.includes(replicaId)) {
28778
- tombstone.confirmedBy.push(replicaId);
28779
- changed = true;
28780
- }
28918
+ if (tombstone.confirmedBy.includes(replicaId)) continue;
28919
+ if (!confirmedReplicas?.has(replicaId)) continue;
28920
+ tombstone.confirmedBy.push(replicaId);
28921
+ changed = true;
28781
28922
  }
28782
28923
  if (changed) {
28783
28924
  try {
@@ -28796,6 +28937,29 @@ var ZenFSConfig = (() => {
28796
28937
  log7.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
28797
28938
  if (modified > 0) this.invalidateTombstoneCache();
28798
28939
  }
28940
+ /**
28941
+ * 墓碑路径是否已在所有副本上确认不存在。
28942
+ *
28943
+ * `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),
28944
+ * 因此只能相信本轮 `processTombstones` 的 unlink 结果;其余路径在 GC 前
28945
+ * 现场复核一次,避免"确认之后副本又把残留带了回来"。
28946
+ *
28947
+ * 任一位置仍存在就返回 false —— 墓碑必须保留,直到真正删干净。
28948
+ */
28949
+ async allReplicasConfirmAbsent(path) {
28950
+ const confirmed = this.tombstoneConfirmations.get(path);
28951
+ const hiddenPlaceholder = isMtimeSidecar(path) || path === "/.keep" || path.endsWith("/.keep");
28952
+ if (hiddenPlaceholder) {
28953
+ for (const replicaId of this.replicaBackends.keys()) {
28954
+ if (!confirmed?.has(replicaId)) return false;
28955
+ }
28956
+ return true;
28957
+ }
28958
+ for (const [, replica] of this.replicaBackends) {
28959
+ if (await this.pathExistsOnBackend(replica.instance, path)) return false;
28960
+ }
28961
+ return true;
28962
+ }
28799
28963
  /**
28800
28964
  * GC: remove tombstones where all backends in backends.json have confirmed.
28801
28965
  *
@@ -28809,7 +28973,7 @@ var ZenFSConfig = (() => {
28809
28973
  if (tombstones.length === 0) return;
28810
28974
  const allBackendIds = [...this.replicaBackends.keys()];
28811
28975
  for (const tombstone of tombstones) {
28812
- const allConfirmed = allBackendIds.every((id) => tombstone.confirmedBy.includes(id));
28976
+ const allConfirmed = await this.allReplicasConfirmAbsent(tombstone.path);
28813
28977
  if (allConfirmed) {
28814
28978
  for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
28815
28979
  const tombstonePath = tombstonePathFor(tombstone.path, dir);
@@ -29039,6 +29203,9 @@ var ZenFSConfig = (() => {
29039
29203
  direction: SyncDirection.BiDirectional,
29040
29204
  conflictStrategy: "source-wins",
29041
29205
  pollIntervalMs,
29206
+ // 墓碑未清理前排除被删路径:副本残留(含 `.keep` 占位)不会被当成
29207
+ // "远端新增"再拉回本地。
29208
+ filter: this.syncFilter,
29042
29209
  preSyncHook: async () => {
29043
29210
  try {
29044
29211
  this.invalidateTombstoneCache();
@@ -29529,6 +29696,8 @@ var ZenFSConfig = (() => {
29529
29696
  {
29530
29697
  direction: SyncDirection.BiDirectional,
29531
29698
  conflictStrategy: "source-wins",
29699
+ // 墓碑未清理前排除被删路径,避免副本残留复活到本地。
29700
+ filter: this.syncFilter,
29532
29701
  preSyncHook: async () => {
29533
29702
  try {
29534
29703
  this.invalidateTombstoneCache();
@@ -30805,6 +30974,13 @@ var ZenFSConfig = (() => {
30805
30974
  });
30806
30975
  return repo;
30807
30976
  }
30977
+ function sidecarOwnerPath(path) {
30978
+ let owner = null;
30979
+ if (path.endsWith(".mtime")) owner = path.slice(0, -".mtime".length);
30980
+ else if (path.endsWith(".version")) owner = path.slice(0, -".version".length);
30981
+ if (owner && owner.endsWith(".version")) owner = owner.slice(0, -".version".length);
30982
+ return owner === "" ? null : owner;
30983
+ }
30808
30984
 
30809
30985
  // src/connect.ts
30810
30986
  init_backend_registry();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zen-fs-config",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
4
4
  "description": "Distributed config management library built on ZenFS, zen-fs-cache, and zen-fs-sync",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",