zen-fs-config 0.10.2 → 0.10.3

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
@@ -1014,8 +1014,13 @@ interface IConfigRepo {
1014
1014
  * replaceBackend: old pair is rebuilt against the new target).
1015
1015
  */
1016
1016
  replaceAppDataGroupBackend(groupId: string, backendId: string, type: string, options: Record<string, unknown>, description?: string): Promise<AppDataGroup>;
1017
- /** Remove a data-sync group (stops sync, removes descriptor). */
1018
- removeAppDataGroup(id: string): Promise<void>;
1017
+ /**
1018
+ * Remove a data-sync group (stops sync, removes descriptor).
1019
+ *
1020
+ * @param appId 目标登记所属 appId;默认本实例的 appId。传其它 appId 时只删
1021
+ * 配置仓里该 appId 的登记与引导副本(写墓碑),不会 dispose 别的实例里的组。
1022
+ */
1023
+ removeAppDataGroup(id: string, appId?: string): Promise<void>;
1019
1024
  /**
1020
1025
  * List config-sync backends that can be used as account sources
1021
1026
  * for data-sync backends. Returns backends that have `accountFields`
@@ -1353,6 +1358,12 @@ declare class ConfigRepo implements IConfigRepo {
1353
1358
  * unlink() 是否成功来判定。
1354
1359
  */
1355
1360
  private readonly tombstoneConfirmations;
1361
+ /**
1362
+ * 上次从副本预取墓碑的时间戳(毫秒)。
1363
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
1364
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
1365
+ */
1366
+ private lastTombstonePrefetchAt;
1356
1367
  /** Per-backend sync state (successful pairs + connect failures). */
1357
1368
  private backendStates;
1358
1369
  /**
@@ -1442,6 +1453,21 @@ declare class ConfigRepo implements IConfigRepo {
1442
1453
  private refreshSyncExclusions;
1443
1454
  /** Invalidate the tombstone cache — call after tombstones are modified. */
1444
1455
  private invalidateTombstoneCache;
1456
+ /**
1457
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
1458
+ *
1459
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
1460
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
1461
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
1462
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
1463
+ *
1464
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
1465
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
1466
+ * 一并清掉,同步再不会把它推上去。
1467
+ *
1468
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
1469
+ */
1470
+ private prefetchReplicaTombstones;
1445
1471
  /**
1446
1472
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
1447
1473
  *
@@ -1944,7 +1970,15 @@ declare class ConfigRepo implements IConfigRepo {
1944
1970
  * 真实意图,允许推送空副本,不参与自愈。
1945
1971
  */
1946
1972
  private healEmptyBootstrapDescriptors;
1947
- removeAppDataGroup(id: string): Promise<void>;
1973
+ /**
1974
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
1975
+ * 在配置仓的后端描述符)。
1976
+ *
1977
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
1978
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
1979
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
1980
+ */
1981
+ removeAppDataGroup(id: string, appId?: string): Promise<void>;
1948
1982
  listAccountBackends(): Promise<BackendDescriptor[]>;
1949
1983
  private tryParse;
1950
1984
  private assertNotDisposed;
package/dist/index.d.ts CHANGED
@@ -1014,8 +1014,13 @@ interface IConfigRepo {
1014
1014
  * replaceBackend: old pair is rebuilt against the new target).
1015
1015
  */
1016
1016
  replaceAppDataGroupBackend(groupId: string, backendId: string, type: string, options: Record<string, unknown>, description?: string): Promise<AppDataGroup>;
1017
- /** Remove a data-sync group (stops sync, removes descriptor). */
1018
- removeAppDataGroup(id: string): Promise<void>;
1017
+ /**
1018
+ * Remove a data-sync group (stops sync, removes descriptor).
1019
+ *
1020
+ * @param appId 目标登记所属 appId;默认本实例的 appId。传其它 appId 时只删
1021
+ * 配置仓里该 appId 的登记与引导副本(写墓碑),不会 dispose 别的实例里的组。
1022
+ */
1023
+ removeAppDataGroup(id: string, appId?: string): Promise<void>;
1019
1024
  /**
1020
1025
  * List config-sync backends that can be used as account sources
1021
1026
  * for data-sync backends. Returns backends that have `accountFields`
@@ -1353,6 +1358,12 @@ declare class ConfigRepo implements IConfigRepo {
1353
1358
  * unlink() 是否成功来判定。
1354
1359
  */
1355
1360
  private readonly tombstoneConfirmations;
1361
+ /**
1362
+ * 上次从副本预取墓碑的时间戳(毫秒)。
1363
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
1364
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
1365
+ */
1366
+ private lastTombstonePrefetchAt;
1356
1367
  /** Per-backend sync state (successful pairs + connect failures). */
1357
1368
  private backendStates;
1358
1369
  /**
@@ -1442,6 +1453,21 @@ declare class ConfigRepo implements IConfigRepo {
1442
1453
  private refreshSyncExclusions;
1443
1454
  /** Invalidate the tombstone cache — call after tombstones are modified. */
1444
1455
  private invalidateTombstoneCache;
1456
+ /**
1457
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
1458
+ *
1459
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
1460
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
1461
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
1462
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
1463
+ *
1464
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
1465
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
1466
+ * 一并清掉,同步再不会把它推上去。
1467
+ *
1468
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
1469
+ */
1470
+ private prefetchReplicaTombstones;
1445
1471
  /**
1446
1472
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
1447
1473
  *
@@ -1944,7 +1970,15 @@ declare class ConfigRepo implements IConfigRepo {
1944
1970
  * 真实意图,允许推送空副本,不参与自愈。
1945
1971
  */
1946
1972
  private healEmptyBootstrapDescriptors;
1947
- removeAppDataGroup(id: string): Promise<void>;
1973
+ /**
1974
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
1975
+ * 在配置仓的后端描述符)。
1976
+ *
1977
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
1978
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
1979
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
1980
+ */
1981
+ removeAppDataGroup(id: string, appId?: string): Promise<void>;
1948
1982
  listAccountBackends(): Promise<BackendDescriptor[]>;
1949
1983
  private tryParse;
1950
1984
  private assertNotDisposed;
package/dist/index.js CHANGED
@@ -1789,7 +1789,7 @@ var META_BACKENDS_DIR = `${META_DIR}/backends`;
1789
1789
  var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
1790
1790
  var ALIASES_DIR = `${META_DIR}/aliases`;
1791
1791
  var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
1792
- var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
1792
+ var TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
1793
1793
  var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
