zen-fs-config 0.7.4 → 0.7.6
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/DESIGN.md +20 -0
- package/README.md +16 -0
- package/README.zh-CN.md +16 -0
- package/dist/{backend-registry-RBKWNJZI.mjs → backend-registry-UCAMGG6O.mjs} +1 -1
- package/dist/{chunk-S2S3XBK2.mjs → chunk-WURWDHNT.mjs} +31 -16
- package/dist/index.d.mts +120 -6
- package/dist/index.d.ts +120 -6
- package/dist/index.js +1180 -625
- package/dist/index.mjs +1142 -602
- package/dist/zen-fs-config.js +1176 -623
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -97,6 +97,17 @@ async function wrapZenFSFileSystem(config) {
|
|
|
97
97
|
const notifyChange = () => {
|
|
98
98
|
if (changeCallback) changeCallback();
|
|
99
99
|
};
|
|
100
|
+
const writeQueues = /* @__PURE__ */ new Map();
|
|
101
|
+
const runExclusive = async (path, task) => {
|
|
102
|
+
const prev = writeQueues.get(path);
|
|
103
|
+
const run = (prev ?? Promise.resolve()).catch(() => void 0).then(task);
|
|
104
|
+
writeQueues.set(path, run);
|
|
105
|
+
try {
|
|
106
|
+
await run;
|
|
107
|
+
} finally {
|
|
108
|
+
if (writeQueues.get(path) === run) writeQueues.delete(path);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
100
111
|
const backend = {
|
|
101
112
|
async readFile(path, ...args) {
|
|
102
113
|
const st = await isolatedFS.stat(path);
|
|
@@ -107,24 +118,28 @@ async function wrapZenFSFileSystem(config) {
|
|
|
107
118
|
return buf;
|
|
108
119
|
},
|
|
109
120
|
async writeFile(path, data, _options) {
|
|
110
|
-
const
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
dir
|
|
116
|
-
|
|
117
|
-
|
|
121
|
+
const source = data instanceof ArrayBuffer ? new Uint8Array(data) : data instanceof Uint8Array ? data : new TextEncoder().encode(data);
|
|
122
|
+
const bytes = new Uint8Array(source);
|
|
123
|
+
await runExclusive(path, async () => {
|
|
124
|
+
const parts = path.split("/").filter(Boolean);
|
|
125
|
+
parts.pop();
|
|
126
|
+
let dir = "";
|
|
127
|
+
for (const p of parts) {
|
|
128
|
+
dir += "/" + p;
|
|
129
|
+
if (!await isolatedFS.exists(dir)) {
|
|
130
|
+
await isolatedFS.mkdir(dir, { uid: 0, gid: 0, mode: 493 });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (await isolatedFS.exists(path)) {
|
|
134
|
+
await isolatedFS.unlink(path);
|
|
118
135
|
}
|
|
119
|
-
}
|
|
120
|
-
if (!await isolatedFS.exists(path)) {
|
|
121
136
|
await isolatedFS.createFile(path, { uid: 0, gid: 0, mode: 420 });
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
}
|
|
137
|
+
await isolatedFS.write(path, bytes, 0);
|
|
138
|
+
try {
|
|
139
|
+
await isolatedFS.touch(path, { size: bytes.byteLength, mtimeMs: _options?.mtime ?? Date.now() });
|
|
140
|
+
} catch {
|
|
141
|
+
}
|
|
142
|
+
});
|
|
128
143
|
notifyChange();
|
|
129
144
|
},
|
|
130
145
|
async readdir(path) {
|
|
@@ -519,7 +534,7 @@ __export(index_exports, {
|
|
|
519
534
|
ConflictStore: () => ConflictStore,
|
|
520
535
|
DATA_GROUP_DEFAULT_FEATURES: () => DATA_GROUP_DEFAULT_FEATURES,
|
|
521
536
|
FolderStore: () => FolderStore,
|
|
522
|
-
GROUP_DESCRIPTOR_FILE: () =>
|
|
537
|
+
GROUP_DESCRIPTOR_FILE: () => GROUP_DESCRIPTOR_FILE2,
|
|
523
538
|
LEGACY_CONFLICTS_DIR: () => LEGACY_CONFLICTS_DIR,
|
|
524
539
|
LEGACY_TOMBSTONES_DIR: () => LEGACY_TOMBSTONES_DIR,
|
|
525
540
|
LOCAL_IDB_BACKEND_ID: () => LOCAL_IDB_BACKEND_ID,
|
|
@@ -770,6 +785,92 @@ function createChrootFS(inner, root, options = {}) {
|
|
|
770
785
|
async function ensureParentDir(absolutePath) {
|
|
771
786
|
}
|
|
772
787
|
|
|
788
|
+
// src/group-type-guard.ts
|
|
789
|
+
var import_localstorage_logger = require("@richard432/localstorage-logger");
|
|
790
|
+
var log = (0, import_localstorage_logger.createLogger)("zen-fs-config:group-type-guard");
|
|
791
|
+
var GROUP_TYPE_FILES = /* @__PURE__ */ new Set(["/.config/group-type", "/.meta/group-type"]);
|
|
792
|
+
var GROUP_DESCRIPTOR_FILE = "/.meta/group.json";
|
|
793
|
+
var APP_DATA_GROUP_DESCRIPTOR_RE = /^\/\.config\/app-data-groups\/[^/]+\/[^/]+\.json$/;
|
|
794
|
+
function decode(data) {
|
|
795
|
+
if (typeof data === "string") return data;
|
|
796
|
+
if (data instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(data));
|
|
797
|
+
return new TextDecoder().decode(data);
|
|
798
|
+
}
|
|
799
|
+
function safeParse(text) {
|
|
800
|
+
try {
|
|
801
|
+
return JSON.parse(text);
|
|
802
|
+
} catch {
|
|
803
|
+
return null;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
function readGroupIdentity(path, data) {
|
|
807
|
+
const normalized = path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
|
|
808
|
+
const isGroupType = GROUP_TYPE_FILES.has(normalized);
|
|
809
|
+
const isGroupDescriptor = normalized === GROUP_DESCRIPTOR_FILE;
|
|
810
|
+
const isAppDataGroup = APP_DATA_GROUP_DESCRIPTOR_RE.test(normalized);
|
|
811
|
+
if (!isGroupType && !isGroupDescriptor && !isAppDataGroup) return null;
|
|
812
|
+
const text = decode(data);
|
|
813
|
+
if (isGroupType) {
|
|
814
|
+
const value = text.trim();
|
|
815
|
+
return value || null;
|
|
816
|
+
}
|
|
817
|
+
const parsed = safeParse(text);
|
|
818
|
+
if (isGroupDescriptor) {
|
|
819
|
+
return typeof parsed?.kind === "string" ? `kind:${parsed.kind}` : null;
|
|
820
|
+
}
|
|
821
|
+
return typeof parsed?.groupType === "string" ? `groupType:${parsed.groupType}` : null;
|
|
822
|
+
}
|
|
823
|
+
async function readExistingIdentity(fs, path) {
|
|
824
|
+
try {
|
|
825
|
+
const raw = await fs.readFile(path, "utf-8");
|
|
826
|
+
return readGroupIdentity(path, raw);
|
|
827
|
+
} catch {
|
|
828
|
+
return null;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
function wrapGroupTypeGuard(fs, side, onBlock) {
|
|
832
|
+
const reported = /* @__PURE__ */ new Set();
|
|
833
|
+
const guarded = Object.create(fs);
|
|
834
|
+
const lastBlock = { current: null };
|
|
835
|
+
guarded.getLastBlockedGroupType = () => lastBlock.current;
|
|
836
|
+
const allow = async (path, data) => {
|
|
837
|
+
const incoming = readGroupIdentity(path, data);
|
|
838
|
+
if (incoming === null) return true;
|
|
839
|
+
const existing = await readExistingIdentity(fs, path);
|
|
840
|
+
if (existing === null || existing === incoming) return true;
|
|
841
|
+
const signature = `${side}|${path}|${existing}->${incoming}`;
|
|
842
|
+
const block = { side, path, existing, incoming };
|
|
843
|
+
lastBlock.current = block;
|
|
844
|
+
if (!reported.has(signature)) {
|
|
845
|
+
reported.add(signature);
|
|
846
|
+
log.warn(
|
|
847
|
+
`[GroupType] blocked group-type change on ${side}: ${path} would change "${existing}" \u2192 "${incoming}" \u2014 identity is write-once, the incoming value is dropped (fix the group wiring instead of syncing it)`
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
try {
|
|
851
|
+
onBlock?.(block);
|
|
852
|
+
} catch {
|
|
853
|
+
}
|
|
854
|
+
return false;
|
|
855
|
+
};
|
|
856
|
+
guarded.writeFile = async (path, data) => {
|
|
857
|
+
if (!await allow(path, data)) return;
|
|
858
|
+
return fs.writeFile(path, data);
|
|
859
|
+
};
|
|
860
|
+
if (typeof fs.writeFileWithMtime === "function") {
|
|
861
|
+
guarded.writeFileWithMtime = async (path, data, mtime) => {
|
|
862
|
+
if (!await allow(path, data)) return;
|
|
863
|
+
return fs.writeFileWithMtime(path, data, mtime);
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
guarded.backendName = sideLabel(fs.backendName, side);
|
|
867
|
+
return guarded;
|
|
868
|
+
}
|
|
869
|
+
function sideLabel(name, side) {
|
|
870
|
+
if (!name) return side;
|
|
871
|
+
return name.includes(side) ? name : `${name}\xB7${side}`;
|
|
872
|
+
}
|
|
873
|
+
|
|
773
874
|
// src/adapters.ts
|
|
774
875
|
function toUint8Array(data) {
|
|
775
876
|
if (data instanceof Uint8Array) return data;
|
|
@@ -843,7 +944,7 @@ function backendToSyncableFS(backend, name) {
|
|
|
843
944
|
} else {
|
|
844
945
|
syncable.backendName = backend.constructor.name || "Backend";
|
|
845
946
|
}
|
|
846
|
-
return syncable;
|
|
947
|
+
return wrapGroupTypeGuard(syncable, syncable.backendName || "backend");
|
|
847
948
|
}
|
|
848
949
|
|
|
849
950
|
// src/config-repo.ts
|
|
@@ -854,15 +955,15 @@ init_backend_registry();
|
|
|
854
955
|
var import_core = require("@zenfs/core");
|
|
855
956
|
|
|
856
957
|
// src/logger.ts
|
|
857
|
-
var
|
|
958
|
+
var import_localstorage_logger2 = require("@richard432/localstorage-logger");
|
|
858
959
|
var MODULE_PREFIX = "zen-fs-config";
|
|
859
|
-
function
|
|
860
|
-
const logger = (0,
|
|
960
|
+
function createLogger2(prefix) {
|
|
961
|
+
const logger = (0, import_localstorage_logger2.createLogger)(`${MODULE_PREFIX}:${prefix}`);
|
|
861
962
|
return (...args) => logger.log(...args);
|
|
862
963
|
}
|
|
863
964
|
|
|
864
965
|
// src/folder-backend.ts
|
|
865
|
-
var
|
|
966
|
+
var log2 = createLogger2("folder-backend");
|
|
866
967
|
var FolderStore = class {
|
|
867
968
|
name = "folder";
|
|
868
969
|
label;
|
|
@@ -949,7 +1050,7 @@ function registerFolderBackend() {
|
|
|
949
1050
|
defaultOptions: { path: "" }
|
|
950
1051
|
}
|
|
951
1052
|
);
|
|
952
|
-
|
|
1053
|
+
log2("Folder backend registered");
|
|
953
1054
|
}
|
|
954
1055
|
registerFolderBackend();
|
|
955
1056
|
function isBrowserEnv() {
|
|
@@ -1102,7 +1203,7 @@ function deleteDataGroupLocalStore(appId, groupId, options = {}) {
|
|
|
1102
1203
|
}
|
|
1103
1204
|
|
|
1104
1205
|
// src/config-repo.ts
|
|
1105
|
-
var
|
|
1206
|
+
var import_localstorage_logger5 = require("@richard432/localstorage-logger");
|
|
1106
1207
|
|
|
1107
1208
|
// src/version.ts
|
|
1108
1209
|
function versionPathFor(configFilePath) {
|
|
@@ -1345,330 +1446,165 @@ async function verifyOrRepairVersion(fs, configFilePath, author) {
|
|
|
1345
1446
|
}
|
|
1346
1447
|
}
|
|
1347
1448
|
|
|
1348
|
-
// src/
|
|
1349
|
-
|
|
1350
|
-
|
|
1449
|
+
// src/group-meta.ts
|
|
1450
|
+
var import_localstorage_logger3 = require("@richard432/localstorage-logger");
|
|
1451
|
+
|
|
1452
|
+
// src/canonical-json.ts
|
|
1453
|
+
var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
|
|
1454
|
+
var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "instanceId", "name", "features"];
|
|
1455
|
+
var APP_DATA_GROUP_ORDER = ["id", "groupType", "instanceId", "name", "features", "backends"];
|
|
1456
|
+
var BACKEND_ORDER = ["id", "type", "options", "accountBackendId", "description", "createdAt"];
|
|
1457
|
+
function compareKeys(a, b) {
|
|
1458
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
1351
1459
|
}
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
return typeof stat.mode === "number" && (stat.mode & S_IFDIR) === S_IFDIR;
|
|
1460
|
+
function isPlainObject(value) {
|
|
1461
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1355
1462
|
}
|
|
1356
|
-
function
|
|
1357
|
-
|
|
1358
|
-
|
|
1463
|
+
function canonicalObject(value, order = []) {
|
|
1464
|
+
const out = {};
|
|
1465
|
+
for (const key of order) {
|
|
1466
|
+
if (value[key] !== void 0) out[key] = canonicalField(key, value[key]);
|
|
1467
|
+
}
|
|
1468
|
+
for (const key of Object.keys(value).sort(compareKeys)) {
|
|
1469
|
+
if (order.includes(key) || value[key] === void 0) continue;
|
|
1470
|
+
out[key] = canonicalField(key, value[key]);
|
|
1471
|
+
}
|
|
1472
|
+
return out;
|
|
1359
1473
|
}
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
const dir = stack.pop();
|
|
1367
|
-
let entries;
|
|
1368
|
-
try {
|
|
1369
|
-
entries = await fs.readdir(dir);
|
|
1370
|
-
} catch {
|
|
1371
|
-
continue;
|
|
1372
|
-
}
|
|
1373
|
-
for (const entry of entries) {
|
|
1374
|
-
const fullPath = joinPath(dir, entry);
|
|
1375
|
-
let stat;
|
|
1376
|
-
try {
|
|
1377
|
-
stat = await fs.stat(fullPath);
|
|
1378
|
-
} catch {
|
|
1379
|
-
continue;
|
|
1380
|
-
}
|
|
1381
|
-
if (isDirectory(stat)) {
|
|
1382
|
-
stack.push(fullPath);
|
|
1383
|
-
continue;
|
|
1384
|
-
}
|
|
1385
|
-
result.scanned++;
|
|
1386
|
-
if (!isMtimeSidecar(entry)) continue;
|
|
1387
|
-
if (dryRun) {
|
|
1388
|
-
result.removed.push(fullPath);
|
|
1389
|
-
continue;
|
|
1390
|
-
}
|
|
1391
|
-
try {
|
|
1392
|
-
await fs.unlink(fullPath);
|
|
1393
|
-
result.removed.push(fullPath);
|
|
1394
|
-
} catch {
|
|
1395
|
-
result.failed.push(fullPath);
|
|
1396
|
-
}
|
|
1474
|
+
function canonicalField(key, value) {
|
|
1475
|
+
if (Array.isArray(value)) {
|
|
1476
|
+
if (key === "backends") {
|
|
1477
|
+
return value.map((item) => isPlainObject(item) ? canonicalObject(item, BACKEND_ORDER) : item).sort(
|
|
1478
|
+
(a, b) => compareKeys(String(a?.id ?? ""), String(b?.id ?? ""))
|
|
1479
|
+
);
|
|
1397
1480
|
}
|
|
1481
|
+
return value.map((item) => canonicalField("", item));
|
|
1398
1482
|
}
|
|
1399
|
-
|
|
1483
|
+
if (isPlainObject(value)) {
|
|
1484
|
+
if (key === "features") return canonicalObject(value, FEATURE_ORDER);
|
|
1485
|
+
return canonicalObject(value);
|
|
1486
|
+
}
|
|
1487
|
+
return value;
|
|
1488
|
+
}
|
|
1489
|
+
function stringify(value) {
|
|
1490
|
+
return JSON.stringify(value, null, 2);
|
|
1491
|
+
}
|
|
1492
|
+
function serializeGroupDescriptor(descriptor) {
|
|
1493
|
+
const { updatedAt: _ignored, ...rest } = descriptor;
|
|
1494
|
+
return stringify(canonicalObject(rest, GROUP_DESCRIPTOR_ORDER));
|
|
1495
|
+
}
|
|
1496
|
+
function serializeBackendDescriptor(descriptor) {
|
|
1497
|
+
return stringify(canonicalObject(descriptor, BACKEND_ORDER));
|
|
1498
|
+
}
|
|
1499
|
+
function serializeAppDataGroupDescriptor(descriptor) {
|
|
1500
|
+
return stringify(canonicalObject(descriptor, APP_DATA_GROUP_ORDER));
|
|
1501
|
+
}
|
|
1502
|
+
function stripBackendCreatedAt(descriptor) {
|
|
1503
|
+
const { createdAt: _ignored, ...rest } = descriptor;
|
|
1504
|
+
return rest;
|
|
1505
|
+
}
|
|
1506
|
+
function mergeBackendDescriptor(existing, incoming) {
|
|
1507
|
+
const existingCreatedAt = typeof existing?.createdAt === "number" ? existing.createdAt : void 0;
|
|
1508
|
+
const incomingCreatedAt = typeof incoming.createdAt === "number" ? incoming.createdAt : void 0;
|
|
1509
|
+
const createdAt = existingCreatedAt === void 0 ? incomingCreatedAt : incomingCreatedAt === void 0 ? existingCreatedAt : Math.min(existingCreatedAt, incomingCreatedAt);
|
|
1510
|
+
return createdAt === void 0 ? stripBackendCreatedAt(incoming) : { ...incoming, createdAt };
|
|
1511
|
+
}
|
|
1512
|
+
function mergeBackendCreatedAt(incoming, existing) {
|
|
1513
|
+
if (!existing || existing.length === 0) return incoming;
|
|
1514
|
+
const byId = new Map(existing.map((d) => [d.id, d]));
|
|
1515
|
+
return incoming.map((desc) => mergeBackendDescriptor(byId.get(desc.id), desc));
|
|
1516
|
+
}
|
|
1517
|
+
function mergeDescriptorCreatedAt(descriptor, existing) {
|
|
1518
|
+
return {
|
|
1519
|
+
...descriptor,
|
|
1520
|
+
backends: mergeBackendCreatedAt(descriptor.backends, existing?.backends)
|
|
1521
|
+
};
|
|
1400
1522
|
}
|
|
1401
1523
|
|
|
1402
|
-
// src/
|
|
1403
|
-
|
|
1404
|
-
|
|
1524
|
+
// src/group-meta.ts
|
|
1525
|
+
var log3 = (0, import_localstorage_logger3.createLogger)("zen-fs-config:tombstones");
|
|
1526
|
+
var META_DIR = "/.meta";
|
|
1527
|
+
var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
|
|
1528
|
+
var META_BACKENDS_DIR = `${META_DIR}/backends`;
|
|
1529
|
+
var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
|
|
1530
|
+
var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
|
|
1531
|
+
var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
|
|
1532
|
+
var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
|
|
1533
|
+
function tombstoneRetentionMs(tombstonePath) {
|
|
1534
|
+
if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
|
|
1535
|
+
return TOMBSTONE_PLACEHOLDER_RETENTION_MS;
|
|
1536
|
+
}
|
|
1537
|
+
return TOMBSTONE_RETENTION_MS;
|
|
1405
1538
|
}
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
return
|
|
1539
|
+
function isTombstoneRetentionElapsed(tombstone, now = Date.now()) {
|
|
1540
|
+
const deletedAt = Number(tombstone.deletedAt);
|
|
1541
|
+
if (!Number.isFinite(deletedAt)) return true;
|
|
1542
|
+
return now - deletedAt >= tombstoneRetentionMs(tombstone.path);
|
|
1410
1543
|
}
|
|
1411
|
-
function
|
|
1412
|
-
|
|
1413
|
-
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
1544
|
+
function isDirectoryTombstone(tombstone) {
|
|
1545
|
+
return tombstone.type === "directory";
|
|
1414
1546
|
}
|
|
1415
|
-
function
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1547
|
+
function serializeTombstone(tombstone) {
|
|
1548
|
+
const ordered = {
|
|
1549
|
+
path: tombstone.path,
|
|
1550
|
+
deletedAt: tombstone.deletedAt,
|
|
1551
|
+
deletedBy: tombstone.deletedBy,
|
|
1552
|
+
confirmedBy: tombstone.confirmedBy
|
|
1553
|
+
};
|
|
1554
|
+
if (tombstone.type) ordered.type = tombstone.type;
|
|
1555
|
+
return JSON.stringify(ordered, null, 2);
|
|
1420
1556
|
}
|
|
1421
|
-
async function
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1557
|
+
async function purgeTombstonedTree(fs, targetPath) {
|
|
1558
|
+
let isDir2 = false;
|
|
1559
|
+
try {
|
|
1560
|
+
const stat = await fs.stat?.(targetPath);
|
|
1561
|
+
if (stat) {
|
|
1562
|
+
if (typeof stat.isDirectory === "function") isDir2 = stat.isDirectory();
|
|
1563
|
+
else {
|
|
1564
|
+
const mode = Number(stat.mode ?? 0);
|
|
1565
|
+
isDir2 = mode > 0 && (mode & 61440) === 16384;
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
} catch {
|
|
1569
|
+
isDir2 = false;
|
|
1570
|
+
}
|
|
1571
|
+
if (!isDir2) {
|
|
1431
1572
|
try {
|
|
1432
|
-
|
|
1573
|
+
await fs.readdir(targetPath);
|
|
1574
|
+
isDir2 = true;
|
|
1433
1575
|
} catch {
|
|
1434
|
-
|
|
1576
|
+
isDir2 = false;
|
|
1435
1577
|
}
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
}
|
|
1449
|
-
result.scanned++;
|
|
1450
|
-
if (!isKeepFile(entry)) continue;
|
|
1451
|
-
if (dryRun) {
|
|
1452
|
-
result.removed.push(fullPath);
|
|
1453
|
-
continue;
|
|
1454
|
-
}
|
|
1455
|
-
try {
|
|
1456
|
-
await fs.unlink(fullPath);
|
|
1457
|
-
result.removed.push(fullPath);
|
|
1458
|
-
} catch {
|
|
1459
|
-
result.failed.push(fullPath);
|
|
1460
|
-
}
|
|
1578
|
+
}
|
|
1579
|
+
if (!isDir2) {
|
|
1580
|
+
try {
|
|
1581
|
+
await fs.unlink(targetPath);
|
|
1582
|
+
} catch {
|
|
1583
|
+
}
|
|
1584
|
+
return;
|
|
1585
|
+
}
|
|
1586
|
+
for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
|
|
1587
|
+
try {
|
|
1588
|
+
await fs.unlink(placeholder);
|
|
1589
|
+
} catch {
|
|
1461
1590
|
}
|
|
1462
1591
|
}
|
|
1463
|
-
|
|
1464
|
-
}
|
|
1465
|
-
|
|
1466
|
-
// src/version-migration.ts
|
|
1467
|
-
var S_IFDIR3 = 16384;
|
|
1468
|
-
function isDir(stat) {
|
|
1469
|
-
return typeof stat.mode === "number" && (stat.mode & S_IFDIR3) === S_IFDIR3;
|
|
1470
|
-
}
|
|
1471
|
-
function joinPath3(dir, entry) {
|
|
1472
|
-
if (dir === "/" || dir === "") return `/${entry}`;
|
|
1473
|
-
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
1474
|
-
}
|
|
1475
|
-
async function existsPath(fs, p) {
|
|
1592
|
+
let children = [];
|
|
1476
1593
|
try {
|
|
1477
|
-
await fs.
|
|
1478
|
-
return true;
|
|
1594
|
+
children = await fs.readdir(targetPath);
|
|
1479
1595
|
} catch {
|
|
1480
|
-
|
|
1596
|
+
}
|
|
1597
|
+
for (const child of children) await purgeTombstonedTree(fs, `${targetPath}/${child}`);
|
|
1598
|
+
try {
|
|
1599
|
+
if (typeof fs.rmdir === "function") await fs.rmdir(targetPath);
|
|
1600
|
+
else await fs.unlink(targetPath);
|
|
1601
|
+
} catch {
|
|
1602
|
+
try {
|
|
1603
|
+
await fs.unlink(targetPath);
|
|
1604
|
+
} catch {
|
|
1605
|
+
}
|
|
1481
1606
|
}
|
|
1482
1607
|
}
|
|
1483
|
-
function configNameFromLegacy(entry) {
|
|
1484
|
-
const noMtime = entry.endsWith(".version.mtime") ? entry.slice(0, -".version.mtime".length) : entry.slice(0, -".version".length);
|
|
1485
|
-
return noMtime.slice(1);
|
|
1486
|
-
}
|
|
1487
|
-
async function resolveTarget(fs, dir, entry) {
|
|
1488
|
-
const configName = configNameFromLegacy(entry);
|
|
1489
|
-
const configPath = joinPath3(dir, configName);
|
|
1490
|
-
const dotConfigPath = joinPath3(dir, `.${configName}`);
|
|
1491
|
-
if (await existsPath(fs, dotConfigPath)) {
|
|
1492
|
-
return { action: "skip" };
|
|
1493
|
-
}
|
|
1494
|
-
if (await existsPath(fs, configPath)) {
|
|
1495
|
-
return { action: "rename", newPath: versionPathFor(configPath) ?? `${configName}.version` };
|
|
1496
|
-
}
|
|
1497
|
-
return { action: "delete" };
|
|
1498
|
-
}
|
|
1499
|
-
async function migrateVersionSidecars(fs, options = {}) {
|
|
1500
|
-
const root = options.root && options.root !== "" ? options.root : "/";
|
|
1501
|
-
const dryRun = options.dryRun ?? false;
|
|
1502
|
-
const replicas = options.replicas ?? [];
|
|
1503
|
-
const result = {
|
|
1504
|
-
renamed: [],
|
|
1505
|
-
deleted: [],
|
|
1506
|
-
remoteDeleted: [],
|
|
1507
|
-
failed: []
|
|
1508
|
-
};
|
|
1509
|
-
const stack = [root];
|
|
1510
|
-
while (stack.length > 0) {
|
|
1511
|
-
const dir = stack.pop();
|
|
1512
|
-
let entries;
|
|
1513
|
-
try {
|
|
1514
|
-
entries = await fs.readdir(dir);
|
|
1515
|
-
} catch {
|
|
1516
|
-
continue;
|
|
1517
|
-
}
|
|
1518
|
-
for (const entry of entries) {
|
|
1519
|
-
const full = joinPath3(dir, entry);
|
|
1520
|
-
let stat;
|
|
1521
|
-
try {
|
|
1522
|
-
stat = await fs.stat(full);
|
|
1523
|
-
} catch {
|
|
1524
|
-
continue;
|
|
1525
|
-
}
|
|
1526
|
-
if (isDir(stat)) {
|
|
1527
|
-
stack.push(full);
|
|
1528
|
-
continue;
|
|
1529
|
-
}
|
|
1530
|
-
const isLegacyVersion = entry.startsWith(".") && (entry.endsWith(".version") || entry.endsWith(".version.mtime"));
|
|
1531
|
-
if (!isLegacyVersion) continue;
|
|
1532
|
-
const legacyVerPath = entry.endsWith(".version.mtime") ? full.slice(0, -".mtime".length) : full;
|
|
1533
|
-
const target = await resolveTarget(fs, dir, entry);
|
|
1534
|
-
if (target.action === "skip") continue;
|
|
1535
|
-
const legacyMtimePath = `${legacyVerPath}.mtime`;
|
|
1536
|
-
const newMtimePath = target.newPath ? `${target.newPath}.mtime` : null;
|
|
1537
|
-
if (dryRun) {
|
|
1538
|
-
if (target.action === "rename") result.renamed.push(full);
|
|
1539
|
-
else result.deleted.push(full);
|
|
1540
|
-
continue;
|
|
1541
|
-
}
|
|
1542
|
-
try {
|
|
1543
|
-
if (target.action === "rename") {
|
|
1544
|
-
if (await existsPath(fs, target.newPath)) {
|
|
1545
|
-
await fs.unlink(legacyVerPath);
|
|
1546
|
-
result.deleted.push(full);
|
|
1547
|
-
} else {
|
|
1548
|
-
const content = await fs.readFile(legacyVerPath);
|
|
1549
|
-
const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
|
|
1550
|
-
await fs.writeFile(target.newPath, bytes);
|
|
1551
|
-
await fs.unlink(legacyVerPath);
|
|
1552
|
-
result.renamed.push(full);
|
|
1553
|
-
}
|
|
1554
|
-
if (newMtimePath && await existsPath(fs, legacyMtimePath)) {
|
|
1555
|
-
try {
|
|
1556
|
-
const mc = await fs.readFile(legacyMtimePath);
|
|
1557
|
-
const mb = typeof mc === "string" ? new TextEncoder().encode(mc) : mc;
|
|
1558
|
-
await fs.writeFile(newMtimePath, mb);
|
|
1559
|
-
await fs.unlink(legacyMtimePath);
|
|
1560
|
-
} catch {
|
|
1561
|
-
}
|
|
1562
|
-
}
|
|
1563
|
-
} else {
|
|
1564
|
-
await fs.unlink(legacyVerPath);
|
|
1565
|
-
result.deleted.push(full);
|
|
1566
|
-
if (await existsPath(fs, legacyMtimePath)) {
|
|
1567
|
-
try {
|
|
1568
|
-
await fs.unlink(legacyMtimePath);
|
|
1569
|
-
} catch {
|
|
1570
|
-
}
|
|
1571
|
-
}
|
|
1572
|
-
}
|
|
1573
|
-
} catch (e) {
|
|
1574
|
-
result.failed.push(full);
|
|
1575
|
-
continue;
|
|
1576
|
-
}
|
|
1577
|
-
for (const rep of replicas) {
|
|
1578
|
-
for (const rp of [legacyVerPath, legacyMtimePath]) {
|
|
1579
|
-
try {
|
|
1580
|
-
await rep.unlink(rp);
|
|
1581
|
-
result.remoteDeleted.push(rp);
|
|
1582
|
-
} catch {
|
|
1583
|
-
}
|
|
1584
|
-
}
|
|
1585
|
-
}
|
|
1586
|
-
}
|
|
1587
|
-
}
|
|
1588
|
-
return result;
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
// src/group-meta.ts
|
|
1592
|
-
var import_localstorage_logger2 = require("@richard432/localstorage-logger");
|
|
1593
|
-
|
|
1594
|
-
// src/canonical-json.ts
|
|
1595
|
-
var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
|
|
1596
|
-
var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "name", "features"];
|
|
1597
|
-
var APP_DATA_GROUP_ORDER = ["id", "groupType", "name", "features", "backends"];
|
|
1598
|
-
var BACKEND_ORDER = ["id", "type", "options", "accountBackendId", "description", "createdAt"];
|
|
1599
|
-
function compareKeys(a, b) {
|
|
1600
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
1601
|
-
}
|
|
1602
|
-
function isPlainObject(value) {
|
|
1603
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1604
|
-
}
|
|
1605
|
-
function canonicalObject(value, order = []) {
|
|
1606
|
-
const out = {};
|
|
1607
|
-
for (const key of order) {
|
|
1608
|
-
if (value[key] !== void 0) out[key] = canonicalField(key, value[key]);
|
|
1609
|
-
}
|
|
1610
|
-
for (const key of Object.keys(value).sort(compareKeys)) {
|
|
1611
|
-
if (order.includes(key) || value[key] === void 0) continue;
|
|
1612
|
-
out[key] = canonicalField(key, value[key]);
|
|
1613
|
-
}
|
|
1614
|
-
return out;
|
|
1615
|
-
}
|
|
1616
|
-
function canonicalField(key, value) {
|
|
1617
|
-
if (Array.isArray(value)) {
|
|
1618
|
-
if (key === "backends") {
|
|
1619
|
-
return value.map((item) => isPlainObject(item) ? canonicalObject(item, BACKEND_ORDER) : item).sort(
|
|
1620
|
-
(a, b) => compareKeys(String(a?.id ?? ""), String(b?.id ?? ""))
|
|
1621
|
-
);
|
|
1622
|
-
}
|
|
1623
|
-
return value.map((item) => canonicalField("", item));
|
|
1624
|
-
}
|
|
1625
|
-
if (isPlainObject(value)) {
|
|
1626
|
-
if (key === "features") return canonicalObject(value, FEATURE_ORDER);
|
|
1627
|
-
return canonicalObject(value);
|
|
1628
|
-
}
|
|
1629
|
-
return value;
|
|
1630
|
-
}
|
|
1631
|
-
function stringify(value) {
|
|
1632
|
-
return JSON.stringify(value, null, 2);
|
|
1633
|
-
}
|
|
1634
|
-
function serializeGroupDescriptor(descriptor) {
|
|
1635
|
-
const { updatedAt: _ignored, ...rest } = descriptor;
|
|
1636
|
-
return stringify(canonicalObject(rest, GROUP_DESCRIPTOR_ORDER));
|
|
1637
|
-
}
|
|
1638
|
-
function serializeBackendDescriptor(descriptor) {
|
|
1639
|
-
return stringify(canonicalObject(descriptor, BACKEND_ORDER));
|
|
1640
|
-
}
|
|
1641
|
-
function serializeAppDataGroupDescriptor(descriptor) {
|
|
1642
|
-
return stringify(canonicalObject(descriptor, APP_DATA_GROUP_ORDER));
|
|
1643
|
-
}
|
|
1644
|
-
function stripBackendCreatedAt(descriptor) {
|
|
1645
|
-
const { createdAt: _ignored, ...rest } = descriptor;
|
|
1646
|
-
return rest;
|
|
1647
|
-
}
|
|
1648
|
-
function mergeBackendDescriptor(existing, incoming) {
|
|
1649
|
-
const existingCreatedAt = typeof existing?.createdAt === "number" ? existing.createdAt : void 0;
|
|
1650
|
-
const incomingCreatedAt = typeof incoming.createdAt === "number" ? incoming.createdAt : void 0;
|
|
1651
|
-
const createdAt = existingCreatedAt === void 0 ? incomingCreatedAt : incomingCreatedAt === void 0 ? existingCreatedAt : Math.min(existingCreatedAt, incomingCreatedAt);
|
|
1652
|
-
return createdAt === void 0 ? stripBackendCreatedAt(incoming) : { ...incoming, createdAt };
|
|
1653
|
-
}
|
|
1654
|
-
function mergeBackendCreatedAt(incoming, existing) {
|
|
1655
|
-
if (!existing || existing.length === 0) return incoming;
|
|
1656
|
-
const byId = new Map(existing.map((d) => [d.id, d]));
|
|
1657
|
-
return incoming.map((desc) => mergeBackendDescriptor(byId.get(desc.id), desc));
|
|
1658
|
-
}
|
|
1659
|
-
function mergeDescriptorCreatedAt(descriptor, existing) {
|
|
1660
|
-
return {
|
|
1661
|
-
...descriptor,
|
|
1662
|
-
backends: mergeBackendCreatedAt(descriptor.backends, existing?.backends)
|
|
1663
|
-
};
|
|
1664
|
-
}
|
|
1665
|
-
|
|
1666
|
-
// src/group-meta.ts
|
|
1667
|
-
var log2 = (0, import_localstorage_logger2.createLogger)("zen-fs-config:tombstones");
|
|
1668
|
-
var META_DIR = "/.meta";
|
|
1669
|
-
var GROUP_DESCRIPTOR_FILE = `${META_DIR}/group.json`;
|
|
1670
|
-
var META_BACKENDS_DIR = `${META_DIR}/backends`;
|
|
1671
|
-
var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
|
|
1672
1608
|
var LEGACY_TOMBSTONES_DIR = `${META_DIR}/.deleted`;
|
|
1673
1609
|
var VERSIONS_DIR = `${META_DIR}/versions`;
|
|
1674
1610
|
var CONFLICTS_DIR = `${META_DIR}/conflicts`;
|
|
@@ -1731,6 +1667,9 @@ async function existsSafe(fs, path) {
|
|
|
1731
1667
|
function isMtimeSidecarPath(path) {
|
|
1732
1668
|
return path.endsWith(".mtime");
|
|
1733
1669
|
}
|
|
1670
|
+
function isHiddenPlaceholderPath(path) {
|
|
1671
|
+
return isMtimeSidecarPath(path) || path === "/.keep" || path.endsWith("/.keep");
|
|
1672
|
+
}
|
|
1734
1673
|
function encodeMetaPath(filePath) {
|
|
1735
1674
|
const normalized = filePath.startsWith("/") ? filePath : `/${filePath}`;
|
|
1736
1675
|
return normalized.replace(/^\//, "").replace(/\//g, "__").replace(/\./g, "++");
|
|
@@ -1749,15 +1688,21 @@ function normalizeTombstoneRecord(value, fallbackPath) {
|
|
|
1749
1688
|
const record = value;
|
|
1750
1689
|
const rawPath = typeof record.path === "string" ? record.path : fallbackPath;
|
|
1751
1690
|
if (!rawPath) return null;
|
|
1752
|
-
const path = rawPath
|
|
1691
|
+
const path = normalizeTombstonePath(rawPath);
|
|
1753
1692
|
const confirmedBy = Array.isArray(record.confirmedBy) ? record.confirmedBy.filter((id) => typeof id === "string") : [];
|
|
1693
|
+
const type = record.type === "directory" ? "directory" : record.type === "file" ? "file" : void 0;
|
|
1754
1694
|
return {
|
|
1755
1695
|
path,
|
|
1756
1696
|
deletedAt: typeof record.deletedAt === "number" ? record.deletedAt : 0,
|
|
1757
1697
|
deletedBy: typeof record.deletedBy === "string" ? record.deletedBy : "unknown",
|
|
1758
|
-
confirmedBy
|
|
1698
|
+
confirmedBy,
|
|
1699
|
+
...type ? { type } : {}
|
|
1759
1700
|
};
|
|
1760
1701
|
}
|
|
1702
|
+
function normalizeTombstonePath(rawPath) {
|
|
1703
|
+
const withLeading = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
|
|
1704
|
+
return withLeading.length > 1 ? withLeading.replace(/\/+$/, "") || "/" : withLeading;
|
|
1705
|
+
}
|
|
1761
1706
|
function extractJsonObjects(raw) {
|
|
1762
1707
|
const objects = [];
|
|
1763
1708
|
let depth = 0;
|
|
@@ -1838,6 +1783,7 @@ function mergeTombstone(byPath, tombstone) {
|
|
|
1838
1783
|
for (const id of tombstone.confirmedBy) {
|
|
1839
1784
|
if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
|
|
1840
1785
|
}
|
|
1786
|
+
if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) prev.type = "directory";
|
|
1841
1787
|
}
|
|
1842
1788
|
async function readTombstonesFromFs(fs, warn) {
|
|
1843
1789
|
const byPath = /* @__PURE__ */ new Map();
|
|
@@ -1872,16 +1818,16 @@ async function readTombstonesFromFs(fs, warn) {
|
|
|
1872
1818
|
return Array.from(byPath.values());
|
|
1873
1819
|
}
|
|
1874
1820
|
async function readGroupDescriptor(fs) {
|
|
1875
|
-
const parsed = await readJson(fs,
|
|
1821
|
+
const parsed = await readJson(fs, GROUP_DESCRIPTOR_FILE2);
|
|
1876
1822
|
if (!parsed) return null;
|
|
1877
1823
|
const { updatedAt: _ignored, ...rest } = parsed;
|
|
1878
1824
|
return rest;
|
|
1879
1825
|
}
|
|
1880
1826
|
async function writeGroupDescriptor(fs, descriptor) {
|
|
1881
1827
|
const bytes = serializeGroupDescriptor(descriptor);
|
|
1882
|
-
if (await readText(fs,
|
|
1883
|
-
await ensureParentDir2(fs,
|
|
1884
|
-
await fs.writeFile(
|
|
1828
|
+
if (await readText(fs, GROUP_DESCRIPTOR_FILE2) === bytes) return;
|
|
1829
|
+
await ensureParentDir2(fs, GROUP_DESCRIPTOR_FILE2);
|
|
1830
|
+
await fs.writeFile(GROUP_DESCRIPTOR_FILE2, new TextEncoder().encode(bytes));
|
|
1885
1831
|
}
|
|
1886
1832
|
function assertValidBackendId(id) {
|
|
1887
1833
|
if (typeof id !== "string" || id.trim() === "") {
|
|
@@ -1943,23 +1889,31 @@ var TombstoneStore = class {
|
|
|
1943
1889
|
}
|
|
1944
1890
|
fs;
|
|
1945
1891
|
author;
|
|
1892
|
+
/**
|
|
1893
|
+
* 本轮 `process()` 真正核对过"确实不存在"的(路径 → 目标 id)。
|
|
1894
|
+
*
|
|
1895
|
+
* 只有出现在这里的副本才会被写进 `confirmedBy`(见 {@link confirm}),与
|
|
1896
|
+
* 配置组 `ConfigRepo.updateTombstoneConfirmations` 的保守语义一致:副本删除
|
|
1897
|
+
* 失败(网络、后端限制、只剩占位目录)时绝不算已确认。
|
|
1898
|
+
*/
|
|
1899
|
+
verifiedAbsent = /* @__PURE__ */ new Map();
|
|
1946
1900
|
pathFor(filePath) {
|
|
1947
1901
|
return `${TOMBSTONES_DIR}/${encodeMetaPath(filePath)}.json`;
|
|
1948
1902
|
}
|
|
1949
1903
|
/** All tombstones. */
|
|
1950
1904
|
async list() {
|
|
1951
|
-
return readTombstonesFromFs(this.fs, (message) =>
|
|
1905
|
+
return readTombstonesFromFs(this.fs, (message) => log3.warn(message));
|
|
1952
1906
|
}
|
|
1953
1907
|
/** Write a tombstone. */
|
|
1954
1908
|
async write(tombstone) {
|
|
1955
|
-
const bytes = new TextEncoder().encode(
|
|
1909
|
+
const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
|
|
1956
1910
|
const p = this.pathFor(tombstone.path);
|
|
1957
1911
|
await ensureParentDir2(this.fs, p);
|
|
1958
1912
|
await this.fs.writeFile(p, bytes);
|
|
1959
1913
|
}
|
|
1960
1914
|
/** Persist an updated tombstone (confirmations) when it still exists. */
|
|
1961
1915
|
async save(tombstone) {
|
|
1962
|
-
const bytes = new TextEncoder().encode(
|
|
1916
|
+
const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
|
|
1963
1917
|
const p = this.pathFor(tombstone.path);
|
|
1964
1918
|
if (!await existsSafe(this.fs, p)) return;
|
|
1965
1919
|
await this.fs.writeFile(p, bytes);
|
|
@@ -1976,34 +1930,121 @@ var TombstoneStore = class {
|
|
|
1976
1930
|
/**
|
|
1977
1931
|
* Delete every tombstoned file (and its version record) on the local store
|
|
1978
1932
|
* and on each target backend, so bi-directional sync cannot resurrect it.
|
|
1933
|
+
*
|
|
1934
|
+
* 墓碑只对「删除之后没有再写入」的路径有效。同步类工具会不断重建某些文件
|
|
1935
|
+
* (最典型的是 `.sync.lock`:每轮删除 → 重建),若墓碑永久生效,路径会被每一
|
|
1936
|
+
* 轮 preSync 删掉,表现为「刚写完 1 秒就消失、锁永远拿不到」。因此这里先判定
|
|
1937
|
+
* 目标路径是否在 `deletedAt` 之后被重新写入:是则墓碑已被用户写操作撤销,保留
|
|
1938
|
+
* 文件并删除墓碑;否则按删除传播处理。
|
|
1979
1939
|
*/
|
|
1980
1940
|
async process(targets = []) {
|
|
1981
1941
|
const tombstones = await this.list();
|
|
1942
|
+
const expired = [];
|
|
1943
|
+
this.verifiedAbsent.clear();
|
|
1982
1944
|
for (const tombstone of tombstones) {
|
|
1983
|
-
await this.
|
|
1945
|
+
if (await this.wasRecreatedAfterDeletion(tombstone)) {
|
|
1946
|
+
expired.push(tombstone);
|
|
1947
|
+
continue;
|
|
1948
|
+
}
|
|
1949
|
+
await this.deleteEverywhere(this.fs, tombstone);
|
|
1984
1950
|
for (const target of targets) {
|
|
1985
|
-
await this.deleteEverywhere(target.fs, tombstone
|
|
1951
|
+
await this.deleteEverywhere(target.fs, tombstone);
|
|
1986
1952
|
}
|
|
1953
|
+
for (const target of targets) {
|
|
1954
|
+
if (await this.absentOnTarget(target.fs, tombstone)) {
|
|
1955
|
+
this.markVerified(tombstone.path, target.id);
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
for (const tombstone of expired) {
|
|
1960
|
+
await this.remove(tombstone);
|
|
1961
|
+
log3.log(
|
|
1962
|
+
`[TombstoneStore] expired tombstone for ${tombstone.path} \u2014 recreated after deletion`
|
|
1963
|
+
);
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
markVerified(path, targetId) {
|
|
1967
|
+
let ids = this.verifiedAbsent.get(path);
|
|
1968
|
+
if (!ids) {
|
|
1969
|
+
ids = /* @__PURE__ */ new Set();
|
|
1970
|
+
this.verifiedAbsent.set(path, ids);
|
|
1987
1971
|
}
|
|
1972
|
+
ids.add(targetId);
|
|
1988
1973
|
}
|
|
1989
|
-
|
|
1990
|
-
|
|
1974
|
+
/**
|
|
1975
|
+
* 目标上该路径当前是否确实不存在。
|
|
1976
|
+
*
|
|
1977
|
+
* `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),这类
|
|
1978
|
+
* 路径只能相信本轮 unlink 没有报错,因此按"不可见即可信"处理(与配置组的
|
|
1979
|
+
* `allReplicasConfirmAbsent` 一致)。
|
|
1980
|
+
*/
|
|
1981
|
+
async absentOnTarget(fs, tombstone) {
|
|
1982
|
+
if (!isDirectoryTombstone(tombstone) && isHiddenPlaceholderPath(tombstone.path)) {
|
|
1983
|
+
return true;
|
|
1984
|
+
}
|
|
1991
1985
|
try {
|
|
1992
|
-
await fs.
|
|
1986
|
+
const stat = await fs.stat?.(tombstone.path);
|
|
1987
|
+
if (stat) return false;
|
|
1993
1988
|
} catch {
|
|
1994
1989
|
}
|
|
1990
|
+
try {
|
|
1991
|
+
if (typeof fs.exists === "function") return !await fs.exists(tombstone.path);
|
|
1992
|
+
} catch {
|
|
1993
|
+
}
|
|
1994
|
+
return true;
|
|
1995
1995
|
}
|
|
1996
|
-
/**
|
|
1997
|
-
|
|
1996
|
+
/**
|
|
1997
|
+
* 本地存储上该路径的 mtime 是否晚于墓碑的删除时刻。
|
|
1998
|
+
*
|
|
1999
|
+
* 只看本地主存储:副本上的同路径文件可能只是「删除之前的旧副本」,它的 mtime
|
|
2000
|
+
* 本来就旧,用副本判定既不可靠又会掩盖真正的删除传播。
|
|
2001
|
+
*/
|
|
2002
|
+
async wasRecreatedAfterDeletion(tombstone) {
|
|
2003
|
+
const mtimeMs = await this.mtimeOf(this.fs, tombstone.path);
|
|
2004
|
+
if (mtimeMs === null) return false;
|
|
2005
|
+
return mtimeMs > tombstone.deletedAt + RECREATE_AFTER_DELETE_SKEW_MS;
|
|
2006
|
+
}
|
|
2007
|
+
async mtimeOf(fs, filePath) {
|
|
2008
|
+
try {
|
|
2009
|
+
const stat = await fs.stat?.(filePath);
|
|
2010
|
+
const mtimeMs = Number(stat?.mtimeMs);
|
|
2011
|
+
return Number.isFinite(mtimeMs) ? mtimeMs : null;
|
|
2012
|
+
} catch {
|
|
2013
|
+
return null;
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
async deleteEverywhere(fs, tombstone) {
|
|
2017
|
+
if (isDirectoryTombstone(tombstone)) {
|
|
2018
|
+
await purgeTombstonedTree(fs, tombstone.path);
|
|
2019
|
+
return;
|
|
2020
|
+
}
|
|
2021
|
+
if (!isMtimeSidecarPath(tombstone.path) && !await existsSafe(fs, tombstone.path)) return;
|
|
2022
|
+
try {
|
|
2023
|
+
await fs.unlink(tombstone.path);
|
|
2024
|
+
} catch {
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
/**
|
|
2028
|
+
* 把本轮真正核对过"确实不存在"的目标写进墓碑的 `confirmedBy`。
|
|
2029
|
+
*
|
|
2030
|
+
* 旧实现把传入的后端 id 无条件写入,等于"跑过一轮就算所有副本都清干净了";
|
|
2031
|
+
* 副本删除失败时墓碑仍会被 GC,下一轮同步再把残留拉回本地。现在只确认
|
|
2032
|
+
* {@link process} 中现场核对通过的目标(与配置组语义一致),并支持只传 id
|
|
2033
|
+
* 的旧调用方式(此时沿用同一份核对结果)。
|
|
2034
|
+
*/
|
|
2035
|
+
async confirm(targets) {
|
|
2036
|
+
const isTargetList = (value) => value.length > 0 && typeof value[0] === "object";
|
|
2037
|
+
const ids = isTargetList(targets) ? targets.map((t) => t.id) : targets;
|
|
1998
2038
|
const tombstones = await this.list();
|
|
1999
2039
|
let modified = 0;
|
|
2000
2040
|
for (const tombstone of tombstones) {
|
|
2041
|
+
const verified = this.verifiedAbsent.get(tombstone.path);
|
|
2001
2042
|
let changed = false;
|
|
2002
|
-
for (const id of
|
|
2003
|
-
if (
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2043
|
+
for (const id of ids) {
|
|
2044
|
+
if (tombstone.confirmedBy.includes(id)) continue;
|
|
2045
|
+
if (!verified?.has(id)) continue;
|
|
2046
|
+
tombstone.confirmedBy.push(id);
|
|
2047
|
+
changed = true;
|
|
2007
2048
|
}
|
|
2008
2049
|
if (!changed) continue;
|
|
2009
2050
|
try {
|
|
@@ -2018,8 +2059,17 @@ var TombstoneStore = class {
|
|
|
2018
2059
|
async gc(allBackendIds, targets = []) {
|
|
2019
2060
|
const tombstones = await this.list();
|
|
2020
2061
|
for (const tombstone of tombstones) {
|
|
2062
|
+
if (!isTombstoneRetentionElapsed(tombstone)) continue;
|
|
2021
2063
|
const allConfirmed = allBackendIds.every((id) => tombstone.confirmedBy.includes(id));
|
|
2022
2064
|
if (!allConfirmed) continue;
|
|
2065
|
+
let stillAbsent = true;
|
|
2066
|
+
for (const target of targets) {
|
|
2067
|
+
if (!await this.absentOnTarget(target.fs, tombstone)) {
|
|
2068
|
+
stillAbsent = false;
|
|
2069
|
+
break;
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
if (!stillAbsent) continue;
|
|
2023
2073
|
const p = this.pathFor(tombstone.path);
|
|
2024
2074
|
if (await existsSafe(this.fs, p)) {
|
|
2025
2075
|
try {
|
|
@@ -2125,52 +2175,362 @@ var ConflictStore = class {
|
|
|
2125
2175
|
} catch {
|
|
2126
2176
|
continue;
|
|
2127
2177
|
}
|
|
2128
|
-
for (const entry of entries) {
|
|
2129
|
-
if (seen.has(entry)) continue;
|
|
2130
|
-
const archive = await readJson(this.fs, `${dir}/${entry}/meta.json`);
|
|
2131
|
-
if (!archive) continue;
|
|
2132
|
-
seen.add(entry);
|
|
2133
|
-
archives.push(archive);
|
|
2134
|
-
}
|
|
2135
|
-
}
|
|
2136
|
-
return archives.sort((a, b) => a.timestamp - b.timestamp);
|
|
2137
|
-
}
|
|
2138
|
-
candidatesFor(conflictId) {
|
|
2139
|
-
const id = conflictId.replace(/\/meta\.json$/, "");
|
|
2140
|
-
return [`${CONFLICTS_DIR}/${id}`, `${LEGACY_CONFLICTS_DIR}/${id}`];
|
|
2141
|
-
}
|
|
2142
|
-
async readBackup(conflictId, fileType) {
|
|
2143
|
-
for (const dir of this.candidatesFor(conflictId)) {
|
|
2144
|
-
const p = `${dir}/${fileType}`;
|
|
2178
|
+
for (const entry of entries) {
|
|
2179
|
+
if (seen.has(entry)) continue;
|
|
2180
|
+
const archive = await readJson(this.fs, `${dir}/${entry}/meta.json`);
|
|
2181
|
+
if (!archive) continue;
|
|
2182
|
+
seen.add(entry);
|
|
2183
|
+
archives.push(archive);
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
return archives.sort((a, b) => a.timestamp - b.timestamp);
|
|
2187
|
+
}
|
|
2188
|
+
candidatesFor(conflictId) {
|
|
2189
|
+
const id = conflictId.replace(/\/meta\.json$/, "");
|
|
2190
|
+
return [`${CONFLICTS_DIR}/${id}`, `${LEGACY_CONFLICTS_DIR}/${id}`];
|
|
2191
|
+
}
|
|
2192
|
+
async readBackup(conflictId, fileType) {
|
|
2193
|
+
for (const dir of this.candidatesFor(conflictId)) {
|
|
2194
|
+
const p = `${dir}/${fileType}`;
|
|
2195
|
+
try {
|
|
2196
|
+
return new TextDecoder().decode(toBytes(await this.fs.readFile(p)));
|
|
2197
|
+
} catch {
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
throw new Error(`Conflict backup not found: ${conflictId}/${fileType}`);
|
|
2201
|
+
}
|
|
2202
|
+
/** Resolve a conflict with raw (already serialized) content. */
|
|
2203
|
+
async resolve(conflictId, mergedContent) {
|
|
2204
|
+
for (const dir of this.candidatesFor(conflictId)) {
|
|
2205
|
+
const metaPath = `${dir}/meta.json`;
|
|
2206
|
+
const archive = await readJson(this.fs, metaPath);
|
|
2207
|
+
if (!archive) continue;
|
|
2208
|
+
const bytes = typeof mergedContent === "string" ? new TextEncoder().encode(mergedContent) : mergedContent;
|
|
2209
|
+
await ensureParentDir2(this.fs, archive.conflictPath);
|
|
2210
|
+
await this.fs.writeFile(archive.conflictPath, bytes);
|
|
2211
|
+
await this.versions.record(archive.conflictPath, bytes);
|
|
2212
|
+
await this.fs.writeFile(`${dir}/resolved`, bytes);
|
|
2213
|
+
archive.resolvedBackupPath = "./resolved";
|
|
2214
|
+
await writeJson(this.fs, metaPath, archive);
|
|
2215
|
+
return;
|
|
2216
|
+
}
|
|
2217
|
+
throw new Error(`Failed to resolve conflict ${conflictId}: archive not found`);
|
|
2218
|
+
}
|
|
2219
|
+
};
|
|
2220
|
+
|
|
2221
|
+
// src/group-identity.ts
|
|
2222
|
+
var import_localstorage_logger4 = require("@richard432/localstorage-logger");
|
|
2223
|
+
var log4 = (0, import_localstorage_logger4.createLogger)("zen-fs-config:group-identity");
|
|
2224
|
+
var INSTANCE_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
2225
|
+
function newGroupInstanceId() {
|
|
2226
|
+
const cryptoObj = globalThis?.crypto;
|
|
2227
|
+
if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();
|
|
2228
|
+
const bytes = new Uint8Array(16);
|
|
2229
|
+
if (cryptoObj?.getRandomValues) {
|
|
2230
|
+
cryptoObj.getRandomValues(bytes);
|
|
2231
|
+
} else {
|
|
2232
|
+
for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
|
|
2233
|
+
}
|
|
2234
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
2235
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
2236
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
2237
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
2238
|
+
}
|
|
2239
|
+
function isValidGroupInstanceId(value) {
|
|
2240
|
+
return typeof value === "string" && INSTANCE_ID_RE.test(value.trim());
|
|
2241
|
+
}
|
|
2242
|
+
async function bindRemoteGroupIdentity(remoteFS, identity) {
|
|
2243
|
+
let remote = null;
|
|
2244
|
+
try {
|
|
2245
|
+
remote = await readGroupDescriptor(remoteFS);
|
|
2246
|
+
} catch (err) {
|
|
2247
|
+
log4.warn(`[GroupIdentity] failed to read remote ${identity.kind}/"${identity.id}" group.json:`, err);
|
|
2248
|
+
throw err;
|
|
2249
|
+
}
|
|
2250
|
+
const current = remote?.instanceId;
|
|
2251
|
+
if (isValidGroupInstanceId(current)) {
|
|
2252
|
+
if (current === identity.instanceId) return "match";
|
|
2253
|
+
log4.warn(
|
|
2254
|
+
`[GroupIdentity] backend belongs to another sync group (remote instanceId=${current}, this group=${identity.instanceId}, kind ${remote?.kind ?? "?"}/"${remote?.id ?? "?"}") \u2014 sync pair NOT created`
|
|
2255
|
+
);
|
|
2256
|
+
return "conflict";
|
|
2257
|
+
}
|
|
2258
|
+
const next = {
|
|
2259
|
+
schemaVersion: 2,
|
|
2260
|
+
kind: remote?.kind ?? identity.kind,
|
|
2261
|
+
id: remote?.id ?? identity.id,
|
|
2262
|
+
instanceId: identity.instanceId,
|
|
2263
|
+
...remote?.name ?? identity.name ? { name: remote?.name ?? identity.name } : {},
|
|
2264
|
+
...remote?.features ?? identity.features ? { features: remote?.features ?? identity.features } : {}
|
|
2265
|
+
};
|
|
2266
|
+
if (next.kind !== identity.kind) {
|
|
2267
|
+
log4.warn(
|
|
2268
|
+
`[GroupIdentity] remote kind "${next.kind}" \u2260 this group kind "${identity.kind}" \u2014 sync pair NOT created`
|
|
2269
|
+
);
|
|
2270
|
+
return "conflict";
|
|
2271
|
+
}
|
|
2272
|
+
try {
|
|
2273
|
+
await writeGroupDescriptor(remoteFS, next);
|
|
2274
|
+
} catch (err) {
|
|
2275
|
+
log4.warn(`[GroupIdentity] failed to claim remote root for "${identity.id}":`, err);
|
|
2276
|
+
return "conflict";
|
|
2277
|
+
}
|
|
2278
|
+
log4.log(
|
|
2279
|
+
`[GroupIdentity] claimed remote root for ${identity.kind}/"${identity.id}" (instanceId=${identity.instanceId})`
|
|
2280
|
+
);
|
|
2281
|
+
return "claimed";
|
|
2282
|
+
}
|
|
2283
|
+
function pickInstanceId(descriptor) {
|
|
2284
|
+
const value = descriptor?.instanceId;
|
|
2285
|
+
return isValidGroupInstanceId(value) ? value : void 0;
|
|
2286
|
+
}
|
|
2287
|
+
|
|
2288
|
+
// src/mtime-cleanup.ts
|
|
2289
|
+
function isMtimeSidecar(fileName) {
|
|
2290
|
+
return fileName.endsWith(".mtime");
|
|
2291
|
+
}
|
|
2292
|
+
var S_IFDIR = 16384;
|
|
2293
|
+
function isDirectory(stat) {
|
|
2294
|
+
return typeof stat.mode === "number" && (stat.mode & S_IFDIR) === S_IFDIR;
|
|
2295
|
+
}
|
|
2296
|
+
function joinPath(dir, entry) {
|
|
2297
|
+
if (dir === "/" || dir === "") return `/${entry}`;
|
|
2298
|
+
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
2299
|
+
}
|
|
2300
|
+
async function purgeMtimeSidecars(fs, options = {}) {
|
|
2301
|
+
const root = options.root && options.root !== "" ? options.root : "/";
|
|
2302
|
+
const dryRun = options.dryRun ?? false;
|
|
2303
|
+
const result = { scanned: 0, removed: [], failed: [] };
|
|
2304
|
+
const stack = [root];
|
|
2305
|
+
while (stack.length > 0) {
|
|
2306
|
+
const dir = stack.pop();
|
|
2307
|
+
let entries;
|
|
2308
|
+
try {
|
|
2309
|
+
entries = await fs.readdir(dir);
|
|
2310
|
+
} catch {
|
|
2311
|
+
continue;
|
|
2312
|
+
}
|
|
2313
|
+
for (const entry of entries) {
|
|
2314
|
+
const fullPath = joinPath(dir, entry);
|
|
2315
|
+
let stat;
|
|
2316
|
+
try {
|
|
2317
|
+
stat = await fs.stat(fullPath);
|
|
2318
|
+
} catch {
|
|
2319
|
+
continue;
|
|
2320
|
+
}
|
|
2321
|
+
if (isDirectory(stat)) {
|
|
2322
|
+
stack.push(fullPath);
|
|
2323
|
+
continue;
|
|
2324
|
+
}
|
|
2325
|
+
result.scanned++;
|
|
2326
|
+
if (!isMtimeSidecar(entry)) continue;
|
|
2327
|
+
if (dryRun) {
|
|
2328
|
+
result.removed.push(fullPath);
|
|
2329
|
+
continue;
|
|
2330
|
+
}
|
|
2331
|
+
try {
|
|
2332
|
+
await fs.unlink(fullPath);
|
|
2333
|
+
result.removed.push(fullPath);
|
|
2334
|
+
} catch {
|
|
2335
|
+
result.failed.push(fullPath);
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
return result;
|
|
2340
|
+
}
|
|
2341
|
+
|
|
2342
|
+
// src/keep-cleanup.ts
|
|
2343
|
+
function isKeepFile(fileName) {
|
|
2344
|
+
return fileName === ".keep";
|
|
2345
|
+
}
|
|
2346
|
+
var S_IFDIR2 = 16384;
|
|
2347
|
+
var DEFAULT_PROTECTED_DIRS = ["/.meta/backends/.keep"];
|
|
2348
|
+
function isDirectory2(stat) {
|
|
2349
|
+
return typeof stat.mode === "number" && (stat.mode & S_IFDIR2) === S_IFDIR2;
|
|
2350
|
+
}
|
|
2351
|
+
function joinPath2(dir, entry) {
|
|
2352
|
+
if (dir === "/" || dir === "") return `/${entry}`;
|
|
2353
|
+
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
2354
|
+
}
|
|
2355
|
+
function isProtected(fullPath, protectedDirs) {
|
|
2356
|
+
return protectedDirs.some((d) => {
|
|
2357
|
+
const dir = d.endsWith("/") ? d.slice(0, -1) : d;
|
|
2358
|
+
return fullPath === dir || fullPath.startsWith(dir + "/");
|
|
2359
|
+
});
|
|
2360
|
+
}
|
|
2361
|
+
async function purgeKeepFiles(fs, options = {}) {
|
|
2362
|
+
const root = options.root && options.root !== "" ? options.root : "/";
|
|
2363
|
+
const dryRun = options.dryRun ?? false;
|
|
2364
|
+
const protectedDirs = options.protectedDirs ?? DEFAULT_PROTECTED_DIRS;
|
|
2365
|
+
const result = { scanned: 0, removed: [], failed: [] };
|
|
2366
|
+
const stack = [root];
|
|
2367
|
+
while (stack.length > 0) {
|
|
2368
|
+
const dir = stack.pop();
|
|
2369
|
+
if (isProtected(dir, protectedDirs)) continue;
|
|
2370
|
+
let entries;
|
|
2371
|
+
try {
|
|
2372
|
+
entries = await fs.readdir(dir);
|
|
2373
|
+
} catch {
|
|
2374
|
+
continue;
|
|
2375
|
+
}
|
|
2376
|
+
for (const entry of entries) {
|
|
2377
|
+
const fullPath = joinPath2(dir, entry);
|
|
2378
|
+
if (isProtected(fullPath, protectedDirs)) continue;
|
|
2379
|
+
let stat;
|
|
2380
|
+
try {
|
|
2381
|
+
stat = await fs.stat(fullPath);
|
|
2382
|
+
} catch {
|
|
2383
|
+
continue;
|
|
2384
|
+
}
|
|
2385
|
+
if (isDirectory2(stat)) {
|
|
2386
|
+
stack.push(fullPath);
|
|
2387
|
+
continue;
|
|
2388
|
+
}
|
|
2389
|
+
result.scanned++;
|
|
2390
|
+
if (!isKeepFile(entry)) continue;
|
|
2391
|
+
if (dryRun) {
|
|
2392
|
+
result.removed.push(fullPath);
|
|
2393
|
+
continue;
|
|
2394
|
+
}
|
|
2395
|
+
try {
|
|
2396
|
+
await fs.unlink(fullPath);
|
|
2397
|
+
result.removed.push(fullPath);
|
|
2398
|
+
} catch {
|
|
2399
|
+
result.failed.push(fullPath);
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
return result;
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
// src/version-migration.ts
|
|
2407
|
+
var S_IFDIR3 = 16384;
|
|
2408
|
+
function isDir(stat) {
|
|
2409
|
+
return typeof stat.mode === "number" && (stat.mode & S_IFDIR3) === S_IFDIR3;
|
|
2410
|
+
}
|
|
2411
|
+
function joinPath3(dir, entry) {
|
|
2412
|
+
if (dir === "/" || dir === "") return `/${entry}`;
|
|
2413
|
+
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
2414
|
+
}
|
|
2415
|
+
async function existsPath(fs, p) {
|
|
2416
|
+
try {
|
|
2417
|
+
await fs.stat(p);
|
|
2418
|
+
return true;
|
|
2419
|
+
} catch {
|
|
2420
|
+
return false;
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
function configNameFromLegacy(entry) {
|
|
2424
|
+
const noMtime = entry.endsWith(".version.mtime") ? entry.slice(0, -".version.mtime".length) : entry.slice(0, -".version".length);
|
|
2425
|
+
return noMtime.slice(1);
|
|
2426
|
+
}
|
|
2427
|
+
async function resolveTarget(fs, dir, entry) {
|
|
2428
|
+
const configName = configNameFromLegacy(entry);
|
|
2429
|
+
const configPath = joinPath3(dir, configName);
|
|
2430
|
+
const dotConfigPath = joinPath3(dir, `.${configName}`);
|
|
2431
|
+
if (await existsPath(fs, dotConfigPath)) {
|
|
2432
|
+
return { action: "skip" };
|
|
2433
|
+
}
|
|
2434
|
+
if (await existsPath(fs, configPath)) {
|
|
2435
|
+
return { action: "rename", newPath: versionPathFor(configPath) ?? `${configName}.version` };
|
|
2436
|
+
}
|
|
2437
|
+
return { action: "delete" };
|
|
2438
|
+
}
|
|
2439
|
+
async function migrateVersionSidecars(fs, options = {}) {
|
|
2440
|
+
const root = options.root && options.root !== "" ? options.root : "/";
|
|
2441
|
+
const dryRun = options.dryRun ?? false;
|
|
2442
|
+
const replicas = options.replicas ?? [];
|
|
2443
|
+
const result = {
|
|
2444
|
+
renamed: [],
|
|
2445
|
+
deleted: [],
|
|
2446
|
+
remoteDeleted: [],
|
|
2447
|
+
failed: []
|
|
2448
|
+
};
|
|
2449
|
+
const stack = [root];
|
|
2450
|
+
while (stack.length > 0) {
|
|
2451
|
+
const dir = stack.pop();
|
|
2452
|
+
let entries;
|
|
2453
|
+
try {
|
|
2454
|
+
entries = await fs.readdir(dir);
|
|
2455
|
+
} catch {
|
|
2456
|
+
continue;
|
|
2457
|
+
}
|
|
2458
|
+
for (const entry of entries) {
|
|
2459
|
+
const full = joinPath3(dir, entry);
|
|
2460
|
+
let stat;
|
|
2461
|
+
try {
|
|
2462
|
+
stat = await fs.stat(full);
|
|
2463
|
+
} catch {
|
|
2464
|
+
continue;
|
|
2465
|
+
}
|
|
2466
|
+
if (isDir(stat)) {
|
|
2467
|
+
stack.push(full);
|
|
2468
|
+
continue;
|
|
2469
|
+
}
|
|
2470
|
+
const isLegacyVersion = entry.startsWith(".") && (entry.endsWith(".version") || entry.endsWith(".version.mtime"));
|
|
2471
|
+
if (!isLegacyVersion) continue;
|
|
2472
|
+
const legacyVerPath = entry.endsWith(".version.mtime") ? full.slice(0, -".mtime".length) : full;
|
|
2473
|
+
const target = await resolveTarget(fs, dir, entry);
|
|
2474
|
+
if (target.action === "skip") continue;
|
|
2475
|
+
const legacyMtimePath = `${legacyVerPath}.mtime`;
|
|
2476
|
+
const newMtimePath = target.newPath ? `${target.newPath}.mtime` : null;
|
|
2477
|
+
if (dryRun) {
|
|
2478
|
+
if (target.action === "rename") result.renamed.push(full);
|
|
2479
|
+
else result.deleted.push(full);
|
|
2480
|
+
continue;
|
|
2481
|
+
}
|
|
2145
2482
|
try {
|
|
2146
|
-
|
|
2147
|
-
|
|
2483
|
+
if (target.action === "rename") {
|
|
2484
|
+
if (await existsPath(fs, target.newPath)) {
|
|
2485
|
+
await fs.unlink(legacyVerPath);
|
|
2486
|
+
result.deleted.push(full);
|
|
2487
|
+
} else {
|
|
2488
|
+
const content = await fs.readFile(legacyVerPath);
|
|
2489
|
+
const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
|
|
2490
|
+
await fs.writeFile(target.newPath, bytes);
|
|
2491
|
+
await fs.unlink(legacyVerPath);
|
|
2492
|
+
result.renamed.push(full);
|
|
2493
|
+
}
|
|
2494
|
+
if (newMtimePath && await existsPath(fs, legacyMtimePath)) {
|
|
2495
|
+
try {
|
|
2496
|
+
const mc = await fs.readFile(legacyMtimePath);
|
|
2497
|
+
const mb = typeof mc === "string" ? new TextEncoder().encode(mc) : mc;
|
|
2498
|
+
await fs.writeFile(newMtimePath, mb);
|
|
2499
|
+
await fs.unlink(legacyMtimePath);
|
|
2500
|
+
} catch {
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
} else {
|
|
2504
|
+
await fs.unlink(legacyVerPath);
|
|
2505
|
+
result.deleted.push(full);
|
|
2506
|
+
if (await existsPath(fs, legacyMtimePath)) {
|
|
2507
|
+
try {
|
|
2508
|
+
await fs.unlink(legacyMtimePath);
|
|
2509
|
+
} catch {
|
|
2510
|
+
}
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
} catch (e) {
|
|
2514
|
+
result.failed.push(full);
|
|
2515
|
+
continue;
|
|
2516
|
+
}
|
|
2517
|
+
for (const rep of replicas) {
|
|
2518
|
+
for (const rp of [legacyVerPath, legacyMtimePath]) {
|
|
2519
|
+
try {
|
|
2520
|
+
await rep.unlink(rp);
|
|
2521
|
+
result.remoteDeleted.push(rp);
|
|
2522
|
+
} catch {
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2148
2525
|
}
|
|
2149
2526
|
}
|
|
2150
|
-
throw new Error(`Conflict backup not found: ${conflictId}/${fileType}`);
|
|
2151
|
-
}
|
|
2152
|
-
/** Resolve a conflict with raw (already serialized) content. */
|
|
2153
|
-
async resolve(conflictId, mergedContent) {
|
|
2154
|
-
for (const dir of this.candidatesFor(conflictId)) {
|
|
2155
|
-
const metaPath = `${dir}/meta.json`;
|
|
2156
|
-
const archive = await readJson(this.fs, metaPath);
|
|
2157
|
-
if (!archive) continue;
|
|
2158
|
-
const bytes = typeof mergedContent === "string" ? new TextEncoder().encode(mergedContent) : mergedContent;
|
|
2159
|
-
await ensureParentDir2(this.fs, archive.conflictPath);
|
|
2160
|
-
await this.fs.writeFile(archive.conflictPath, bytes);
|
|
2161
|
-
await this.versions.record(archive.conflictPath, bytes);
|
|
2162
|
-
await this.fs.writeFile(`${dir}/resolved`, bytes);
|
|
2163
|
-
archive.resolvedBackupPath = "./resolved";
|
|
2164
|
-
await writeJson(this.fs, metaPath, archive);
|
|
2165
|
-
return;
|
|
2166
|
-
}
|
|
2167
|
-
throw new Error(`Failed to resolve conflict ${conflictId}: archive not found`);
|
|
2168
2527
|
}
|
|
2169
|
-
|
|
2528
|
+
return result;
|
|
2529
|
+
}
|
|
2170
2530
|
|
|
2171
2531
|
// src/config-repo.ts
|
|
2172
|
-
var
|
|
2173
|
-
var
|
|
2532
|
+
var log5 = (0, import_localstorage_logger5.createLogger)("zen-fs-config:config-repo");
|
|
2533
|
+
var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
|
|
2174
2534
|
var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
|
|
2175
2535
|
var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
|
|
2176
2536
|
var BACKENDS_FILE = `${META_DIR}/backends.json`;
|
|
@@ -2202,81 +2562,6 @@ async function isDirectoryPath(fs, absolutePath) {
|
|
|
2202
2562
|
return false;
|
|
2203
2563
|
}
|
|
2204
2564
|
}
|
|
2205
|
-
async function collectFilesUnder(fs, dir, out = []) {
|
|
2206
|
-
const entries = await fs.readdir(dir);
|
|
2207
|
-
for (const entry of entries) {
|
|
2208
|
-
const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
|
|
2209
|
-
if (await isDirectoryPath(fs, child)) {
|
|
2210
|
-
await collectFilesUnder(fs, child, out);
|
|
2211
|
-
} else {
|
|
2212
|
-
out.push(child);
|
|
2213
|
-
}
|
|
2214
|
-
}
|
|
2215
|
-
return out;
|
|
2216
|
-
}
|
|
2217
|
-
async function collectDirectoriesUnder(fs, dir, out = []) {
|
|
2218
|
-
out.push(dir);
|
|
2219
|
-
let entries;
|
|
2220
|
-
try {
|
|
2221
|
-
entries = await fs.readdir(dir);
|
|
2222
|
-
} catch {
|
|
2223
|
-
return out;
|
|
2224
|
-
}
|
|
2225
|
-
for (const entry of entries) {
|
|
2226
|
-
const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
|
|
2227
|
-
if (await isDirectoryPath(fs, child)) await collectDirectoriesUnder(fs, child, out);
|
|
2228
|
-
}
|
|
2229
|
-
return out;
|
|
2230
|
-
}
|
|
2231
|
-
async function removeDirectoryTree(fs, dir) {
|
|
2232
|
-
let entries;
|
|
2233
|
-
try {
|
|
2234
|
-
entries = await fs.readdir(dir);
|
|
2235
|
-
} catch {
|
|
2236
|
-
return;
|
|
2237
|
-
}
|
|
2238
|
-
for (const entry of entries) {
|
|
2239
|
-
const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
|
|
2240
|
-
if (await isDirectoryPath(fs, child)) await removeDirectoryTree(fs, child);
|
|
2241
|
-
}
|
|
2242
|
-
try {
|
|
2243
|
-
await fs.rmdir?.(dir);
|
|
2244
|
-
} catch {
|
|
2245
|
-
}
|
|
2246
|
-
}
|
|
2247
|
-
async function collectFilesUnderAny(surfaces, dir, onError) {
|
|
2248
|
-
const merged = /* @__PURE__ */ new Set();
|
|
2249
|
-
for (const surface of surfaces) {
|
|
2250
|
-
try {
|
|
2251
|
-
for (const file of await collectFilesUnder(surface.fs, dir)) merged.add(file);
|
|
2252
|
-
} catch (error) {
|
|
2253
|
-
onError(surface.label, error);
|
|
2254
|
-
}
|
|
2255
|
-
}
|
|
2256
|
-
return [...merged];
|
|
2257
|
-
}
|
|
2258
|
-
async function collectDirectoriesUnderStrict(fs, dir, out = []) {
|
|
2259
|
-
out.push(dir);
|
|
2260
|
-
const entries = await fs.readdir(dir);
|
|
2261
|
-
for (const entry of entries) {
|
|
2262
|
-
const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
|
|
2263
|
-
if (await isDirectoryPath(fs, child)) await collectDirectoriesUnderStrict(fs, child, out);
|
|
2264
|
-
}
|
|
2265
|
-
return out;
|
|
2266
|
-
}
|
|
2267
|
-
async function collectDirectoriesUnderAny(surfaces, dir, onError) {
|
|
2268
|
-
const merged = /* @__PURE__ */ new Set();
|
|
2269
|
-
for (const surface of surfaces) {
|
|
2270
|
-
const found = [];
|
|
2271
|
-
try {
|
|
2272
|
-
await collectDirectoriesUnderStrict(surface.fs, dir, found);
|
|
2273
|
-
} catch (error) {
|
|
2274
|
-
onError(surface.label, error);
|
|
2275
|
-
}
|
|
2276
|
-
for (const child of found) merged.add(child);
|
|
2277
|
-
}
|
|
2278
|
-
return [...merged];
|
|
2279
|
-
}
|
|
2280
2565
|
async function isDirectoryAny(surfaces, path) {
|
|
2281
2566
|
for (const surface of surfaces) {
|
|
2282
2567
|
if (await isDirectoryPath(surface.fs, path)) return true;
|
|
@@ -2304,6 +2589,7 @@ function normalizeGroupName(value) {
|
|
|
2304
2589
|
}
|
|
2305
2590
|
var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
|
|
2306
2591
|
var LOCAL_IDB_BACKEND_ID = "local-idb";
|
|
2592
|
+
var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
|
|
2307
2593
|
function tombstoneFileName(filePath) {
|
|
2308
2594
|
return `${encodeMetaPath(filePath)}.json`;
|
|
2309
2595
|
}
|
|
@@ -2412,6 +2698,15 @@ var ConfigRepo = class {
|
|
|
2412
2698
|
tombstoneConfirmations = /* @__PURE__ */ new Map();
|
|
2413
2699
|
/** Per-backend sync state (successful pairs + connect failures). */
|
|
2414
2700
|
backendStates = /* @__PURE__ */ new Map();
|
|
2701
|
+
/**
|
|
2702
|
+
* 本组的实例身份(UUID,见 `group-identity.ts`)。
|
|
2703
|
+
*
|
|
2704
|
+
* 它同时是同步边界:连接任何远端副本前先比对对方 `.meta/group.json` 里的
|
|
2705
|
+
* `instanceId`,不一致就不建同步对 —— 两个不同的同步组永不互相同步。
|
|
2706
|
+
*/
|
|
2707
|
+
instanceId;
|
|
2708
|
+
/** 因归属他人而被跳过的后端 id → 原因,供 UI 展示。 */
|
|
2709
|
+
skippedBackends = /* @__PURE__ */ new Map();
|
|
2415
2710
|
/** Last known backend descriptors, for the synchronous unified handle API. */
|
|
2416
2711
|
backendDescriptorCache = [];
|
|
2417
2712
|
/**
|
|
@@ -2483,7 +2778,7 @@ var ConfigRepo = class {
|
|
|
2483
2778
|
const bytes = this.serializer.serialize(data, fullPath);
|
|
2484
2779
|
this.configCache.set(fullPath, data);
|
|
2485
2780
|
this.persistConfig(fullPath, bytes).catch((err) => {
|
|
2486
|
-
|
|
2781
|
+
log5.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
|
|
2487
2782
|
});
|
|
2488
2783
|
}
|
|
2489
2784
|
// -----------------------------------------------------------------------
|
|
@@ -2600,19 +2895,22 @@ var ConfigRepo = class {
|
|
|
2600
2895
|
// Tombstone (Deletion Tracking)
|
|
2601
2896
|
// -----------------------------------------------------------------------
|
|
2602
2897
|
/**
|
|
2603
|
-
* Write the tombstone record for `
|
|
2604
|
-
* Records only metadata — it never creates the deleted
|
|
2898
|
+
* Write the tombstone record for `path` under `.meta/tombstones/`.
|
|
2899
|
+
* Records only metadata — it never creates the deleted path locally, and the
|
|
2605
2900
|
* legacy `/.meta/.deleted/` archive is neither read nor written.
|
|
2901
|
+
*
|
|
2902
|
+
* `type: 'directory'` 表示这是一条目录墓碑:应用时按整棵树清理。
|
|
2606
2903
|
*/
|
|
2607
|
-
async writeTombstoneFor(
|
|
2608
|
-
const normalizedPath =
|
|
2904
|
+
async writeTombstoneFor(path, type) {
|
|
2905
|
+
const normalizedPath = normalizeTombstonePath(path);
|
|
2609
2906
|
const tombstone = {
|
|
2610
2907
|
path: normalizedPath,
|
|
2611
2908
|
deletedAt: Date.now(),
|
|
2612
2909
|
deletedBy: this.primaryBackendId,
|
|
2613
|
-
confirmedBy: [this.primaryBackendId]
|
|
2910
|
+
confirmedBy: [this.primaryBackendId],
|
|
2911
|
+
...type ? { type } : {}
|
|
2614
2912
|
};
|
|
2615
|
-
const tombstoneBytes = new TextEncoder().encode(
|
|
2913
|
+
const tombstoneBytes = new TextEncoder().encode(serializeTombstone(tombstone));
|
|
2616
2914
|
const tombstonePath = tombstonePathFor(normalizedPath, TOMBSTONES_DIR);
|
|
2617
2915
|
await this.ensureDir(tombstonePath);
|
|
2618
2916
|
await this.cachedFS.writeFile(tombstonePath, tombstoneBytes);
|
|
@@ -2623,29 +2921,17 @@ var ConfigRepo = class {
|
|
|
2623
2921
|
*/
|
|
2624
2922
|
async deleteFile(path) {
|
|
2625
2923
|
this.assertNotDisposed();
|
|
2626
|
-
const normalizedPath = path
|
|
2924
|
+
const normalizedPath = normalizeTombstonePath(path);
|
|
2627
2925
|
const surfaces = [{ label: "local-cache", fs: this.cachedFS }];
|
|
2628
2926
|
for (const [id, replica] of this.replicaBackends) {
|
|
2629
2927
|
surfaces.push({ label: id, fs: replica.instance });
|
|
2630
2928
|
}
|
|
2631
|
-
const onEnumerateError = (label, error) => {
|
|
2632
|
-
const reason = error?.message ?? String(error);
|
|
2633
|
-
log3.warn(
|
|
2634
|
-
`[ConfigRepo] deleteFile(directory): cannot enumerate "${label}" under ${normalizedPath}: ${reason}`
|
|
2635
|
-
);
|
|
2636
|
-
};
|
|
2637
2929
|
if (await isDirectoryAny(surfaces, normalizedPath)) {
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
for (const dir of await collectDirectoriesUnderAny(surfaces, normalizedPath, onEnumerateError)) {
|
|
2641
|
-
const keepPath = dir === "/" ? "/.keep" : `${dir}/.keep`;
|
|
2642
|
-
await this.writeTombstoneFor(keepPath);
|
|
2643
|
-
await this.writeTombstoneFor(`${keepPath}.mtime`);
|
|
2644
|
-
}
|
|
2645
|
-
await removeDirectoryTree(this.cachedFS, normalizedPath);
|
|
2930
|
+
await this.writeTombstoneFor(normalizedPath, "directory");
|
|
2931
|
+
await this.purgePathOnBackend(this.cachedFS, normalizedPath);
|
|
2646
2932
|
this.invalidateTombstoneCache();
|
|
2647
2933
|
this.schedulePostDeleteSync();
|
|
2648
|
-
|
|
2934
|
+
log5.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (single directory tombstone)`);
|
|
2649
2935
|
return;
|
|
2650
2936
|
}
|
|
2651
2937
|
await this.writeTombstoneFor(normalizedPath);
|
|
@@ -2666,7 +2952,7 @@ var ConfigRepo = class {
|
|
|
2666
2952
|
} catch {
|
|
2667
2953
|
}
|
|
2668
2954
|
}
|
|
2669
|
-
|
|
2955
|
+
log5.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
|
|
2670
2956
|
this.invalidateTombstoneCache();
|
|
2671
2957
|
this.schedulePostDeleteSync();
|
|
2672
2958
|
}
|
|
@@ -2684,7 +2970,7 @@ var ConfigRepo = class {
|
|
|
2684
2970
|
this.postDeleteSyncTimer = void 0;
|
|
2685
2971
|
if (this.disposed) return;
|
|
2686
2972
|
this.syncEngine.syncAll().catch((err) => {
|
|
2687
|
-
|
|
2973
|
+
log5.warn("[ConfigRepo] post-delete sync failed:", err);
|
|
2688
2974
|
});
|
|
2689
2975
|
}, 500);
|
|
2690
2976
|
}
|
|
@@ -2696,7 +2982,7 @@ var ConfigRepo = class {
|
|
|
2696
2982
|
if (this.tombstoneCache !== null) {
|
|
2697
2983
|
return this.tombstoneCache;
|
|
2698
2984
|
}
|
|
2699
|
-
this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) =>
|
|
2985
|
+
this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log5.warn(message));
|
|
2700
2986
|
this.refreshSyncExclusions(this.tombstoneCache);
|
|
2701
2987
|
return this.tombstoneCache;
|
|
2702
2988
|
}
|
|
@@ -2714,16 +3000,40 @@ var ConfigRepo = class {
|
|
|
2714
3000
|
for (const tombstone of tombstones) {
|
|
2715
3001
|
if (!tombstone.path) continue;
|
|
2716
3002
|
add(tombstone.path);
|
|
2717
|
-
if (tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep") || tombstone.path.endsWith("/.keep.mtime")) {
|
|
2718
|
-
const dir = tombstone.path.slice(0, tombstone.path.lastIndexOf("/")) || "/";
|
|
2719
|
-
if (dir !== "/") add(dir);
|
|
2720
|
-
}
|
|
2721
3003
|
}
|
|
2722
3004
|
}
|
|
2723
3005
|
/** Invalidate the tombstone cache — call after tombstones are modified. */
|
|
2724
3006
|
invalidateTombstoneCache() {
|
|
2725
3007
|
this.tombstoneCache = null;
|
|
2726
3008
|
}
|
|
3009
|
+
/**
|
|
3010
|
+
* 判定墓碑目标路径是否在删除之后被重新创建。
|
|
3011
|
+
*
|
|
3012
|
+
* 墓碑表达的是「删除意图」,但删除之后同一路径完全可能被再次写入。同步类工具
|
|
3013
|
+
* 的锁文件(`.sync.lock`)就是每轮「删除 → 重建」;若把墓碑当作永久否决权,
|
|
3014
|
+
* 这个路径会被每一轮 sync 反复删除,表现为「刚写进去 1 秒后就消失」、锁永远拿
|
|
3015
|
+
* 不到、深层目录刚建就没了。
|
|
3016
|
+
*
|
|
3017
|
+
* 判定依据是文件 mtime 晚于 `deletedAt`:写入必然刷新 mtime,因此 mtime 比删除
|
|
3018
|
+
* 时刻新就意味着这条墓碑已经被写操作撤销。
|
|
3019
|
+
*/
|
|
3020
|
+
async isPathRecreatedAfterTombstone(tombstone) {
|
|
3021
|
+
const surfaces = [{ label: "local-cache", fs: this.cachedFS }];
|
|
3022
|
+
for (const [id, replica] of this.replicaBackends) {
|
|
3023
|
+
surfaces.push({ label: id, fs: replica.instance });
|
|
3024
|
+
}
|
|
3025
|
+
for (const surface of surfaces) {
|
|
3026
|
+
let mtimeMs;
|
|
3027
|
+
try {
|
|
3028
|
+
const inode = await surface.fs.stat(tombstone.path);
|
|
3029
|
+
mtimeMs = Number(inode?.mtimeMs ?? 0);
|
|
3030
|
+
} catch {
|
|
3031
|
+
continue;
|
|
3032
|
+
}
|
|
3033
|
+
if (mtimeMs > tombstone.deletedAt + TOMBSTONE_RECREATE_SKEW_MS) return true;
|
|
3034
|
+
}
|
|
3035
|
+
return false;
|
|
3036
|
+
}
|
|
2727
3037
|
/**
|
|
2728
3038
|
* Before sync: for each tombstone, delete the actual file on all replicas.
|
|
2729
3039
|
* This prevents bi-directional sync from copying the file back.
|
|
@@ -2741,10 +3051,16 @@ var ConfigRepo = class {
|
|
|
2741
3051
|
let processed = 0;
|
|
2742
3052
|
let alreadyDeleted = 0;
|
|
2743
3053
|
let unresolved = 0;
|
|
3054
|
+
const expired = [];
|
|
2744
3055
|
for (const tombstone of tombstones) {
|
|
2745
3056
|
const isKeepPlaceholder = tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep");
|
|
2746
3057
|
const forceDelete = isMtimeSidecar(tombstone.path) || isKeepPlaceholder;
|
|
2747
|
-
const
|
|
3058
|
+
const isDirTombstone = isDirectoryTombstone(tombstone);
|
|
3059
|
+
const tVersionPath = forceDelete || isDirTombstone ? null : versionPathFor(tombstone.path);
|
|
3060
|
+
if (!forceDelete && await this.isPathRecreatedAfterTombstone(tombstone)) {
|
|
3061
|
+
expired.push(tombstone);
|
|
3062
|
+
continue;
|
|
3063
|
+
}
|
|
2748
3064
|
const sidecarOwner = sidecarOwnerPath(tombstone.path);
|
|
2749
3065
|
const isKeepSidecar = sidecarOwner === "/.keep" || (sidecarOwner?.endsWith("/.keep") ?? false);
|
|
2750
3066
|
const liveSidecarCandidate = sidecarOwner !== null && !isKeepSidecar;
|
|
@@ -2798,14 +3114,27 @@ var ConfigRepo = class {
|
|
|
2798
3114
|
confirmed.add(replicaId);
|
|
2799
3115
|
} else {
|
|
2800
3116
|
unresolved++;
|
|
2801
|
-
|
|
3117
|
+
log5.warn(
|
|
2802
3118
|
`[ConfigRepo] tombstone kept: ${tombstone.path} still present on replica ${replicaId}`
|
|
2803
3119
|
);
|
|
2804
3120
|
}
|
|
2805
3121
|
}
|
|
2806
3122
|
}
|
|
3123
|
+
if (expired.length > 0) {
|
|
3124
|
+
for (const tombstone of expired) {
|
|
3125
|
+
try {
|
|
3126
|
+
await this.cachedFS.unlink(tombstonePathFor(tombstone.path, TOMBSTONES_DIR));
|
|
3127
|
+
} catch {
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
this.invalidateTombstoneCache();
|
|
3131
|
+
await this.readTombstones();
|
|
3132
|
+
log5.log(
|
|
3133
|
+
`[ConfigRepo] processTombstones: expired ${expired.length} tombstone(s) \u2014 path recreated after deletion`
|
|
3134
|
+
);
|
|
3135
|
+
}
|
|
2807
3136
|
if (processed > 0 || alreadyDeleted > 0 || unresolved > 0) {
|
|
2808
|
-
|
|
3137
|
+
log5.log(
|
|
2809
3138
|
`[ConfigRepo] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone, ${unresolved} unresolved`
|
|
2810
3139
|
);
|
|
2811
3140
|
}
|
|
@@ -2906,21 +3235,21 @@ var ConfigRepo = class {
|
|
|
2906
3235
|
const innerBackendName = fs?.inner?.backendName;
|
|
2907
3236
|
const directBackendName = fs?.backendName;
|
|
2908
3237
|
const backendLabel = innerBackendName ?? directBackendName ?? innerBackend ?? ctorName;
|
|
2909
|
-
|
|
3238
|
+
log5.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
|
|
2910
3239
|
if (hasExists) {
|
|
2911
|
-
|
|
3240
|
+
log5.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
|
|
2912
3241
|
const result = await fs.exists(path);
|
|
2913
|
-
|
|
3242
|
+
log5.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
|
|
2914
3243
|
return result;
|
|
2915
3244
|
}
|
|
2916
|
-
|
|
3245
|
+
log5.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
|
|
2917
3246
|
await fs.stat(path);
|
|
2918
|
-
|
|
3247
|
+
log5.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
|
|
2919
3248
|
return true;
|
|
2920
3249
|
} catch (err) {
|
|
2921
3250
|
const errCode = err?.code ?? err?.status ?? "";
|
|
2922
3251
|
const errName = err?.constructor?.name ?? "";
|
|
2923
|
-
|
|
3252
|
+
log5.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
|
|
2924
3253
|
return false;
|
|
2925
3254
|
}
|
|
2926
3255
|
}
|
|
@@ -2947,13 +3276,13 @@ var ConfigRepo = class {
|
|
|
2947
3276
|
this.assertNotDisposed();
|
|
2948
3277
|
const result = await purgeMtimeSidecars(this.cachedFS, options);
|
|
2949
3278
|
if (result.removed.length > 0) {
|
|
2950
|
-
|
|
3279
|
+
log5.log(
|
|
2951
3280
|
`[ConfigRepo] purged ${result.removed.length} .mtime sidecar(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
|
|
2952
3281
|
result.removed
|
|
2953
3282
|
);
|
|
2954
3283
|
}
|
|
2955
3284
|
if (result.failed.length > 0) {
|
|
2956
|
-
|
|
3285
|
+
log5.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
|
|
2957
3286
|
}
|
|
2958
3287
|
return result;
|
|
2959
3288
|
}
|
|
@@ -2973,13 +3302,13 @@ var ConfigRepo = class {
|
|
|
2973
3302
|
this.assertNotDisposed();
|
|
2974
3303
|
const result = await purgeKeepFiles(this.cachedFS, options);
|
|
2975
3304
|
if (result.removed.length > 0) {
|
|
2976
|
-
|
|
3305
|
+
log5.log(
|
|
2977
3306
|
`[ConfigRepo] purged ${result.removed.length} .keep placeholder(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
|
|
2978
3307
|
result.removed
|
|
2979
3308
|
);
|
|
2980
3309
|
}
|
|
2981
3310
|
if (result.failed.length > 0) {
|
|
2982
|
-
|
|
3311
|
+
log5.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
|
|
2983
3312
|
}
|
|
2984
3313
|
return result;
|
|
2985
3314
|
}
|
|
@@ -2998,24 +3327,24 @@ var ConfigRepo = class {
|
|
|
2998
3327
|
}));
|
|
2999
3328
|
const result = await migrateVersionSidecars(this.cachedFS, { replicas });
|
|
3000
3329
|
if (result.renamed.length > 0) {
|
|
3001
|
-
|
|
3330
|
+
log5.log(
|
|
3002
3331
|
`[ConfigRepo] migrated ${result.renamed.length} legacy version sidecar(s) to new naming`,
|
|
3003
3332
|
result.renamed
|
|
3004
3333
|
);
|
|
3005
3334
|
}
|
|
3006
3335
|
if (result.deleted.length > 0) {
|
|
3007
|
-
|
|
3336
|
+
log5.log(
|
|
3008
3337
|
`[ConfigRepo] removed ${result.deleted.length} orphaned legacy version sidecar(s)`,
|
|
3009
3338
|
result.deleted
|
|
3010
3339
|
);
|
|
3011
3340
|
}
|
|
3012
3341
|
if (result.remoteDeleted.length > 0) {
|
|
3013
|
-
|
|
3342
|
+
log5.log(
|
|
3014
3343
|
`[ConfigRepo] removed ${result.remoteDeleted.length} remote residual legacy version sidecar(s)`
|
|
3015
3344
|
);
|
|
3016
3345
|
}
|
|
3017
3346
|
if (result.failed.length > 0) {
|
|
3018
|
-
|
|
3347
|
+
log5.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
|
|
3019
3348
|
}
|
|
3020
3349
|
return result;
|
|
3021
3350
|
}
|
|
@@ -3038,9 +3367,9 @@ var ConfigRepo = class {
|
|
|
3038
3367
|
*/
|
|
3039
3368
|
startBackgroundSync() {
|
|
3040
3369
|
this.initialSyncPromise = this.initialSyncAndDedup().then(() => {
|
|
3041
|
-
|
|
3370
|
+
log5.log("[ConfigRepo] Background initial sync complete");
|
|
3042
3371
|
}).catch((err) => {
|
|
3043
|
-
|
|
3372
|
+
log5.error("[ConfigRepo] Background initial sync failed:", err);
|
|
3044
3373
|
}).finally(() => {
|
|
3045
3374
|
this.initialSyncPromise = null;
|
|
3046
3375
|
});
|
|
@@ -3069,7 +3398,7 @@ var ConfigRepo = class {
|
|
|
3069
3398
|
}
|
|
3070
3399
|
if (changed) {
|
|
3071
3400
|
try {
|
|
3072
|
-
const bytes = new TextEncoder().encode(
|
|
3401
|
+
const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
|
|
3073
3402
|
const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
|
|
3074
3403
|
if (await this.safeExists(this.cachedFS, tombstonePath)) {
|
|
3075
3404
|
await this.cachedFS.writeFile(tombstonePath, bytes);
|
|
@@ -3079,7 +3408,7 @@ var ConfigRepo = class {
|
|
|
3079
3408
|
}
|
|
3080
3409
|
}
|
|
3081
3410
|
}
|
|
3082
|
-
|
|
3411
|
+
log5.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
|
|
3083
3412
|
if (modified > 0) this.invalidateTombstoneCache();
|
|
3084
3413
|
}
|
|
3085
3414
|
/**
|
|
@@ -3117,7 +3446,12 @@ var ConfigRepo = class {
|
|
|
3117
3446
|
const tombstones = await this.readTombstones();
|
|
3118
3447
|
if (tombstones.length === 0) return;
|
|
3119
3448
|
const allBackendIds = [...this.replicaBackends.keys()];
|
|
3449
|
+
let keptByRetention = 0;
|
|
3120
3450
|
for (const tombstone of tombstones) {
|
|
3451
|
+
if (!isTombstoneRetentionElapsed(tombstone)) {
|
|
3452
|
+
keptByRetention++;
|
|
3453
|
+
continue;
|
|
3454
|
+
}
|
|
3121
3455
|
const allConfirmed = await this.allReplicasConfirmAbsent(tombstone.path);
|
|
3122
3456
|
if (allConfirmed) {
|
|
3123
3457
|
const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
|
|
@@ -3133,9 +3467,12 @@ var ConfigRepo = class {
|
|
|
3133
3467
|
}
|
|
3134
3468
|
}
|
|
3135
3469
|
}
|
|
3136
|
-
|
|
3470
|
+
log5.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
|
|
3137
3471
|
}
|
|
3138
3472
|
}
|
|
3473
|
+
if (keptByRetention > 0) {
|
|
3474
|
+
log5.log(`[ConfigRepo] gcTombstones: kept ${keptByRetention} tombstone(s) within retention window`);
|
|
3475
|
+
}
|
|
3139
3476
|
}
|
|
3140
3477
|
/**
|
|
3141
3478
|
* Sync .meta/ files (backends.json) to all replica backends.
|
|
@@ -3149,7 +3486,7 @@ var ConfigRepo = class {
|
|
|
3149
3486
|
this.assertNotDisposed();
|
|
3150
3487
|
const results = await this.flush();
|
|
3151
3488
|
for (const result of results) {
|
|
3152
|
-
|
|
3489
|
+
log5.log(
|
|
3153
3490
|
`[ConfigRepo] syncMetaToReplicas: ${result.pairId} +${result.filesCreated}/~${result.filesUpdated}/-${result.filesDeleted} skip:${result.filesSkipped} ${result.durationMs}ms`
|
|
3154
3491
|
);
|
|
3155
3492
|
}
|
|
@@ -3322,21 +3659,29 @@ var ConfigRepo = class {
|
|
|
3322
3659
|
// Internal — Setup
|
|
3323
3660
|
// -----------------------------------------------------------------------
|
|
3324
3661
|
async setupSync(backends, primaryBackendId, pollIntervalMs) {
|
|
3325
|
-
|
|
3662
|
+
log5.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
|
|
3326
3663
|
for (const desc of backends) {
|
|
3327
3664
|
if (desc.id === primaryBackendId) continue;
|
|
3328
3665
|
if (desc.enabled === false) {
|
|
3329
|
-
|
|
3666
|
+
log5.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
|
|
3330
3667
|
continue;
|
|
3331
3668
|
}
|
|
3332
|
-
|
|
3669
|
+
log5.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
|
|
3333
3670
|
try {
|
|
3334
3671
|
const instance = await createBackend(desc);
|
|
3672
|
+
const owner = await this.bindBackendIdentity(instance, desc.id);
|
|
3673
|
+
if (owner === "conflict") {
|
|
3674
|
+
try {
|
|
3675
|
+
await instance.dispose?.();
|
|
3676
|
+
} catch {
|
|
3677
|
+
}
|
|
3678
|
+
continue;
|
|
3679
|
+
}
|
|
3335
3680
|
let fsInstance = instance;
|
|
3336
3681
|
if (this.cacheOptions) {
|
|
3337
3682
|
const { wrapWithCache: wrapWithCache2 } = await Promise.resolve().then(() => (init_cache_wrapper(), cache_wrapper_exports));
|
|
3338
3683
|
fsInstance = wrapWithCache2(instance, desc.id, this.cacheOptions);
|
|
3339
|
-
|
|
3684
|
+
log5.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
|
|
3340
3685
|
}
|
|
3341
3686
|
const syncable = backendToSyncableFS(fsInstance, `${desc.type}(${desc.id})`);
|
|
3342
3687
|
const pair = this.syncEngine.addPair(
|
|
@@ -3354,7 +3699,7 @@ var ConfigRepo = class {
|
|
|
3354
3699
|
this.invalidateTombstoneCache();
|
|
3355
3700
|
await this.processTombstones();
|
|
3356
3701
|
} catch (err) {
|
|
3357
|
-
|
|
3702
|
+
log5.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
|
|
3358
3703
|
}
|
|
3359
3704
|
},
|
|
3360
3705
|
postSyncHook: async () => {
|
|
@@ -3363,7 +3708,7 @@ var ConfigRepo = class {
|
|
|
3363
3708
|
await this.processTombstones();
|
|
3364
3709
|
await this.updateTombstoneConfirmations();
|
|
3365
3710
|
} catch (err) {
|
|
3366
|
-
|
|
3711
|
+
log5.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
|
|
3367
3712
|
}
|
|
3368
3713
|
}
|
|
3369
3714
|
},
|
|
@@ -3376,9 +3721,9 @@ var ConfigRepo = class {
|
|
|
3376
3721
|
};
|
|
3377
3722
|
this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
|
|
3378
3723
|
this.trackSyncErrors(desc.id, pair.pairId);
|
|
3379
|
-
|
|
3724
|
+
log5.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
|
|
3380
3725
|
} catch (err) {
|
|
3381
|
-
|
|
3726
|
+
log5.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
|
|
3382
3727
|
this.backendStates.set(desc.id, {
|
|
3383
3728
|
backendId: desc.id,
|
|
3384
3729
|
error: {
|
|
@@ -3388,8 +3733,8 @@ var ConfigRepo = class {
|
|
|
3388
3733
|
});
|
|
3389
3734
|
}
|
|
3390
3735
|
}
|
|
3391
|
-
|
|
3392
|
-
|
|
3736
|
+
log5.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
|
|
3737
|
+
log5.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
|
|
3393
3738
|
}
|
|
3394
3739
|
// -----------------------------------------------------------------------
|
|
3395
3740
|
// Internal — Persistence
|
|
@@ -3401,12 +3746,12 @@ var ConfigRepo = class {
|
|
|
3401
3746
|
try {
|
|
3402
3747
|
const existing = await readVersion(this.fullFS, vPath);
|
|
3403
3748
|
if (existing && existing.hash === version.hash) {
|
|
3404
|
-
|
|
3749
|
+
log5.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
|
|
3405
3750
|
return;
|
|
3406
3751
|
}
|
|
3407
3752
|
} catch {
|
|
3408
3753
|
}
|
|
3409
|
-
|
|
3754
|
+
log5.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
|
|
3410
3755
|
await this.ensureDir(vPath);
|
|
3411
3756
|
await writeVersion(this.fullFS, vPath, version);
|
|
3412
3757
|
}
|
|
@@ -3510,7 +3855,7 @@ var ConfigRepo = class {
|
|
|
3510
3855
|
await this.resolveConflict(`${conflictId}/meta.json`, customMerge);
|
|
3511
3856
|
}
|
|
3512
3857
|
} catch (err) {
|
|
3513
|
-
|
|
3858
|
+
log5.error("[zen-fs-config] Conflict handler error:", err);
|
|
3514
3859
|
}
|
|
3515
3860
|
}
|
|
3516
3861
|
}
|
|
@@ -3626,11 +3971,11 @@ var ConfigRepo = class {
|
|
|
3626
3971
|
}
|
|
3627
3972
|
return { kind: "ok", desc, mtime };
|
|
3628
3973
|
} else {
|
|
3629
|
-
|
|
3974
|
+
log5.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
|
|
3630
3975
|
return { kind: "corrupt", filePath };
|
|
3631
3976
|
}
|
|
3632
3977
|
} catch (parseErr) {
|
|
3633
|
-
|
|
3978
|
+
log5.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
|
|
3634
3979
|
return { kind: "corrupt", filePath };
|
|
3635
3980
|
}
|
|
3636
3981
|
})
|
|
@@ -3696,7 +4041,7 @@ var ConfigRepo = class {
|
|
|
3696
4041
|
}
|
|
3697
4042
|
}
|
|
3698
4043
|
if (duplicates.length > 0) {
|
|
3699
|
-
|
|
4044
|
+
log5.log(
|
|
3700
4045
|
`[ConfigRepo] readAllBackendDescriptors: removing ${duplicates.length} duplicate(s): ${duplicates.join(", ")}`
|
|
3701
4046
|
);
|
|
3702
4047
|
for (const dupId of duplicates) {
|
|
@@ -3828,7 +4173,7 @@ var ConfigRepo = class {
|
|
|
3828
4173
|
* Shared by addBackend() and replaceBackend().
|
|
3829
4174
|
*/
|
|
3830
4175
|
async setupReplica(id, type, options, description) {
|
|
3831
|
-
|
|
4176
|
+
log5.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
|
|
3832
4177
|
const instance = await createBackend({ type, options });
|
|
3833
4178
|
const syncable = backendToSyncableFS(instance, `${type}(${id})`);
|
|
3834
4179
|
const desc = { id, type, options, description };
|
|
@@ -3846,7 +4191,7 @@ var ConfigRepo = class {
|
|
|
3846
4191
|
this.invalidateTombstoneCache();
|
|
3847
4192
|
await this.processTombstones();
|
|
3848
4193
|
} catch (err) {
|
|
3849
|
-
|
|
4194
|
+
log5.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
|
|
3850
4195
|
}
|
|
3851
4196
|
},
|
|
3852
4197
|
postSyncHook: async () => {
|
|
@@ -3855,7 +4200,7 @@ var ConfigRepo = class {
|
|
|
3855
4200
|
await this.processTombstones();
|
|
3856
4201
|
await this.updateTombstoneConfirmations();
|
|
3857
4202
|
} catch (err) {
|
|
3858
|
-
|
|
4203
|
+
log5.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
|
|
3859
4204
|
}
|
|
3860
4205
|
}
|
|
3861
4206
|
},
|
|
@@ -3868,7 +4213,7 @@ var ConfigRepo = class {
|
|
|
3868
4213
|
};
|
|
3869
4214
|
this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
|
|
3870
4215
|
this.trackSyncErrors(id, pair.pairId);
|
|
3871
|
-
|
|
4216
|
+
log5.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
|
|
3872
4217
|
await this.syncMetaToReplicas();
|
|
3873
4218
|
this.syncEngine.watch(pair.pairId);
|
|
3874
4219
|
return pair.pairId;
|
|
@@ -3894,13 +4239,13 @@ var ConfigRepo = class {
|
|
|
3894
4239
|
}
|
|
3895
4240
|
}
|
|
3896
4241
|
this.syncEngine.removePair(replica.pairId);
|
|
3897
|
-
|
|
4242
|
+
log5.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
|
|
3898
4243
|
this.replicaBackends.delete(id);
|
|
3899
4244
|
if (replica.instance?.dispose) {
|
|
3900
4245
|
await replica.instance.dispose();
|
|
3901
4246
|
}
|
|
3902
4247
|
} else {
|
|
3903
|
-
|
|
4248
|
+
log5.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
|
|
3904
4249
|
for (const descPath of descPaths) {
|
|
3905
4250
|
try {
|
|
3906
4251
|
await this.deleteFile(descPath);
|
|
@@ -3911,7 +4256,7 @@ var ConfigRepo = class {
|
|
|
3911
4256
|
}
|
|
3912
4257
|
this.backendStates.delete(id);
|
|
3913
4258
|
this.schedulePostDeleteSync();
|
|
3914
|
-
|
|
4259
|
+
log5.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
|
|
3915
4260
|
}
|
|
3916
4261
|
/**
|
|
3917
4262
|
* Replace a config-sync backend's parameters in place (same id).
|
|
@@ -3958,11 +4303,11 @@ var ConfigRepo = class {
|
|
|
3958
4303
|
await this.setupReplica(id, type, options, description ?? before.description);
|
|
3959
4304
|
} catch (err) {
|
|
3960
4305
|
const reason = err instanceof Error ? err.message : String(err);
|
|
3961
|
-
|
|
4306
|
+
log5.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
|
|
3962
4307
|
try {
|
|
3963
4308
|
await this.setupReplica(id, before.type, before.options, before.description);
|
|
3964
4309
|
} catch (rollbackErr) {
|
|
3965
|
-
|
|
4310
|
+
log5.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
|
|
3966
4311
|
}
|
|
3967
4312
|
throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
|
|
3968
4313
|
}
|
|
@@ -3970,6 +4315,80 @@ var ConfigRepo = class {
|
|
|
3970
4315
|
// -----------------------------------------------------------------------
|
|
3971
4316
|
// IConfigRepo — Group Type
|
|
3972
4317
|
// -----------------------------------------------------------------------
|
|
4318
|
+
/**
|
|
4319
|
+
* 本组的同步身份(kind + id + 不可变 instanceId)。
|
|
4320
|
+
*
|
|
4321
|
+
* 首次调用时若 `.meta/group.json` 里还没有 `instanceId`(老部署),生成一个
|
|
4322
|
+
* 并就地写回 —— 只写一次,之后字节相同不再落盘。
|
|
4323
|
+
*/
|
|
4324
|
+
async ensureGroupIdentity(kind = "config", id = CONFIG_GROUP_ID) {
|
|
4325
|
+
let existingFeatures;
|
|
4326
|
+
if (!this.instanceId) {
|
|
4327
|
+
let existing = null;
|
|
4328
|
+
try {
|
|
4329
|
+
existing = await readGroupDescriptor(this.cachedFS);
|
|
4330
|
+
} catch {
|
|
4331
|
+
}
|
|
4332
|
+
const known = pickInstanceId(existing);
|
|
4333
|
+
existingFeatures = existing?.features ?? CONFIG_GROUP_FEATURES;
|
|
4334
|
+
this.instanceId = known ?? newGroupInstanceId();
|
|
4335
|
+
if (!known) {
|
|
4336
|
+
try {
|
|
4337
|
+
await writeGroupDescriptor(this.cachedFS, {
|
|
4338
|
+
schemaVersion: 2,
|
|
4339
|
+
kind: existing?.kind ?? kind,
|
|
4340
|
+
id: existing?.id ?? id,
|
|
4341
|
+
instanceId: this.instanceId,
|
|
4342
|
+
...existing?.name ?? this.name ? { name: existing?.name ?? this.name } : {},
|
|
4343
|
+
features: existing?.features ?? CONFIG_GROUP_FEATURES
|
|
4344
|
+
});
|
|
4345
|
+
log5.log(`[ConfigRepo] group instanceId assigned: ${this.instanceId} (kind=${existing?.kind ?? kind})`);
|
|
4346
|
+
} catch (err) {
|
|
4347
|
+
log5.warn("[ConfigRepo] failed to persist group instanceId:", err);
|
|
4348
|
+
}
|
|
4349
|
+
}
|
|
4350
|
+
}
|
|
4351
|
+
return {
|
|
4352
|
+
kind,
|
|
4353
|
+
id,
|
|
4354
|
+
instanceId: this.instanceId,
|
|
4355
|
+
...this.name ? { name: this.name } : {},
|
|
4356
|
+
...existingFeatures ? { features: existingFeatures } : {}
|
|
4357
|
+
};
|
|
4358
|
+
}
|
|
4359
|
+
/** 组实例身份(未初始化时先兜底生成并落盘)。 */
|
|
4360
|
+
async ensureGroupInstanceId() {
|
|
4361
|
+
return (await this.ensureGroupIdentity()).instanceId;
|
|
4362
|
+
}
|
|
4363
|
+
/** 组实例身份(同步读取;init 之前可能为 `undefined`)。 */
|
|
4364
|
+
getGroupInstanceId() {
|
|
4365
|
+
return this.instanceId;
|
|
4366
|
+
}
|
|
4367
|
+
/**
|
|
4368
|
+
* 连接远端前校验归属:属于别的组 → `conflict`(调用方必须跳过、不建同步对)。
|
|
4369
|
+
* 老仓库(无 instanceId)会被本组认领。
|
|
4370
|
+
*/
|
|
4371
|
+
async bindBackendIdentity(instance, backendId) {
|
|
4372
|
+
try {
|
|
4373
|
+
const identity = await this.ensureGroupIdentity();
|
|
4374
|
+
const state = await bindRemoteGroupIdentity(instance, identity);
|
|
4375
|
+
if (state === "conflict") {
|
|
4376
|
+
this.skippedBackends.set(
|
|
4377
|
+
backendId,
|
|
4378
|
+
`\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`
|
|
4379
|
+
);
|
|
4380
|
+
}
|
|
4381
|
+
return state;
|
|
4382
|
+
} catch (err) {
|
|
4383
|
+
log5.warn(`[ConfigRepo] identity check failed for backend "${backendId}", skipping it:`, err);
|
|
4384
|
+
this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
|
|
4385
|
+
return "conflict";
|
|
4386
|
+
}
|
|
4387
|
+
}
|
|
4388
|
+
/** 因归属他人而被跳过的后端(id → 原因)。 */
|
|
4389
|
+
listSkippedBackends() {
|
|
4390
|
+
return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
|
|
4391
|
+
}
|
|
3973
4392
|
/** Write the group-type marker file if it doesn't exist. */
|
|
3974
4393
|
async ensureGroupType(type) {
|
|
3975
4394
|
this.assertNotDisposed();
|
|
@@ -3978,7 +4397,7 @@ var ConfigRepo = class {
|
|
|
3978
4397
|
const existing = await this.cachedFS.readFile(path, "utf-8");
|
|
3979
4398
|
const current = existing.trim();
|
|
3980
4399
|
if (current && current !== type) {
|
|
3981
|
-
|
|
4400
|
+
log5.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
|
|
3982
4401
|
return;
|
|
3983
4402
|
}
|
|
3984
4403
|
} catch {
|
|
@@ -3992,10 +4411,12 @@ var ConfigRepo = class {
|
|
|
3992
4411
|
}
|
|
3993
4412
|
const existingDescriptor = await readGroupDescriptor(this.cachedFS);
|
|
3994
4413
|
if (!existingDescriptor) {
|
|
4414
|
+
this.instanceId = newGroupInstanceId();
|
|
3995
4415
|
await writeGroupDescriptor(this.cachedFS, {
|
|
3996
4416
|
schemaVersion: 2,
|
|
3997
4417
|
kind: "config",
|
|
3998
4418
|
id: CONFIG_GROUP_ID,
|
|
4419
|
+
instanceId: this.instanceId,
|
|
3999
4420
|
...this.name ? { name: this.name } : {},
|
|
4000
4421
|
features: CONFIG_GROUP_FEATURES
|
|
4001
4422
|
});
|
|
@@ -4009,7 +4430,22 @@ var ConfigRepo = class {
|
|
|
4009
4430
|
features: existingDescriptor.features ?? CONFIG_GROUP_FEATURES
|
|
4010
4431
|
});
|
|
4011
4432
|
}
|
|
4012
|
-
|
|
4433
|
+
const knownInstanceId = pickInstanceId(existingDescriptor);
|
|
4434
|
+
if (knownInstanceId) {
|
|
4435
|
+
this.instanceId = knownInstanceId;
|
|
4436
|
+
} else if (!this.instanceId) {
|
|
4437
|
+
this.instanceId = newGroupInstanceId();
|
|
4438
|
+
await writeGroupDescriptor(this.cachedFS, {
|
|
4439
|
+
schemaVersion: 2,
|
|
4440
|
+
kind: existingDescriptor?.kind ?? "config",
|
|
4441
|
+
id: existingDescriptor?.id ?? CONFIG_GROUP_ID,
|
|
4442
|
+
instanceId: this.instanceId,
|
|
4443
|
+
...existingDescriptor?.name ?? this.name ? { name: existingDescriptor?.name ?? this.name } : {},
|
|
4444
|
+
...existingDescriptor?.features ? { features: existingDescriptor.features } : {}
|
|
4445
|
+
});
|
|
4446
|
+
log5.log(`[ConfigRepo] assigned group instanceId ${this.instanceId} (kind=${existingDescriptor?.kind ?? "config"})`);
|
|
4447
|
+
}
|
|
4448
|
+
log5.log(`[ConfigRepo] group-type set to "${type}"`);
|
|
4013
4449
|
}
|
|
4014
4450
|
/** Read the group-type marker. Returns null if not set (new path, then legacy). */
|
|
4015
4451
|
async getGroupType() {
|
|
@@ -4104,7 +4540,7 @@ var ConfigRepo = class {
|
|
|
4104
4540
|
if (this.appDataGroups.has(id)) {
|
|
4105
4541
|
throw new Error(`App data group "${id}" already exists. Use removeAppDataGroup() first.`);
|
|
4106
4542
|
}
|
|
4107
|
-
|
|
4543
|
+
log5.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
|
|
4108
4544
|
const resolvedBackends = [];
|
|
4109
4545
|
for (const desc of backends) {
|
|
4110
4546
|
assertValidBackendId(desc.id);
|
|
@@ -4112,6 +4548,7 @@ var ConfigRepo = class {
|
|
|
4112
4548
|
resolvedBackends.push({ ...desc, options: mergedOptions });
|
|
4113
4549
|
}
|
|
4114
4550
|
await this.assertNoSharedRemote(resolvedBackends, id);
|
|
4551
|
+
const instanceId = newGroupInstanceId();
|
|
4115
4552
|
const group = new AppDataGroupImpl(
|
|
4116
4553
|
id,
|
|
4117
4554
|
this.appId,
|
|
@@ -4119,19 +4556,25 @@ var ConfigRepo = class {
|
|
|
4119
4556
|
this.pollIntervalMs,
|
|
4120
4557
|
this,
|
|
4121
4558
|
// 显式新拓扑:以参数为准并写入 `.meta/backends/`。
|
|
4122
|
-
{
|
|
4559
|
+
{
|
|
4560
|
+
name: options.name,
|
|
4561
|
+
features: options.features,
|
|
4562
|
+
backendsAreAuthoritative: true,
|
|
4563
|
+
instanceId
|
|
4564
|
+
}
|
|
4123
4565
|
);
|
|
4124
4566
|
await group.init();
|
|
4125
4567
|
const descriptor = {
|
|
4126
4568
|
id,
|
|
4127
4569
|
groupType: "data-sync",
|
|
4570
|
+
instanceId: group.getGroupInstanceId() ?? instanceId,
|
|
4128
4571
|
...options.name ? { name: options.name } : {},
|
|
4129
4572
|
...options.features ? { features: options.features } : {},
|
|
4130
4573
|
backends: group.listDeclaredBackends()
|
|
4131
4574
|
};
|
|
4132
4575
|
await this.writeAppDataGroupDescriptorFile(id, descriptor);
|
|
4133
4576
|
this.appDataGroups.set(id, group);
|
|
4134
|
-
|
|
4577
|
+
log5.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
|
|
4135
4578
|
return group;
|
|
4136
4579
|
}
|
|
4137
4580
|
/**
|
|
@@ -4148,9 +4591,13 @@ var ConfigRepo = class {
|
|
|
4148
4591
|
const existing = await this.readAppDataGroupDescriptor(id);
|
|
4149
4592
|
const name = meta?.name ?? existing?.name;
|
|
4150
4593
|
const features = meta?.features ?? existing?.features;
|
|
4594
|
+
const liveGroup = this.appDataGroups.get(id);
|
|
4595
|
+
const liveInstanceId = liveGroup?.getGroupInstanceId();
|
|
4596
|
+
const instanceId = pickInstanceId(existing) ?? (isValidGroupInstanceId(liveInstanceId) ? liveInstanceId : void 0);
|
|
4151
4597
|
const descriptor = {
|
|
4152
4598
|
id,
|
|
4153
4599
|
groupType: "data-sync",
|
|
4600
|
+
...instanceId ? { instanceId } : {},
|
|
4154
4601
|
...name ? { name } : {},
|
|
4155
4602
|
...features ? { features } : {},
|
|
4156
4603
|
backends
|
|
@@ -4174,7 +4621,7 @@ var ConfigRepo = class {
|
|
|
4174
4621
|
try {
|
|
4175
4622
|
await live.writeOwnGroupDescriptor();
|
|
4176
4623
|
} catch (err) {
|
|
4177
|
-
|
|
4624
|
+
log5.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
|
|
4178
4625
|
}
|
|
4179
4626
|
}
|
|
4180
4627
|
const descriptor = {
|
|
@@ -4218,6 +4665,9 @@ var ConfigRepo = class {
|
|
|
4218
4665
|
const nextBackends = declared.map(
|
|
4219
4666
|
(b, i) => i === index ? { ...candidate, options: mergedOptions } : b
|
|
4220
4667
|
);
|
|
4668
|
+
const descriptorNow = await this.readAppDataGroupDescriptor(groupId);
|
|
4669
|
+
const instanceIdFromLive = live?.getGroupInstanceId();
|
|
4670
|
+
const instanceId = pickInstanceId(descriptorNow) ?? (isValidGroupInstanceId(instanceIdFromLive) ? instanceIdFromLive : void 0);
|
|
4221
4671
|
if (live) {
|
|
4222
4672
|
await live.dispose();
|
|
4223
4673
|
this.appDataGroups.delete(groupId);
|
|
@@ -4229,7 +4679,7 @@ var ConfigRepo = class {
|
|
|
4229
4679
|
nextBackends,
|
|
4230
4680
|
this.pollIntervalMs,
|
|
4231
4681
|
this,
|
|
4232
|
-
{ backendsAreAuthoritative: true }
|
|
4682
|
+
{ backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
|
|
4233
4683
|
);
|
|
4234
4684
|
await group.init();
|
|
4235
4685
|
await this.updateAppDataGroupDescriptor(groupId, group.listDeclaredBackends());
|
|
@@ -4237,7 +4687,7 @@ var ConfigRepo = class {
|
|
|
4237
4687
|
return group;
|
|
4238
4688
|
} catch (err) {
|
|
4239
4689
|
const reason = err instanceof Error ? err.message : String(err);
|
|
4240
|
-
|
|
4690
|
+
log5.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
|
|
4241
4691
|
try {
|
|
4242
4692
|
const restored = new AppDataGroupImpl(
|
|
4243
4693
|
groupId,
|
|
@@ -4245,13 +4695,13 @@ var ConfigRepo = class {
|
|
|
4245
4695
|
oldBackends,
|
|
4246
4696
|
this.pollIntervalMs,
|
|
4247
4697
|
this,
|
|
4248
|
-
{ backendsAreAuthoritative: true }
|
|
4698
|
+
{ backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
|
|
4249
4699
|
);
|
|
4250
4700
|
await restored.init();
|
|
4251
4701
|
await this.updateAppDataGroupDescriptor(groupId, restored.listDeclaredBackends());
|
|
4252
4702
|
this.appDataGroups.set(groupId, restored);
|
|
4253
4703
|
} catch (rollbackErr) {
|
|
4254
|
-
|
|
4704
|
+
log5.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
|
|
4255
4705
|
}
|
|
4256
4706
|
throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
|
|
4257
4707
|
}
|
|
@@ -4289,10 +4739,12 @@ var ConfigRepo = class {
|
|
|
4289
4739
|
const version = await incrementVersion(this.fullFS, path, bytes, author);
|
|
4290
4740
|
await this.writeVersionSidecar(path, version);
|
|
4291
4741
|
}
|
|
4742
|
+
const identity = await this.ensureGroupIdentity();
|
|
4292
4743
|
await writeGroupDescriptor(this.cachedFS, {
|
|
4293
4744
|
schemaVersion: 2,
|
|
4294
4745
|
kind: "config",
|
|
4295
4746
|
id: CONFIG_GROUP_ID,
|
|
4747
|
+
instanceId: identity.instanceId,
|
|
4296
4748
|
name: normalized,
|
|
4297
4749
|
features: CONFIG_GROUP_FEATURES
|
|
4298
4750
|
});
|
|
@@ -4369,7 +4821,7 @@ var ConfigRepo = class {
|
|
|
4369
4821
|
try {
|
|
4370
4822
|
await this.deleteFile(descPath);
|
|
4371
4823
|
} catch (err) {
|
|
4372
|
-
|
|
4824
|
+
log5.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
|
|
4373
4825
|
try {
|
|
4374
4826
|
await this.cachedFS.unlink(descPath);
|
|
4375
4827
|
} catch {
|
|
@@ -4377,7 +4829,7 @@ var ConfigRepo = class {
|
|
|
4377
4829
|
await this.unlinkVersionSidecar(this.cachedFS, descPath);
|
|
4378
4830
|
}
|
|
4379
4831
|
}
|
|
4380
|
-
|
|
4832
|
+
log5.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
|
|
4381
4833
|
}
|
|
4382
4834
|
async listAccountBackends() {
|
|
4383
4835
|
this.assertNotDisposed();
|
|
@@ -4414,10 +4866,20 @@ var AppDataGroupImpl = class {
|
|
|
4414
4866
|
versions;
|
|
4415
4867
|
conflicts;
|
|
4416
4868
|
postDeleteTimer;
|
|
4869
|
+
/**
|
|
4870
|
+
* 墓碑路径的同步排除表(与配置组同一套机制)。
|
|
4871
|
+
*
|
|
4872
|
+
* 保留期内的墓碑路径不参与同步:否则副本上的残留会被当作"远端内容"逐文件
|
|
4873
|
+
* 拉回本地,把已删除的目录复活。数组与各同步对共享同一实例(zen-fs-sync
|
|
4874
|
+
* 每次检测时实时读取 `filter.excludePrefixes`),原地更新即可生效。
|
|
4875
|
+
*/
|
|
4876
|
+
tombstoneExcludePrefixes = [...CONFIG_ONLY_PREFIXES];
|
|
4877
|
+
syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
|
|
4417
4878
|
constructor(groupId, appId, backends, pollIntervalMs, parent, descriptor = {}) {
|
|
4418
4879
|
this.groupId = groupId;
|
|
4419
4880
|
this.appId = appId;
|
|
4420
4881
|
this.name = descriptor.name;
|
|
4882
|
+
this.instanceId = isValidGroupInstanceId(descriptor.instanceId) ? descriptor.instanceId : void 0;
|
|
4421
4883
|
this.features = {
|
|
4422
4884
|
...DATA_GROUP_DEFAULT_FEATURES,
|
|
4423
4885
|
...descriptor.features,
|
|
@@ -4435,6 +4897,13 @@ var AppDataGroupImpl = class {
|
|
|
4435
4897
|
}
|
|
4436
4898
|
parent;
|
|
4437
4899
|
_backends;
|
|
4900
|
+
/**
|
|
4901
|
+
* 组实例身份(UUID)。同步边界:远端 `.meta/group.json` 的 `instanceId`
|
|
4902
|
+
* 不一致就不建同步对,因此不同同步组之间永不互相搬运数据。
|
|
4903
|
+
*/
|
|
4904
|
+
instanceId;
|
|
4905
|
+
/** 因归属他人而被跳过的后端 id → 原因。 */
|
|
4906
|
+
skippedBackends = /* @__PURE__ */ new Map();
|
|
4438
4907
|
_pollIntervalMs;
|
|
4439
4908
|
_backendsAreAuthoritative;
|
|
4440
4909
|
/** 引导副本(`.config/` 里的描述符)原有的能力位,用于回刷时不丢信息。 */
|
|
@@ -4531,14 +5000,64 @@ var AppDataGroupImpl = class {
|
|
|
4531
5000
|
}
|
|
4532
5001
|
/** Write this group's own `.meta/group.json` (idempotent: identical bytes → no write). */
|
|
4533
5002
|
async writeOwnGroupDescriptor() {
|
|
5003
|
+
if (!this.instanceId) {
|
|
5004
|
+
this.instanceId = newGroupInstanceId();
|
|
5005
|
+
log5.log(`[AppDataGroup:${this.groupId}] assigned instanceId ${this.instanceId}`);
|
|
5006
|
+
}
|
|
4534
5007
|
await writeGroupDescriptor(this.localFS, {
|
|
4535
5008
|
schemaVersion: 2,
|
|
4536
5009
|
kind: "data",
|
|
4537
5010
|
id: this.groupId,
|
|
5011
|
+
instanceId: this.instanceId,
|
|
4538
5012
|
...this.name ? { name: this.name } : {},
|
|
4539
5013
|
features: this.features
|
|
4540
5014
|
});
|
|
4541
5015
|
}
|
|
5016
|
+
/** 本组实例身份(初始化后可用)。 */
|
|
5017
|
+
getGroupInstanceId() {
|
|
5018
|
+
return this.instanceId;
|
|
5019
|
+
}
|
|
5020
|
+
/** 因归属他人而被跳过的后端(id → 原因)。 */
|
|
5021
|
+
listSkippedBackends() {
|
|
5022
|
+
return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
|
|
5023
|
+
}
|
|
5024
|
+
/**
|
|
5025
|
+
* 连接数据后端前的归属校验。
|
|
5026
|
+
*
|
|
5027
|
+
* - `match`:远端 `.meta/group.json` 的 `instanceId` 与本组一致 → 建同步对;
|
|
5028
|
+
* - `claimed`:远端是老仓库(无身份)→ 本组认领并写入,再建同步对;
|
|
5029
|
+
* - `conflict`:远端属于另一个同步组(或类型不符 / 读不到)→ 跳过,
|
|
5030
|
+
* **绝不建立同步对**,因此跨组数据不会被搬运。
|
|
5031
|
+
*/
|
|
5032
|
+
async checkBackendOwnership(instance, backendId) {
|
|
5033
|
+
if (!this.instanceId) {
|
|
5034
|
+
this.skippedBackends.set(backendId, "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF");
|
|
5035
|
+
return "conflict";
|
|
5036
|
+
}
|
|
5037
|
+
try {
|
|
5038
|
+
const state = await bindRemoteGroupIdentity(instance, {
|
|
5039
|
+
kind: "data",
|
|
5040
|
+
id: this.groupId,
|
|
5041
|
+
instanceId: this.instanceId,
|
|
5042
|
+
...this.name ? { name: this.name } : {},
|
|
5043
|
+
features: this.features
|
|
5044
|
+
});
|
|
5045
|
+
if (state === "conflict") {
|
|
5046
|
+
this.skippedBackends.set(
|
|
5047
|
+
backendId,
|
|
5048
|
+
"\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF"
|
|
5049
|
+
);
|
|
5050
|
+
log5.warn(
|
|
5051
|
+
`[AppDataGroup:${this.groupId}] backend "${backendId}" belongs to another sync group \u2014 sync pair skipped`
|
|
5052
|
+
);
|
|
5053
|
+
}
|
|
5054
|
+
return state;
|
|
5055
|
+
} catch (err) {
|
|
5056
|
+
log5.warn(`[AppDataGroup:${this.groupId}] ownership check failed for "${backendId}":`, err);
|
|
5057
|
+
this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
|
|
5058
|
+
return "conflict";
|
|
5059
|
+
}
|
|
5060
|
+
}
|
|
4542
5061
|
async init() {
|
|
4543
5062
|
const storeName = dataGroupLocalStoreName(this.appId, this.groupId);
|
|
4544
5063
|
try {
|
|
@@ -4566,40 +5085,56 @@ var AppDataGroupImpl = class {
|
|
|
4566
5085
|
try {
|
|
4567
5086
|
const purged = await purgeMtimeSidecars(this.localFS);
|
|
4568
5087
|
if (purged.removed.length > 0) {
|
|
4569
|
-
|
|
5088
|
+
log5.warn(
|
|
4570
5089
|
`[AppDataGroup:${this.groupId}] purged ${purged.removed.length} leaked .mtime sidecar(s):`,
|
|
4571
5090
|
purged.removed
|
|
4572
5091
|
);
|
|
4573
5092
|
}
|
|
4574
5093
|
} catch (err) {
|
|
4575
|
-
|
|
5094
|
+
log5.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
|
|
4576
5095
|
}
|
|
4577
5096
|
try {
|
|
4578
5097
|
const purgedKeep = await purgeKeepFiles(this.localFS);
|
|
4579
5098
|
if (purgedKeep.removed.length > 0) {
|
|
4580
|
-
|
|
5099
|
+
log5.warn(
|
|
4581
5100
|
`[AppDataGroup:${this.groupId}] purged ${purgedKeep.removed.length} leaked .keep placeholder(s):`,
|
|
4582
5101
|
purgedKeep.removed
|
|
4583
5102
|
);
|
|
4584
5103
|
}
|
|
4585
5104
|
} catch (err) {
|
|
4586
|
-
|
|
5105
|
+
log5.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
|
|
4587
5106
|
}
|
|
4588
5107
|
const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
|
|
4589
5108
|
this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
|
|
4590
5109
|
this.versions = new VersionStore(this.localFS, `${this.appId}/${this.groupId}`);
|
|
4591
5110
|
this.conflicts = new ConflictStore(this.localFS, this.appId, `${this.groupId}`, this.versions);
|
|
5111
|
+
try {
|
|
5112
|
+
this.refreshSyncExclusions(await this.tombstones.list());
|
|
5113
|
+
} catch (err) {
|
|
5114
|
+
log5.warn(`[AppDataGroup:${this.groupId}] failed to load tombstones for exclusions:`, err);
|
|
5115
|
+
}
|
|
4592
5116
|
let backendsChanged = false;
|
|
4593
5117
|
try {
|
|
4594
5118
|
backendsChanged = await this.loadBackendDescriptors();
|
|
4595
5119
|
} catch (err) {
|
|
4596
|
-
|
|
5120
|
+
log5.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
|
|
4597
5121
|
this._backends = this._backends ?? [];
|
|
4598
5122
|
}
|
|
5123
|
+
if (!this.instanceId) {
|
|
5124
|
+
try {
|
|
5125
|
+
const existing = await readGroupDescriptor(this.localFS);
|
|
5126
|
+
this.instanceId = pickInstanceId(existing);
|
|
5127
|
+
if (this.instanceId) {
|
|
5128
|
+
log5.log(`[AppDataGroup:${this.groupId}] adopted instanceId ${this.instanceId} from local group.json`);
|
|
5129
|
+
}
|
|
5130
|
+
} catch (err) {
|
|
5131
|
+
log5.warn(`[AppDataGroup:${this.groupId}] failed to read local group.json:`, err);
|
|
5132
|
+
}
|
|
5133
|
+
}
|
|
4599
5134
|
try {
|
|
4600
5135
|
await this.writeOwnGroupDescriptor();
|
|
4601
5136
|
} catch (err) {
|
|
4602
|
-
|
|
5137
|
+
log5.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
|
|
4603
5138
|
}
|
|
4604
5139
|
this.fs = createChrootFS(this.localFS, "/", {
|
|
4605
5140
|
hiddenPrefixes: [META_DIR, CONFIG_DIR],
|
|
@@ -4609,7 +5144,7 @@ var AppDataGroupImpl = class {
|
|
|
4609
5144
|
});
|
|
4610
5145
|
const { kept, removed } = dedupeAppDataBackends(this._backends);
|
|
4611
5146
|
if (removed.length > 0) {
|
|
4612
|
-
|
|
5147
|
+
log5.warn(
|
|
4613
5148
|
`[AppDataGroup:${this.groupId}] dedupe: removing ${removed.length} duplicate backend(s) (${removed.map((b) => b.id).join(", ")}) \u2014 keeping ${kept.map((b) => b.id).join(", ")}`
|
|
4614
5149
|
);
|
|
4615
5150
|
this._backends = kept;
|
|
@@ -4623,12 +5158,20 @@ var AppDataGroupImpl = class {
|
|
|
4623
5158
|
features: this._declaredFeatures
|
|
4624
5159
|
});
|
|
4625
5160
|
} catch (err) {
|
|
4626
|
-
|
|
5161
|
+
log5.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
|
|
4627
5162
|
}
|
|
4628
5163
|
}
|
|
4629
5164
|
for (const desc of this._backends) {
|
|
4630
5165
|
try {
|
|
4631
5166
|
const instance = await createBackend({ type: desc.type, options: desc.options });
|
|
5167
|
+
const owned = await this.checkBackendOwnership(instance, desc.id);
|
|
5168
|
+
if (owned === "conflict") {
|
|
5169
|
+
try {
|
|
5170
|
+
await instance.dispose?.();
|
|
5171
|
+
} catch {
|
|
5172
|
+
}
|
|
5173
|
+
continue;
|
|
5174
|
+
}
|
|
4632
5175
|
const syncable = backendToSyncableFS(instance, `${desc.type}(${desc.id})`);
|
|
4633
5176
|
const pair = this.syncEngine.addPair(
|
|
4634
5177
|
localSyncable,
|
|
@@ -4639,7 +5182,8 @@ var AppDataGroupImpl = class {
|
|
|
4639
5182
|
pollIntervalMs: this._pollIntervalMs,
|
|
4640
5183
|
// `.meta/` is intentionally NOT excluded: tombstones, versions and
|
|
4641
5184
|
// conflicts must sync, otherwise deletions resurrect on other devices.
|
|
4642
|
-
|
|
5185
|
+
// 但要排除"当前墓碑指向的路径"(与配置组同一张表,实时生效)。
|
|
5186
|
+
filter: this.syncFilter,
|
|
4643
5187
|
preSyncHook: async () => {
|
|
4644
5188
|
await this.runTombstonePass("preSync");
|
|
4645
5189
|
},
|
|
@@ -4655,26 +5199,26 @@ var AppDataGroupImpl = class {
|
|
|
4655
5199
|
if (this.features.conflicts) {
|
|
4656
5200
|
const conflictHandler = (event) => {
|
|
4657
5201
|
this.archiveConflict(event).catch((err) => {
|
|
4658
|
-
|
|
5202
|
+
log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
|
|
4659
5203
|
});
|
|
4660
5204
|
};
|
|
4661
5205
|
this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
|
|
4662
5206
|
}
|
|
4663
5207
|
this.trackSyncErrors(desc.id, pair.pairId);
|
|
4664
|
-
|
|
5208
|
+
log5.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
|
|
4665
5209
|
} catch (err) {
|
|
4666
5210
|
const message = err instanceof Error ? err.message : String(err);
|
|
4667
5211
|
this.backendStates.set(desc.id, {
|
|
4668
5212
|
backendId: desc.id,
|
|
4669
5213
|
error: { message, timestamp: Date.now() }
|
|
4670
5214
|
});
|
|
4671
|
-
|
|
5215
|
+
log5.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
|
|
4672
5216
|
}
|
|
4673
5217
|
}
|
|
4674
5218
|
try {
|
|
4675
5219
|
await this.syncEngine.syncAll();
|
|
4676
5220
|
} catch (err) {
|
|
4677
|
-
|
|
5221
|
+
log5.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
|
|
4678
5222
|
}
|
|
4679
5223
|
this.syncEngine.watchAll();
|
|
4680
5224
|
}
|
|
@@ -4689,7 +5233,7 @@ var AppDataGroupImpl = class {
|
|
|
4689
5233
|
try {
|
|
4690
5234
|
await this.tombstones.gc(this.allBackendIds(), this.tombstoneTargets());
|
|
4691
5235
|
} catch (err) {
|
|
4692
|
-
|
|
5236
|
+
log5.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
|
|
4693
5237
|
}
|
|
4694
5238
|
return Array.from(results.values());
|
|
4695
5239
|
}
|
|
@@ -4724,31 +5268,47 @@ var AppDataGroupImpl = class {
|
|
|
4724
5268
|
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : toUint8Array2(data);
|
|
4725
5269
|
await this.versions.record(path, bytes);
|
|
4726
5270
|
} catch (err) {
|
|
4727
|
-
|
|
5271
|
+
log5.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
|
|
4728
5272
|
}
|
|
4729
5273
|
}
|
|
4730
5274
|
/** Delete tombstoned files on local + every connected backend before/after sync. */
|
|
4731
5275
|
async runTombstonePass(stage) {
|
|
4732
5276
|
try {
|
|
4733
5277
|
await this.tombstones.process(this.tombstoneTargets());
|
|
5278
|
+
this.refreshSyncExclusions(await this.tombstones.list());
|
|
4734
5279
|
} catch (err) {
|
|
4735
|
-
|
|
5280
|
+
log5.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
|
|
5281
|
+
}
|
|
5282
|
+
}
|
|
5283
|
+
/**
|
|
5284
|
+
* 把当前墓碑路径写进同步排除表(原地更新共享数组)。
|
|
5285
|
+
*
|
|
5286
|
+
* 目录墓碑的 `${path}/` 前缀是故意的:整棵树已删除,保留期内任何子路径都不
|
|
5287
|
+
* 参与同步。注意**不能**为 `.keep` 占位排除父目录,否则真实数据会被一起挡掉。
|
|
5288
|
+
*/
|
|
5289
|
+
refreshSyncExclusions(tombstones) {
|
|
5290
|
+
this.tombstoneExcludePrefixes.length = 0;
|
|
5291
|
+
this.tombstoneExcludePrefixes.push(...CONFIG_ONLY_PREFIXES);
|
|
5292
|
+
for (const tombstone of tombstones) {
|
|
5293
|
+
if (!tombstone.path) continue;
|
|
5294
|
+
this.tombstoneExcludePrefixes.push(tombstone.path, `${tombstone.path}/`);
|
|
4736
5295
|
}
|
|
4737
5296
|
}
|
|
4738
5297
|
async confirmTombstones() {
|
|
4739
5298
|
try {
|
|
4740
|
-
await this.tombstones.confirm(this.
|
|
5299
|
+
await this.tombstones.confirm(this.tombstoneTargets());
|
|
4741
5300
|
} catch (err) {
|
|
4742
|
-
|
|
5301
|
+
log5.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
|
|
4743
5302
|
}
|
|
4744
5303
|
}
|
|
4745
|
-
/** Write a tombstone for `
|
|
4746
|
-
async writeTombstoneFor(
|
|
5304
|
+
/** Write a tombstone for `path`. Records metadata only — it never creates the path. */
|
|
5305
|
+
async writeTombstoneFor(path, type) {
|
|
4747
5306
|
await this.tombstones.write({
|
|
4748
|
-
path:
|
|
5307
|
+
path: normalizeTombstonePath(path),
|
|
4749
5308
|
deletedAt: Date.now(),
|
|
4750
5309
|
deletedBy: this.localBackendId,
|
|
4751
|
-
confirmedBy: [this.localBackendId]
|
|
5310
|
+
confirmedBy: [this.localBackendId],
|
|
5311
|
+
...type ? { type } : {}
|
|
4752
5312
|
});
|
|
4753
5313
|
}
|
|
4754
5314
|
/**
|
|
@@ -4763,16 +5323,10 @@ var AppDataGroupImpl = class {
|
|
|
4763
5323
|
throw new Error(`Cannot delete metadata path "${normalized}"`);
|
|
4764
5324
|
}
|
|
4765
5325
|
if (await isDirectoryPath(this.localFS, normalized)) {
|
|
4766
|
-
|
|
4767
|
-
|
|
4768
|
-
for (const dir of await collectDirectoriesUnder(this.localFS, normalized)) {
|
|
4769
|
-
const keepPath = dir === "/" ? "/.keep" : `${dir}/.keep`;
|
|
4770
|
-
await this.writeTombstoneFor(keepPath);
|
|
4771
|
-
await this.writeTombstoneFor(`${keepPath}.mtime`);
|
|
4772
|
-
}
|
|
4773
|
-
await removeDirectoryTree(this.localFS, normalized);
|
|
5326
|
+
await this.writeTombstoneFor(normalized, "directory");
|
|
5327
|
+
await purgeTombstonedTree(this.localFS, normalized);
|
|
4774
5328
|
this.schedulePostDeleteSync();
|
|
4775
|
-
|
|
5329
|
+
log5.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (single directory tombstone)`);
|
|
4776
5330
|
return;
|
|
4777
5331
|
}
|
|
4778
5332
|
await this.writeTombstoneFor(normalized);
|
|
@@ -4811,7 +5365,7 @@ var AppDataGroupImpl = class {
|
|
|
4811
5365
|
try {
|
|
4812
5366
|
await this.syncEngine.syncAll();
|
|
4813
5367
|
} catch (err) {
|
|
4814
|
-
|
|
5368
|
+
log5.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
|
|
4815
5369
|
}
|
|
4816
5370
|
}
|
|
4817
5371
|
readConflictBackup(conflictId, fileType) {
|
|
@@ -4846,7 +5400,7 @@ var AppDataGroupImpl = class {
|
|
|
4846
5400
|
if (this.dataBackends.has(id)) {
|
|
4847
5401
|
throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
|
|
4848
5402
|
}
|
|
4849
|
-
|
|
5403
|
+
log5.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
|
|
4850
5404
|
const instance = await createBackend({ type, options });
|
|
4851
5405
|
const syncable = backendToSyncableFS(instance, `${type}(${id})`);
|
|
4852
5406
|
const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
|
|
@@ -4857,7 +5411,7 @@ var AppDataGroupImpl = class {
|
|
|
4857
5411
|
direction: import_zen_fs_sync.SyncDirection.BiDirectional,
|
|
4858
5412
|
conflictStrategy: "source-wins",
|
|
4859
5413
|
pollIntervalMs: this._pollIntervalMs,
|
|
4860
|
-
filter:
|
|
5414
|
+
filter: this.syncFilter,
|
|
4861
5415
|
preSyncHook: async () => {
|
|
4862
5416
|
await this.runTombstonePass("preSync");
|
|
4863
5417
|
},
|
|
@@ -4874,13 +5428,13 @@ var AppDataGroupImpl = class {
|
|
|
4874
5428
|
if (this.features.conflicts) {
|
|
4875
5429
|
this.syncEngine.on(pair.pairId, "conflict", (event) => {
|
|
4876
5430
|
this.archiveConflict(event).catch((err) => {
|
|
4877
|
-
|
|
5431
|
+
log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
|
|
4878
5432
|
});
|
|
4879
5433
|
});
|
|
4880
5434
|
}
|
|
4881
5435
|
this.trackSyncErrors(id, pair.pairId);
|
|
4882
5436
|
this._backends = [...this._backends.filter((b) => b.id !== id), desc];
|
|
4883
|
-
|
|
5437
|
+
log5.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
|
|
4884
5438
|
try {
|
|
4885
5439
|
const stale = (await this.tombstones.list()).find(
|
|
4886
5440
|
(t) => t.path === backendMetaFilePath(id)
|
|
@@ -4888,12 +5442,12 @@ var AppDataGroupImpl = class {
|
|
|
4888
5442
|
if (stale) await this.tombstones.remove(stale);
|
|
4889
5443
|
await writeBackendMetaDescriptor(this.localFS, desc);
|
|
4890
5444
|
} catch (err) {
|
|
4891
|
-
|
|
5445
|
+
log5.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
|
|
4892
5446
|
}
|
|
4893
5447
|
try {
|
|
4894
5448
|
await this.syncEngine.sync(pair.pairId);
|
|
4895
5449
|
} catch (err) {
|
|
4896
|
-
|
|
5450
|
+
log5.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
|
|
4897
5451
|
}
|
|
4898
5452
|
this.syncEngine.watch(pair.pairId);
|
|
4899
5453
|
await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends, {
|
|
@@ -4924,7 +5478,7 @@ var AppDataGroupImpl = class {
|
|
|
4924
5478
|
if (backend?.instance?.dispose) {
|
|
4925
5479
|
await backend.instance.dispose();
|
|
4926
5480
|
}
|
|
4927
|
-
|
|
5481
|
+
log5.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
|
|
4928
5482
|
}
|
|
4929
5483
|
listBackends() {
|
|
4930
5484
|
return Array.from(this.dataBackends.values()).map((b) => b.desc);
|
|
@@ -4966,44 +5520,44 @@ async function createConfigRepo(appId, options = {}) {
|
|
|
4966
5520
|
idbStoreName: options.idbStoreName,
|
|
4967
5521
|
folderPath: options.folderPath
|
|
4968
5522
|
});
|
|
4969
|
-
|
|
5523
|
+
log5.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
|
|
4970
5524
|
const primaryInstance = await createBackend(localPrimary);
|
|
4971
5525
|
const cachedFS = primaryInstance;
|
|
4972
5526
|
if (options.purgeMtimeSidecars !== false) {
|
|
4973
5527
|
try {
|
|
4974
5528
|
const purged = await purgeMtimeSidecars(cachedFS);
|
|
4975
5529
|
if (purged.removed.length > 0) {
|
|
4976
|
-
|
|
5530
|
+
log5.warn(
|
|
4977
5531
|
`[createConfigRepo] purged ${purged.removed.length} leaked .mtime sidecar(s) from local primary:`,
|
|
4978
5532
|
purged.removed
|
|
4979
5533
|
);
|
|
4980
5534
|
}
|
|
4981
5535
|
} catch (err) {
|
|
4982
|
-
|
|
5536
|
+
log5.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
|
|
4983
5537
|
}
|
|
4984
5538
|
}
|
|
4985
5539
|
if (options.purgeKeepFiles !== false) {
|
|
4986
5540
|
try {
|
|
4987
5541
|
const purged = await purgeKeepFiles(cachedFS);
|
|
4988
5542
|
if (purged.removed.length > 0) {
|
|
4989
|
-
|
|
5543
|
+
log5.warn(
|
|
4990
5544
|
`[createConfigRepo] purged ${purged.removed.length} leaked .keep placeholder(s) from local primary:`,
|
|
4991
5545
|
purged.removed
|
|
4992
5546
|
);
|
|
4993
5547
|
}
|
|
4994
5548
|
} catch (err) {
|
|
4995
|
-
|
|
5549
|
+
log5.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
|
|
4996
5550
|
}
|
|
4997
5551
|
}
|
|
4998
5552
|
const cacheOptions = options.cache === false ? void 0 : options.cache ?? {};
|
|
4999
5553
|
try {
|
|
5000
5554
|
await primaryInstance.mkdir(META_DIR);
|
|
5001
|
-
|
|
5555
|
+
log5.log(`[createConfigRepo] /.meta/ ready`);
|
|
5002
5556
|
} catch (err) {
|
|
5003
5557
|
const msg = err.message || "";
|
|
5004
5558
|
if (msg.includes("File exists") || msg.includes("EEXIST") || err.code === "EEXIST") {
|
|
5005
5559
|
} else {
|
|
5006
|
-
|
|
5560
|
+
log5.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
|
|
5007
5561
|
}
|
|
5008
5562
|
}
|
|
5009
5563
|
try {
|
|
@@ -5014,7 +5568,7 @@ async function createConfigRepo(appId, options = {}) {
|
|
|
5014
5568
|
} catch {
|
|
5015
5569
|
await ensureParentDir2(primaryInstance, path);
|
|
5016
5570
|
await primaryInstance.writeFile(path, groupTypeBytes);
|
|
5017
|
-
|
|
5571
|
+
log5.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
|
|
5018
5572
|
}
|
|
5019
5573
|
}
|
|
5020
5574
|
if (!await readGroupDescriptor(primaryInstance)) {
|
|
@@ -5022,11 +5576,12 @@ async function createConfigRepo(appId, options = {}) {
|
|
|
5022
5576
|
schemaVersion: 2,
|
|
5023
5577
|
kind: "config",
|
|
5024
5578
|
id: CONFIG_GROUP_ID,
|
|
5579
|
+
instanceId: newGroupInstanceId(),
|
|
5025
5580
|
features: CONFIG_GROUP_FEATURES
|
|
5026
5581
|
});
|
|
5027
5582
|
}
|
|
5028
5583
|
} catch (err) {
|
|
5029
|
-
|
|
5584
|
+
log5.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
|
|
5030
5585
|
}
|
|
5031
5586
|
const tempRepo = new ConfigRepo(
|
|
5032
5587
|
appId,
|
|
@@ -5040,11 +5595,11 @@ async function createConfigRepo(appId, options = {}) {
|
|
|
5040
5595
|
);
|
|
5041
5596
|
const oldBackendsMeta = await tempRepo.readMetaFile(BACKENDS_FILE);
|
|
5042
5597
|
if (oldBackendsMeta && oldBackendsMeta.backends?.length > 0) {
|
|
5043
|
-
|
|
5598
|
+
log5.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
|
|
5044
5599
|
await tempRepo.ensureDir(`${BACKENDS_DIR}/.keep`);
|
|
5045
5600
|
for (const desc of oldBackendsMeta.backends) {
|
|
5046
5601
|
if (desc.id === LOCAL_IDB_BACKEND_ID) {
|
|
5047
|
-
|
|
5602
|
+
log5.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
|
|
5048
5603
|
continue;
|
|
5049
5604
|
}
|
|
5050
5605
|
await tempRepo.writeBackendDescriptor(desc);
|
|
@@ -5062,7 +5617,7 @@ async function createConfigRepo(appId, options = {}) {
|
|
|
5062
5617
|
}
|
|
5063
5618
|
}
|
|
5064
5619
|
}
|
|
5065
|
-
|
|
5620
|
+
log5.log(`[createConfigRepo] Migration complete`);
|
|
5066
5621
|
}
|
|
5067
5622
|
let allBackends = await tempRepo.readAllBackendDescriptors();
|
|
5068
5623
|
if (options.backendInfo) {
|
|
@@ -5080,19 +5635,19 @@ async function createConfigRepo(appId, options = {}) {
|
|
|
5080
5635
|
type: options.backendInfo.type,
|
|
5081
5636
|
options: options.backendInfo.options
|
|
5082
5637
|
});
|
|
5083
|
-
|
|
5638
|
+
log5.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
|
|
5084
5639
|
allBackends = [...allBackends, { id: replicaId, type: options.backendInfo.type, options: options.backendInfo.options }];
|
|
5085
5640
|
} else if (dupConfig) {
|
|
5086
|
-
|
|
5641
|
+
log5.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
|
|
5087
5642
|
} else {
|
|
5088
|
-
|
|
5643
|
+
log5.log(`[createConfigRepo] Replica ${replicaId} already registered`);
|
|
5089
5644
|
}
|
|
5090
5645
|
}
|
|
5091
|
-
|
|
5646
|
+
log5.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
|
|
5092
5647
|
let nodeId = options.nodeId;
|
|
5093
5648
|
if (!nodeId) {
|
|
5094
5649
|
nodeId = `node-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
5095
|
-
|
|
5650
|
+
log5.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
|
|
5096
5651
|
}
|
|
5097
5652
|
const serializer = createSerializerChain(options.serializer);
|
|
5098
5653
|
const repo = new ConfigRepo(
|
|
@@ -5115,19 +5670,19 @@ async function createConfigRepo(appId, options = {}) {
|
|
|
5115
5670
|
try {
|
|
5116
5671
|
const mig = await repo.migrateLegacyVersionSidecars();
|
|
5117
5672
|
if (mig.renamed.length === 0 && mig.deleted.length === 0 && mig.remoteDeleted.length === 0) {
|
|
5118
|
-
|
|
5673
|
+
log5.log("[createConfigRepo] no legacy version sidecars to migrate");
|
|
5119
5674
|
}
|
|
5120
5675
|
} catch (err) {
|
|
5121
|
-
|
|
5676
|
+
log5.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
|
|
5122
5677
|
}
|
|
5123
5678
|
}
|
|
5124
5679
|
await repo.load();
|
|
5125
5680
|
if (repo.replicaCount > 0) {
|
|
5126
|
-
|
|
5681
|
+
log5.log("[createConfigRepo] Starting background initial sync + dedup...");
|
|
5127
5682
|
repo.startBackgroundSync();
|
|
5128
5683
|
}
|
|
5129
5684
|
repo.syncMetaToReplicas().catch((err) => {
|
|
5130
|
-
|
|
5685
|
+
log5.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
|
|
5131
5686
|
});
|
|
5132
5687
|
return repo;
|
|
5133
5688
|
}
|
|
@@ -5141,11 +5696,11 @@ function sidecarOwnerPath(path) {
|
|
|
5141
5696
|
|
|
5142
5697
|
// src/connect.ts
|
|
5143
5698
|
init_backend_registry();
|
|
5144
|
-
var
|
|
5699
|
+
var log6 = createLogger2("connect");
|
|
5145
5700
|
var GROUP_TYPE_FILE2 = "/.config/group-type";
|
|
5146
5701
|
var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
|
|
5147
5702
|
async function detectGroupType(type, options) {
|
|
5148
|
-
|
|
5703
|
+
log6(`detectGroupType: connecting to ${type}...`);
|
|
5149
5704
|
const tempBackend = await createBackend({ type, options });
|
|
5150
5705
|
try {
|
|
5151
5706
|
for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
|
|
@@ -5153,15 +5708,15 @@ async function detectGroupType(type, options) {
|
|
|
5153
5708
|
const raw = await tempBackend.readFile(path, "utf-8");
|
|
5154
5709
|
const groupType = raw.trim();
|
|
5155
5710
|
if (groupType === "config-sync" || groupType === "data-sync") {
|
|
5156
|
-
|
|
5711
|
+
log6(`detectGroupType: detected "${groupType}" at ${path}`);
|
|
5157
5712
|
return groupType;
|
|
5158
5713
|
}
|
|
5159
|
-
|
|
5714
|
+
log6(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
|
|
5160
5715
|
return null;
|
|
5161
5716
|
} catch {
|
|
5162
5717
|
}
|
|
5163
5718
|
}
|
|
5164
|
-
|
|
5719
|
+
log6(`detectGroupType: no group-type file found (new backend)`);
|
|
5165
5720
|
return null;
|
|
5166
5721
|
} finally {
|
|
5167
5722
|
if (tempBackend?.dispose) {
|
|
@@ -5170,7 +5725,7 @@ async function detectGroupType(type, options) {
|
|
|
5170
5725
|
}
|
|
5171
5726
|
}
|
|
5172
5727
|
async function connect(appId, options = {}) {
|
|
5173
|
-
|
|
5728
|
+
log6(`connect: appId=${appId}`);
|
|
5174
5729
|
if (!options.backendInfo) {
|
|
5175
5730
|
const repo2 = await createConfigRepo(appId, {
|
|
5176
5731
|
idbStoreName: options.idbStoreName,
|
|
@@ -5188,12 +5743,12 @@ async function connect(appId, options = {}) {
|
|
|
5188
5743
|
try {
|
|
5189
5744
|
appDataGroups2.push(await repo2.getAppDataGroup(d.id));
|
|
5190
5745
|
} catch (err) {
|
|
5191
|
-
|
|
5746
|
+
log6(`connect: failed to load app data group "${d.id}":`, err);
|
|
5192
5747
|
}
|
|
5193
5748
|
}
|
|
5194
5749
|
const dataGroup2 = appDataGroups2[0];
|
|
5195
5750
|
if (!dataGroup2 && descriptors2.length > 0) {
|
|
5196
|
-
|
|
5751
|
+
log6(
|
|
5197
5752
|
`connect: ${descriptors2.length} data group descriptor(s) found but none could be loaded; leaving them untouched (no empty group is created)`
|
|
5198
5753
|
);
|
|
5199
5754
|
}
|
|
@@ -5218,7 +5773,7 @@ async function connect(appId, options = {}) {
|
|
|
5218
5773
|
groupType = detectedType;
|
|
5219
5774
|
} else {
|
|
5220
5775
|
groupType = options.groupType ?? "config-sync";
|
|
5221
|
-
|
|
5776
|
+
log6(`connect: new backend, using groupType="${groupType}"`);
|
|
5222
5777
|
}
|
|
5223
5778
|
const repo = await createConfigRepo(
|
|
5224
5779
|
appId,
|
|
@@ -5247,14 +5802,14 @@ async function connect(appId, options = {}) {
|
|
|
5247
5802
|
try {
|
|
5248
5803
|
appDataGroups.push(await repo.getAppDataGroup(d.id));
|
|
5249
5804
|
} catch (err) {
|
|
5250
|
-
|
|
5805
|
+
log6(`connect: failed to load app data group "${d.id}":`, err);
|
|
5251
5806
|
}
|
|
5252
5807
|
}
|
|
5253
5808
|
let dataGroup = appDataGroups[0];
|
|
5254
5809
|
if (groupType === "data-sync") {
|
|
5255
5810
|
if (!dataGroup) {
|
|
5256
5811
|
if (descriptors.length > 0) {
|
|
5257
|
-
|
|
5812
|
+
log6(
|
|
5258
5813
|
`connect: ${descriptors.length} data group descriptor(s) exist but could not be loaded; refusing to create/overwrite "default"`
|
|
5259
5814
|
);
|
|
5260
5815
|
} else {
|