1794
1794
  function tombstoneRetentionMs(tombstonePath) {
1795
1795
  if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
@@ -3286,6 +3286,7 @@ function normalizeGroupName(value) {
3286
3286
  var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
3287
3287
  var LOCAL_IDB_BACKEND_ID = "local-idb";
3288
3288
  var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
3289
+ var TOMBSTONE_PREFETCH_INTERVAL_MS = 60 * 1e3;
3289
3290
  function tombstoneFileName(filePath) {
3290
3291
  return `${encodeMetaPath(filePath)}.json`;
3291
3292
  }
@@ -3431,6 +3432,12 @@ var ConfigRepo = class _ConfigRepo {
3431
3432
  * unlink() 是否成功来判定。
3432
3433
  */
3433
3434
  tombstoneConfirmations = /* @__PURE__ */ new Map();
3435
+ /**
3436
+ * 上次从副本预取墓碑的时间戳(毫秒)。
3437
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
3438
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
3439
+ */
3440
+ lastTombstonePrefetchAt = 0;
3434
3441
  /** Per-backend sync state (successful pairs + connect failures). */
3435
3442
  backendStates = /* @__PURE__ */ new Map();
3436
3443
  /**
@@ -3645,6 +3652,11 @@ var ConfigRepo = class _ConfigRepo {
3645
3652
  await this.initialSyncPromise;
3646
3653
  this.initialSyncPromise = null;
3647
3654
  }
3655
+ try {
3656
+ await this.prefetchReplicaTombstones();
3657
+ } catch (err) {
3658
+ log5.warn("[ConfigRepo] flush tombstone prefetch failed:", err);
3659
+ }
3648
3660
  await this.processTombstones();
3649
3661
  await this.healEmptyBootstrapDescriptors();
3650
3662
  const resultsMap = await this.syncEngine.syncAll();
@@ -3771,6 +3783,89 @@ var ConfigRepo = class _ConfigRepo {
3771
3783
  invalidateTombstoneCache() {
3772
3784
  this.tombstoneCache = null;
3773
3785
  }
3786
+ /**
3787
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
3788
+ *
3789
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
3790
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
3791
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
3792
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
3793
+ *
3794
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
3795
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
3796
+ * 一并清掉,同步再不会把它推上去。
3797
+ *
3798
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
3799
+ */
3800
+ async prefetchReplicaTombstones(minIntervalMs = 0) {
3801
+ if (this.disposed || this.replicaBackends.size === 0) return;
3802
+ const now = Date.now();
3803
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
3804
+ this.lastTombstonePrefetchAt = now;
3805
+ let local;
3806
+ try {
3807
+ local = await this.readTombstones();
3808
+ } catch {
3809
+ return;
3810
+ }
3811
+ const byPath = new Map(local.map((t) => [t.path, t]));
3812
+ let changed = false;
3813
+ for (const [replicaId, replica] of this.replicaBackends) {
3814
+ let remote;
3815
+ try {
3816
+ remote = await readTombstonesFromFs(replica.instance, (message) => log5.warn(`[ConfigRepo] prefetch tombstones (${replicaId}): ${message}`));
3817
+ } catch (err) {
3818
+ log5.warn(`[ConfigRepo] prefetch tombstones from ${replicaId} failed:`, err);
3819
+ continue;
3820
+ }
3821
+ for (const tombstone of remote) {
3822
+ if (!tombstone.path) continue;
3823
+ const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
3824
+ const prev = byPath.get(tombstone.path);
3825
+ if (!prev) {
3826
+ byPath.set(tombstone.path, tombstone);
3827
+ try {
3828
+ await this.ensureDir(tombstonePath);
3829
+ await writeFileOverwrite(
3830
+ this.cachedFS,
3831
+ tombstonePath,
3832
+ new TextEncoder().encode(serializeTombstone(tombstone))
3833
+ );
3834
+ changed = true;
3835
+ } catch (err) {
3836
+ log5.warn(`[ConfigRepo] prefetch tombstone write failed for ${tombstone.path}:`, err);
3837
+ }
3838
+ continue;
3839
+ }
3840
+ const merged = {
3841
+ ...prev,
3842
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
3843
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
3844
+ };
3845
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
3846
+ merged.type = "directory";
3847
+ }
3848
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
3849
+ if (!dirty) continue;
3850
+ byPath.set(tombstone.path, merged);
3851
+ try {
3852
+ await writeFileOverwrite(
3853
+ this.cachedFS,
3854
+ tombstonePath,
3855
+ new TextEncoder().encode(serializeTombstone(merged))
3856
+ );
3857
+ changed = true;
3858
+ } catch (err) {
3859
+ log5.warn(`[ConfigRepo] prefetch tombstone merge failed for ${tombstone.path}:`, err);
3860
+ }
3861
+ }
3862
+ }
3863
+ if (changed) {
3864
+ this.invalidateTombstoneCache();
3865
+ await this.readTombstones();
3866
+ log5.log("[ConfigRepo] prefetchReplicaTombstones: merged remote tombstones");
3867
+ }
3868
+ }
3774
3869
  /**
3775
3870
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
3776
3871
  *
@@ -4198,6 +4293,12 @@ var ConfigRepo = class _ConfigRepo {
4198
4293
  async initialSyncAndDedup() {
4199
4294
  this.syncEngine.unwatchAll();
4200
4295
  await this.healEmptyBootstrapDescriptors();
4296
+ try {
4297
+ await this.prefetchReplicaTombstones();
4298
+ await this.processTombstones();
4299
+ } catch (err) {
4300
+ log5.warn("[ConfigRepo] initial tombstone prefetch failed:", err);
4301
+ }
4201
4302
  await this.syncEngine.syncAll();
4202
4303
  await this.readAllBackendDescriptors();
4203
4304
  await this.processTombstones();
@@ -4691,6 +4792,8 @@ var ConfigRepo = class _ConfigRepo {
4691
4792
  filter: this.syncFilter,
4692
4793
  preSyncHook: async () => {
4693
4794
  try {
4795
+ this.invalidateTombstoneCache();
4796
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
4694
4797
  this.invalidateTombstoneCache();
4695
4798
  await this.processTombstones();
4696
4799
  } catch (err) {
@@ -5236,6 +5339,8 @@ var ConfigRepo = class _ConfigRepo {
5236
5339
  filter: this.syncFilter,
5237
5340
  preSyncHook: async () => {
5238
5341
  try {
5342
+ this.invalidateTombstoneCache();
5343
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
5239
5344
  this.invalidateTombstoneCache();
5240
5345
  await this.processTombstones();
5241
5346
  } catch (err) {
@@ -5811,12 +5916,12 @@ var ConfigRepo = class _ConfigRepo {
5811
5916
  // IConfigRepo — App Data Groups (data-sync groups)
5812
5917
  // -----------------------------------------------------------------------
5813
5918
  /** Path for a single app data group descriptor: .config/app-data-groups/{appId}/{id}.json */
5814
- appDataGroupFilePath(id) {
5815
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
5919
+ appDataGroupFilePath(id, appId = this.appId) {
5920
+ return `${APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
5816
5921
  }
5817
5922
  /** Legacy descriptor path: .meta/app-data-groups/{appId}/{id}.json */
5818
- legacyAppDataGroupFilePath(id) {
5819
- return `${LEGACY_APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
5923
+ legacyAppDataGroupFilePath(id, appId = this.appId) {
5924
+ return `${LEGACY_APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
5820
5925
  }
5821
5926
  /**
5822
5927
  * Write a data-group descriptor to `.config/app-data-groups/` (registration
@@ -5848,15 +5953,15 @@ var ConfigRepo = class _ConfigRepo {
5848
5953
  * 归属靠文件内的 `groupId` 字段区分:同一 app 下不同组即使后端 id 相同,
5849
5954
  * 也各用各自的文件,不会在同步时互相覆盖(同一组不同端点同理)。
5850
5955
  */
5851
- appDataBackendsDirPath() {
5852
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/backends`;
5956
+ appDataBackendsDirPath(appId = this.appId) {
5957
+ return `${APP_DATA_GROUPS_DIR}/${appId}/backends`;
5853
5958
  }
5854
- appDataBackendFilePath(backendId) {
5855
- return `${this.appDataBackendsDirPath()}/${backendId}.json`;
5959
+ appDataBackendFilePath(backendId, appId = this.appId) {
5960
+ return `${this.appDataBackendsDirPath(appId)}/${backendId}.json`;
5856
5961
  }
5857
5962
  /** 读本 app 目录下所有后端文件(忽略损坏/非本格式的文件)。 */
5858
- async readAppDataBackendFiles() {
5859
- const dir = this.appDataBackendsDirPath();
5963
+ async readAppDataBackendFiles(appId = this.appId) {
5964
+ const dir = this.appDataBackendsDirPath(appId);
5860
5965
  let entries;
5861
5966
  try {
5862
5967
  entries = await this.cachedFS.readdir(dir);
@@ -5878,9 +5983,9 @@ var ConfigRepo = class _ConfigRepo {
5878
5983
  return out;
5879
5984
  }
5880
5985
  /** 读某个数据组声明的全部后端文件(按 id 去重,先到先得)。 */
5881
- async readAppDataBackendFilesForGroup(groupId) {
5986
+ async readAppDataBackendFilesForGroup(groupId, appId = this.appId) {
5882
5987
  const byId = /* @__PURE__ */ new Map();
5883
- for (const file of await this.readAppDataBackendFiles()) {
5988
+ for (const file of await this.readAppDataBackendFiles(appId)) {
5884
5989
  if (file.groupId !== groupId) continue;
5885
5990
  if (byId.has(file.id)) continue;
5886
5991
  const { groupId: _groupId, ...desc } = file;
@@ -6499,15 +6604,25 @@ var ConfigRepo = class _ConfigRepo {
6499
6604
  }
6500
6605
  }
6501
6606
  }
6502
- async removeAppDataGroup(id) {
6607
+ /**
6608
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
6609
+ * 在配置仓的后端描述符)。
6610
+ *
6611
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
6612
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
6613
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
6614
+ */
6615
+ async removeAppDataGroup(id, appId = this.appId) {
6503
6616
  this.assertNotDisposed();
6504
- const group = this.appDataGroups.get(id);
6505
- if (group) {
6506
- await group.dispose();
6507
- this.appDataGroups.delete(id);
6617
+ if (appId === this.appId) {
6618
+ const group = this.appDataGroups.get(id);
6619
+ if (group) {
6620
+ await group.dispose();
6621
+ this.appDataGroups.delete(id);
6622
+ }
6508
6623
  }
6509
- for (const backend of await this.readAppDataBackendFilesForGroup(id)) {
6510
- const backendPath = this.appDataBackendFilePath(backend.id);
6624
+ for (const backend of await this.readAppDataBackendFilesForGroup(id, appId)) {
6625
+ const backendPath = this.appDataBackendFilePath(backend.id, appId);
6511
6626
  try {
6512
6627
  await this.deleteFile(backendPath);
6513
6628
  } catch (err) {
@@ -6519,7 +6634,7 @@ var ConfigRepo = class _ConfigRepo {
6519
6634
  await this.unlinkVersionSidecar(this.cachedFS, backendPath);
6520
6635
  }
6521
6636
  }
6522
- for (const descPath of [this.appDataGroupFilePath(id), this.legacyAppDataGroupFilePath(id)]) {
6637
+ for (const descPath of [this.appDataGroupFilePath(id, appId), this.legacyAppDataGroupFilePath(id, appId)]) {
6523
6638
  try {
6524
6639
  await this.deleteFile(descPath);
6525
6640
  } catch (err) {
@@ -6531,7 +6646,7 @@ var ConfigRepo = class _ConfigRepo {
6531
6646
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
6532
6647
  }
6533
6648
  }
6534
- log5.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
6649
+ log5.log(`[ConfigRepo] removeAppDataGroup: "${appId}/${id}" removed`);
6535
6650
  }
6536
6651
  async listAccountBackends() {
6537
6652
  this.assertNotDisposed();
@@ -6593,6 +6708,8 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6593
6708
  static PERMANENT_SYNC_EXCLUSIONS = [...CONFIG_ONLY_PREFIXES, GROUP_DESCRIPTOR_FILE3];
6594
6709
  tombstoneExcludePrefixes = [..._AppDataGroupImpl.PERMANENT_SYNC_EXCLUSIONS];
6595
6710
  syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
6711
+ /** 上次从数据后端预取墓碑的时间戳(节流用,见 prefetchRemoteTombstones)。 */
6712
+ lastTombstonePrefetchAt = 0;
6596
6713
  constructor(groupId, appId, backends, pollIntervalMs, parent, descriptor = {}) {
6597
6714
  this.groupId = groupId;
6598
6715
  this.appId = appId;
@@ -7446,12 +7563,70 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
7446
7563
  /** Delete tombstoned files on local + every connected backend before/after sync. */
7447
7564
  async runTombstonePass(stage) {
7448
7565
  try {
7566
+ await this.prefetchRemoteTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
7449
7567
  await this.tombstones.process(this.tombstoneTargets());
7450
7568
  this.refreshSyncExclusions(await this.tombstones.list());
7451
7569
  } catch (err) {
7452
7570
  log5.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
7453
7571
  }
7454
7572
  }
7573
+ /**
7574
+ * 把各数据后端上的墓碑合并进本地 `.meta/tombstones/`。
7575
+ *
7576
+ * 与配置组的 `ConfigRepo.prefetchReplicaTombstones` 同一目的、同一合并规则:
7577
+ * 远端删除意图优先于本地副本,先合并再让 `process()` 清掉陈旧数据,避免
7578
+ * 「本地有、别处已删」的文件被这一轮同步写回后端。
7579
+ */
7580
+ async prefetchRemoteTombstones(minIntervalMs = 0) {
7581
+ if (this.disposed || this.dataBackends.size === 0) return;
7582
+ const now = Date.now();
7583
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
7584
+ this.lastTombstonePrefetchAt = now;
7585
+ let local;
7586
+ try {
7587
+ local = await this.tombstones.list();
7588
+ } catch {
7589
+ return;
7590
+ }
7591
+ const byPath = new Map(local.map((t) => [t.path, t]));
7592
+ let changed = false;
7593
+ for (const [backendId, backend] of this.dataBackends) {
7594
+ let remote;
7595
+ try {
7596
+ remote = await readTombstonesFromFs(backend.instance, (message) => log5.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones (${backendId}): ${message}`));
7597
+ } catch (err) {
7598
+ log5.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones from ${backendId} failed:`, err);
7599
+ continue;
7600
+ }
7601
+ for (const tombstone of remote) {
7602
+ if (!tombstone.path) continue;
7603
+ const prev = byPath.get(tombstone.path);
7604
+ if (!prev) {
7605
+ byPath.set(tombstone.path, tombstone);
7606
+ await this.tombstones.write(tombstone);
7607
+ changed = true;
7608
+ continue;
7609
+ }
7610
+ const merged = {
7611
+ ...prev,
7612
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
7613
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
7614
+ };
7615
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
7616
+ merged.type = "directory";
7617
+ }
7618
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
7619
+ if (!dirty) continue;
7620
+ byPath.set(tombstone.path, merged);
7621
+ await this.tombstones.write(merged);
7622
+ changed = true;
7623
+ }
7624
+ }
7625
+ if (changed) {
7626
+ this.refreshSyncExclusions(await this.tombstones.list());
7627
+ log5.log(`[AppDataGroup:${this.groupId}] prefetchRemoteTombstones: merged remote tombstones`);
7628
+ }
7629
+ }
7455
7630
  /**
7456
7631
  * 把当前墓碑路径写进同步排除表(原地更新共享数组)。
7457
7632
  *
package/dist/index.mjs CHANGED
@@ -995,7 +995,7 @@ var META_BACKENDS_DIR = `${META_DIR}/backends`;
995
995
  var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
996
996
  var ALIASES_DIR = `${META_DIR}/aliases`;
997
997
  var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
998
- var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
998
+ var TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
999
999
  var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
1000
1000
  function tombstoneRetentionMs(tombstonePath) {
1001
1001
  if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
@@ -2492,6 +2492,7 @@ function normalizeGroupName(value) {
2492
2492
  var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
2493
2493
  var LOCAL_IDB_BACKEND_ID = "local-idb";
2494
2494
  var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
2495
+ var TOMBSTONE_PREFETCH_INTERVAL_MS = 60 * 1e3;
2495
2496
  function tombstoneFileName(filePath) {
2496
2497
  return `${encodeMetaPath(filePath)}.json`;
2497
2498
  }
@@ -2637,6 +2638,12 @@ var ConfigRepo = class _ConfigRepo {
2637
2638
  * unlink() 是否成功来判定。
2638
2639
  */
2639
2640
  tombstoneConfirmations = /* @__PURE__ */ new Map();
2641
+ /**
2642
+ * 上次从副本预取墓碑的时间戳(毫秒)。
2643
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
2644
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
2645
+ */
2646
+ lastTombstonePrefetchAt = 0;
2640
2647
  /** Per-backend sync state (successful pairs + connect failures). */
2641
2648
  backendStates = /* @__PURE__ */ new Map();
2642
2649
  /**
@@ -2851,6 +2858,11 @@ var ConfigRepo = class _ConfigRepo {
2851
2858
  await this.initialSyncPromise;
2852
2859
  this.initialSyncPromise = null;
2853
2860
  }
2861
+ try {
2862
+ await this.prefetchReplicaTombstones();
2863
+ } catch (err) {
2864
+ log5.warn("[ConfigRepo] flush tombstone prefetch failed:", err);
2865
+ }
2854
2866
  await this.processTombstones();
2855
2867
  await this.healEmptyBootstrapDescriptors();
2856
2868
  const resultsMap = await this.syncEngine.syncAll();
@@ -2977,6 +2989,89 @@ var ConfigRepo = class _ConfigRepo {
2977
2989
  invalidateTombstoneCache() {
2978
2990
  this.tombstoneCache = null;
2979
2991
  }
2992
+ /**
2993
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
2994
+ *
2995
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
2996
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
2997
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
2998
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
2999
+ *
3000
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
3001
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
3002
+ * 一并清掉,同步再不会把它推上去。
3003
+ *
3004
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
3005
+ */
3006
+ async prefetchReplicaTombstones(minIntervalMs = 0) {
3007
+ if (this.disposed || this.replicaBackends.size === 0) return;
3008
+ const now = Date.now();
3009
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
3010
+ this.lastTombstonePrefetchAt = now;
3011
+ let local;
3012
+ try {
3013
+ local = await this.readTombstones();
3014
+ } catch {
3015
+ return;
3016
+ }
3017
+ const byPath = new Map(local.map((t) => [t.path, t]));
3018
+ let changed = false;
3019
+ for (const [replicaId, replica] of this.replicaBackends) {
3020
+ let remote;
3021
+ try {
3022
+ remote = await readTombstonesFromFs(replica.instance, (message) => log5.warn(`[ConfigRepo] prefetch tombstones (${replicaId}): ${message}`));
3023
+ } catch (err) {
3024
+ log5.warn(`[ConfigRepo] prefetch tombstones from ${replicaId} failed:`, err);
3025
+ continue;
3026
+ }
3027
+ for (const tombstone of remote) {
3028
+ if (!tombstone.path) continue;
3029
+ const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
3030
+ const prev = byPath.get(tombstone.path);
3031
+ if (!prev) {
3032
+ byPath.set(tombstone.path, tombstone);
3033
+ try {
3034
+ await this.ensureDir(tombstonePath);
3035
+ await writeFileOverwrite(
3036
+ this.cachedFS,
3037
+ tombstonePath,
3038
+ new TextEncoder().encode(serializeTombstone(tombstone))
3039
+ );
3040
+ changed = true;
3041
+ } catch (err) {
3042
+ log5.warn(`[ConfigRepo] prefetch tombstone write failed for ${tombstone.path}:`, err);
3043
+ }
3044
+ continue;
3045
+ }
3046
+ const merged = {
3047
+ ...prev,
3048
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
3049
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
3050
+ };
3051
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
3052
+ merged.type = "directory";
3053
+ }
3054
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
3055
+ if (!dirty) continue;
3056
+ byPath.set(tombstone.path, merged);
3057
+ try {
3058
+ await writeFileOverwrite(
3059
+ this.cachedFS,
3060
+ tombstonePath,
3061
+ new TextEncoder().encode(serializeTombstone(merged))
3062
+ );
3063
+ changed = true;
3064
+ } catch (err) {
3065
+ log5.warn(`[ConfigRepo] prefetch tombstone merge failed for ${tombstone.path}:`, err);
3066
+ }
3067
+ }
3068
+ }
3069
+ if (changed) {
3070
+ this.invalidateTombstoneCache();
3071
+ await this.readTombstones();
3072
+ log5.log("[ConfigRepo] prefetchReplicaTombstones: merged remote tombstones");
3073
+ }
3074
+ }
2980
3075
  /**
2981
3076
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
2982
3077
  *
@@ -3404,6 +3499,12 @@ var ConfigRepo = class _ConfigRepo {
3404
3499
  async initialSyncAndDedup() {
3405
3500
  this.syncEngine.unwatchAll();
3406
3501
  await this.healEmptyBootstrapDescriptors();
3502
+ try {
3503
+ await this.prefetchReplicaTombstones();
3504
+ await this.processTombstones();
3505
+ } catch (err) {
3506
+ log5.warn("[ConfigRepo] initial tombstone prefetch failed:", err);
3507
+ }
3407
3508
  await this.syncEngine.syncAll();
3408
3509
  await this.readAllBackendDescriptors();
3409
3510
  await this.processTombstones();
@@ -3897,6 +3998,8 @@ var ConfigRepo = class _ConfigRepo {
3897
3998
  filter: this.syncFilter,
3898
3999
  preSyncHook: async () => {
3899
4000
  try {
4001
+ this.invalidateTombstoneCache();
4002
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
3900
4003
  this.invalidateTombstoneCache();
3901
4004
  await this.processTombstones();
3902
4005
  } catch (err) {
@@ -4442,6 +4545,8 @@ var ConfigRepo = class _ConfigRepo {
4442
4545
  filter: this.syncFilter,
4443
4546
  preSyncHook: async () => {
4444
4547
  try {
4548
+ this.invalidateTombstoneCache();
4549
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
4445
4550
  this.invalidateTombstoneCache();
4446
4551
  await this.processTombstones();
4447
4552
  } catch (err) {
@@ -5017,12 +5122,12 @@ var ConfigRepo = class _ConfigRepo {
5017
5122
  // IConfigRepo — App Data Groups (data-sync groups)
5018
5123
  // -----------------------------------------------------------------------
5019
5124
  /** Path for a single app data group descriptor: .config/app-data-groups/{appId}/{id}.json */
5020
- appDataGroupFilePath(id) {
5021
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
5125
+ appDataGroupFilePath(id, appId = this.appId) {
5126
+ return `${APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
5022
5127
  }
5023
5128
  /** Legacy descriptor path: .meta/app-data-groups/{appId}/{id}.json */
5024
- legacyAppDataGroupFilePath(id) {
5025
- return `${LEGACY_APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
5129
+ legacyAppDataGroupFilePath(id, appId = this.appId) {
5130
+ return `${LEGACY_APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
5026
5131
  }
5027
5132
  /**
5028
5133
  * Write a data-group descriptor to `.config/app-data-groups/` (registration
@@ -5054,15 +5159,15 @@ var ConfigRepo = class _ConfigRepo {
5054
5159
  * 归属靠文件内的 `groupId` 字段区分:同一 app 下不同组即使后端 id 相同,
5055
5160
  * 也各用各自的文件,不会在同步时互相覆盖(同一组不同端点同理)。
5056
5161
  */
5057
- appDataBackendsDirPath() {
5058
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/backends`;
5162
+ appDataBackendsDirPath(appId = this.appId) {
5163
+ return `${APP_DATA_GROUPS_DIR}/${appId}/backends`;
5059
5164
  }
5060
- appDataBackendFilePath(backendId) {
5061
- return `${this.appDataBackendsDirPath()}/${backendId}.json`;
5165
+ appDataBackendFilePath(backendId, appId = this.appId) {
5166
+ return `${this.appDataBackendsDirPath(appId)}/${backendId}.json`;
5062
5167
  }
5063
5168
  /** 读本 app 目录下所有后端文件(忽略损坏/非本格式的文件)。 */
5064
- async readAppDataBackendFiles() {
5065
- const dir = this.appDataBackendsDirPath();
5169
+ async readAppDataBackendFiles(appId = this.appId) {
5170
+ const dir = this.appDataBackendsDirPath(appId);
5066
5171
  let entries;
5067
5172
  try {
5068
5173
  entries = await this.cachedFS.readdir(dir);
@@ -5084,9 +5189,9 @@ var ConfigRepo = class _ConfigRepo {
5084
5189
  return out;
5085
5190
  }
5086
5191
  /** 读某个数据组声明的全部后端文件(按 id 去重,先到先得)。 */
5087
- async readAppDataBackendFilesForGroup(groupId) {
5192
+ async readAppDataBackendFilesForGroup(groupId, appId = this.appId) {
5088
5193
  const byId = /* @__PURE__ */ new Map();
5089
- for (const file of await this.readAppDataBackendFiles()) {
5194
+ for (const file of await this.readAppDataBackendFiles(appId)) {
5090
5195
  if (file.groupId !== groupId) continue;
5091
5196
  if (byId.has(file.id)) continue;
5092
5197
  const { groupId: _groupId, ...desc } = file;
@@ -5705,15 +5810,25 @@ var ConfigRepo = class _ConfigRepo {
5705
5810
  }
5706
5811
  }
5707
5812
  }
5708
- async removeAppDataGroup(id) {
5813
+ /**
5814
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
5815
+ * 在配置仓的后端描述符)。
5816
+ *
5817
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
5818
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
5819
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
5820
+ */
5821
+ async removeAppDataGroup(id, appId = this.appId) {
5709
5822
  this.assertNotDisposed();
5710
- const group = this.appDataGroups.get(id);
5711
- if (group) {
5712
- await group.dispose();
5713
- this.appDataGroups.delete(id);
5823
+ if (appId === this.appId) {
5824
+ const group = this.appDataGroups.get(id);
5825
+ if (group) {
5826
+ await group.dispose();
5827
+ this.appDataGroups.delete(id);
5828
+ }
5714
5829
  }
5715
- for (const backend of await this.readAppDataBackendFilesForGroup(id)) {
5716
- const backendPath = this.appDataBackendFilePath(backend.id);
5830
+ for (const backend of await this.readAppDataBackendFilesForGroup(id, appId)) {
5831
+ const backendPath = this.appDataBackendFilePath(backend.id, appId);
5717
5832
  try {
5718
5833
  await this.deleteFile(backendPath);
5719
5834
  } catch (err) {
@@ -5725,7 +5840,7 @@ var ConfigRepo = class _ConfigRepo {
5725
5840
  await this.unlinkVersionSidecar(this.cachedFS, backendPath);
5726
5841
  }
5727
5842
  }
5728
- for (const descPath of [this.appDataGroupFilePath(id), this.legacyAppDataGroupFilePath(id)]) {
5843
+ for (const descPath of [this.appDataGroupFilePath(id, appId), this.legacyAppDataGroupFilePath(id, appId)]) {
5729
5844
  try {
5730
5845
  await this.deleteFile(descPath);
5731
5846
  } catch (err) {
@@ -5737,7 +5852,7 @@ var ConfigRepo = class _ConfigRepo {
5737
5852
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
5738
5853
  }
5739
5854
  }
5740
- log5.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
5855
+ log5.log(`[ConfigRepo] removeAppDataGroup: "${appId}/${id}" removed`);
5741
5856
  }
5742
5857
  async listAccountBackends() {
5743
5858
  this.assertNotDisposed();
@@ -5799,6 +5914,8 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
5799
5914
  static PERMANENT_SYNC_EXCLUSIONS = [...CONFIG_ONLY_PREFIXES, GROUP_DESCRIPTOR_FILE3];
5800
5915
  tombstoneExcludePrefixes = [..._AppDataGroupImpl.PERMANENT_SYNC_EXCLUSIONS];
5801
5916
  syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
5917
+ /** 上次从数据后端预取墓碑的时间戳(节流用,见 prefetchRemoteTombstones)。 */
5918
+ lastTombstonePrefetchAt = 0;
5802
5919
  constructor(groupId, appId, backends, pollIntervalMs, parent, descriptor = {}) {
5803
5920
  this.groupId = groupId;
5804
5921
  this.appId = appId;
@@ -6652,12 +6769,70 @@ var AppDataGroupImpl = class _AppDataGroupImpl {
6652
6769
  /** Delete tombstoned files on local + every connected backend before/after sync. */
6653
6770
  async runTombstonePass(stage) {
6654
6771
  try {
6772
+ await this.prefetchRemoteTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
6655
6773
  await this.tombstones.process(this.tombstoneTargets());
6656
6774
  this.refreshSyncExclusions(await this.tombstones.list());
6657
6775
  } catch (err) {
6658
6776
  log5.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
6659
6777
  }
6660
6778
  }
6779
+ /**
6780
+ * 把各数据后端上的墓碑合并进本地 `.meta/tombstones/`。
6781
+ *
6782
+ * 与配置组的 `ConfigRepo.prefetchReplicaTombstones` 同一目的、同一合并规则:
6783
+ * 远端删除意图优先于本地副本,先合并再让 `process()` 清掉陈旧数据,避免
6784
+ * 「本地有、别处已删」的文件被这一轮同步写回后端。
6785
+ */
6786
+ async prefetchRemoteTombstones(minIntervalMs = 0) {
6787
+ if (this.disposed || this.dataBackends.size === 0) return;
6788
+ const now = Date.now();
6789
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
6790
+ this.lastTombstonePrefetchAt = now;
6791
+ let local;
6792
+ try {
6793
+ local = await this.tombstones.list();
6794
+ } catch {
6795
+ return;
6796
+ }
6797
+ const byPath = new Map(local.map((t) => [t.path, t]));
6798
+ let changed = false;
6799
+ for (const [backendId, backend] of this.dataBackends) {
6800
+ let remote;
6801
+ try {
6802
+ remote = await readTombstonesFromFs(backend.instance, (message) => log5.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones (${backendId}): ${message}`));
6803
+ } catch (err) {
6804
+ log5.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones from ${backendId} failed:`, err);
6805
+ continue;
6806
+ }
6807
+ for (const tombstone of remote) {
6808
+ if (!tombstone.path) continue;
6809
+ const prev = byPath.get(tombstone.path);
6810
+ if (!prev) {
6811
+ byPath.set(tombstone.path, tombstone);
6812
+ await this.tombstones.write(tombstone);
6813
+ changed = true;
6814
+ continue;
6815
+ }
6816
+ const merged = {
6817
+ ...prev,
6818
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
6819
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
6820
+ };
6821
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
6822
+ merged.type = "directory";
6823
+ }
6824
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
6825
+ if (!dirty) continue;
6826
+ byPath.set(tombstone.path, merged);
6827
+ await this.tombstones.write(merged);
6828
+ changed = true;
6829
+ }
6830
+ }
6831
+ if (changed) {
6832
+ this.refreshSyncExclusions(await this.tombstones.list());
6833
+ log5.log(`[AppDataGroup:${this.groupId}] prefetchRemoteTombstones: merged remote tombstones`);
6834
+ }
6835
+ }
6661
6836
  /**
6662
6837
  * 把当前墓碑路径写进同步排除表(原地更新共享数组)。
6663
6838
  *
@@ -27755,7 +27755,7 @@ var ZenFSConfig = (() => {
27755
27755
  var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
27756
27756
  var ALIASES_DIR = `${META_DIR}/aliases`;
27757
27757
  var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
27758
- var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
27758
+ var TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
27759
27759
  var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
27760
27760
  function tombstoneRetentionMs(tombstonePath) {
27761
27761
  if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
@@ -29243,6 +29243,7 @@ var ZenFSConfig = (() => {
29243
29243
  var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
29244
29244
  var LOCAL_IDB_BACKEND_ID = "local-idb";
29245
29245
  var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
29246
+ var TOMBSTONE_PREFETCH_INTERVAL_MS = 60 * 1e3;
29246
29247
  function tombstoneFileName(filePath) {
29247
29248
  return `${encodeMetaPath(filePath)}.json`;
29248
29249
  }
@@ -29371,6 +29372,12 @@ var ZenFSConfig = (() => {
29371
29372
  * unlink() 是否成功来判定。
29372
29373
  */
29373
29374
  __publicField(this, "tombstoneConfirmations", /* @__PURE__ */ new Map());
29375
+ /**
29376
+ * 上次从副本预取墓碑的时间戳(毫秒)。
29377
+ * 节流用:preSyncHook 每轮都会调用 {@link prefetchReplicaTombstones},
29378
+ * 但远端墓碑不会秒级变化,一分钟一次足够。
29379
+ */
29380
+ __publicField(this, "lastTombstonePrefetchAt", 0);
29374
29381
  /** Per-backend sync state (successful pairs + connect failures). */
29375
29382
  __publicField(this, "backendStates", /* @__PURE__ */ new Map());
29376
29383
  /**
@@ -29594,6 +29601,11 @@ var ZenFSConfig = (() => {
29594
29601
  await this.initialSyncPromise;
29595
29602
  this.initialSyncPromise = null;
29596
29603
  }
29604
+ try {
29605
+ await this.prefetchReplicaTombstones();
29606
+ } catch (err2) {
29607
+ log9.warn("[ConfigRepo] flush tombstone prefetch failed:", err2);
29608
+ }
29597
29609
  await this.processTombstones();
29598
29610
  await this.healEmptyBootstrapDescriptors();
29599
29611
  const resultsMap = await this.syncEngine.syncAll();
@@ -29714,6 +29726,89 @@ var ZenFSConfig = (() => {
29714
29726
  invalidateTombstoneCache() {
29715
29727
  this.tombstoneCache = null;
29716
29728
  }
29729
+ /**
29730
+ * 把各副本上的墓碑合并进本地,必须早于本轮的快照比对。
29731
+ *
29732
+ * 为什么需要它:墓碑文件本身也是被同步的文件,一个节点在「拿到墓碑」之前
29733
+ * 就已经跑完了 preSyncHook —— 这时它本地没有该路径的墓碑,同步就会把自己
29734
+ * 那份陈旧副本当成「本地新增」推回远端(BiDirectional + source-wins),
29735
+ * 删除被复活。只靠墓碑文件被同步拉下来,永远慢半拍。
29736
+ *
29737
+ * 所以在每轮同步之前先只读地把副本上的 `.meta/tombstones/` 合并到本地:
29738
+ * 合并完成后排除表立刻生效,随后的 processTombstones() 会把本地陈旧副本
29739
+ * 一并清掉,同步再不会把它推上去。
29740
+ *
29741
+ * @param minIntervalMs 节流间隔(0 = 立即执行)。preSyncHook 传 60s。
29742
+ */
29743
+ async prefetchReplicaTombstones(minIntervalMs = 0) {
29744
+ if (this.disposed || this.replicaBackends.size === 0) return;
29745
+ const now = Date.now();
29746
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
29747
+ this.lastTombstonePrefetchAt = now;
29748
+ let local;
29749
+ try {
29750
+ local = await this.readTombstones();
29751
+ } catch {
29752
+ return;
29753
+ }
29754
+ const byPath = new Map(local.map((t) => [t.path, t]));
29755
+ let changed = false;
29756
+ for (const [replicaId, replica] of this.replicaBackends) {
29757
+ let remote;
29758
+ try {
29759
+ remote = await readTombstonesFromFs(replica.instance, (message) => log9.warn(`[ConfigRepo] prefetch tombstones (${replicaId}): ${message}`));
29760
+ } catch (err2) {
29761
+ log9.warn(`[ConfigRepo] prefetch tombstones from ${replicaId} failed:`, err2);
29762
+ continue;
29763
+ }
29764
+ for (const tombstone of remote) {
29765
+ if (!tombstone.path) continue;
29766
+ const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
29767
+ const prev = byPath.get(tombstone.path);
29768
+ if (!prev) {
29769
+ byPath.set(tombstone.path, tombstone);
29770
+ try {
29771
+ await this.ensureDir(tombstonePath);
29772
+ await writeFileOverwrite(
29773
+ this.cachedFS,
29774
+ tombstonePath,
29775
+ new TextEncoder().encode(serializeTombstone(tombstone))
29776
+ );
29777
+ changed = true;
29778
+ } catch (err2) {
29779
+ log9.warn(`[ConfigRepo] prefetch tombstone write failed for ${tombstone.path}:`, err2);
29780
+ }
29781
+ continue;
29782
+ }
29783
+ const merged = {
29784
+ ...prev,
29785
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
29786
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
29787
+ };
29788
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
29789
+ merged.type = "directory";
29790
+ }
29791
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
29792
+ if (!dirty) continue;
29793
+ byPath.set(tombstone.path, merged);
29794
+ try {
29795
+ await writeFileOverwrite(
29796
+ this.cachedFS,
29797
+ tombstonePath,
29798
+ new TextEncoder().encode(serializeTombstone(merged))
29799
+ );
29800
+ changed = true;
29801
+ } catch (err2) {
29802
+ log9.warn(`[ConfigRepo] prefetch tombstone merge failed for ${tombstone.path}:`, err2);
29803
+ }
29804
+ }
29805
+ }
29806
+ if (changed) {
29807
+ this.invalidateTombstoneCache();
29808
+ await this.readTombstones();
29809
+ log9.log("[ConfigRepo] prefetchReplicaTombstones: merged remote tombstones");
29810
+ }
29811
+ }
29717
29812
  /**
29718
29813
  * 写入成功即撤销该路径(及其被删祖先目录)上的墓碑。
29719
29814
  *
@@ -30141,6 +30236,12 @@ var ZenFSConfig = (() => {
30141
30236
  async initialSyncAndDedup() {
30142
30237
  this.syncEngine.unwatchAll();
30143
30238
  await this.healEmptyBootstrapDescriptors();
30239
+ try {
30240
+ await this.prefetchReplicaTombstones();
30241
+ await this.processTombstones();
30242
+ } catch (err2) {
30243
+ log9.warn("[ConfigRepo] initial tombstone prefetch failed:", err2);
30244
+ }
30144
30245
  await this.syncEngine.syncAll();
30145
30246
  await this.readAllBackendDescriptors();
30146
30247
  await this.processTombstones();
@@ -30634,6 +30735,8 @@ var ZenFSConfig = (() => {
30634
30735
  filter: this.syncFilter,
30635
30736
  preSyncHook: async () => {
30636
30737
  try {
30738
+ this.invalidateTombstoneCache();
30739
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
30637
30740
  this.invalidateTombstoneCache();
30638
30741
  await this.processTombstones();
30639
30742
  } catch (err2) {
@@ -31179,6 +31282,8 @@ var ZenFSConfig = (() => {
31179
31282
  filter: this.syncFilter,
31180
31283
  preSyncHook: async () => {
31181
31284
  try {
31285
+ this.invalidateTombstoneCache();
31286
+ await this.prefetchReplicaTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
31182
31287
  this.invalidateTombstoneCache();
31183
31288
  await this.processTombstones();
31184
31289
  } catch (err2) {
@@ -31750,12 +31855,12 @@ var ZenFSConfig = (() => {
31750
31855
  // IConfigRepo — App Data Groups (data-sync groups)
31751
31856
  // -----------------------------------------------------------------------
31752
31857
  /** Path for a single app data group descriptor: .config/app-data-groups/{appId}/{id}.json */
31753
- appDataGroupFilePath(id) {
31754
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
31858
+ appDataGroupFilePath(id, appId = this.appId) {
31859
+ return `${APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
31755
31860
  }
31756
31861
  /** Legacy descriptor path: .meta/app-data-groups/{appId}/{id}.json */
31757
- legacyAppDataGroupFilePath(id) {
31758
- return `${LEGACY_APP_DATA_GROUPS_DIR}/${this.appId}/${id}.json`;
31862
+ legacyAppDataGroupFilePath(id, appId = this.appId) {
31863
+ return `${LEGACY_APP_DATA_GROUPS_DIR}/${appId}/${id}.json`;
31759
31864
  }
31760
31865
  /**
31761
31866
  * Write a data-group descriptor to `.config/app-data-groups/` (registration
@@ -31787,15 +31892,15 @@ var ZenFSConfig = (() => {
31787
31892
  * 归属靠文件内的 `groupId` 字段区分:同一 app 下不同组即使后端 id 相同,
31788
31893
  * 也各用各自的文件,不会在同步时互相覆盖(同一组不同端点同理)。
31789
31894
  */
31790
- appDataBackendsDirPath() {
31791
- return `${APP_DATA_GROUPS_DIR}/${this.appId}/backends`;
31895
+ appDataBackendsDirPath(appId = this.appId) {
31896
+ return `${APP_DATA_GROUPS_DIR}/${appId}/backends`;
31792
31897
  }
31793
- appDataBackendFilePath(backendId) {
31794
- return `${this.appDataBackendsDirPath()}/${backendId}.json`;
31898
+ appDataBackendFilePath(backendId, appId = this.appId) {
31899
+ return `${this.appDataBackendsDirPath(appId)}/${backendId}.json`;
31795
31900
  }
31796
31901
  /** 读本 app 目录下所有后端文件(忽略损坏/非本格式的文件)。 */
31797
- async readAppDataBackendFiles() {
31798
- const dir = this.appDataBackendsDirPath();
31902
+ async readAppDataBackendFiles(appId = this.appId) {
31903
+ const dir = this.appDataBackendsDirPath(appId);
31799
31904
  let entries2;
31800
31905
  try {
31801
31906
  entries2 = await this.cachedFS.readdir(dir);
@@ -31817,9 +31922,9 @@ var ZenFSConfig = (() => {
31817
31922
  return out;
31818
31923
  }
31819
31924
  /** 读某个数据组声明的全部后端文件(按 id 去重,先到先得)。 */
31820
- async readAppDataBackendFilesForGroup(groupId) {
31925
+ async readAppDataBackendFilesForGroup(groupId, appId = this.appId) {
31821
31926
  const byId = /* @__PURE__ */ new Map();
31822
- for (const file of await this.readAppDataBackendFiles()) {
31927
+ for (const file of await this.readAppDataBackendFiles(appId)) {
31823
31928
  if (file.groupId !== groupId) continue;
31824
31929
  if (byId.has(file.id)) continue;
31825
31930
  const { groupId: _groupId, ...desc } = file;
@@ -32438,15 +32543,25 @@ var ZenFSConfig = (() => {
32438
32543
  }
32439
32544
  }
32440
32545
  }
32441
- async removeAppDataGroup(id) {
32546
+ /**
32547
+ * 删除一个数据组的登记(`.config/app-data-groups/{appId}/{id}.json` + 该组
32548
+ * 在配置仓的后端描述符)。
32549
+ *
32550
+ * @param appId 目标登记所属的 appId,默认为本实例的 appId。传其它 appId 时
32551
+ * 只删配置仓里那份登记与引导副本,不会(也无法)去 dispose 另一个
32552
+ * appId 实例里的组句柄 —— 调用方应优先走实例注册表,让实例自己刷新。
32553
+ */
32554
+ async removeAppDataGroup(id, appId = this.appId) {
32442
32555
  this.assertNotDisposed();
32443
- const group = this.appDataGroups.get(id);
32444
- if (group) {
32445
- await group.dispose();
32446
- this.appDataGroups.delete(id);
32556
+ if (appId === this.appId) {
32557
+ const group = this.appDataGroups.get(id);
32558
+ if (group) {
32559
+ await group.dispose();
32560
+ this.appDataGroups.delete(id);
32561
+ }
32447
32562
  }
32448
- for (const backend of await this.readAppDataBackendFilesForGroup(id)) {
32449
- const backendPath = this.appDataBackendFilePath(backend.id);
32563
+ for (const backend of await this.readAppDataBackendFilesForGroup(id, appId)) {
32564
+ const backendPath = this.appDataBackendFilePath(backend.id, appId);
32450
32565
  try {
32451
32566
  await this.deleteFile(backendPath);
32452
32567
  } catch (err2) {
@@ -32458,7 +32573,7 @@ var ZenFSConfig = (() => {
32458
32573
  await this.unlinkVersionSidecar(this.cachedFS, backendPath);
32459
32574
  }
32460
32575
  }
32461
- for (const descPath of [this.appDataGroupFilePath(id), this.legacyAppDataGroupFilePath(id)]) {
32576
+ for (const descPath of [this.appDataGroupFilePath(id, appId), this.legacyAppDataGroupFilePath(id, appId)]) {
32462
32577
  try {
32463
32578
  await this.deleteFile(descPath);
32464
32579
  } catch (err2) {
@@ -32470,7 +32585,7 @@ var ZenFSConfig = (() => {
32470
32585
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
32471
32586
  }
32472
32587
  }
32473
- log9.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
32588
+ log9.log(`[ConfigRepo] removeAppDataGroup: "${appId}/${id}" removed`);
32474
32589
  }
32475
32590
  async listAccountBackends() {
32476
32591
  this.assertNotDisposed();
@@ -32541,6 +32656,8 @@ var ZenFSConfig = (() => {
32541
32656
  __publicField(this, "postDeleteTimer");
32542
32657
  __publicField(this, "tombstoneExcludePrefixes", [..._AppDataGroupImpl.PERMANENT_SYNC_EXCLUSIONS]);
32543
32658
  __publicField(this, "syncFilter", { excludePrefixes: this.tombstoneExcludePrefixes });
32659
+ /** 上次从数据后端预取墓碑的时间戳(节流用,见 prefetchRemoteTombstones)。 */
32660
+ __publicField(this, "lastTombstonePrefetchAt", 0);
32544
32661
  __publicField(this, "parent");
32545
32662
  __publicField(this, "_backends");
32546
32663
  /**
@@ -33393,12 +33510,70 @@ var ZenFSConfig = (() => {
33393
33510
  /** Delete tombstoned files on local + every connected backend before/after sync. */
33394
33511
  async runTombstonePass(stage) {
33395
33512
  try {
33513
+ await this.prefetchRemoteTombstones(TOMBSTONE_PREFETCH_INTERVAL_MS);
33396
33514
  await this.tombstones.process(this.tombstoneTargets());
33397
33515
  this.refreshSyncExclusions(await this.tombstones.list());
33398
33516
  } catch (err2) {
33399
33517
  log9.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err2);
33400
33518
  }
33401
33519
  }
33520
+ /**
33521
+ * 把各数据后端上的墓碑合并进本地 `.meta/tombstones/`。
33522
+ *
33523
+ * 与配置组的 `ConfigRepo.prefetchReplicaTombstones` 同一目的、同一合并规则:
33524
+ * 远端删除意图优先于本地副本,先合并再让 `process()` 清掉陈旧数据,避免
33525
+ * 「本地有、别处已删」的文件被这一轮同步写回后端。
33526
+ */
33527
+ async prefetchRemoteTombstones(minIntervalMs = 0) {
33528
+ if (this.disposed || this.dataBackends.size === 0) return;
33529
+ const now = Date.now();
33530
+ if (minIntervalMs > 0 && now - this.lastTombstonePrefetchAt < minIntervalMs) return;
33531
+ this.lastTombstonePrefetchAt = now;
33532
+ let local;
33533
+ try {
33534
+ local = await this.tombstones.list();
33535
+ } catch {
33536
+ return;
33537
+ }
33538
+ const byPath = new Map(local.map((t) => [t.path, t]));
33539
+ let changed = false;
33540
+ for (const [backendId, backend] of this.dataBackends) {
33541
+ let remote;
33542
+ try {
33543
+ remote = await readTombstonesFromFs(backend.instance, (message) => log9.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones (${backendId}): ${message}`));
33544
+ } catch (err2) {
33545
+ log9.warn(`[AppDataGroup:${this.groupId}] prefetch tombstones from ${backendId} failed:`, err2);
33546
+ continue;
33547
+ }
33548
+ for (const tombstone of remote) {
33549
+ if (!tombstone.path) continue;
33550
+ const prev = byPath.get(tombstone.path);
33551
+ if (!prev) {
33552
+ byPath.set(tombstone.path, tombstone);
33553
+ await this.tombstones.write(tombstone);
33554
+ changed = true;
33555
+ continue;
33556
+ }
33557
+ const merged = {
33558
+ ...prev,
33559
+ deletedAt: Math.min(prev.deletedAt, tombstone.deletedAt),
33560
+ confirmedBy: Array.from(/* @__PURE__ */ new Set([...prev.confirmedBy, ...tombstone.confirmedBy]))
33561
+ };
33562
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) {
33563
+ merged.type = "directory";
33564
+ }
33565
+ const dirty = merged.deletedAt !== prev.deletedAt || merged.confirmedBy.length !== prev.confirmedBy.length || merged.type === "directory" && prev.type !== "directory";
33566
+ if (!dirty) continue;
33567
+ byPath.set(tombstone.path, merged);
33568
+ await this.tombstones.write(merged);
33569
+ changed = true;
33570
+ }
33571
+ }
33572
+ if (changed) {
33573
+ this.refreshSyncExclusions(await this.tombstones.list());
33574
+ log9.log(`[AppDataGroup:${this.groupId}] prefetchRemoteTombstones: merged remote tombstones`);
33575
+ }
33576
+ }
33402
33577
  /**
33403
33578
  * 把当前墓碑路径写进同步排除表(原地更新共享数组)。
33404
33579
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zen-fs-config",
3
- "version": "0.10.2",
3
+ "version": "0.10.3",
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",