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/zen-fs-config.js
CHANGED
|
@@ -1166,14 +1166,14 @@ var ZenFSConfig = (() => {
|
|
|
1166
1166
|
isEnabled: () => isEnabled2,
|
|
1167
1167
|
levelOf: () => levelOf,
|
|
1168
1168
|
levels: () => levels,
|
|
1169
|
-
log: () =>
|
|
1169
|
+
log: () => log5,
|
|
1170
1170
|
notice: () => notice,
|
|
1171
1171
|
warn: () => warn
|
|
1172
1172
|
});
|
|
1173
1173
|
function levelOf(value) {
|
|
1174
1174
|
return levels.indexOf(value);
|
|
1175
1175
|
}
|
|
1176
|
-
function
|
|
1176
|
+
function log5(level, message) {
|
|
1177
1177
|
if (!isEnabled2)
|
|
1178
1178
|
return;
|
|
1179
1179
|
const entry = {
|
|
@@ -1187,12 +1187,12 @@ var ZenFSConfig = (() => {
|
|
|
1187
1187
|
}
|
|
1188
1188
|
function _shortcut(level) {
|
|
1189
1189
|
return function(message) {
|
|
1190
|
-
|
|
1190
|
+
log5(level, message.toString());
|
|
1191
1191
|
return message;
|
|
1192
1192
|
};
|
|
1193
1193
|
}
|
|
1194
1194
|
function deprecated(symbol) {
|
|
1195
|
-
|
|
1195
|
+
log5(Level.WARN, symbol + " is deprecated and should not be used.");
|
|
1196
1196
|
}
|
|
1197
1197
|
function ansi(text, format4) {
|
|
1198
1198
|
return `\x1B[${format4}m${text}\x1B[0m`;
|
|
@@ -24410,6 +24410,17 @@ var ZenFSConfig = (() => {
|
|
|
24410
24410
|
const notifyChange = () => {
|
|
24411
24411
|
if (changeCallback) changeCallback();
|
|
24412
24412
|
};
|
|
24413
|
+
const writeQueues = /* @__PURE__ */ new Map();
|
|
24414
|
+
const runExclusive = async (path, task) => {
|
|
24415
|
+
const prev = writeQueues.get(path);
|
|
24416
|
+
const run = (prev ?? Promise.resolve()).catch(() => void 0).then(task);
|
|
24417
|
+
writeQueues.set(path, run);
|
|
24418
|
+
try {
|
|
24419
|
+
await run;
|
|
24420
|
+
} finally {
|
|
24421
|
+
if (writeQueues.get(path) === run) writeQueues.delete(path);
|
|
24422
|
+
}
|
|
24423
|
+
};
|
|
24413
24424
|
const backend = {
|
|
24414
24425
|
async readFile(path, ...args) {
|
|
24415
24426
|
const st = await isolatedFS.stat(path);
|
|
@@ -24420,24 +24431,28 @@ var ZenFSConfig = (() => {
|
|
|
24420
24431
|
return buf;
|
|
24421
24432
|
},
|
|
24422
24433
|
async writeFile(path, data, _options) {
|
|
24423
|
-
const
|
|
24424
|
-
const
|
|
24425
|
-
|
|
24426
|
-
|
|
24427
|
-
|
|
24428
|
-
dir
|
|
24429
|
-
|
|
24430
|
-
|
|
24434
|
+
const source = data instanceof ArrayBuffer ? new Uint8Array(data) : data instanceof Uint8Array ? data : new TextEncoder().encode(data);
|
|
24435
|
+
const bytes = new Uint8Array(source);
|
|
24436
|
+
await runExclusive(path, async () => {
|
|
24437
|
+
const parts = path.split("/").filter(Boolean);
|
|
24438
|
+
parts.pop();
|
|
24439
|
+
let dir = "";
|
|
24440
|
+
for (const p of parts) {
|
|
24441
|
+
dir += "/" + p;
|
|
24442
|
+
if (!await isolatedFS.exists(dir)) {
|
|
24443
|
+
await isolatedFS.mkdir(dir, { uid: 0, gid: 0, mode: 493 });
|
|
24444
|
+
}
|
|
24445
|
+
}
|
|
24446
|
+
if (await isolatedFS.exists(path)) {
|
|
24447
|
+
await isolatedFS.unlink(path);
|
|
24431
24448
|
}
|
|
24432
|
-
}
|
|
24433
|
-
if (!await isolatedFS.exists(path)) {
|
|
24434
24449
|
await isolatedFS.createFile(path, { uid: 0, gid: 0, mode: 420 });
|
|
24435
|
-
|
|
24436
|
-
|
|
24437
|
-
|
|
24438
|
-
|
|
24439
|
-
|
|
24440
|
-
}
|
|
24450
|
+
await isolatedFS.write(path, bytes, 0);
|
|
24451
|
+
try {
|
|
24452
|
+
await isolatedFS.touch(path, { size: bytes.byteLength, mtimeMs: _options?.mtime ?? Date.now() });
|
|
24453
|
+
} catch {
|
|
24454
|
+
}
|
|
24455
|
+
});
|
|
24441
24456
|
notifyChange();
|
|
24442
24457
|
},
|
|
24443
24458
|
async readdir(path) {
|
|
@@ -25268,7 +25283,7 @@ var ZenFSConfig = (() => {
|
|
|
25268
25283
|
ConflictStore: () => ConflictStore,
|
|
25269
25284
|
DATA_GROUP_DEFAULT_FEATURES: () => DATA_GROUP_DEFAULT_FEATURES,
|
|
25270
25285
|
FolderStore: () => FolderStore,
|
|
25271
|
-
GROUP_DESCRIPTOR_FILE: () =>
|
|
25286
|
+
GROUP_DESCRIPTOR_FILE: () => GROUP_DESCRIPTOR_FILE2,
|
|
25272
25287
|
LEGACY_CONFLICTS_DIR: () => LEGACY_CONFLICTS_DIR,
|
|
25273
25288
|
LEGACY_TOMBSTONES_DIR: () => LEGACY_TOMBSTONES_DIR,
|
|
25274
25289
|
LOCAL_IDB_BACKEND_ID: () => LOCAL_IDB_BACKEND_ID,
|
|
@@ -26744,6 +26759,91 @@ var ZenFSConfig = (() => {
|
|
|
26744
26759
|
async function ensureParentDir(absolutePath) {
|
|
26745
26760
|
}
|
|
26746
26761
|
|
|
26762
|
+
// src/group-type-guard.ts
|
|
26763
|
+
var log4 = createLogger("zen-fs-config:group-type-guard");
|
|
26764
|
+
var GROUP_TYPE_FILES = /* @__PURE__ */ new Set(["/.config/group-type", "/.meta/group-type"]);
|
|
26765
|
+
var GROUP_DESCRIPTOR_FILE = "/.meta/group.json";
|
|
26766
|
+
var APP_DATA_GROUP_DESCRIPTOR_RE = /^\/\.config\/app-data-groups\/[^/]+\/[^/]+\.json$/;
|
|
26767
|
+
function decode(data) {
|
|
26768
|
+
if (typeof data === "string") return data;
|
|
26769
|
+
if (data instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(data));
|
|
26770
|
+
return new TextDecoder().decode(data);
|
|
26771
|
+
}
|
|
26772
|
+
function safeParse(text) {
|
|
26773
|
+
try {
|
|
26774
|
+
return JSON.parse(text);
|
|
26775
|
+
} catch {
|
|
26776
|
+
return null;
|
|
26777
|
+
}
|
|
26778
|
+
}
|
|
26779
|
+
function readGroupIdentity(path, data) {
|
|
26780
|
+
const normalized = path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
|
|
26781
|
+
const isGroupType = GROUP_TYPE_FILES.has(normalized);
|
|
26782
|
+
const isGroupDescriptor = normalized === GROUP_DESCRIPTOR_FILE;
|
|
26783
|
+
const isAppDataGroup = APP_DATA_GROUP_DESCRIPTOR_RE.test(normalized);
|
|
26784
|
+
if (!isGroupType && !isGroupDescriptor && !isAppDataGroup) return null;
|
|
26785
|
+
const text = decode(data);
|
|
26786
|
+
if (isGroupType) {
|
|
26787
|
+
const value = text.trim();
|
|
26788
|
+
return value || null;
|
|
26789
|
+
}
|
|
26790
|
+
const parsed = safeParse(text);
|
|
26791
|
+
if (isGroupDescriptor) {
|
|
26792
|
+
return typeof parsed?.kind === "string" ? `kind:${parsed.kind}` : null;
|
|
26793
|
+
}
|
|
26794
|
+
return typeof parsed?.groupType === "string" ? `groupType:${parsed.groupType}` : null;
|
|
26795
|
+
}
|
|
26796
|
+
async function readExistingIdentity(fs, path) {
|
|
26797
|
+
try {
|
|
26798
|
+
const raw = await fs.readFile(path, "utf-8");
|
|
26799
|
+
return readGroupIdentity(path, raw);
|
|
26800
|
+
} catch {
|
|
26801
|
+
return null;
|
|
26802
|
+
}
|
|
26803
|
+
}
|
|
26804
|
+
function wrapGroupTypeGuard(fs, side, onBlock) {
|
|
26805
|
+
const reported = /* @__PURE__ */ new Set();
|
|
26806
|
+
const guarded = Object.create(fs);
|
|
26807
|
+
const lastBlock = { current: null };
|
|
26808
|
+
guarded.getLastBlockedGroupType = () => lastBlock.current;
|
|
26809
|
+
const allow = async (path, data) => {
|
|
26810
|
+
const incoming = readGroupIdentity(path, data);
|
|
26811
|
+
if (incoming === null) return true;
|
|
26812
|
+
const existing = await readExistingIdentity(fs, path);
|
|
26813
|
+
if (existing === null || existing === incoming) return true;
|
|
26814
|
+
const signature = `${side}|${path}|${existing}->${incoming}`;
|
|
26815
|
+
const block = { side, path, existing, incoming };
|
|
26816
|
+
lastBlock.current = block;
|
|
26817
|
+
if (!reported.has(signature)) {
|
|
26818
|
+
reported.add(signature);
|
|
26819
|
+
log4.warn(
|
|
26820
|
+
`[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)`
|
|
26821
|
+
);
|
|
26822
|
+
}
|
|
26823
|
+
try {
|
|
26824
|
+
onBlock?.(block);
|
|
26825
|
+
} catch {
|
|
26826
|
+
}
|
|
26827
|
+
return false;
|
|
26828
|
+
};
|
|
26829
|
+
guarded.writeFile = async (path, data) => {
|
|
26830
|
+
if (!await allow(path, data)) return;
|
|
26831
|
+
return fs.writeFile(path, data);
|
|
26832
|
+
};
|
|
26833
|
+
if (typeof fs.writeFileWithMtime === "function") {
|
|
26834
|
+
guarded.writeFileWithMtime = async (path, data, mtime) => {
|
|
26835
|
+
if (!await allow(path, data)) return;
|
|
26836
|
+
return fs.writeFileWithMtime(path, data, mtime);
|
|
26837
|
+
};
|
|
26838
|
+
}
|
|
26839
|
+
guarded.backendName = sideLabel(fs.backendName, side);
|
|
26840
|
+
return guarded;
|
|
26841
|
+
}
|
|
26842
|
+
function sideLabel(name, side) {
|
|
26843
|
+
if (!name) return side;
|
|
26844
|
+
return name.includes(side) ? name : `${name}\xB7${side}`;
|
|
26845
|
+
}
|
|
26846
|
+
|
|
26747
26847
|
// src/adapters.ts
|
|
26748
26848
|
function toUint8Array(data) {
|
|
26749
26849
|
if (data instanceof Uint8Array) return data;
|
|
@@ -26817,7 +26917,7 @@ var ZenFSConfig = (() => {
|
|
|
26817
26917
|
} else {
|
|
26818
26918
|
syncable.backendName = backend.constructor.name || "Backend";
|
|
26819
26919
|
}
|
|
26820
|
-
return syncable;
|
|
26920
|
+
return wrapGroupTypeGuard(syncable, syncable.backendName || "backend");
|
|
26821
26921
|
}
|
|
26822
26922
|
|
|
26823
26923
|
// src/config-repo.ts
|
|
@@ -26835,7 +26935,7 @@ var ZenFSConfig = (() => {
|
|
|
26835
26935
|
}
|
|
26836
26936
|
|
|
26837
26937
|
// src/folder-backend.ts
|
|
26838
|
-
var
|
|
26938
|
+
var log6 = createLogger3("folder-backend");
|
|
26839
26939
|
var FolderStore = class {
|
|
26840
26940
|
constructor(init2) {
|
|
26841
26941
|
__publicField(this, "name", "folder");
|
|
@@ -26922,7 +27022,7 @@ var ZenFSConfig = (() => {
|
|
|
26922
27022
|
defaultOptions: { path: "" }
|
|
26923
27023
|
}
|
|
26924
27024
|
);
|
|
26925
|
-
|
|
27025
|
+
log6("Folder backend registered");
|
|
26926
27026
|
}
|
|
26927
27027
|
registerFolderBackend();
|
|
26928
27028
|
function isBrowserEnv() {
|
|
@@ -27315,327 +27415,162 @@ var ZenFSConfig = (() => {
|
|
|
27315
27415
|
}
|
|
27316
27416
|
}
|
|
27317
27417
|
|
|
27318
|
-
// src/
|
|
27319
|
-
|
|
27320
|
-
|
|
27418
|
+
// src/canonical-json.ts
|
|
27419
|
+
var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
|
|
27420
|
+
var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "instanceId", "name", "features"];
|
|
27421
|
+
var APP_DATA_GROUP_ORDER = ["id", "groupType", "instanceId", "name", "features", "backends"];
|
|
27422
|
+
var BACKEND_ORDER = ["id", "type", "options", "accountBackendId", "description", "createdAt"];
|
|
27423
|
+
function compareKeys(a, b) {
|
|
27424
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
27321
27425
|
}
|
|
27322
|
-
|
|
27323
|
-
|
|
27324
|
-
return typeof stat5.mode === "number" && (stat5.mode & S_IFDIR2) === S_IFDIR2;
|
|
27426
|
+
function isPlainObject(value) {
|
|
27427
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
27325
27428
|
}
|
|
27326
|
-
function
|
|
27327
|
-
|
|
27328
|
-
|
|
27429
|
+
function canonicalObject(value, order = []) {
|
|
27430
|
+
const out = {};
|
|
27431
|
+
for (const key of order) {
|
|
27432
|
+
if (value[key] !== void 0) out[key] = canonicalField(key, value[key]);
|
|
27433
|
+
}
|
|
27434
|
+
for (const key of Object.keys(value).sort(compareKeys)) {
|
|
27435
|
+
if (order.includes(key) || value[key] === void 0) continue;
|
|
27436
|
+
out[key] = canonicalField(key, value[key]);
|
|
27437
|
+
}
|
|
27438
|
+
return out;
|
|
27329
27439
|
}
|
|
27330
|
-
|
|
27331
|
-
|
|
27332
|
-
|
|
27333
|
-
|
|
27334
|
-
|
|
27335
|
-
|
|
27336
|
-
const dir = stack.pop();
|
|
27337
|
-
let entries2;
|
|
27338
|
-
try {
|
|
27339
|
-
entries2 = await fs.readdir(dir);
|
|
27340
|
-
} catch {
|
|
27341
|
-
continue;
|
|
27342
|
-
}
|
|
27343
|
-
for (const entry of entries2) {
|
|
27344
|
-
const fullPath = joinPath(dir, entry);
|
|
27345
|
-
let stat5;
|
|
27346
|
-
try {
|
|
27347
|
-
stat5 = await fs.stat(fullPath);
|
|
27348
|
-
} catch {
|
|
27349
|
-
continue;
|
|
27350
|
-
}
|
|
27351
|
-
if (isDirectory3(stat5)) {
|
|
27352
|
-
stack.push(fullPath);
|
|
27353
|
-
continue;
|
|
27354
|
-
}
|
|
27355
|
-
result.scanned++;
|
|
27356
|
-
if (!isMtimeSidecar(entry)) continue;
|
|
27357
|
-
if (dryRun) {
|
|
27358
|
-
result.removed.push(fullPath);
|
|
27359
|
-
continue;
|
|
27360
|
-
}
|
|
27361
|
-
try {
|
|
27362
|
-
await fs.unlink(fullPath);
|
|
27363
|
-
result.removed.push(fullPath);
|
|
27364
|
-
} catch {
|
|
27365
|
-
result.failed.push(fullPath);
|
|
27366
|
-
}
|
|
27440
|
+
function canonicalField(key, value) {
|
|
27441
|
+
if (Array.isArray(value)) {
|
|
27442
|
+
if (key === "backends") {
|
|
27443
|
+
return value.map((item) => isPlainObject(item) ? canonicalObject(item, BACKEND_ORDER) : item).sort(
|
|
27444
|
+
(a, b) => compareKeys(String(a?.id ?? ""), String(b?.id ?? ""))
|
|
27445
|
+
);
|
|
27367
27446
|
}
|
|
27447
|
+
return value.map((item) => canonicalField("", item));
|
|
27368
27448
|
}
|
|
27369
|
-
|
|
27449
|
+
if (isPlainObject(value)) {
|
|
27450
|
+
if (key === "features") return canonicalObject(value, FEATURE_ORDER);
|
|
27451
|
+
return canonicalObject(value);
|
|
27452
|
+
}
|
|
27453
|
+
return value;
|
|
27370
27454
|
}
|
|
27371
|
-
|
|
27372
|
-
|
|
27373
|
-
function isKeepFile(fileName) {
|
|
27374
|
-
return fileName === ".keep";
|
|
27455
|
+
function stringify(value) {
|
|
27456
|
+
return JSON.stringify(value, null, 2);
|
|
27375
27457
|
}
|
|
27376
|
-
|
|
27377
|
-
|
|
27378
|
-
|
|
27379
|
-
return typeof stat5.mode === "number" && (stat5.mode & S_IFDIR3) === S_IFDIR3;
|
|
27458
|
+
function serializeGroupDescriptor(descriptor) {
|
|
27459
|
+
const { updatedAt: _ignored, ...rest } = descriptor;
|
|
27460
|
+
return stringify(canonicalObject(rest, GROUP_DESCRIPTOR_ORDER));
|
|
27380
27461
|
}
|
|
27381
|
-
function
|
|
27382
|
-
|
|
27383
|
-
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
27462
|
+
function serializeBackendDescriptor(descriptor) {
|
|
27463
|
+
return stringify(canonicalObject(descriptor, BACKEND_ORDER));
|
|
27384
27464
|
}
|
|
27385
|
-
function
|
|
27386
|
-
return
|
|
27387
|
-
const dir = d.endsWith("/") ? d.slice(0, -1) : d;
|
|
27388
|
-
return fullPath === dir || fullPath.startsWith(dir + "/");
|
|
27389
|
-
});
|
|
27465
|
+
function serializeAppDataGroupDescriptor(descriptor) {
|
|
27466
|
+
return stringify(canonicalObject(descriptor, APP_DATA_GROUP_ORDER));
|
|
27390
27467
|
}
|
|
27391
|
-
|
|
27392
|
-
const
|
|
27393
|
-
|
|
27394
|
-
|
|
27395
|
-
|
|
27396
|
-
const
|
|
27397
|
-
|
|
27398
|
-
|
|
27399
|
-
|
|
27400
|
-
|
|
27468
|
+
function stripBackendCreatedAt(descriptor) {
|
|
27469
|
+
const { createdAt: _ignored, ...rest } = descriptor;
|
|
27470
|
+
return rest;
|
|
27471
|
+
}
|
|
27472
|
+
function mergeBackendDescriptor(existing, incoming) {
|
|
27473
|
+
const existingCreatedAt = typeof existing?.createdAt === "number" ? existing.createdAt : void 0;
|
|
27474
|
+
const incomingCreatedAt = typeof incoming.createdAt === "number" ? incoming.createdAt : void 0;
|
|
27475
|
+
const createdAt = existingCreatedAt === void 0 ? incomingCreatedAt : incomingCreatedAt === void 0 ? existingCreatedAt : Math.min(existingCreatedAt, incomingCreatedAt);
|
|
27476
|
+
return createdAt === void 0 ? stripBackendCreatedAt(incoming) : { ...incoming, createdAt };
|
|
27477
|
+
}
|
|
27478
|
+
function mergeBackendCreatedAt(incoming, existing) {
|
|
27479
|
+
if (!existing || existing.length === 0) return incoming;
|
|
27480
|
+
const byId = new Map(existing.map((d) => [d.id, d]));
|
|
27481
|
+
return incoming.map((desc) => mergeBackendDescriptor(byId.get(desc.id), desc));
|
|
27482
|
+
}
|
|
27483
|
+
function mergeDescriptorCreatedAt(descriptor, existing) {
|
|
27484
|
+
return {
|
|
27485
|
+
...descriptor,
|
|
27486
|
+
backends: mergeBackendCreatedAt(descriptor.backends, existing?.backends)
|
|
27487
|
+
};
|
|
27488
|
+
}
|
|
27489
|
+
|
|
27490
|
+
// src/group-meta.ts
|
|
27491
|
+
var log7 = createLogger("zen-fs-config:tombstones");
|
|
27492
|
+
var META_DIR = "/.meta";
|
|
27493
|
+
var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
|
|
27494
|
+
var META_BACKENDS_DIR = `${META_DIR}/backends`;
|
|
27495
|
+
var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
|
|
27496
|
+
var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
|
|
27497
|
+
var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
|
|
27498
|
+
var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
|
|
27499
|
+
function tombstoneRetentionMs(tombstonePath) {
|
|
27500
|
+
if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
|
|
27501
|
+
return TOMBSTONE_PLACEHOLDER_RETENTION_MS;
|
|
27502
|
+
}
|
|
27503
|
+
return TOMBSTONE_RETENTION_MS;
|
|
27504
|
+
}
|
|
27505
|
+
function isTombstoneRetentionElapsed(tombstone, now = Date.now()) {
|
|
27506
|
+
const deletedAt = Number(tombstone.deletedAt);
|
|
27507
|
+
if (!Number.isFinite(deletedAt)) return true;
|
|
27508
|
+
return now - deletedAt >= tombstoneRetentionMs(tombstone.path);
|
|
27509
|
+
}
|
|
27510
|
+
function isDirectoryTombstone(tombstone) {
|
|
27511
|
+
return tombstone.type === "directory";
|
|
27512
|
+
}
|
|
27513
|
+
function serializeTombstone(tombstone) {
|
|
27514
|
+
const ordered = {
|
|
27515
|
+
path: tombstone.path,
|
|
27516
|
+
deletedAt: tombstone.deletedAt,
|
|
27517
|
+
deletedBy: tombstone.deletedBy,
|
|
27518
|
+
confirmedBy: tombstone.confirmedBy
|
|
27519
|
+
};
|
|
27520
|
+
if (tombstone.type) ordered.type = tombstone.type;
|
|
27521
|
+
return JSON.stringify(ordered, null, 2);
|
|
27522
|
+
}
|
|
27523
|
+
async function purgeTombstonedTree(fs, targetPath) {
|
|
27524
|
+
let isDir2 = false;
|
|
27525
|
+
try {
|
|
27526
|
+
const stat5 = await fs.stat?.(targetPath);
|
|
27527
|
+
if (stat5) {
|
|
27528
|
+
if (typeof stat5.isDirectory === "function") isDir2 = stat5.isDirectory();
|
|
27529
|
+
else {
|
|
27530
|
+
const mode = Number(stat5.mode ?? 0);
|
|
27531
|
+
isDir2 = mode > 0 && (mode & 61440) === 16384;
|
|
27532
|
+
}
|
|
27533
|
+
}
|
|
27534
|
+
} catch {
|
|
27535
|
+
isDir2 = false;
|
|
27536
|
+
}
|
|
27537
|
+
if (!isDir2) {
|
|
27401
27538
|
try {
|
|
27402
|
-
|
|
27539
|
+
await fs.readdir(targetPath);
|
|
27540
|
+
isDir2 = true;
|
|
27403
27541
|
} catch {
|
|
27404
|
-
|
|
27542
|
+
isDir2 = false;
|
|
27405
27543
|
}
|
|
27406
|
-
|
|
27407
|
-
|
|
27408
|
-
|
|
27409
|
-
|
|
27410
|
-
|
|
27411
|
-
stat5 = await fs.stat(fullPath);
|
|
27412
|
-
} catch {
|
|
27413
|
-
continue;
|
|
27414
|
-
}
|
|
27415
|
-
if (isDirectory4(stat5)) {
|
|
27416
|
-
stack.push(fullPath);
|
|
27417
|
-
continue;
|
|
27418
|
-
}
|
|
27419
|
-
result.scanned++;
|
|
27420
|
-
if (!isKeepFile(entry)) continue;
|
|
27421
|
-
if (dryRun) {
|
|
27422
|
-
result.removed.push(fullPath);
|
|
27423
|
-
continue;
|
|
27424
|
-
}
|
|
27425
|
-
try {
|
|
27426
|
-
await fs.unlink(fullPath);
|
|
27427
|
-
result.removed.push(fullPath);
|
|
27428
|
-
} catch {
|
|
27429
|
-
result.failed.push(fullPath);
|
|
27430
|
-
}
|
|
27544
|
+
}
|
|
27545
|
+
if (!isDir2) {
|
|
27546
|
+
try {
|
|
27547
|
+
await fs.unlink(targetPath);
|
|
27548
|
+
} catch {
|
|
27431
27549
|
}
|
|
27550
|
+
return;
|
|
27432
27551
|
}
|
|
27433
|
-
|
|
27434
|
-
|
|
27435
|
-
|
|
27436
|
-
|
|
27437
|
-
|
|
27438
|
-
|
|
27439
|
-
|
|
27440
|
-
}
|
|
27441
|
-
function joinPath3(dir, entry) {
|
|
27442
|
-
if (dir === "/" || dir === "") return `/${entry}`;
|
|
27443
|
-
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
27444
|
-
}
|
|
27445
|
-
async function existsPath(fs, p) {
|
|
27552
|
+
for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
|
|
27553
|
+
try {
|
|
27554
|
+
await fs.unlink(placeholder);
|
|
27555
|
+
} catch {
|
|
27556
|
+
}
|
|
27557
|
+
}
|
|
27558
|
+
let children = [];
|
|
27446
27559
|
try {
|
|
27447
|
-
await fs.
|
|
27448
|
-
return true;
|
|
27560
|
+
children = await fs.readdir(targetPath);
|
|
27449
27561
|
} catch {
|
|
27450
|
-
|
|
27562
|
+
}
|
|
27563
|
+
for (const child of children) await purgeTombstonedTree(fs, `${targetPath}/${child}`);
|
|
27564
|
+
try {
|
|
27565
|
+
if (typeof fs.rmdir === "function") await fs.rmdir(targetPath);
|
|
27566
|
+
else await fs.unlink(targetPath);
|
|
27567
|
+
} catch {
|
|
27568
|
+
try {
|
|
27569
|
+
await fs.unlink(targetPath);
|
|
27570
|
+
} catch {
|
|
27571
|
+
}
|
|
27451
27572
|
}
|
|
27452
27573
|
}
|
|
27453
|
-
function configNameFromLegacy(entry) {
|
|
27454
|
-
const noMtime = entry.endsWith(".version.mtime") ? entry.slice(0, -".version.mtime".length) : entry.slice(0, -".version".length);
|
|
27455
|
-
return noMtime.slice(1);
|
|
27456
|
-
}
|
|
27457
|
-
async function resolveTarget(fs, dir, entry) {
|
|
27458
|
-
const configName = configNameFromLegacy(entry);
|
|
27459
|
-
const configPath = joinPath3(dir, configName);
|
|
27460
|
-
const dotConfigPath = joinPath3(dir, `.${configName}`);
|
|
27461
|
-
if (await existsPath(fs, dotConfigPath)) {
|
|
27462
|
-
return { action: "skip" };
|
|
27463
|
-
}
|
|
27464
|
-
if (await existsPath(fs, configPath)) {
|
|
27465
|
-
return { action: "rename", newPath: versionPathFor(configPath) ?? `${configName}.version` };
|
|
27466
|
-
}
|
|
27467
|
-
return { action: "delete" };
|
|
27468
|
-
}
|
|
27469
|
-
async function migrateVersionSidecars(fs, options = {}) {
|
|
27470
|
-
const root = options.root && options.root !== "" ? options.root : "/";
|
|
27471
|
-
const dryRun = options.dryRun ?? false;
|
|
27472
|
-
const replicas = options.replicas ?? [];
|
|
27473
|
-
const result = {
|
|
27474
|
-
renamed: [],
|
|
27475
|
-
deleted: [],
|
|
27476
|
-
remoteDeleted: [],
|
|
27477
|
-
failed: []
|
|
27478
|
-
};
|
|
27479
|
-
const stack = [root];
|
|
27480
|
-
while (stack.length > 0) {
|
|
27481
|
-
const dir = stack.pop();
|
|
27482
|
-
let entries2;
|
|
27483
|
-
try {
|
|
27484
|
-
entries2 = await fs.readdir(dir);
|
|
27485
|
-
} catch {
|
|
27486
|
-
continue;
|
|
27487
|
-
}
|
|
27488
|
-
for (const entry of entries2) {
|
|
27489
|
-
const full = joinPath3(dir, entry);
|
|
27490
|
-
let stat5;
|
|
27491
|
-
try {
|
|
27492
|
-
stat5 = await fs.stat(full);
|
|
27493
|
-
} catch {
|
|
27494
|
-
continue;
|
|
27495
|
-
}
|
|
27496
|
-
if (isDir(stat5)) {
|
|
27497
|
-
stack.push(full);
|
|
27498
|
-
continue;
|
|
27499
|
-
}
|
|
27500
|
-
const isLegacyVersion = entry.startsWith(".") && (entry.endsWith(".version") || entry.endsWith(".version.mtime"));
|
|
27501
|
-
if (!isLegacyVersion) continue;
|
|
27502
|
-
const legacyVerPath = entry.endsWith(".version.mtime") ? full.slice(0, -".mtime".length) : full;
|
|
27503
|
-
const target = await resolveTarget(fs, dir, entry);
|
|
27504
|
-
if (target.action === "skip") continue;
|
|
27505
|
-
const legacyMtimePath = `${legacyVerPath}.mtime`;
|
|
27506
|
-
const newMtimePath = target.newPath ? `${target.newPath}.mtime` : null;
|
|
27507
|
-
if (dryRun) {
|
|
27508
|
-
if (target.action === "rename") result.renamed.push(full);
|
|
27509
|
-
else result.deleted.push(full);
|
|
27510
|
-
continue;
|
|
27511
|
-
}
|
|
27512
|
-
try {
|
|
27513
|
-
if (target.action === "rename") {
|
|
27514
|
-
if (await existsPath(fs, target.newPath)) {
|
|
27515
|
-
await fs.unlink(legacyVerPath);
|
|
27516
|
-
result.deleted.push(full);
|
|
27517
|
-
} else {
|
|
27518
|
-
const content = await fs.readFile(legacyVerPath);
|
|
27519
|
-
const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
|
|
27520
|
-
await fs.writeFile(target.newPath, bytes);
|
|
27521
|
-
await fs.unlink(legacyVerPath);
|
|
27522
|
-
result.renamed.push(full);
|
|
27523
|
-
}
|
|
27524
|
-
if (newMtimePath && await existsPath(fs, legacyMtimePath)) {
|
|
27525
|
-
try {
|
|
27526
|
-
const mc = await fs.readFile(legacyMtimePath);
|
|
27527
|
-
const mb = typeof mc === "string" ? new TextEncoder().encode(mc) : mc;
|
|
27528
|
-
await fs.writeFile(newMtimePath, mb);
|
|
27529
|
-
await fs.unlink(legacyMtimePath);
|
|
27530
|
-
} catch {
|
|
27531
|
-
}
|
|
27532
|
-
}
|
|
27533
|
-
} else {
|
|
27534
|
-
await fs.unlink(legacyVerPath);
|
|
27535
|
-
result.deleted.push(full);
|
|
27536
|
-
if (await existsPath(fs, legacyMtimePath)) {
|
|
27537
|
-
try {
|
|
27538
|
-
await fs.unlink(legacyMtimePath);
|
|
27539
|
-
} catch {
|
|
27540
|
-
}
|
|
27541
|
-
}
|
|
27542
|
-
}
|
|
27543
|
-
} catch (e) {
|
|
27544
|
-
result.failed.push(full);
|
|
27545
|
-
continue;
|
|
27546
|
-
}
|
|
27547
|
-
for (const rep of replicas) {
|
|
27548
|
-
for (const rp of [legacyVerPath, legacyMtimePath]) {
|
|
27549
|
-
try {
|
|
27550
|
-
await rep.unlink(rp);
|
|
27551
|
-
result.remoteDeleted.push(rp);
|
|
27552
|
-
} catch {
|
|
27553
|
-
}
|
|
27554
|
-
}
|
|
27555
|
-
}
|
|
27556
|
-
}
|
|
27557
|
-
}
|
|
27558
|
-
return result;
|
|
27559
|
-
}
|
|
27560
|
-
|
|
27561
|
-
// src/canonical-json.ts
|
|
27562
|
-
var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
|
|
27563
|
-
var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "name", "features"];
|
|
27564
|
-
var APP_DATA_GROUP_ORDER = ["id", "groupType", "name", "features", "backends"];
|
|
27565
|
-
var BACKEND_ORDER = ["id", "type", "options", "accountBackendId", "description", "createdAt"];
|
|
27566
|
-
function compareKeys(a, b) {
|
|
27567
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
27568
|
-
}
|
|
27569
|
-
function isPlainObject(value) {
|
|
27570
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
27571
|
-
}
|
|
27572
|
-
function canonicalObject(value, order = []) {
|
|
27573
|
-
const out = {};
|
|
27574
|
-
for (const key of order) {
|
|
27575
|
-
if (value[key] !== void 0) out[key] = canonicalField(key, value[key]);
|
|
27576
|
-
}
|
|
27577
|
-
for (const key of Object.keys(value).sort(compareKeys)) {
|
|
27578
|
-
if (order.includes(key) || value[key] === void 0) continue;
|
|
27579
|
-
out[key] = canonicalField(key, value[key]);
|
|
27580
|
-
}
|
|
27581
|
-
return out;
|
|
27582
|
-
}
|
|
27583
|
-
function canonicalField(key, value) {
|
|
27584
|
-
if (Array.isArray(value)) {
|
|
27585
|
-
if (key === "backends") {
|
|
27586
|
-
return value.map((item) => isPlainObject(item) ? canonicalObject(item, BACKEND_ORDER) : item).sort(
|
|
27587
|
-
(a, b) => compareKeys(String(a?.id ?? ""), String(b?.id ?? ""))
|
|
27588
|
-
);
|
|
27589
|
-
}
|
|
27590
|
-
return value.map((item) => canonicalField("", item));
|
|
27591
|
-
}
|
|
27592
|
-
if (isPlainObject(value)) {
|
|
27593
|
-
if (key === "features") return canonicalObject(value, FEATURE_ORDER);
|
|
27594
|
-
return canonicalObject(value);
|
|
27595
|
-
}
|
|
27596
|
-
return value;
|
|
27597
|
-
}
|
|
27598
|
-
function stringify(value) {
|
|
27599
|
-
return JSON.stringify(value, null, 2);
|
|
27600
|
-
}
|
|
27601
|
-
function serializeGroupDescriptor(descriptor) {
|
|
27602
|
-
const { updatedAt: _ignored, ...rest } = descriptor;
|
|
27603
|
-
return stringify(canonicalObject(rest, GROUP_DESCRIPTOR_ORDER));
|
|
27604
|
-
}
|
|
27605
|
-
function serializeBackendDescriptor(descriptor) {
|
|
27606
|
-
return stringify(canonicalObject(descriptor, BACKEND_ORDER));
|
|
27607
|
-
}
|
|
27608
|
-
function serializeAppDataGroupDescriptor(descriptor) {
|
|
27609
|
-
return stringify(canonicalObject(descriptor, APP_DATA_GROUP_ORDER));
|
|
27610
|
-
}
|
|
27611
|
-
function stripBackendCreatedAt(descriptor) {
|
|
27612
|
-
const { createdAt: _ignored, ...rest } = descriptor;
|
|
27613
|
-
return rest;
|
|
27614
|
-
}
|
|
27615
|
-
function mergeBackendDescriptor(existing, incoming) {
|
|
27616
|
-
const existingCreatedAt = typeof existing?.createdAt === "number" ? existing.createdAt : void 0;
|
|
27617
|
-
const incomingCreatedAt = typeof incoming.createdAt === "number" ? incoming.createdAt : void 0;
|
|
27618
|
-
const createdAt = existingCreatedAt === void 0 ? incomingCreatedAt : incomingCreatedAt === void 0 ? existingCreatedAt : Math.min(existingCreatedAt, incomingCreatedAt);
|
|
27619
|
-
return createdAt === void 0 ? stripBackendCreatedAt(incoming) : { ...incoming, createdAt };
|
|
27620
|
-
}
|
|
27621
|
-
function mergeBackendCreatedAt(incoming, existing) {
|
|
27622
|
-
if (!existing || existing.length === 0) return incoming;
|
|
27623
|
-
const byId = new Map(existing.map((d) => [d.id, d]));
|
|
27624
|
-
return incoming.map((desc) => mergeBackendDescriptor(byId.get(desc.id), desc));
|
|
27625
|
-
}
|
|
27626
|
-
function mergeDescriptorCreatedAt(descriptor, existing) {
|
|
27627
|
-
return {
|
|
27628
|
-
...descriptor,
|
|
27629
|
-
backends: mergeBackendCreatedAt(descriptor.backends, existing?.backends)
|
|
27630
|
-
};
|
|
27631
|
-
}
|
|
27632
|
-
|
|
27633
|
-
// src/group-meta.ts
|
|
27634
|
-
var log6 = createLogger("zen-fs-config:tombstones");
|
|
27635
|
-
var META_DIR = "/.meta";
|
|
27636
|
-
var GROUP_DESCRIPTOR_FILE = `${META_DIR}/group.json`;
|
|
27637
|
-
var META_BACKENDS_DIR = `${META_DIR}/backends`;
|
|
27638
|
-
var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
|
|
27639
27574
|
var LEGACY_TOMBSTONES_DIR = `${META_DIR}/.deleted`;
|
|
27640
27575
|
var VERSIONS_DIR = `${META_DIR}/versions`;
|
|
27641
27576
|
var CONFLICTS_DIR = `${META_DIR}/conflicts`;
|
|
@@ -27698,6 +27633,9 @@ var ZenFSConfig = (() => {
|
|
|
27698
27633
|
function isMtimeSidecarPath(path) {
|
|
27699
27634
|
return path.endsWith(".mtime");
|
|
27700
27635
|
}
|
|
27636
|
+
function isHiddenPlaceholderPath(path) {
|
|
27637
|
+
return isMtimeSidecarPath(path) || path === "/.keep" || path.endsWith("/.keep");
|
|
27638
|
+
}
|
|
27701
27639
|
function encodeMetaPath(filePath) {
|
|
27702
27640
|
const normalized = filePath.startsWith("/") ? filePath : `/${filePath}`;
|
|
27703
27641
|
return normalized.replace(/^\//, "").replace(/\//g, "__").replace(/\./g, "++");
|
|
@@ -27716,15 +27654,21 @@ var ZenFSConfig = (() => {
|
|
|
27716
27654
|
const record = value;
|
|
27717
27655
|
const rawPath = typeof record.path === "string" ? record.path : fallbackPath;
|
|
27718
27656
|
if (!rawPath) return null;
|
|
27719
|
-
const path = rawPath
|
|
27657
|
+
const path = normalizeTombstonePath(rawPath);
|
|
27720
27658
|
const confirmedBy = Array.isArray(record.confirmedBy) ? record.confirmedBy.filter((id) => typeof id === "string") : [];
|
|
27659
|
+
const type = record.type === "directory" ? "directory" : record.type === "file" ? "file" : void 0;
|
|
27721
27660
|
return {
|
|
27722
27661
|
path,
|
|
27723
27662
|
deletedAt: typeof record.deletedAt === "number" ? record.deletedAt : 0,
|
|
27724
27663
|
deletedBy: typeof record.deletedBy === "string" ? record.deletedBy : "unknown",
|
|
27725
|
-
confirmedBy
|
|
27664
|
+
confirmedBy,
|
|
27665
|
+
...type ? { type } : {}
|
|
27726
27666
|
};
|
|
27727
27667
|
}
|
|
27668
|
+
function normalizeTombstonePath(rawPath) {
|
|
27669
|
+
const withLeading = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
|
|
27670
|
+
return withLeading.length > 1 ? withLeading.replace(/\/+$/, "") || "/" : withLeading;
|
|
27671
|
+
}
|
|
27728
27672
|
function extractJsonObjects(raw) {
|
|
27729
27673
|
const objects = [];
|
|
27730
27674
|
let depth = 0;
|
|
@@ -27805,6 +27749,7 @@ var ZenFSConfig = (() => {
|
|
|
27805
27749
|
for (const id of tombstone.confirmedBy) {
|
|
27806
27750
|
if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
|
|
27807
27751
|
}
|
|
27752
|
+
if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) prev.type = "directory";
|
|
27808
27753
|
}
|
|
27809
27754
|
async function readTombstonesFromFs(fs, warn2) {
|
|
27810
27755
|
const byPath = /* @__PURE__ */ new Map();
|
|
@@ -27839,16 +27784,16 @@ var ZenFSConfig = (() => {
|
|
|
27839
27784
|
return Array.from(byPath.values());
|
|
27840
27785
|
}
|
|
27841
27786
|
async function readGroupDescriptor(fs) {
|
|
27842
|
-
const parsed = await readJson(fs,
|
|
27787
|
+
const parsed = await readJson(fs, GROUP_DESCRIPTOR_FILE2);
|
|
27843
27788
|
if (!parsed) return null;
|
|
27844
27789
|
const { updatedAt: _ignored, ...rest } = parsed;
|
|
27845
27790
|
return rest;
|
|
27846
27791
|
}
|
|
27847
27792
|
async function writeGroupDescriptor(fs, descriptor) {
|
|
27848
27793
|
const bytes = serializeGroupDescriptor(descriptor);
|
|
27849
|
-
if (await readText(fs,
|
|
27850
|
-
await ensureParentDir2(fs,
|
|
27851
|
-
await fs.writeFile(
|
|
27794
|
+
if (await readText(fs, GROUP_DESCRIPTOR_FILE2) === bytes) return;
|
|
27795
|
+
await ensureParentDir2(fs, GROUP_DESCRIPTOR_FILE2);
|
|
27796
|
+
await fs.writeFile(GROUP_DESCRIPTOR_FILE2, new TextEncoder().encode(bytes));
|
|
27852
27797
|
}
|
|
27853
27798
|
function assertValidBackendId(id) {
|
|
27854
27799
|
if (typeof id !== "string" || id.trim() === "") {
|
|
@@ -27907,24 +27852,32 @@ var ZenFSConfig = (() => {
|
|
|
27907
27852
|
constructor(fs, author) {
|
|
27908
27853
|
__publicField(this, "fs", fs);
|
|
27909
27854
|
__publicField(this, "author", author);
|
|
27855
|
+
/**
|
|
27856
|
+
* 本轮 `process()` 真正核对过"确实不存在"的(路径 → 目标 id)。
|
|
27857
|
+
*
|
|
27858
|
+
* 只有出现在这里的副本才会被写进 `confirmedBy`(见 {@link confirm}),与
|
|
27859
|
+
* 配置组 `ConfigRepo.updateTombstoneConfirmations` 的保守语义一致:副本删除
|
|
27860
|
+
* 失败(网络、后端限制、只剩占位目录)时绝不算已确认。
|
|
27861
|
+
*/
|
|
27862
|
+
__publicField(this, "verifiedAbsent", /* @__PURE__ */ new Map());
|
|
27910
27863
|
}
|
|
27911
27864
|
pathFor(filePath) {
|
|
27912
27865
|
return `${TOMBSTONES_DIR}/${encodeMetaPath(filePath)}.json`;
|
|
27913
27866
|
}
|
|
27914
27867
|
/** All tombstones. */
|
|
27915
27868
|
async list() {
|
|
27916
|
-
return readTombstonesFromFs(this.fs, (message) =>
|
|
27869
|
+
return readTombstonesFromFs(this.fs, (message) => log7.warn(message));
|
|
27917
27870
|
}
|
|
27918
27871
|
/** Write a tombstone. */
|
|
27919
27872
|
async write(tombstone) {
|
|
27920
|
-
const bytes = new TextEncoder().encode(
|
|
27873
|
+
const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
|
|
27921
27874
|
const p = this.pathFor(tombstone.path);
|
|
27922
27875
|
await ensureParentDir2(this.fs, p);
|
|
27923
27876
|
await this.fs.writeFile(p, bytes);
|
|
27924
27877
|
}
|
|
27925
27878
|
/** Persist an updated tombstone (confirmations) when it still exists. */
|
|
27926
27879
|
async save(tombstone) {
|
|
27927
|
-
const bytes = new TextEncoder().encode(
|
|
27880
|
+
const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
|
|
27928
27881
|
const p = this.pathFor(tombstone.path);
|
|
27929
27882
|
if (!await existsSafe(this.fs, p)) return;
|
|
27930
27883
|
await this.fs.writeFile(p, bytes);
|
|
@@ -27941,34 +27894,121 @@ var ZenFSConfig = (() => {
|
|
|
27941
27894
|
/**
|
|
27942
27895
|
* Delete every tombstoned file (and its version record) on the local store
|
|
27943
27896
|
* and on each target backend, so bi-directional sync cannot resurrect it.
|
|
27897
|
+
*
|
|
27898
|
+
* 墓碑只对「删除之后没有再写入」的路径有效。同步类工具会不断重建某些文件
|
|
27899
|
+
* (最典型的是 `.sync.lock`:每轮删除 → 重建),若墓碑永久生效,路径会被每一
|
|
27900
|
+
* 轮 preSync 删掉,表现为「刚写完 1 秒就消失、锁永远拿不到」。因此这里先判定
|
|
27901
|
+
* 目标路径是否在 `deletedAt` 之后被重新写入:是则墓碑已被用户写操作撤销,保留
|
|
27902
|
+
* 文件并删除墓碑;否则按删除传播处理。
|
|
27944
27903
|
*/
|
|
27945
27904
|
async process(targets = []) {
|
|
27946
27905
|
const tombstones = await this.list();
|
|
27906
|
+
const expired = [];
|
|
27907
|
+
this.verifiedAbsent.clear();
|
|
27947
27908
|
for (const tombstone of tombstones) {
|
|
27948
|
-
await this.
|
|
27909
|
+
if (await this.wasRecreatedAfterDeletion(tombstone)) {
|
|
27910
|
+
expired.push(tombstone);
|
|
27911
|
+
continue;
|
|
27912
|
+
}
|
|
27913
|
+
await this.deleteEverywhere(this.fs, tombstone);
|
|
27914
|
+
for (const target of targets) {
|
|
27915
|
+
await this.deleteEverywhere(target.fs, tombstone);
|
|
27916
|
+
}
|
|
27949
27917
|
for (const target of targets) {
|
|
27950
|
-
await this.
|
|
27918
|
+
if (await this.absentOnTarget(target.fs, tombstone)) {
|
|
27919
|
+
this.markVerified(tombstone.path, target.id);
|
|
27920
|
+
}
|
|
27951
27921
|
}
|
|
27952
27922
|
}
|
|
27923
|
+
for (const tombstone of expired) {
|
|
27924
|
+
await this.remove(tombstone);
|
|
27925
|
+
log7.log(
|
|
27926
|
+
`[TombstoneStore] expired tombstone for ${tombstone.path} \u2014 recreated after deletion`
|
|
27927
|
+
);
|
|
27928
|
+
}
|
|
27929
|
+
}
|
|
27930
|
+
markVerified(path, targetId) {
|
|
27931
|
+
let ids = this.verifiedAbsent.get(path);
|
|
27932
|
+
if (!ids) {
|
|
27933
|
+
ids = /* @__PURE__ */ new Set();
|
|
27934
|
+
this.verifiedAbsent.set(path, ids);
|
|
27935
|
+
}
|
|
27936
|
+
ids.add(targetId);
|
|
27937
|
+
}
|
|
27938
|
+
/**
|
|
27939
|
+
* 目标上该路径当前是否确实不存在。
|
|
27940
|
+
*
|
|
27941
|
+
* `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),这类
|
|
27942
|
+
* 路径只能相信本轮 unlink 没有报错,因此按"不可见即可信"处理(与配置组的
|
|
27943
|
+
* `allReplicasConfirmAbsent` 一致)。
|
|
27944
|
+
*/
|
|
27945
|
+
async absentOnTarget(fs, tombstone) {
|
|
27946
|
+
if (!isDirectoryTombstone(tombstone) && isHiddenPlaceholderPath(tombstone.path)) {
|
|
27947
|
+
return true;
|
|
27948
|
+
}
|
|
27949
|
+
try {
|
|
27950
|
+
const stat5 = await fs.stat?.(tombstone.path);
|
|
27951
|
+
if (stat5) return false;
|
|
27952
|
+
} catch {
|
|
27953
|
+
}
|
|
27954
|
+
try {
|
|
27955
|
+
if (typeof fs.exists === "function") return !await fs.exists(tombstone.path);
|
|
27956
|
+
} catch {
|
|
27957
|
+
}
|
|
27958
|
+
return true;
|
|
27953
27959
|
}
|
|
27954
|
-
|
|
27955
|
-
|
|
27960
|
+
/**
|
|
27961
|
+
* 本地存储上该路径的 mtime 是否晚于墓碑的删除时刻。
|
|
27962
|
+
*
|
|
27963
|
+
* 只看本地主存储:副本上的同路径文件可能只是「删除之前的旧副本」,它的 mtime
|
|
27964
|
+
* 本来就旧,用副本判定既不可靠又会掩盖真正的删除传播。
|
|
27965
|
+
*/
|
|
27966
|
+
async wasRecreatedAfterDeletion(tombstone) {
|
|
27967
|
+
const mtimeMs = await this.mtimeOf(this.fs, tombstone.path);
|
|
27968
|
+
if (mtimeMs === null) return false;
|
|
27969
|
+
return mtimeMs > tombstone.deletedAt + RECREATE_AFTER_DELETE_SKEW_MS;
|
|
27970
|
+
}
|
|
27971
|
+
async mtimeOf(fs, filePath) {
|
|
27956
27972
|
try {
|
|
27957
|
-
await fs.
|
|
27973
|
+
const stat5 = await fs.stat?.(filePath);
|
|
27974
|
+
const mtimeMs = Number(stat5?.mtimeMs);
|
|
27975
|
+
return Number.isFinite(mtimeMs) ? mtimeMs : null;
|
|
27958
27976
|
} catch {
|
|
27977
|
+
return null;
|
|
27959
27978
|
}
|
|
27960
27979
|
}
|
|
27961
|
-
|
|
27962
|
-
|
|
27980
|
+
async deleteEverywhere(fs, tombstone) {
|
|
27981
|
+
if (isDirectoryTombstone(tombstone)) {
|
|
27982
|
+
await purgeTombstonedTree(fs, tombstone.path);
|
|
27983
|
+
return;
|
|
27984
|
+
}
|
|
27985
|
+
if (!isMtimeSidecarPath(tombstone.path) && !await existsSafe(fs, tombstone.path)) return;
|
|
27986
|
+
try {
|
|
27987
|
+
await fs.unlink(tombstone.path);
|
|
27988
|
+
} catch {
|
|
27989
|
+
}
|
|
27990
|
+
}
|
|
27991
|
+
/**
|
|
27992
|
+
* 把本轮真正核对过"确实不存在"的目标写进墓碑的 `confirmedBy`。
|
|
27993
|
+
*
|
|
27994
|
+
* 旧实现把传入的后端 id 无条件写入,等于"跑过一轮就算所有副本都清干净了";
|
|
27995
|
+
* 副本删除失败时墓碑仍会被 GC,下一轮同步再把残留拉回本地。现在只确认
|
|
27996
|
+
* {@link process} 中现场核对通过的目标(与配置组语义一致),并支持只传 id
|
|
27997
|
+
* 的旧调用方式(此时沿用同一份核对结果)。
|
|
27998
|
+
*/
|
|
27999
|
+
async confirm(targets) {
|
|
28000
|
+
const isTargetList = (value) => value.length > 0 && typeof value[0] === "object";
|
|
28001
|
+
const ids = isTargetList(targets) ? targets.map((t) => t.id) : targets;
|
|
27963
28002
|
const tombstones = await this.list();
|
|
27964
28003
|
let modified = 0;
|
|
27965
28004
|
for (const tombstone of tombstones) {
|
|
28005
|
+
const verified = this.verifiedAbsent.get(tombstone.path);
|
|
27966
28006
|
let changed = false;
|
|
27967
|
-
for (const id of
|
|
27968
|
-
if (
|
|
27969
|
-
|
|
27970
|
-
|
|
27971
|
-
|
|
28007
|
+
for (const id of ids) {
|
|
28008
|
+
if (tombstone.confirmedBy.includes(id)) continue;
|
|
28009
|
+
if (!verified?.has(id)) continue;
|
|
28010
|
+
tombstone.confirmedBy.push(id);
|
|
28011
|
+
changed = true;
|
|
27972
28012
|
}
|
|
27973
28013
|
if (!changed) continue;
|
|
27974
28014
|
try {
|
|
@@ -27983,8 +28023,17 @@ var ZenFSConfig = (() => {
|
|
|
27983
28023
|
async gc(allBackendIds, targets = []) {
|
|
27984
28024
|
const tombstones = await this.list();
|
|
27985
28025
|
for (const tombstone of tombstones) {
|
|
28026
|
+
if (!isTombstoneRetentionElapsed(tombstone)) continue;
|
|
27986
28027
|
const allConfirmed = allBackendIds.every((id) => tombstone.confirmedBy.includes(id));
|
|
27987
28028
|
if (!allConfirmed) continue;
|
|
28029
|
+
let stillAbsent = true;
|
|
28030
|
+
for (const target of targets) {
|
|
28031
|
+
if (!await this.absentOnTarget(target.fs, tombstone)) {
|
|
28032
|
+
stillAbsent = false;
|
|
28033
|
+
break;
|
|
28034
|
+
}
|
|
28035
|
+
}
|
|
28036
|
+
if (!stillAbsent) continue;
|
|
27988
28037
|
const p = this.pathFor(tombstone.path);
|
|
27989
28038
|
if (await existsSafe(this.fs, p)) {
|
|
27990
28039
|
try {
|
|
@@ -28084,52 +28133,361 @@ var ZenFSConfig = (() => {
|
|
|
28084
28133
|
} catch {
|
|
28085
28134
|
continue;
|
|
28086
28135
|
}
|
|
28087
|
-
for (const entry of entries2) {
|
|
28088
|
-
if (seen.has(entry)) continue;
|
|
28089
|
-
const archive = await readJson(this.fs, `${dir}/${entry}/meta.json`);
|
|
28090
|
-
if (!archive) continue;
|
|
28091
|
-
seen.add(entry);
|
|
28092
|
-
archives.push(archive);
|
|
28093
|
-
}
|
|
28094
|
-
}
|
|
28095
|
-
return archives.sort((a, b) => a.timestamp - b.timestamp);
|
|
28096
|
-
}
|
|
28097
|
-
candidatesFor(conflictId) {
|
|
28098
|
-
const id = conflictId.replace(/\/meta\.json$/, "");
|
|
28099
|
-
return [`${CONFLICTS_DIR}/${id}`, `${LEGACY_CONFLICTS_DIR}/${id}`];
|
|
28100
|
-
}
|
|
28101
|
-
async readBackup(conflictId, fileType) {
|
|
28102
|
-
for (const dir of this.candidatesFor(conflictId)) {
|
|
28103
|
-
const p = `${dir}/${fileType}`;
|
|
28136
|
+
for (const entry of entries2) {
|
|
28137
|
+
if (seen.has(entry)) continue;
|
|
28138
|
+
const archive = await readJson(this.fs, `${dir}/${entry}/meta.json`);
|
|
28139
|
+
if (!archive) continue;
|
|
28140
|
+
seen.add(entry);
|
|
28141
|
+
archives.push(archive);
|
|
28142
|
+
}
|
|
28143
|
+
}
|
|
28144
|
+
return archives.sort((a, b) => a.timestamp - b.timestamp);
|
|
28145
|
+
}
|
|
28146
|
+
candidatesFor(conflictId) {
|
|
28147
|
+
const id = conflictId.replace(/\/meta\.json$/, "");
|
|
28148
|
+
return [`${CONFLICTS_DIR}/${id}`, `${LEGACY_CONFLICTS_DIR}/${id}`];
|
|
28149
|
+
}
|
|
28150
|
+
async readBackup(conflictId, fileType) {
|
|
28151
|
+
for (const dir of this.candidatesFor(conflictId)) {
|
|
28152
|
+
const p = `${dir}/${fileType}`;
|
|
28153
|
+
try {
|
|
28154
|
+
return new TextDecoder().decode(toBytes(await this.fs.readFile(p)));
|
|
28155
|
+
} catch {
|
|
28156
|
+
}
|
|
28157
|
+
}
|
|
28158
|
+
throw new Error(`Conflict backup not found: ${conflictId}/${fileType}`);
|
|
28159
|
+
}
|
|
28160
|
+
/** Resolve a conflict with raw (already serialized) content. */
|
|
28161
|
+
async resolve(conflictId, mergedContent) {
|
|
28162
|
+
for (const dir of this.candidatesFor(conflictId)) {
|
|
28163
|
+
const metaPath = `${dir}/meta.json`;
|
|
28164
|
+
const archive = await readJson(this.fs, metaPath);
|
|
28165
|
+
if (!archive) continue;
|
|
28166
|
+
const bytes = typeof mergedContent === "string" ? new TextEncoder().encode(mergedContent) : mergedContent;
|
|
28167
|
+
await ensureParentDir2(this.fs, archive.conflictPath);
|
|
28168
|
+
await this.fs.writeFile(archive.conflictPath, bytes);
|
|
28169
|
+
await this.versions.record(archive.conflictPath, bytes);
|
|
28170
|
+
await this.fs.writeFile(`${dir}/resolved`, bytes);
|
|
28171
|
+
archive.resolvedBackupPath = "./resolved";
|
|
28172
|
+
await writeJson(this.fs, metaPath, archive);
|
|
28173
|
+
return;
|
|
28174
|
+
}
|
|
28175
|
+
throw new Error(`Failed to resolve conflict ${conflictId}: archive not found`);
|
|
28176
|
+
}
|
|
28177
|
+
};
|
|
28178
|
+
|
|
28179
|
+
// src/group-identity.ts
|
|
28180
|
+
var log8 = createLogger("zen-fs-config:group-identity");
|
|
28181
|
+
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;
|
|
28182
|
+
function newGroupInstanceId() {
|
|
28183
|
+
const cryptoObj = globalThis?.crypto;
|
|
28184
|
+
if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();
|
|
28185
|
+
const bytes = new Uint8Array(16);
|
|
28186
|
+
if (cryptoObj?.getRandomValues) {
|
|
28187
|
+
cryptoObj.getRandomValues(bytes);
|
|
28188
|
+
} else {
|
|
28189
|
+
for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
|
|
28190
|
+
}
|
|
28191
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
28192
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
28193
|
+
const hex2 = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
28194
|
+
return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
|
|
28195
|
+
}
|
|
28196
|
+
function isValidGroupInstanceId(value) {
|
|
28197
|
+
return typeof value === "string" && INSTANCE_ID_RE.test(value.trim());
|
|
28198
|
+
}
|
|
28199
|
+
async function bindRemoteGroupIdentity(remoteFS, identity) {
|
|
28200
|
+
let remote = null;
|
|
28201
|
+
try {
|
|
28202
|
+
remote = await readGroupDescriptor(remoteFS);
|
|
28203
|
+
} catch (err2) {
|
|
28204
|
+
log8.warn(`[GroupIdentity] failed to read remote ${identity.kind}/"${identity.id}" group.json:`, err2);
|
|
28205
|
+
throw err2;
|
|
28206
|
+
}
|
|
28207
|
+
const current = remote?.instanceId;
|
|
28208
|
+
if (isValidGroupInstanceId(current)) {
|
|
28209
|
+
if (current === identity.instanceId) return "match";
|
|
28210
|
+
log8.warn(
|
|
28211
|
+
`[GroupIdentity] backend belongs to another sync group (remote instanceId=${current}, this group=${identity.instanceId}, kind ${remote?.kind ?? "?"}/"${remote?.id ?? "?"}") \u2014 sync pair NOT created`
|
|
28212
|
+
);
|
|
28213
|
+
return "conflict";
|
|
28214
|
+
}
|
|
28215
|
+
const next = {
|
|
28216
|
+
schemaVersion: 2,
|
|
28217
|
+
kind: remote?.kind ?? identity.kind,
|
|
28218
|
+
id: remote?.id ?? identity.id,
|
|
28219
|
+
instanceId: identity.instanceId,
|
|
28220
|
+
...remote?.name ?? identity.name ? { name: remote?.name ?? identity.name } : {},
|
|
28221
|
+
...remote?.features ?? identity.features ? { features: remote?.features ?? identity.features } : {}
|
|
28222
|
+
};
|
|
28223
|
+
if (next.kind !== identity.kind) {
|
|
28224
|
+
log8.warn(
|
|
28225
|
+
`[GroupIdentity] remote kind "${next.kind}" \u2260 this group kind "${identity.kind}" \u2014 sync pair NOT created`
|
|
28226
|
+
);
|
|
28227
|
+
return "conflict";
|
|
28228
|
+
}
|
|
28229
|
+
try {
|
|
28230
|
+
await writeGroupDescriptor(remoteFS, next);
|
|
28231
|
+
} catch (err2) {
|
|
28232
|
+
log8.warn(`[GroupIdentity] failed to claim remote root for "${identity.id}":`, err2);
|
|
28233
|
+
return "conflict";
|
|
28234
|
+
}
|
|
28235
|
+
log8.log(
|
|
28236
|
+
`[GroupIdentity] claimed remote root for ${identity.kind}/"${identity.id}" (instanceId=${identity.instanceId})`
|
|
28237
|
+
);
|
|
28238
|
+
return "claimed";
|
|
28239
|
+
}
|
|
28240
|
+
function pickInstanceId(descriptor) {
|
|
28241
|
+
const value = descriptor?.instanceId;
|
|
28242
|
+
return isValidGroupInstanceId(value) ? value : void 0;
|
|
28243
|
+
}
|
|
28244
|
+
|
|
28245
|
+
// src/mtime-cleanup.ts
|
|
28246
|
+
function isMtimeSidecar(fileName) {
|
|
28247
|
+
return fileName.endsWith(".mtime");
|
|
28248
|
+
}
|
|
28249
|
+
var S_IFDIR2 = 16384;
|
|
28250
|
+
function isDirectory3(stat5) {
|
|
28251
|
+
return typeof stat5.mode === "number" && (stat5.mode & S_IFDIR2) === S_IFDIR2;
|
|
28252
|
+
}
|
|
28253
|
+
function joinPath(dir, entry) {
|
|
28254
|
+
if (dir === "/" || dir === "") return `/${entry}`;
|
|
28255
|
+
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
28256
|
+
}
|
|
28257
|
+
async function purgeMtimeSidecars(fs, options = {}) {
|
|
28258
|
+
const root = options.root && options.root !== "" ? options.root : "/";
|
|
28259
|
+
const dryRun = options.dryRun ?? false;
|
|
28260
|
+
const result = { scanned: 0, removed: [], failed: [] };
|
|
28261
|
+
const stack = [root];
|
|
28262
|
+
while (stack.length > 0) {
|
|
28263
|
+
const dir = stack.pop();
|
|
28264
|
+
let entries2;
|
|
28265
|
+
try {
|
|
28266
|
+
entries2 = await fs.readdir(dir);
|
|
28267
|
+
} catch {
|
|
28268
|
+
continue;
|
|
28269
|
+
}
|
|
28270
|
+
for (const entry of entries2) {
|
|
28271
|
+
const fullPath = joinPath(dir, entry);
|
|
28272
|
+
let stat5;
|
|
28273
|
+
try {
|
|
28274
|
+
stat5 = await fs.stat(fullPath);
|
|
28275
|
+
} catch {
|
|
28276
|
+
continue;
|
|
28277
|
+
}
|
|
28278
|
+
if (isDirectory3(stat5)) {
|
|
28279
|
+
stack.push(fullPath);
|
|
28280
|
+
continue;
|
|
28281
|
+
}
|
|
28282
|
+
result.scanned++;
|
|
28283
|
+
if (!isMtimeSidecar(entry)) continue;
|
|
28284
|
+
if (dryRun) {
|
|
28285
|
+
result.removed.push(fullPath);
|
|
28286
|
+
continue;
|
|
28287
|
+
}
|
|
28288
|
+
try {
|
|
28289
|
+
await fs.unlink(fullPath);
|
|
28290
|
+
result.removed.push(fullPath);
|
|
28291
|
+
} catch {
|
|
28292
|
+
result.failed.push(fullPath);
|
|
28293
|
+
}
|
|
28294
|
+
}
|
|
28295
|
+
}
|
|
28296
|
+
return result;
|
|
28297
|
+
}
|
|
28298
|
+
|
|
28299
|
+
// src/keep-cleanup.ts
|
|
28300
|
+
function isKeepFile(fileName) {
|
|
28301
|
+
return fileName === ".keep";
|
|
28302
|
+
}
|
|
28303
|
+
var S_IFDIR3 = 16384;
|
|
28304
|
+
var DEFAULT_PROTECTED_DIRS = ["/.meta/backends/.keep"];
|
|
28305
|
+
function isDirectory4(stat5) {
|
|
28306
|
+
return typeof stat5.mode === "number" && (stat5.mode & S_IFDIR3) === S_IFDIR3;
|
|
28307
|
+
}
|
|
28308
|
+
function joinPath2(dir, entry) {
|
|
28309
|
+
if (dir === "/" || dir === "") return `/${entry}`;
|
|
28310
|
+
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
28311
|
+
}
|
|
28312
|
+
function isProtected(fullPath, protectedDirs) {
|
|
28313
|
+
return protectedDirs.some((d) => {
|
|
28314
|
+
const dir = d.endsWith("/") ? d.slice(0, -1) : d;
|
|
28315
|
+
return fullPath === dir || fullPath.startsWith(dir + "/");
|
|
28316
|
+
});
|
|
28317
|
+
}
|
|
28318
|
+
async function purgeKeepFiles(fs, options = {}) {
|
|
28319
|
+
const root = options.root && options.root !== "" ? options.root : "/";
|
|
28320
|
+
const dryRun = options.dryRun ?? false;
|
|
28321
|
+
const protectedDirs = options.protectedDirs ?? DEFAULT_PROTECTED_DIRS;
|
|
28322
|
+
const result = { scanned: 0, removed: [], failed: [] };
|
|
28323
|
+
const stack = [root];
|
|
28324
|
+
while (stack.length > 0) {
|
|
28325
|
+
const dir = stack.pop();
|
|
28326
|
+
if (isProtected(dir, protectedDirs)) continue;
|
|
28327
|
+
let entries2;
|
|
28328
|
+
try {
|
|
28329
|
+
entries2 = await fs.readdir(dir);
|
|
28330
|
+
} catch {
|
|
28331
|
+
continue;
|
|
28332
|
+
}
|
|
28333
|
+
for (const entry of entries2) {
|
|
28334
|
+
const fullPath = joinPath2(dir, entry);
|
|
28335
|
+
if (isProtected(fullPath, protectedDirs)) continue;
|
|
28336
|
+
let stat5;
|
|
28337
|
+
try {
|
|
28338
|
+
stat5 = await fs.stat(fullPath);
|
|
28339
|
+
} catch {
|
|
28340
|
+
continue;
|
|
28341
|
+
}
|
|
28342
|
+
if (isDirectory4(stat5)) {
|
|
28343
|
+
stack.push(fullPath);
|
|
28344
|
+
continue;
|
|
28345
|
+
}
|
|
28346
|
+
result.scanned++;
|
|
28347
|
+
if (!isKeepFile(entry)) continue;
|
|
28348
|
+
if (dryRun) {
|
|
28349
|
+
result.removed.push(fullPath);
|
|
28350
|
+
continue;
|
|
28351
|
+
}
|
|
28352
|
+
try {
|
|
28353
|
+
await fs.unlink(fullPath);
|
|
28354
|
+
result.removed.push(fullPath);
|
|
28355
|
+
} catch {
|
|
28356
|
+
result.failed.push(fullPath);
|
|
28357
|
+
}
|
|
28358
|
+
}
|
|
28359
|
+
}
|
|
28360
|
+
return result;
|
|
28361
|
+
}
|
|
28362
|
+
|
|
28363
|
+
// src/version-migration.ts
|
|
28364
|
+
var S_IFDIR4 = 16384;
|
|
28365
|
+
function isDir(stat5) {
|
|
28366
|
+
return typeof stat5.mode === "number" && (stat5.mode & S_IFDIR4) === S_IFDIR4;
|
|
28367
|
+
}
|
|
28368
|
+
function joinPath3(dir, entry) {
|
|
28369
|
+
if (dir === "/" || dir === "") return `/${entry}`;
|
|
28370
|
+
return `${dir.replace(/\/+$/, "")}/${entry}`;
|
|
28371
|
+
}
|
|
28372
|
+
async function existsPath(fs, p) {
|
|
28373
|
+
try {
|
|
28374
|
+
await fs.stat(p);
|
|
28375
|
+
return true;
|
|
28376
|
+
} catch {
|
|
28377
|
+
return false;
|
|
28378
|
+
}
|
|
28379
|
+
}
|
|
28380
|
+
function configNameFromLegacy(entry) {
|
|
28381
|
+
const noMtime = entry.endsWith(".version.mtime") ? entry.slice(0, -".version.mtime".length) : entry.slice(0, -".version".length);
|
|
28382
|
+
return noMtime.slice(1);
|
|
28383
|
+
}
|
|
28384
|
+
async function resolveTarget(fs, dir, entry) {
|
|
28385
|
+
const configName = configNameFromLegacy(entry);
|
|
28386
|
+
const configPath = joinPath3(dir, configName);
|
|
28387
|
+
const dotConfigPath = joinPath3(dir, `.${configName}`);
|
|
28388
|
+
if (await existsPath(fs, dotConfigPath)) {
|
|
28389
|
+
return { action: "skip" };
|
|
28390
|
+
}
|
|
28391
|
+
if (await existsPath(fs, configPath)) {
|
|
28392
|
+
return { action: "rename", newPath: versionPathFor(configPath) ?? `${configName}.version` };
|
|
28393
|
+
}
|
|
28394
|
+
return { action: "delete" };
|
|
28395
|
+
}
|
|
28396
|
+
async function migrateVersionSidecars(fs, options = {}) {
|
|
28397
|
+
const root = options.root && options.root !== "" ? options.root : "/";
|
|
28398
|
+
const dryRun = options.dryRun ?? false;
|
|
28399
|
+
const replicas = options.replicas ?? [];
|
|
28400
|
+
const result = {
|
|
28401
|
+
renamed: [],
|
|
28402
|
+
deleted: [],
|
|
28403
|
+
remoteDeleted: [],
|
|
28404
|
+
failed: []
|
|
28405
|
+
};
|
|
28406
|
+
const stack = [root];
|
|
28407
|
+
while (stack.length > 0) {
|
|
28408
|
+
const dir = stack.pop();
|
|
28409
|
+
let entries2;
|
|
28410
|
+
try {
|
|
28411
|
+
entries2 = await fs.readdir(dir);
|
|
28412
|
+
} catch {
|
|
28413
|
+
continue;
|
|
28414
|
+
}
|
|
28415
|
+
for (const entry of entries2) {
|
|
28416
|
+
const full = joinPath3(dir, entry);
|
|
28417
|
+
let stat5;
|
|
28418
|
+
try {
|
|
28419
|
+
stat5 = await fs.stat(full);
|
|
28420
|
+
} catch {
|
|
28421
|
+
continue;
|
|
28422
|
+
}
|
|
28423
|
+
if (isDir(stat5)) {
|
|
28424
|
+
stack.push(full);
|
|
28425
|
+
continue;
|
|
28426
|
+
}
|
|
28427
|
+
const isLegacyVersion = entry.startsWith(".") && (entry.endsWith(".version") || entry.endsWith(".version.mtime"));
|
|
28428
|
+
if (!isLegacyVersion) continue;
|
|
28429
|
+
const legacyVerPath = entry.endsWith(".version.mtime") ? full.slice(0, -".mtime".length) : full;
|
|
28430
|
+
const target = await resolveTarget(fs, dir, entry);
|
|
28431
|
+
if (target.action === "skip") continue;
|
|
28432
|
+
const legacyMtimePath = `${legacyVerPath}.mtime`;
|
|
28433
|
+
const newMtimePath = target.newPath ? `${target.newPath}.mtime` : null;
|
|
28434
|
+
if (dryRun) {
|
|
28435
|
+
if (target.action === "rename") result.renamed.push(full);
|
|
28436
|
+
else result.deleted.push(full);
|
|
28437
|
+
continue;
|
|
28438
|
+
}
|
|
28104
28439
|
try {
|
|
28105
|
-
|
|
28106
|
-
|
|
28440
|
+
if (target.action === "rename") {
|
|
28441
|
+
if (await existsPath(fs, target.newPath)) {
|
|
28442
|
+
await fs.unlink(legacyVerPath);
|
|
28443
|
+
result.deleted.push(full);
|
|
28444
|
+
} else {
|
|
28445
|
+
const content = await fs.readFile(legacyVerPath);
|
|
28446
|
+
const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
|
|
28447
|
+
await fs.writeFile(target.newPath, bytes);
|
|
28448
|
+
await fs.unlink(legacyVerPath);
|
|
28449
|
+
result.renamed.push(full);
|
|
28450
|
+
}
|
|
28451
|
+
if (newMtimePath && await existsPath(fs, legacyMtimePath)) {
|
|
28452
|
+
try {
|
|
28453
|
+
const mc = await fs.readFile(legacyMtimePath);
|
|
28454
|
+
const mb = typeof mc === "string" ? new TextEncoder().encode(mc) : mc;
|
|
28455
|
+
await fs.writeFile(newMtimePath, mb);
|
|
28456
|
+
await fs.unlink(legacyMtimePath);
|
|
28457
|
+
} catch {
|
|
28458
|
+
}
|
|
28459
|
+
}
|
|
28460
|
+
} else {
|
|
28461
|
+
await fs.unlink(legacyVerPath);
|
|
28462
|
+
result.deleted.push(full);
|
|
28463
|
+
if (await existsPath(fs, legacyMtimePath)) {
|
|
28464
|
+
try {
|
|
28465
|
+
await fs.unlink(legacyMtimePath);
|
|
28466
|
+
} catch {
|
|
28467
|
+
}
|
|
28468
|
+
}
|
|
28469
|
+
}
|
|
28470
|
+
} catch (e) {
|
|
28471
|
+
result.failed.push(full);
|
|
28472
|
+
continue;
|
|
28473
|
+
}
|
|
28474
|
+
for (const rep of replicas) {
|
|
28475
|
+
for (const rp of [legacyVerPath, legacyMtimePath]) {
|
|
28476
|
+
try {
|
|
28477
|
+
await rep.unlink(rp);
|
|
28478
|
+
result.remoteDeleted.push(rp);
|
|
28479
|
+
} catch {
|
|
28480
|
+
}
|
|
28481
|
+
}
|
|
28107
28482
|
}
|
|
28108
28483
|
}
|
|
28109
|
-
throw new Error(`Conflict backup not found: ${conflictId}/${fileType}`);
|
|
28110
|
-
}
|
|
28111
|
-
/** Resolve a conflict with raw (already serialized) content. */
|
|
28112
|
-
async resolve(conflictId, mergedContent) {
|
|
28113
|
-
for (const dir of this.candidatesFor(conflictId)) {
|
|
28114
|
-
const metaPath = `${dir}/meta.json`;
|
|
28115
|
-
const archive = await readJson(this.fs, metaPath);
|
|
28116
|
-
if (!archive) continue;
|
|
28117
|
-
const bytes = typeof mergedContent === "string" ? new TextEncoder().encode(mergedContent) : mergedContent;
|
|
28118
|
-
await ensureParentDir2(this.fs, archive.conflictPath);
|
|
28119
|
-
await this.fs.writeFile(archive.conflictPath, bytes);
|
|
28120
|
-
await this.versions.record(archive.conflictPath, bytes);
|
|
28121
|
-
await this.fs.writeFile(`${dir}/resolved`, bytes);
|
|
28122
|
-
archive.resolvedBackupPath = "./resolved";
|
|
28123
|
-
await writeJson(this.fs, metaPath, archive);
|
|
28124
|
-
return;
|
|
28125
|
-
}
|
|
28126
|
-
throw new Error(`Failed to resolve conflict ${conflictId}: archive not found`);
|
|
28127
28484
|
}
|
|
28128
|
-
|
|
28485
|
+
return result;
|
|
28486
|
+
}
|
|
28129
28487
|
|
|
28130
28488
|
// src/config-repo.ts
|
|
28131
|
-
var
|
|
28132
|
-
var
|
|
28489
|
+
var log9 = createLogger("zen-fs-config:config-repo");
|
|
28490
|
+
var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
|
|
28133
28491
|
var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
|
|
28134
28492
|
var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
|
|
28135
28493
|
var BACKENDS_FILE = `${META_DIR}/backends.json`;
|
|
@@ -28161,81 +28519,6 @@ var ZenFSConfig = (() => {
|
|
|
28161
28519
|
return false;
|
|
28162
28520
|
}
|
|
28163
28521
|
}
|
|
28164
|
-
async function collectFilesUnder(fs, dir, out = []) {
|
|
28165
|
-
const entries2 = await fs.readdir(dir);
|
|
28166
|
-
for (const entry of entries2) {
|
|
28167
|
-
const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
|
|
28168
|
-
if (await isDirectoryPath(fs, child)) {
|
|
28169
|
-
await collectFilesUnder(fs, child, out);
|
|
28170
|
-
} else {
|
|
28171
|
-
out.push(child);
|
|
28172
|
-
}
|
|
28173
|
-
}
|
|
28174
|
-
return out;
|
|
28175
|
-
}
|
|
28176
|
-
async function collectDirectoriesUnder(fs, dir, out = []) {
|
|
28177
|
-
out.push(dir);
|
|
28178
|
-
let entries2;
|
|
28179
|
-
try {
|
|
28180
|
-
entries2 = await fs.readdir(dir);
|
|
28181
|
-
} catch {
|
|
28182
|
-
return out;
|
|
28183
|
-
}
|
|
28184
|
-
for (const entry of entries2) {
|
|
28185
|
-
const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
|
|
28186
|
-
if (await isDirectoryPath(fs, child)) await collectDirectoriesUnder(fs, child, out);
|
|
28187
|
-
}
|
|
28188
|
-
return out;
|
|
28189
|
-
}
|
|
28190
|
-
async function removeDirectoryTree(fs, dir) {
|
|
28191
|
-
let entries2;
|
|
28192
|
-
try {
|
|
28193
|
-
entries2 = await fs.readdir(dir);
|
|
28194
|
-
} catch {
|
|
28195
|
-
return;
|
|
28196
|
-
}
|
|
28197
|
-
for (const entry of entries2) {
|
|
28198
|
-
const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
|
|
28199
|
-
if (await isDirectoryPath(fs, child)) await removeDirectoryTree(fs, child);
|
|
28200
|
-
}
|
|
28201
|
-
try {
|
|
28202
|
-
await fs.rmdir?.(dir);
|
|
28203
|
-
} catch {
|
|
28204
|
-
}
|
|
28205
|
-
}
|
|
28206
|
-
async function collectFilesUnderAny(surfaces, dir, onError) {
|
|
28207
|
-
const merged = /* @__PURE__ */ new Set();
|
|
28208
|
-
for (const surface of surfaces) {
|
|
28209
|
-
try {
|
|
28210
|
-
for (const file of await collectFilesUnder(surface.fs, dir)) merged.add(file);
|
|
28211
|
-
} catch (error) {
|
|
28212
|
-
onError(surface.label, error);
|
|
28213
|
-
}
|
|
28214
|
-
}
|
|
28215
|
-
return [...merged];
|
|
28216
|
-
}
|
|
28217
|
-
async function collectDirectoriesUnderStrict(fs, dir, out = []) {
|
|
28218
|
-
out.push(dir);
|
|
28219
|
-
const entries2 = await fs.readdir(dir);
|
|
28220
|
-
for (const entry of entries2) {
|
|
28221
|
-
const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
|
|
28222
|
-
if (await isDirectoryPath(fs, child)) await collectDirectoriesUnderStrict(fs, child, out);
|
|
28223
|
-
}
|
|
28224
|
-
return out;
|
|
28225
|
-
}
|
|
28226
|
-
async function collectDirectoriesUnderAny(surfaces, dir, onError) {
|
|
28227
|
-
const merged = /* @__PURE__ */ new Set();
|
|
28228
|
-
for (const surface of surfaces) {
|
|
28229
|
-
const found = [];
|
|
28230
|
-
try {
|
|
28231
|
-
await collectDirectoriesUnderStrict(surface.fs, dir, found);
|
|
28232
|
-
} catch (error) {
|
|
28233
|
-
onError(surface.label, error);
|
|
28234
|
-
}
|
|
28235
|
-
for (const child of found) merged.add(child);
|
|
28236
|
-
}
|
|
28237
|
-
return [...merged];
|
|
28238
|
-
}
|
|
28239
28522
|
async function isDirectoryAny(surfaces, path) {
|
|
28240
28523
|
for (const surface of surfaces) {
|
|
28241
28524
|
if (await isDirectoryPath(surface.fs, path)) return true;
|
|
@@ -28263,6 +28546,7 @@ var ZenFSConfig = (() => {
|
|
|
28263
28546
|
}
|
|
28264
28547
|
var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
|
|
28265
28548
|
var LOCAL_IDB_BACKEND_ID = "local-idb";
|
|
28549
|
+
var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
|
|
28266
28550
|
function tombstoneFileName(filePath) {
|
|
28267
28551
|
return `${encodeMetaPath(filePath)}.json`;
|
|
28268
28552
|
}
|
|
@@ -28372,6 +28656,15 @@ var ZenFSConfig = (() => {
|
|
|
28372
28656
|
__publicField(this, "tombstoneConfirmations", /* @__PURE__ */ new Map());
|
|
28373
28657
|
/** Per-backend sync state (successful pairs + connect failures). */
|
|
28374
28658
|
__publicField(this, "backendStates", /* @__PURE__ */ new Map());
|
|
28659
|
+
/**
|
|
28660
|
+
* 本组的实例身份(UUID,见 `group-identity.ts`)。
|
|
28661
|
+
*
|
|
28662
|
+
* 它同时是同步边界:连接任何远端副本前先比对对方 `.meta/group.json` 里的
|
|
28663
|
+
* `instanceId`,不一致就不建同步对 —— 两个不同的同步组永不互相同步。
|
|
28664
|
+
*/
|
|
28665
|
+
__publicField(this, "instanceId");
|
|
28666
|
+
/** 因归属他人而被跳过的后端 id → 原因,供 UI 展示。 */
|
|
28667
|
+
__publicField(this, "skippedBackends", /* @__PURE__ */ new Map());
|
|
28375
28668
|
/** Last known backend descriptors, for the synchronous unified handle API. */
|
|
28376
28669
|
__publicField(this, "backendDescriptorCache", []);
|
|
28377
28670
|
/**
|
|
@@ -28448,7 +28741,7 @@ var ZenFSConfig = (() => {
|
|
|
28448
28741
|
const bytes = this.serializer.serialize(data, fullPath);
|
|
28449
28742
|
this.configCache.set(fullPath, data);
|
|
28450
28743
|
this.persistConfig(fullPath, bytes).catch((err2) => {
|
|
28451
|
-
|
|
28744
|
+
log9.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err2);
|
|
28452
28745
|
});
|
|
28453
28746
|
}
|
|
28454
28747
|
// -----------------------------------------------------------------------
|
|
@@ -28565,19 +28858,22 @@ var ZenFSConfig = (() => {
|
|
|
28565
28858
|
// Tombstone (Deletion Tracking)
|
|
28566
28859
|
// -----------------------------------------------------------------------
|
|
28567
28860
|
/**
|
|
28568
|
-
* Write the tombstone record for `
|
|
28569
|
-
* Records only metadata — it never creates the deleted
|
|
28861
|
+
* Write the tombstone record for `path` under `.meta/tombstones/`.
|
|
28862
|
+
* Records only metadata — it never creates the deleted path locally, and the
|
|
28570
28863
|
* legacy `/.meta/.deleted/` archive is neither read nor written.
|
|
28864
|
+
*
|
|
28865
|
+
* `type: 'directory'` 表示这是一条目录墓碑:应用时按整棵树清理。
|
|
28571
28866
|
*/
|
|
28572
|
-
async writeTombstoneFor(
|
|
28573
|
-
const normalizedPath =
|
|
28867
|
+
async writeTombstoneFor(path, type) {
|
|
28868
|
+
const normalizedPath = normalizeTombstonePath(path);
|
|
28574
28869
|
const tombstone = {
|
|
28575
28870
|
path: normalizedPath,
|
|
28576
28871
|
deletedAt: Date.now(),
|
|
28577
28872
|
deletedBy: this.primaryBackendId,
|
|
28578
|
-
confirmedBy: [this.primaryBackendId]
|
|
28873
|
+
confirmedBy: [this.primaryBackendId],
|
|
28874
|
+
...type ? { type } : {}
|
|
28579
28875
|
};
|
|
28580
|
-
const tombstoneBytes = new TextEncoder().encode(
|
|
28876
|
+
const tombstoneBytes = new TextEncoder().encode(serializeTombstone(tombstone));
|
|
28581
28877
|
const tombstonePath = tombstonePathFor(normalizedPath, TOMBSTONES_DIR);
|
|
28582
28878
|
await this.ensureDir(tombstonePath);
|
|
28583
28879
|
await this.cachedFS.writeFile(tombstonePath, tombstoneBytes);
|
|
@@ -28588,29 +28884,17 @@ var ZenFSConfig = (() => {
|
|
|
28588
28884
|
*/
|
|
28589
28885
|
async deleteFile(path) {
|
|
28590
28886
|
this.assertNotDisposed();
|
|
28591
|
-
const normalizedPath = path
|
|
28887
|
+
const normalizedPath = normalizeTombstonePath(path);
|
|
28592
28888
|
const surfaces = [{ label: "local-cache", fs: this.cachedFS }];
|
|
28593
28889
|
for (const [id, replica] of this.replicaBackends) {
|
|
28594
28890
|
surfaces.push({ label: id, fs: replica.instance });
|
|
28595
28891
|
}
|
|
28596
|
-
const onEnumerateError = (label, error) => {
|
|
28597
|
-
const reason = error?.message ?? String(error);
|
|
28598
|
-
log7.warn(
|
|
28599
|
-
`[ConfigRepo] deleteFile(directory): cannot enumerate "${label}" under ${normalizedPath}: ${reason}`
|
|
28600
|
-
);
|
|
28601
|
-
};
|
|
28602
28892
|
if (await isDirectoryAny(surfaces, normalizedPath)) {
|
|
28603
|
-
|
|
28604
|
-
|
|
28605
|
-
for (const dir of await collectDirectoriesUnderAny(surfaces, normalizedPath, onEnumerateError)) {
|
|
28606
|
-
const keepPath = dir === "/" ? "/.keep" : `${dir}/.keep`;
|
|
28607
|
-
await this.writeTombstoneFor(keepPath);
|
|
28608
|
-
await this.writeTombstoneFor(`${keepPath}.mtime`);
|
|
28609
|
-
}
|
|
28610
|
-
await removeDirectoryTree(this.cachedFS, normalizedPath);
|
|
28893
|
+
await this.writeTombstoneFor(normalizedPath, "directory");
|
|
28894
|
+
await this.purgePathOnBackend(this.cachedFS, normalizedPath);
|
|
28611
28895
|
this.invalidateTombstoneCache();
|
|
28612
28896
|
this.schedulePostDeleteSync();
|
|
28613
|
-
|
|
28897
|
+
log9.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (single directory tombstone)`);
|
|
28614
28898
|
return;
|
|
28615
28899
|
}
|
|
28616
28900
|
await this.writeTombstoneFor(normalizedPath);
|
|
@@ -28631,7 +28915,7 @@ var ZenFSConfig = (() => {
|
|
|
28631
28915
|
} catch {
|
|
28632
28916
|
}
|
|
28633
28917
|
}
|
|
28634
|
-
|
|
28918
|
+
log9.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
|
|
28635
28919
|
this.invalidateTombstoneCache();
|
|
28636
28920
|
this.schedulePostDeleteSync();
|
|
28637
28921
|
}
|
|
@@ -28643,7 +28927,7 @@ var ZenFSConfig = (() => {
|
|
|
28643
28927
|
this.postDeleteSyncTimer = void 0;
|
|
28644
28928
|
if (this.disposed) return;
|
|
28645
28929
|
this.syncEngine.syncAll().catch((err2) => {
|
|
28646
|
-
|
|
28930
|
+
log9.warn("[ConfigRepo] post-delete sync failed:", err2);
|
|
28647
28931
|
});
|
|
28648
28932
|
}, 500);
|
|
28649
28933
|
}
|
|
@@ -28655,7 +28939,7 @@ var ZenFSConfig = (() => {
|
|
|
28655
28939
|
if (this.tombstoneCache !== null) {
|
|
28656
28940
|
return this.tombstoneCache;
|
|
28657
28941
|
}
|
|
28658
|
-
this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) =>
|
|
28942
|
+
this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log9.warn(message));
|
|
28659
28943
|
this.refreshSyncExclusions(this.tombstoneCache);
|
|
28660
28944
|
return this.tombstoneCache;
|
|
28661
28945
|
}
|
|
@@ -28673,16 +28957,40 @@ var ZenFSConfig = (() => {
|
|
|
28673
28957
|
for (const tombstone of tombstones) {
|
|
28674
28958
|
if (!tombstone.path) continue;
|
|
28675
28959
|
add(tombstone.path);
|
|
28676
|
-
if (tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep") || tombstone.path.endsWith("/.keep.mtime")) {
|
|
28677
|
-
const dir = tombstone.path.slice(0, tombstone.path.lastIndexOf("/")) || "/";
|
|
28678
|
-
if (dir !== "/") add(dir);
|
|
28679
|
-
}
|
|
28680
28960
|
}
|
|
28681
28961
|
}
|
|
28682
28962
|
/** Invalidate the tombstone cache — call after tombstones are modified. */
|
|
28683
28963
|
invalidateTombstoneCache() {
|
|
28684
28964
|
this.tombstoneCache = null;
|
|
28685
28965
|
}
|
|
28966
|
+
/**
|
|
28967
|
+
* 判定墓碑目标路径是否在删除之后被重新创建。
|
|
28968
|
+
*
|
|
28969
|
+
* 墓碑表达的是「删除意图」,但删除之后同一路径完全可能被再次写入。同步类工具
|
|
28970
|
+
* 的锁文件(`.sync.lock`)就是每轮「删除 → 重建」;若把墓碑当作永久否决权,
|
|
28971
|
+
* 这个路径会被每一轮 sync 反复删除,表现为「刚写进去 1 秒后就消失」、锁永远拿
|
|
28972
|
+
* 不到、深层目录刚建就没了。
|
|
28973
|
+
*
|
|
28974
|
+
* 判定依据是文件 mtime 晚于 `deletedAt`:写入必然刷新 mtime,因此 mtime 比删除
|
|
28975
|
+
* 时刻新就意味着这条墓碑已经被写操作撤销。
|
|
28976
|
+
*/
|
|
28977
|
+
async isPathRecreatedAfterTombstone(tombstone) {
|
|
28978
|
+
const surfaces = [{ label: "local-cache", fs: this.cachedFS }];
|
|
28979
|
+
for (const [id, replica] of this.replicaBackends) {
|
|
28980
|
+
surfaces.push({ label: id, fs: replica.instance });
|
|
28981
|
+
}
|
|
28982
|
+
for (const surface of surfaces) {
|
|
28983
|
+
let mtimeMs;
|
|
28984
|
+
try {
|
|
28985
|
+
const inode = await surface.fs.stat(tombstone.path);
|
|
28986
|
+
mtimeMs = Number(inode?.mtimeMs ?? 0);
|
|
28987
|
+
} catch {
|
|
28988
|
+
continue;
|
|
28989
|
+
}
|
|
28990
|
+
if (mtimeMs > tombstone.deletedAt + TOMBSTONE_RECREATE_SKEW_MS) return true;
|
|
28991
|
+
}
|
|
28992
|
+
return false;
|
|
28993
|
+
}
|
|
28686
28994
|
/**
|
|
28687
28995
|
* Before sync: for each tombstone, delete the actual file on all replicas.
|
|
28688
28996
|
* This prevents bi-directional sync from copying the file back.
|
|
@@ -28700,10 +29008,16 @@ var ZenFSConfig = (() => {
|
|
|
28700
29008
|
let processed = 0;
|
|
28701
29009
|
let alreadyDeleted = 0;
|
|
28702
29010
|
let unresolved = 0;
|
|
29011
|
+
const expired = [];
|
|
28703
29012
|
for (const tombstone of tombstones) {
|
|
28704
29013
|
const isKeepPlaceholder = tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep");
|
|
28705
29014
|
const forceDelete = isMtimeSidecar(tombstone.path) || isKeepPlaceholder;
|
|
28706
|
-
const
|
|
29015
|
+
const isDirTombstone = isDirectoryTombstone(tombstone);
|
|
29016
|
+
const tVersionPath = forceDelete || isDirTombstone ? null : versionPathFor(tombstone.path);
|
|
29017
|
+
if (!forceDelete && await this.isPathRecreatedAfterTombstone(tombstone)) {
|
|
29018
|
+
expired.push(tombstone);
|
|
29019
|
+
continue;
|
|
29020
|
+
}
|
|
28707
29021
|
const sidecarOwner = sidecarOwnerPath(tombstone.path);
|
|
28708
29022
|
const isKeepSidecar = sidecarOwner === "/.keep" || (sidecarOwner?.endsWith("/.keep") ?? false);
|
|
28709
29023
|
const liveSidecarCandidate = sidecarOwner !== null && !isKeepSidecar;
|
|
@@ -28757,14 +29071,27 @@ var ZenFSConfig = (() => {
|
|
|
28757
29071
|
confirmed.add(replicaId);
|
|
28758
29072
|
} else {
|
|
28759
29073
|
unresolved++;
|
|
28760
|
-
|
|
29074
|
+
log9.warn(
|
|
28761
29075
|
`[ConfigRepo] tombstone kept: ${tombstone.path} still present on replica ${replicaId}`
|
|
28762
29076
|
);
|
|
28763
29077
|
}
|
|
28764
29078
|
}
|
|
28765
29079
|
}
|
|
29080
|
+
if (expired.length > 0) {
|
|
29081
|
+
for (const tombstone of expired) {
|
|
29082
|
+
try {
|
|
29083
|
+
await this.cachedFS.unlink(tombstonePathFor(tombstone.path, TOMBSTONES_DIR));
|
|
29084
|
+
} catch {
|
|
29085
|
+
}
|
|
29086
|
+
}
|
|
29087
|
+
this.invalidateTombstoneCache();
|
|
29088
|
+
await this.readTombstones();
|
|
29089
|
+
log9.log(
|
|
29090
|
+
`[ConfigRepo] processTombstones: expired ${expired.length} tombstone(s) \u2014 path recreated after deletion`
|
|
29091
|
+
);
|
|
29092
|
+
}
|
|
28766
29093
|
if (processed > 0 || alreadyDeleted > 0 || unresolved > 0) {
|
|
28767
|
-
|
|
29094
|
+
log9.log(
|
|
28768
29095
|
`[ConfigRepo] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone, ${unresolved} unresolved`
|
|
28769
29096
|
);
|
|
28770
29097
|
}
|
|
@@ -28865,21 +29192,21 @@ var ZenFSConfig = (() => {
|
|
|
28865
29192
|
const innerBackendName = fs?.inner?.backendName;
|
|
28866
29193
|
const directBackendName = fs?.backendName;
|
|
28867
29194
|
const backendLabel = innerBackendName ?? directBackendName ?? innerBackend ?? ctorName;
|
|
28868
|
-
|
|
29195
|
+
log9.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
|
|
28869
29196
|
if (hasExists) {
|
|
28870
|
-
|
|
29197
|
+
log9.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
|
|
28871
29198
|
const result = await fs.exists(path);
|
|
28872
|
-
|
|
29199
|
+
log9.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
|
|
28873
29200
|
return result;
|
|
28874
29201
|
}
|
|
28875
|
-
|
|
29202
|
+
log9.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
|
|
28876
29203
|
await fs.stat(path);
|
|
28877
|
-
|
|
29204
|
+
log9.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
|
|
28878
29205
|
return true;
|
|
28879
29206
|
} catch (err2) {
|
|
28880
29207
|
const errCode = err2?.code ?? err2?.status ?? "";
|
|
28881
29208
|
const errName = err2?.constructor?.name ?? "";
|
|
28882
|
-
|
|
29209
|
+
log9.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err2?.message ?? err2}`);
|
|
28883
29210
|
return false;
|
|
28884
29211
|
}
|
|
28885
29212
|
}
|
|
@@ -28906,13 +29233,13 @@ var ZenFSConfig = (() => {
|
|
|
28906
29233
|
this.assertNotDisposed();
|
|
28907
29234
|
const result = await purgeMtimeSidecars(this.cachedFS, options);
|
|
28908
29235
|
if (result.removed.length > 0) {
|
|
28909
|
-
|
|
29236
|
+
log9.log(
|
|
28910
29237
|
`[ConfigRepo] purged ${result.removed.length} .mtime sidecar(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
|
|
28911
29238
|
result.removed
|
|
28912
29239
|
);
|
|
28913
29240
|
}
|
|
28914
29241
|
if (result.failed.length > 0) {
|
|
28915
|
-
|
|
29242
|
+
log9.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
|
|
28916
29243
|
}
|
|
28917
29244
|
return result;
|
|
28918
29245
|
}
|
|
@@ -28932,13 +29259,13 @@ var ZenFSConfig = (() => {
|
|
|
28932
29259
|
this.assertNotDisposed();
|
|
28933
29260
|
const result = await purgeKeepFiles(this.cachedFS, options);
|
|
28934
29261
|
if (result.removed.length > 0) {
|
|
28935
|
-
|
|
29262
|
+
log9.log(
|
|
28936
29263
|
`[ConfigRepo] purged ${result.removed.length} .keep placeholder(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
|
|
28937
29264
|
result.removed
|
|
28938
29265
|
);
|
|
28939
29266
|
}
|
|
28940
29267
|
if (result.failed.length > 0) {
|
|
28941
|
-
|
|
29268
|
+
log9.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
|
|
28942
29269
|
}
|
|
28943
29270
|
return result;
|
|
28944
29271
|
}
|
|
@@ -28957,24 +29284,24 @@ var ZenFSConfig = (() => {
|
|
|
28957
29284
|
}));
|
|
28958
29285
|
const result = await migrateVersionSidecars(this.cachedFS, { replicas });
|
|
28959
29286
|
if (result.renamed.length > 0) {
|
|
28960
|
-
|
|
29287
|
+
log9.log(
|
|
28961
29288
|
`[ConfigRepo] migrated ${result.renamed.length} legacy version sidecar(s) to new naming`,
|
|
28962
29289
|
result.renamed
|
|
28963
29290
|
);
|
|
28964
29291
|
}
|
|
28965
29292
|
if (result.deleted.length > 0) {
|
|
28966
|
-
|
|
29293
|
+
log9.log(
|
|
28967
29294
|
`[ConfigRepo] removed ${result.deleted.length} orphaned legacy version sidecar(s)`,
|
|
28968
29295
|
result.deleted
|
|
28969
29296
|
);
|
|
28970
29297
|
}
|
|
28971
29298
|
if (result.remoteDeleted.length > 0) {
|
|
28972
|
-
|
|
29299
|
+
log9.log(
|
|
28973
29300
|
`[ConfigRepo] removed ${result.remoteDeleted.length} remote residual legacy version sidecar(s)`
|
|
28974
29301
|
);
|
|
28975
29302
|
}
|
|
28976
29303
|
if (result.failed.length > 0) {
|
|
28977
|
-
|
|
29304
|
+
log9.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
|
|
28978
29305
|
}
|
|
28979
29306
|
return result;
|
|
28980
29307
|
}
|
|
@@ -28997,9 +29324,9 @@ var ZenFSConfig = (() => {
|
|
|
28997
29324
|
*/
|
|
28998
29325
|
startBackgroundSync() {
|
|
28999
29326
|
this.initialSyncPromise = this.initialSyncAndDedup().then(() => {
|
|
29000
|
-
|
|
29327
|
+
log9.log("[ConfigRepo] Background initial sync complete");
|
|
29001
29328
|
}).catch((err2) => {
|
|
29002
|
-
|
|
29329
|
+
log9.error("[ConfigRepo] Background initial sync failed:", err2);
|
|
29003
29330
|
}).finally(() => {
|
|
29004
29331
|
this.initialSyncPromise = null;
|
|
29005
29332
|
});
|
|
@@ -29028,7 +29355,7 @@ var ZenFSConfig = (() => {
|
|
|
29028
29355
|
}
|
|
29029
29356
|
if (changed) {
|
|
29030
29357
|
try {
|
|
29031
|
-
const bytes = new TextEncoder().encode(
|
|
29358
|
+
const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
|
|
29032
29359
|
const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
|
|
29033
29360
|
if (await this.safeExists(this.cachedFS, tombstonePath)) {
|
|
29034
29361
|
await this.cachedFS.writeFile(tombstonePath, bytes);
|
|
@@ -29038,7 +29365,7 @@ var ZenFSConfig = (() => {
|
|
|
29038
29365
|
}
|
|
29039
29366
|
}
|
|
29040
29367
|
}
|
|
29041
|
-
|
|
29368
|
+
log9.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
|
|
29042
29369
|
if (modified > 0) this.invalidateTombstoneCache();
|
|
29043
29370
|
}
|
|
29044
29371
|
/**
|
|
@@ -29076,7 +29403,12 @@ var ZenFSConfig = (() => {
|
|
|
29076
29403
|
const tombstones = await this.readTombstones();
|
|
29077
29404
|
if (tombstones.length === 0) return;
|
|
29078
29405
|
const allBackendIds = [...this.replicaBackends.keys()];
|
|
29406
|
+
let keptByRetention = 0;
|
|
29079
29407
|
for (const tombstone of tombstones) {
|
|
29408
|
+
if (!isTombstoneRetentionElapsed(tombstone)) {
|
|
29409
|
+
keptByRetention++;
|
|
29410
|
+
continue;
|
|
29411
|
+
}
|
|
29080
29412
|
const allConfirmed = await this.allReplicasConfirmAbsent(tombstone.path);
|
|
29081
29413
|
if (allConfirmed) {
|
|
29082
29414
|
const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
|
|
@@ -29092,9 +29424,12 @@ var ZenFSConfig = (() => {
|
|
|
29092
29424
|
}
|
|
29093
29425
|
}
|
|
29094
29426
|
}
|
|
29095
|
-
|
|
29427
|
+
log9.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
|
|
29096
29428
|
}
|
|
29097
29429
|
}
|
|
29430
|
+
if (keptByRetention > 0) {
|
|
29431
|
+
log9.log(`[ConfigRepo] gcTombstones: kept ${keptByRetention} tombstone(s) within retention window`);
|
|
29432
|
+
}
|
|
29098
29433
|
}
|
|
29099
29434
|
/**
|
|
29100
29435
|
* Sync .meta/ files (backends.json) to all replica backends.
|
|
@@ -29108,7 +29443,7 @@ var ZenFSConfig = (() => {
|
|
|
29108
29443
|
this.assertNotDisposed();
|
|
29109
29444
|
const results = await this.flush();
|
|
29110
29445
|
for (const result of results) {
|
|
29111
|
-
|
|
29446
|
+
log9.log(
|
|
29112
29447
|
`[ConfigRepo] syncMetaToReplicas: ${result.pairId} +${result.filesCreated}/~${result.filesUpdated}/-${result.filesDeleted} skip:${result.filesSkipped} ${result.durationMs}ms`
|
|
29113
29448
|
);
|
|
29114
29449
|
}
|
|
@@ -29281,21 +29616,29 @@ var ZenFSConfig = (() => {
|
|
|
29281
29616
|
// Internal — Setup
|
|
29282
29617
|
// -----------------------------------------------------------------------
|
|
29283
29618
|
async setupSync(backends, primaryBackendId, pollIntervalMs) {
|
|
29284
|
-
|
|
29619
|
+
log9.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
|
|
29285
29620
|
for (const desc of backends) {
|
|
29286
29621
|
if (desc.id === primaryBackendId) continue;
|
|
29287
29622
|
if (desc.enabled === false) {
|
|
29288
|
-
|
|
29623
|
+
log9.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
|
|
29289
29624
|
continue;
|
|
29290
29625
|
}
|
|
29291
|
-
|
|
29626
|
+
log9.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
|
|
29292
29627
|
try {
|
|
29293
29628
|
const instance = await createBackend(desc);
|
|
29629
|
+
const owner = await this.bindBackendIdentity(instance, desc.id);
|
|
29630
|
+
if (owner === "conflict") {
|
|
29631
|
+
try {
|
|
29632
|
+
await instance.dispose?.();
|
|
29633
|
+
} catch {
|
|
29634
|
+
}
|
|
29635
|
+
continue;
|
|
29636
|
+
}
|
|
29294
29637
|
let fsInstance = instance;
|
|
29295
29638
|
if (this.cacheOptions) {
|
|
29296
29639
|
const { wrapWithCache: wrapWithCache2 } = await Promise.resolve().then(() => (init_cache_wrapper(), cache_wrapper_exports));
|
|
29297
29640
|
fsInstance = wrapWithCache2(instance, desc.id, this.cacheOptions);
|
|
29298
|
-
|
|
29641
|
+
log9.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
|
|
29299
29642
|
}
|
|
29300
29643
|
const syncable = backendToSyncableFS(fsInstance, `${desc.type}(${desc.id})`);
|
|
29301
29644
|
const pair = this.syncEngine.addPair(
|
|
@@ -29313,7 +29656,7 @@ var ZenFSConfig = (() => {
|
|
|
29313
29656
|
this.invalidateTombstoneCache();
|
|
29314
29657
|
await this.processTombstones();
|
|
29315
29658
|
} catch (err2) {
|
|
29316
|
-
|
|
29659
|
+
log9.warn("[ConfigRepo] preSyncHook processTombstones failed:", err2);
|
|
29317
29660
|
}
|
|
29318
29661
|
},
|
|
29319
29662
|
postSyncHook: async () => {
|
|
@@ -29322,7 +29665,7 @@ var ZenFSConfig = (() => {
|
|
|
29322
29665
|
await this.processTombstones();
|
|
29323
29666
|
await this.updateTombstoneConfirmations();
|
|
29324
29667
|
} catch (err2) {
|
|
29325
|
-
|
|
29668
|
+
log9.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err2);
|
|
29326
29669
|
}
|
|
29327
29670
|
}
|
|
29328
29671
|
},
|
|
@@ -29335,9 +29678,9 @@ var ZenFSConfig = (() => {
|
|
|
29335
29678
|
};
|
|
29336
29679
|
this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
|
|
29337
29680
|
this.trackSyncErrors(desc.id, pair.pairId);
|
|
29338
|
-
|
|
29681
|
+
log9.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
|
|
29339
29682
|
} catch (err2) {
|
|
29340
|
-
|
|
29683
|
+
log9.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err2);
|
|
29341
29684
|
this.backendStates.set(desc.id, {
|
|
29342
29685
|
backendId: desc.id,
|
|
29343
29686
|
error: {
|
|
@@ -29347,8 +29690,8 @@ var ZenFSConfig = (() => {
|
|
|
29347
29690
|
});
|
|
29348
29691
|
}
|
|
29349
29692
|
}
|
|
29350
|
-
|
|
29351
|
-
|
|
29693
|
+
log9.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
|
|
29694
|
+
log9.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
|
|
29352
29695
|
}
|
|
29353
29696
|
// -----------------------------------------------------------------------
|
|
29354
29697
|
// Internal — Persistence
|
|
@@ -29360,12 +29703,12 @@ var ZenFSConfig = (() => {
|
|
|
29360
29703
|
try {
|
|
29361
29704
|
const existing = await readVersion(this.fullFS, vPath);
|
|
29362
29705
|
if (existing && existing.hash === version2.hash) {
|
|
29363
|
-
|
|
29706
|
+
log9.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
|
|
29364
29707
|
return;
|
|
29365
29708
|
}
|
|
29366
29709
|
} catch {
|
|
29367
29710
|
}
|
|
29368
|
-
|
|
29711
|
+
log9.log("[ConfigRepo] write version sidecar:", vPath, "v" + version2.version);
|
|
29369
29712
|
await this.ensureDir(vPath);
|
|
29370
29713
|
await writeVersion(this.fullFS, vPath, version2);
|
|
29371
29714
|
}
|
|
@@ -29469,7 +29812,7 @@ var ZenFSConfig = (() => {
|
|
|
29469
29812
|
await this.resolveConflict(`${conflictId}/meta.json`, customMerge);
|
|
29470
29813
|
}
|
|
29471
29814
|
} catch (err2) {
|
|
29472
|
-
|
|
29815
|
+
log9.error("[zen-fs-config] Conflict handler error:", err2);
|
|
29473
29816
|
}
|
|
29474
29817
|
}
|
|
29475
29818
|
}
|
|
@@ -29585,11 +29928,11 @@ var ZenFSConfig = (() => {
|
|
|
29585
29928
|
}
|
|
29586
29929
|
return { kind: "ok", desc, mtime };
|
|
29587
29930
|
} else {
|
|
29588
|
-
|
|
29931
|
+
log9.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
|
|
29589
29932
|
return { kind: "corrupt", filePath };
|
|
29590
29933
|
}
|
|
29591
29934
|
} catch (parseErr) {
|
|
29592
|
-
|
|
29935
|
+
log9.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
|
|
29593
29936
|
return { kind: "corrupt", filePath };
|
|
29594
29937
|
}
|
|
29595
29938
|
})
|
|
@@ -29655,7 +29998,7 @@ var ZenFSConfig = (() => {
|
|
|
29655
29998
|
}
|
|
29656
29999
|
}
|
|
29657
30000
|
if (duplicates.length > 0) {
|
|
29658
|
-
|
|
30001
|
+
log9.log(
|
|
29659
30002
|
`[ConfigRepo] readAllBackendDescriptors: removing ${duplicates.length} duplicate(s): ${duplicates.join(", ")}`
|
|
29660
30003
|
);
|
|
29661
30004
|
for (const dupId of duplicates) {
|
|
@@ -29787,7 +30130,7 @@ var ZenFSConfig = (() => {
|
|
|
29787
30130
|
* Shared by addBackend() and replaceBackend().
|
|
29788
30131
|
*/
|
|
29789
30132
|
async setupReplica(id, type, options, description) {
|
|
29790
|
-
|
|
30133
|
+
log9.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
|
|
29791
30134
|
const instance = await createBackend({ type, options });
|
|
29792
30135
|
const syncable = backendToSyncableFS(instance, `${type}(${id})`);
|
|
29793
30136
|
const desc = { id, type, options, description };
|
|
@@ -29805,7 +30148,7 @@ var ZenFSConfig = (() => {
|
|
|
29805
30148
|
this.invalidateTombstoneCache();
|
|
29806
30149
|
await this.processTombstones();
|
|
29807
30150
|
} catch (err2) {
|
|
29808
|
-
|
|
30151
|
+
log9.warn("[ConfigRepo] preSyncHook processTombstones failed:", err2);
|
|
29809
30152
|
}
|
|
29810
30153
|
},
|
|
29811
30154
|
postSyncHook: async () => {
|
|
@@ -29814,7 +30157,7 @@ var ZenFSConfig = (() => {
|
|
|
29814
30157
|
await this.processTombstones();
|
|
29815
30158
|
await this.updateTombstoneConfirmations();
|
|
29816
30159
|
} catch (err2) {
|
|
29817
|
-
|
|
30160
|
+
log9.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err2);
|
|
29818
30161
|
}
|
|
29819
30162
|
}
|
|
29820
30163
|
},
|
|
@@ -29827,7 +30170,7 @@ var ZenFSConfig = (() => {
|
|
|
29827
30170
|
};
|
|
29828
30171
|
this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
|
|
29829
30172
|
this.trackSyncErrors(id, pair.pairId);
|
|
29830
|
-
|
|
30173
|
+
log9.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
|
|
29831
30174
|
await this.syncMetaToReplicas();
|
|
29832
30175
|
this.syncEngine.watch(pair.pairId);
|
|
29833
30176
|
return pair.pairId;
|
|
@@ -29853,13 +30196,13 @@ var ZenFSConfig = (() => {
|
|
|
29853
30196
|
}
|
|
29854
30197
|
}
|
|
29855
30198
|
this.syncEngine.removePair(replica.pairId);
|
|
29856
|
-
|
|
30199
|
+
log9.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
|
|
29857
30200
|
this.replicaBackends.delete(id);
|
|
29858
30201
|
if (replica.instance?.dispose) {
|
|
29859
30202
|
await replica.instance.dispose();
|
|
29860
30203
|
}
|
|
29861
30204
|
} else {
|
|
29862
|
-
|
|
30205
|
+
log9.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
|
|
29863
30206
|
for (const descPath of descPaths) {
|
|
29864
30207
|
try {
|
|
29865
30208
|
await this.deleteFile(descPath);
|
|
@@ -29870,7 +30213,7 @@ var ZenFSConfig = (() => {
|
|
|
29870
30213
|
}
|
|
29871
30214
|
this.backendStates.delete(id);
|
|
29872
30215
|
this.schedulePostDeleteSync();
|
|
29873
|
-
|
|
30216
|
+
log9.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
|
|
29874
30217
|
}
|
|
29875
30218
|
/**
|
|
29876
30219
|
* Replace a config-sync backend's parameters in place (same id).
|
|
@@ -29917,11 +30260,11 @@ var ZenFSConfig = (() => {
|
|
|
29917
30260
|
await this.setupReplica(id, type, options, description ?? before.description);
|
|
29918
30261
|
} catch (err2) {
|
|
29919
30262
|
const reason = err2 instanceof Error ? err2.message : String(err2);
|
|
29920
|
-
|
|
30263
|
+
log9.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err2);
|
|
29921
30264
|
try {
|
|
29922
30265
|
await this.setupReplica(id, before.type, before.options, before.description);
|
|
29923
30266
|
} catch (rollbackErr) {
|
|
29924
|
-
|
|
30267
|
+
log9.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
|
|
29925
30268
|
}
|
|
29926
30269
|
throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
|
|
29927
30270
|
}
|
|
@@ -29929,6 +30272,80 @@ var ZenFSConfig = (() => {
|
|
|
29929
30272
|
// -----------------------------------------------------------------------
|
|
29930
30273
|
// IConfigRepo — Group Type
|
|
29931
30274
|
// -----------------------------------------------------------------------
|
|
30275
|
+
/**
|
|
30276
|
+
* 本组的同步身份(kind + id + 不可变 instanceId)。
|
|
30277
|
+
*
|
|
30278
|
+
* 首次调用时若 `.meta/group.json` 里还没有 `instanceId`(老部署),生成一个
|
|
30279
|
+
* 并就地写回 —— 只写一次,之后字节相同不再落盘。
|
|
30280
|
+
*/
|
|
30281
|
+
async ensureGroupIdentity(kind = "config", id = CONFIG_GROUP_ID) {
|
|
30282
|
+
let existingFeatures;
|
|
30283
|
+
if (!this.instanceId) {
|
|
30284
|
+
let existing = null;
|
|
30285
|
+
try {
|
|
30286
|
+
existing = await readGroupDescriptor(this.cachedFS);
|
|
30287
|
+
} catch {
|
|
30288
|
+
}
|
|
30289
|
+
const known = pickInstanceId(existing);
|
|
30290
|
+
existingFeatures = existing?.features ?? CONFIG_GROUP_FEATURES;
|
|
30291
|
+
this.instanceId = known ?? newGroupInstanceId();
|
|
30292
|
+
if (!known) {
|
|
30293
|
+
try {
|
|
30294
|
+
await writeGroupDescriptor(this.cachedFS, {
|
|
30295
|
+
schemaVersion: 2,
|
|
30296
|
+
kind: existing?.kind ?? kind,
|
|
30297
|
+
id: existing?.id ?? id,
|
|
30298
|
+
instanceId: this.instanceId,
|
|
30299
|
+
...existing?.name ?? this.name ? { name: existing?.name ?? this.name } : {},
|
|
30300
|
+
features: existing?.features ?? CONFIG_GROUP_FEATURES
|
|
30301
|
+
});
|
|
30302
|
+
log9.log(`[ConfigRepo] group instanceId assigned: ${this.instanceId} (kind=${existing?.kind ?? kind})`);
|
|
30303
|
+
} catch (err2) {
|
|
30304
|
+
log9.warn("[ConfigRepo] failed to persist group instanceId:", err2);
|
|
30305
|
+
}
|
|
30306
|
+
}
|
|
30307
|
+
}
|
|
30308
|
+
return {
|
|
30309
|
+
kind,
|
|
30310
|
+
id,
|
|
30311
|
+
instanceId: this.instanceId,
|
|
30312
|
+
...this.name ? { name: this.name } : {},
|
|
30313
|
+
...existingFeatures ? { features: existingFeatures } : {}
|
|
30314
|
+
};
|
|
30315
|
+
}
|
|
30316
|
+
/** 组实例身份(未初始化时先兜底生成并落盘)。 */
|
|
30317
|
+
async ensureGroupInstanceId() {
|
|
30318
|
+
return (await this.ensureGroupIdentity()).instanceId;
|
|
30319
|
+
}
|
|
30320
|
+
/** 组实例身份(同步读取;init 之前可能为 `undefined`)。 */
|
|
30321
|
+
getGroupInstanceId() {
|
|
30322
|
+
return this.instanceId;
|
|
30323
|
+
}
|
|
30324
|
+
/**
|
|
30325
|
+
* 连接远端前校验归属:属于别的组 → `conflict`(调用方必须跳过、不建同步对)。
|
|
30326
|
+
* 老仓库(无 instanceId)会被本组认领。
|
|
30327
|
+
*/
|
|
30328
|
+
async bindBackendIdentity(instance, backendId) {
|
|
30329
|
+
try {
|
|
30330
|
+
const identity = await this.ensureGroupIdentity();
|
|
30331
|
+
const state = await bindRemoteGroupIdentity(instance, identity);
|
|
30332
|
+
if (state === "conflict") {
|
|
30333
|
+
this.skippedBackends.set(
|
|
30334
|
+
backendId,
|
|
30335
|
+
`\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`
|
|
30336
|
+
);
|
|
30337
|
+
}
|
|
30338
|
+
return state;
|
|
30339
|
+
} catch (err2) {
|
|
30340
|
+
log9.warn(`[ConfigRepo] identity check failed for backend "${backendId}", skipping it:`, err2);
|
|
30341
|
+
this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err2?.message ?? String(err2)}`);
|
|
30342
|
+
return "conflict";
|
|
30343
|
+
}
|
|
30344
|
+
}
|
|
30345
|
+
/** 因归属他人而被跳过的后端(id → 原因)。 */
|
|
30346
|
+
listSkippedBackends() {
|
|
30347
|
+
return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
|
|
30348
|
+
}
|
|
29932
30349
|
/** Write the group-type marker file if it doesn't exist. */
|
|
29933
30350
|
async ensureGroupType(type) {
|
|
29934
30351
|
this.assertNotDisposed();
|
|
@@ -29937,7 +30354,7 @@ var ZenFSConfig = (() => {
|
|
|
29937
30354
|
const existing = await this.cachedFS.readFile(path, "utf-8");
|
|
29938
30355
|
const current = existing.trim();
|
|
29939
30356
|
if (current && current !== type) {
|
|
29940
|
-
|
|
30357
|
+
log9.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
|
|
29941
30358
|
return;
|
|
29942
30359
|
}
|
|
29943
30360
|
} catch {
|
|
@@ -29951,10 +30368,12 @@ var ZenFSConfig = (() => {
|
|
|
29951
30368
|
}
|
|
29952
30369
|
const existingDescriptor = await readGroupDescriptor(this.cachedFS);
|
|
29953
30370
|
if (!existingDescriptor) {
|
|
30371
|
+
this.instanceId = newGroupInstanceId();
|
|
29954
30372
|
await writeGroupDescriptor(this.cachedFS, {
|
|
29955
30373
|
schemaVersion: 2,
|
|
29956
30374
|
kind: "config",
|
|
29957
30375
|
id: CONFIG_GROUP_ID,
|
|
30376
|
+
instanceId: this.instanceId,
|
|
29958
30377
|
...this.name ? { name: this.name } : {},
|
|
29959
30378
|
features: CONFIG_GROUP_FEATURES
|
|
29960
30379
|
});
|
|
@@ -29968,7 +30387,22 @@ var ZenFSConfig = (() => {
|
|
|
29968
30387
|
features: existingDescriptor.features ?? CONFIG_GROUP_FEATURES
|
|
29969
30388
|
});
|
|
29970
30389
|
}
|
|
29971
|
-
|
|
30390
|
+
const knownInstanceId = pickInstanceId(existingDescriptor);
|
|
30391
|
+
if (knownInstanceId) {
|
|
30392
|
+
this.instanceId = knownInstanceId;
|
|
30393
|
+
} else if (!this.instanceId) {
|
|
30394
|
+
this.instanceId = newGroupInstanceId();
|
|
30395
|
+
await writeGroupDescriptor(this.cachedFS, {
|
|
30396
|
+
schemaVersion: 2,
|
|
30397
|
+
kind: existingDescriptor?.kind ?? "config",
|
|
30398
|
+
id: existingDescriptor?.id ?? CONFIG_GROUP_ID,
|
|
30399
|
+
instanceId: this.instanceId,
|
|
30400
|
+
...existingDescriptor?.name ?? this.name ? { name: existingDescriptor?.name ?? this.name } : {},
|
|
30401
|
+
...existingDescriptor?.features ? { features: existingDescriptor.features } : {}
|
|
30402
|
+
});
|
|
30403
|
+
log9.log(`[ConfigRepo] assigned group instanceId ${this.instanceId} (kind=${existingDescriptor?.kind ?? "config"})`);
|
|
30404
|
+
}
|
|
30405
|
+
log9.log(`[ConfigRepo] group-type set to "${type}"`);
|
|
29972
30406
|
}
|
|
29973
30407
|
/** Read the group-type marker. Returns null if not set (new path, then legacy). */
|
|
29974
30408
|
async getGroupType() {
|
|
@@ -30063,7 +30497,7 @@ var ZenFSConfig = (() => {
|
|
|
30063
30497
|
if (this.appDataGroups.has(id)) {
|
|
30064
30498
|
throw new Error(`App data group "${id}" already exists. Use removeAppDataGroup() first.`);
|
|
30065
30499
|
}
|
|
30066
|
-
|
|
30500
|
+
log9.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
|
|
30067
30501
|
const resolvedBackends = [];
|
|
30068
30502
|
for (const desc of backends) {
|
|
30069
30503
|
assertValidBackendId(desc.id);
|
|
@@ -30071,6 +30505,7 @@ var ZenFSConfig = (() => {
|
|
|
30071
30505
|
resolvedBackends.push({ ...desc, options: mergedOptions });
|
|
30072
30506
|
}
|
|
30073
30507
|
await this.assertNoSharedRemote(resolvedBackends, id);
|
|
30508
|
+
const instanceId = newGroupInstanceId();
|
|
30074
30509
|
const group = new AppDataGroupImpl(
|
|
30075
30510
|
id,
|
|
30076
30511
|
this.appId,
|
|
@@ -30078,19 +30513,25 @@ var ZenFSConfig = (() => {
|
|
|
30078
30513
|
this.pollIntervalMs,
|
|
30079
30514
|
this,
|
|
30080
30515
|
// 显式新拓扑:以参数为准并写入 `.meta/backends/`。
|
|
30081
|
-
{
|
|
30516
|
+
{
|
|
30517
|
+
name: options.name,
|
|
30518
|
+
features: options.features,
|
|
30519
|
+
backendsAreAuthoritative: true,
|
|
30520
|
+
instanceId
|
|
30521
|
+
}
|
|
30082
30522
|
);
|
|
30083
30523
|
await group.init();
|
|
30084
30524
|
const descriptor = {
|
|
30085
30525
|
id,
|
|
30086
30526
|
groupType: "data-sync",
|
|
30527
|
+
instanceId: group.getGroupInstanceId() ?? instanceId,
|
|
30087
30528
|
...options.name ? { name: options.name } : {},
|
|
30088
30529
|
...options.features ? { features: options.features } : {},
|
|
30089
30530
|
backends: group.listDeclaredBackends()
|
|
30090
30531
|
};
|
|
30091
30532
|
await this.writeAppDataGroupDescriptorFile(id, descriptor);
|
|
30092
30533
|
this.appDataGroups.set(id, group);
|
|
30093
|
-
|
|
30534
|
+
log9.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
|
|
30094
30535
|
return group;
|
|
30095
30536
|
}
|
|
30096
30537
|
/**
|
|
@@ -30107,9 +30548,13 @@ var ZenFSConfig = (() => {
|
|
|
30107
30548
|
const existing = await this.readAppDataGroupDescriptor(id);
|
|
30108
30549
|
const name = meta?.name ?? existing?.name;
|
|
30109
30550
|
const features = meta?.features ?? existing?.features;
|
|
30551
|
+
const liveGroup = this.appDataGroups.get(id);
|
|
30552
|
+
const liveInstanceId = liveGroup?.getGroupInstanceId();
|
|
30553
|
+
const instanceId = pickInstanceId(existing) ?? (isValidGroupInstanceId(liveInstanceId) ? liveInstanceId : void 0);
|
|
30110
30554
|
const descriptor = {
|
|
30111
30555
|
id,
|
|
30112
30556
|
groupType: "data-sync",
|
|
30557
|
+
...instanceId ? { instanceId } : {},
|
|
30113
30558
|
...name ? { name } : {},
|
|
30114
30559
|
...features ? { features } : {},
|
|
30115
30560
|
backends
|
|
@@ -30133,7 +30578,7 @@ var ZenFSConfig = (() => {
|
|
|
30133
30578
|
try {
|
|
30134
30579
|
await live.writeOwnGroupDescriptor();
|
|
30135
30580
|
} catch (err2) {
|
|
30136
|
-
|
|
30581
|
+
log9.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err2);
|
|
30137
30582
|
}
|
|
30138
30583
|
}
|
|
30139
30584
|
const descriptor = {
|
|
@@ -30177,6 +30622,9 @@ var ZenFSConfig = (() => {
|
|
|
30177
30622
|
const nextBackends = declared.map(
|
|
30178
30623
|
(b, i) => i === index ? { ...candidate, options: mergedOptions } : b
|
|
30179
30624
|
);
|
|
30625
|
+
const descriptorNow = await this.readAppDataGroupDescriptor(groupId);
|
|
30626
|
+
const instanceIdFromLive = live?.getGroupInstanceId();
|
|
30627
|
+
const instanceId = pickInstanceId(descriptorNow) ?? (isValidGroupInstanceId(instanceIdFromLive) ? instanceIdFromLive : void 0);
|
|
30180
30628
|
if (live) {
|
|
30181
30629
|
await live.dispose();
|
|
30182
30630
|
this.appDataGroups.delete(groupId);
|
|
@@ -30188,7 +30636,7 @@ var ZenFSConfig = (() => {
|
|
|
30188
30636
|
nextBackends,
|
|
30189
30637
|
this.pollIntervalMs,
|
|
30190
30638
|
this,
|
|
30191
|
-
{ backendsAreAuthoritative: true }
|
|
30639
|
+
{ backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
|
|
30192
30640
|
);
|
|
30193
30641
|
await group.init();
|
|
30194
30642
|
await this.updateAppDataGroupDescriptor(groupId, group.listDeclaredBackends());
|
|
@@ -30196,7 +30644,7 @@ var ZenFSConfig = (() => {
|
|
|
30196
30644
|
return group;
|
|
30197
30645
|
} catch (err2) {
|
|
30198
30646
|
const reason = err2 instanceof Error ? err2.message : String(err2);
|
|
30199
|
-
|
|
30647
|
+
log9.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err2);
|
|
30200
30648
|
try {
|
|
30201
30649
|
const restored = new AppDataGroupImpl(
|
|
30202
30650
|
groupId,
|
|
@@ -30204,13 +30652,13 @@ var ZenFSConfig = (() => {
|
|
|
30204
30652
|
oldBackends,
|
|
30205
30653
|
this.pollIntervalMs,
|
|
30206
30654
|
this,
|
|
30207
|
-
{ backendsAreAuthoritative: true }
|
|
30655
|
+
{ backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
|
|
30208
30656
|
);
|
|
30209
30657
|
await restored.init();
|
|
30210
30658
|
await this.updateAppDataGroupDescriptor(groupId, restored.listDeclaredBackends());
|
|
30211
30659
|
this.appDataGroups.set(groupId, restored);
|
|
30212
30660
|
} catch (rollbackErr) {
|
|
30213
|
-
|
|
30661
|
+
log9.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
|
|
30214
30662
|
}
|
|
30215
30663
|
throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
|
|
30216
30664
|
}
|
|
@@ -30248,10 +30696,12 @@ var ZenFSConfig = (() => {
|
|
|
30248
30696
|
const version2 = await incrementVersion(this.fullFS, path, bytes, author);
|
|
30249
30697
|
await this.writeVersionSidecar(path, version2);
|
|
30250
30698
|
}
|
|
30699
|
+
const identity = await this.ensureGroupIdentity();
|
|
30251
30700
|
await writeGroupDescriptor(this.cachedFS, {
|
|
30252
30701
|
schemaVersion: 2,
|
|
30253
30702
|
kind: "config",
|
|
30254
30703
|
id: CONFIG_GROUP_ID,
|
|
30704
|
+
instanceId: identity.instanceId,
|
|
30255
30705
|
name: normalized,
|
|
30256
30706
|
features: CONFIG_GROUP_FEATURES
|
|
30257
30707
|
});
|
|
@@ -30328,7 +30778,7 @@ var ZenFSConfig = (() => {
|
|
|
30328
30778
|
try {
|
|
30329
30779
|
await this.deleteFile(descPath);
|
|
30330
30780
|
} catch (err2) {
|
|
30331
|
-
|
|
30781
|
+
log9.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err2);
|
|
30332
30782
|
try {
|
|
30333
30783
|
await this.cachedFS.unlink(descPath);
|
|
30334
30784
|
} catch {
|
|
@@ -30336,7 +30786,7 @@ var ZenFSConfig = (() => {
|
|
|
30336
30786
|
await this.unlinkVersionSidecar(this.cachedFS, descPath);
|
|
30337
30787
|
}
|
|
30338
30788
|
}
|
|
30339
|
-
|
|
30789
|
+
log9.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
|
|
30340
30790
|
}
|
|
30341
30791
|
async listAccountBackends() {
|
|
30342
30792
|
this.assertNotDisposed();
|
|
@@ -30374,8 +30824,24 @@ var ZenFSConfig = (() => {
|
|
|
30374
30824
|
__publicField(this, "versions");
|
|
30375
30825
|
__publicField(this, "conflicts");
|
|
30376
30826
|
__publicField(this, "postDeleteTimer");
|
|
30827
|
+
/**
|
|
30828
|
+
* 墓碑路径的同步排除表(与配置组同一套机制)。
|
|
30829
|
+
*
|
|
30830
|
+
* 保留期内的墓碑路径不参与同步:否则副本上的残留会被当作"远端内容"逐文件
|
|
30831
|
+
* 拉回本地,把已删除的目录复活。数组与各同步对共享同一实例(zen-fs-sync
|
|
30832
|
+
* 每次检测时实时读取 `filter.excludePrefixes`),原地更新即可生效。
|
|
30833
|
+
*/
|
|
30834
|
+
__publicField(this, "tombstoneExcludePrefixes", [...CONFIG_ONLY_PREFIXES]);
|
|
30835
|
+
__publicField(this, "syncFilter", { excludePrefixes: this.tombstoneExcludePrefixes });
|
|
30377
30836
|
__publicField(this, "parent");
|
|
30378
30837
|
__publicField(this, "_backends");
|
|
30838
|
+
/**
|
|
30839
|
+
* 组实例身份(UUID)。同步边界:远端 `.meta/group.json` 的 `instanceId`
|
|
30840
|
+
* 不一致就不建同步对,因此不同同步组之间永不互相搬运数据。
|
|
30841
|
+
*/
|
|
30842
|
+
__publicField(this, "instanceId");
|
|
30843
|
+
/** 因归属他人而被跳过的后端 id → 原因。 */
|
|
30844
|
+
__publicField(this, "skippedBackends", /* @__PURE__ */ new Map());
|
|
30379
30845
|
__publicField(this, "_pollIntervalMs");
|
|
30380
30846
|
__publicField(this, "_backendsAreAuthoritative");
|
|
30381
30847
|
/** 引导副本(`.config/` 里的描述符)原有的能力位,用于回刷时不丢信息。 */
|
|
@@ -30383,6 +30849,7 @@ var ZenFSConfig = (() => {
|
|
|
30383
30849
|
this.groupId = groupId;
|
|
30384
30850
|
this.appId = appId;
|
|
30385
30851
|
this.name = descriptor.name;
|
|
30852
|
+
this.instanceId = isValidGroupInstanceId(descriptor.instanceId) ? descriptor.instanceId : void 0;
|
|
30386
30853
|
this.features = {
|
|
30387
30854
|
...DATA_GROUP_DEFAULT_FEATURES,
|
|
30388
30855
|
...descriptor.features,
|
|
@@ -30490,14 +30957,64 @@ var ZenFSConfig = (() => {
|
|
|
30490
30957
|
}
|
|
30491
30958
|
/** Write this group's own `.meta/group.json` (idempotent: identical bytes → no write). */
|
|
30492
30959
|
async writeOwnGroupDescriptor() {
|
|
30960
|
+
if (!this.instanceId) {
|
|
30961
|
+
this.instanceId = newGroupInstanceId();
|
|
30962
|
+
log9.log(`[AppDataGroup:${this.groupId}] assigned instanceId ${this.instanceId}`);
|
|
30963
|
+
}
|
|
30493
30964
|
await writeGroupDescriptor(this.localFS, {
|
|
30494
30965
|
schemaVersion: 2,
|
|
30495
30966
|
kind: "data",
|
|
30496
30967
|
id: this.groupId,
|
|
30968
|
+
instanceId: this.instanceId,
|
|
30497
30969
|
...this.name ? { name: this.name } : {},
|
|
30498
30970
|
features: this.features
|
|
30499
30971
|
});
|
|
30500
30972
|
}
|
|
30973
|
+
/** 本组实例身份(初始化后可用)。 */
|
|
30974
|
+
getGroupInstanceId() {
|
|
30975
|
+
return this.instanceId;
|
|
30976
|
+
}
|
|
30977
|
+
/** 因归属他人而被跳过的后端(id → 原因)。 */
|
|
30978
|
+
listSkippedBackends() {
|
|
30979
|
+
return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
|
|
30980
|
+
}
|
|
30981
|
+
/**
|
|
30982
|
+
* 连接数据后端前的归属校验。
|
|
30983
|
+
*
|
|
30984
|
+
* - `match`:远端 `.meta/group.json` 的 `instanceId` 与本组一致 → 建同步对;
|
|
30985
|
+
* - `claimed`:远端是老仓库(无身份)→ 本组认领并写入,再建同步对;
|
|
30986
|
+
* - `conflict`:远端属于另一个同步组(或类型不符 / 读不到)→ 跳过,
|
|
30987
|
+
* **绝不建立同步对**,因此跨组数据不会被搬运。
|
|
30988
|
+
*/
|
|
30989
|
+
async checkBackendOwnership(instance, backendId) {
|
|
30990
|
+
if (!this.instanceId) {
|
|
30991
|
+
this.skippedBackends.set(backendId, "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF");
|
|
30992
|
+
return "conflict";
|
|
30993
|
+
}
|
|
30994
|
+
try {
|
|
30995
|
+
const state = await bindRemoteGroupIdentity(instance, {
|
|
30996
|
+
kind: "data",
|
|
30997
|
+
id: this.groupId,
|
|
30998
|
+
instanceId: this.instanceId,
|
|
30999
|
+
...this.name ? { name: this.name } : {},
|
|
31000
|
+
features: this.features
|
|
31001
|
+
});
|
|
31002
|
+
if (state === "conflict") {
|
|
31003
|
+
this.skippedBackends.set(
|
|
31004
|
+
backendId,
|
|
31005
|
+
"\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF"
|
|
31006
|
+
);
|
|
31007
|
+
log9.warn(
|
|
31008
|
+
`[AppDataGroup:${this.groupId}] backend "${backendId}" belongs to another sync group \u2014 sync pair skipped`
|
|
31009
|
+
);
|
|
31010
|
+
}
|
|
31011
|
+
return state;
|
|
31012
|
+
} catch (err2) {
|
|
31013
|
+
log9.warn(`[AppDataGroup:${this.groupId}] ownership check failed for "${backendId}":`, err2);
|
|
31014
|
+
this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err2?.message ?? String(err2)}`);
|
|
31015
|
+
return "conflict";
|
|
31016
|
+
}
|
|
31017
|
+
}
|
|
30501
31018
|
async init() {
|
|
30502
31019
|
const storeName = dataGroupLocalStoreName(this.appId, this.groupId);
|
|
30503
31020
|
try {
|
|
@@ -30525,40 +31042,56 @@ var ZenFSConfig = (() => {
|
|
|
30525
31042
|
try {
|
|
30526
31043
|
const purged = await purgeMtimeSidecars(this.localFS);
|
|
30527
31044
|
if (purged.removed.length > 0) {
|
|
30528
|
-
|
|
31045
|
+
log9.warn(
|
|
30529
31046
|
`[AppDataGroup:${this.groupId}] purged ${purged.removed.length} leaked .mtime sidecar(s):`,
|
|
30530
31047
|
purged.removed
|
|
30531
31048
|
);
|
|
30532
31049
|
}
|
|
30533
31050
|
} catch (err2) {
|
|
30534
|
-
|
|
31051
|
+
log9.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err2?.message ?? err2);
|
|
30535
31052
|
}
|
|
30536
31053
|
try {
|
|
30537
31054
|
const purgedKeep = await purgeKeepFiles(this.localFS);
|
|
30538
31055
|
if (purgedKeep.removed.length > 0) {
|
|
30539
|
-
|
|
31056
|
+
log9.warn(
|
|
30540
31057
|
`[AppDataGroup:${this.groupId}] purged ${purgedKeep.removed.length} leaked .keep placeholder(s):`,
|
|
30541
31058
|
purgedKeep.removed
|
|
30542
31059
|
);
|
|
30543
31060
|
}
|
|
30544
31061
|
} catch (err2) {
|
|
30545
|
-
|
|
31062
|
+
log9.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err2?.message ?? err2);
|
|
30546
31063
|
}
|
|
30547
31064
|
const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
|
|
30548
31065
|
this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
|
|
30549
31066
|
this.versions = new VersionStore(this.localFS, `${this.appId}/${this.groupId}`);
|
|
30550
31067
|
this.conflicts = new ConflictStore(this.localFS, this.appId, `${this.groupId}`, this.versions);
|
|
31068
|
+
try {
|
|
31069
|
+
this.refreshSyncExclusions(await this.tombstones.list());
|
|
31070
|
+
} catch (err2) {
|
|
31071
|
+
log9.warn(`[AppDataGroup:${this.groupId}] failed to load tombstones for exclusions:`, err2);
|
|
31072
|
+
}
|
|
30551
31073
|
let backendsChanged = false;
|
|
30552
31074
|
try {
|
|
30553
31075
|
backendsChanged = await this.loadBackendDescriptors();
|
|
30554
31076
|
} catch (err2) {
|
|
30555
|
-
|
|
31077
|
+
log9.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err2);
|
|
30556
31078
|
this._backends = this._backends ?? [];
|
|
30557
31079
|
}
|
|
31080
|
+
if (!this.instanceId) {
|
|
31081
|
+
try {
|
|
31082
|
+
const existing = await readGroupDescriptor(this.localFS);
|
|
31083
|
+
this.instanceId = pickInstanceId(existing);
|
|
31084
|
+
if (this.instanceId) {
|
|
31085
|
+
log9.log(`[AppDataGroup:${this.groupId}] adopted instanceId ${this.instanceId} from local group.json`);
|
|
31086
|
+
}
|
|
31087
|
+
} catch (err2) {
|
|
31088
|
+
log9.warn(`[AppDataGroup:${this.groupId}] failed to read local group.json:`, err2);
|
|
31089
|
+
}
|
|
31090
|
+
}
|
|
30558
31091
|
try {
|
|
30559
31092
|
await this.writeOwnGroupDescriptor();
|
|
30560
31093
|
} catch (err2) {
|
|
30561
|
-
|
|
31094
|
+
log9.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err2);
|
|
30562
31095
|
}
|
|
30563
31096
|
this.fs = createChrootFS(this.localFS, "/", {
|
|
30564
31097
|
hiddenPrefixes: [META_DIR, CONFIG_DIR],
|
|
@@ -30568,7 +31101,7 @@ var ZenFSConfig = (() => {
|
|
|
30568
31101
|
});
|
|
30569
31102
|
const { kept, removed } = dedupeAppDataBackends(this._backends);
|
|
30570
31103
|
if (removed.length > 0) {
|
|
30571
|
-
|
|
31104
|
+
log9.warn(
|
|
30572
31105
|
`[AppDataGroup:${this.groupId}] dedupe: removing ${removed.length} duplicate backend(s) (${removed.map((b) => b.id).join(", ")}) \u2014 keeping ${kept.map((b) => b.id).join(", ")}`
|
|
30573
31106
|
);
|
|
30574
31107
|
this._backends = kept;
|
|
@@ -30582,12 +31115,20 @@ var ZenFSConfig = (() => {
|
|
|
30582
31115
|
features: this._declaredFeatures
|
|
30583
31116
|
});
|
|
30584
31117
|
} catch (err2) {
|
|
30585
|
-
|
|
31118
|
+
log9.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err2);
|
|
30586
31119
|
}
|
|
30587
31120
|
}
|
|
30588
31121
|
for (const desc of this._backends) {
|
|
30589
31122
|
try {
|
|
30590
31123
|
const instance = await createBackend({ type: desc.type, options: desc.options });
|
|
31124
|
+
const owned = await this.checkBackendOwnership(instance, desc.id);
|
|
31125
|
+
if (owned === "conflict") {
|
|
31126
|
+
try {
|
|
31127
|
+
await instance.dispose?.();
|
|
31128
|
+
} catch {
|
|
31129
|
+
}
|
|
31130
|
+
continue;
|
|
31131
|
+
}
|
|
30591
31132
|
const syncable = backendToSyncableFS(instance, `${desc.type}(${desc.id})`);
|
|
30592
31133
|
const pair = this.syncEngine.addPair(
|
|
30593
31134
|
localSyncable,
|
|
@@ -30598,7 +31139,8 @@ var ZenFSConfig = (() => {
|
|
|
30598
31139
|
pollIntervalMs: this._pollIntervalMs,
|
|
30599
31140
|
// `.meta/` is intentionally NOT excluded: tombstones, versions and
|
|
30600
31141
|
// conflicts must sync, otherwise deletions resurrect on other devices.
|
|
30601
|
-
|
|
31142
|
+
// 但要排除"当前墓碑指向的路径"(与配置组同一张表,实时生效)。
|
|
31143
|
+
filter: this.syncFilter,
|
|
30602
31144
|
preSyncHook: async () => {
|
|
30603
31145
|
await this.runTombstonePass("preSync");
|
|
30604
31146
|
},
|
|
@@ -30614,26 +31156,26 @@ var ZenFSConfig = (() => {
|
|
|
30614
31156
|
if (this.features.conflicts) {
|
|
30615
31157
|
const conflictHandler = (event) => {
|
|
30616
31158
|
this.archiveConflict(event).catch((err2) => {
|
|
30617
|
-
|
|
31159
|
+
log9.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err2);
|
|
30618
31160
|
});
|
|
30619
31161
|
};
|
|
30620
31162
|
this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
|
|
30621
31163
|
}
|
|
30622
31164
|
this.trackSyncErrors(desc.id, pair.pairId);
|
|
30623
|
-
|
|
31165
|
+
log9.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
|
|
30624
31166
|
} catch (err2) {
|
|
30625
31167
|
const message = err2 instanceof Error ? err2.message : String(err2);
|
|
30626
31168
|
this.backendStates.set(desc.id, {
|
|
30627
31169
|
backendId: desc.id,
|
|
30628
31170
|
error: { message, timestamp: Date.now() }
|
|
30629
31171
|
});
|
|
30630
|
-
|
|
31172
|
+
log9.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err2);
|
|
30631
31173
|
}
|
|
30632
31174
|
}
|
|
30633
31175
|
try {
|
|
30634
31176
|
await this.syncEngine.syncAll();
|
|
30635
31177
|
} catch (err2) {
|
|
30636
|
-
|
|
31178
|
+
log9.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err2);
|
|
30637
31179
|
}
|
|
30638
31180
|
this.syncEngine.watchAll();
|
|
30639
31181
|
}
|
|
@@ -30648,7 +31190,7 @@ var ZenFSConfig = (() => {
|
|
|
30648
31190
|
try {
|
|
30649
31191
|
await this.tombstones.gc(this.allBackendIds(), this.tombstoneTargets());
|
|
30650
31192
|
} catch (err2) {
|
|
30651
|
-
|
|
31193
|
+
log9.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err2);
|
|
30652
31194
|
}
|
|
30653
31195
|
return Array.from(results.values());
|
|
30654
31196
|
}
|
|
@@ -30683,31 +31225,47 @@ var ZenFSConfig = (() => {
|
|
|
30683
31225
|
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : toUint8Array2(data);
|
|
30684
31226
|
await this.versions.record(path, bytes);
|
|
30685
31227
|
} catch (err2) {
|
|
30686
|
-
|
|
31228
|
+
log9.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err2);
|
|
30687
31229
|
}
|
|
30688
31230
|
}
|
|
30689
31231
|
/** Delete tombstoned files on local + every connected backend before/after sync. */
|
|
30690
31232
|
async runTombstonePass(stage) {
|
|
30691
31233
|
try {
|
|
30692
31234
|
await this.tombstones.process(this.tombstoneTargets());
|
|
31235
|
+
this.refreshSyncExclusions(await this.tombstones.list());
|
|
30693
31236
|
} catch (err2) {
|
|
30694
|
-
|
|
31237
|
+
log9.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err2);
|
|
31238
|
+
}
|
|
31239
|
+
}
|
|
31240
|
+
/**
|
|
31241
|
+
* 把当前墓碑路径写进同步排除表(原地更新共享数组)。
|
|
31242
|
+
*
|
|
31243
|
+
* 目录墓碑的 `${path}/` 前缀是故意的:整棵树已删除,保留期内任何子路径都不
|
|
31244
|
+
* 参与同步。注意**不能**为 `.keep` 占位排除父目录,否则真实数据会被一起挡掉。
|
|
31245
|
+
*/
|
|
31246
|
+
refreshSyncExclusions(tombstones) {
|
|
31247
|
+
this.tombstoneExcludePrefixes.length = 0;
|
|
31248
|
+
this.tombstoneExcludePrefixes.push(...CONFIG_ONLY_PREFIXES);
|
|
31249
|
+
for (const tombstone of tombstones) {
|
|
31250
|
+
if (!tombstone.path) continue;
|
|
31251
|
+
this.tombstoneExcludePrefixes.push(tombstone.path, `${tombstone.path}/`);
|
|
30695
31252
|
}
|
|
30696
31253
|
}
|
|
30697
31254
|
async confirmTombstones() {
|
|
30698
31255
|
try {
|
|
30699
|
-
await this.tombstones.confirm(this.
|
|
31256
|
+
await this.tombstones.confirm(this.tombstoneTargets());
|
|
30700
31257
|
} catch (err2) {
|
|
30701
|
-
|
|
31258
|
+
log9.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err2);
|
|
30702
31259
|
}
|
|
30703
31260
|
}
|
|
30704
|
-
/** Write a tombstone for `
|
|
30705
|
-
async writeTombstoneFor(
|
|
31261
|
+
/** Write a tombstone for `path`. Records metadata only — it never creates the path. */
|
|
31262
|
+
async writeTombstoneFor(path, type) {
|
|
30706
31263
|
await this.tombstones.write({
|
|
30707
|
-
path:
|
|
31264
|
+
path: normalizeTombstonePath(path),
|
|
30708
31265
|
deletedAt: Date.now(),
|
|
30709
31266
|
deletedBy: this.localBackendId,
|
|
30710
|
-
confirmedBy: [this.localBackendId]
|
|
31267
|
+
confirmedBy: [this.localBackendId],
|
|
31268
|
+
...type ? { type } : {}
|
|
30711
31269
|
});
|
|
30712
31270
|
}
|
|
30713
31271
|
/**
|
|
@@ -30722,16 +31280,10 @@ var ZenFSConfig = (() => {
|
|
|
30722
31280
|
throw new Error(`Cannot delete metadata path "${normalized}"`);
|
|
30723
31281
|
}
|
|
30724
31282
|
if (await isDirectoryPath(this.localFS, normalized)) {
|
|
30725
|
-
|
|
30726
|
-
|
|
30727
|
-
for (const dir of await collectDirectoriesUnder(this.localFS, normalized)) {
|
|
30728
|
-
const keepPath = dir === "/" ? "/.keep" : `${dir}/.keep`;
|
|
30729
|
-
await this.writeTombstoneFor(keepPath);
|
|
30730
|
-
await this.writeTombstoneFor(`${keepPath}.mtime`);
|
|
30731
|
-
}
|
|
30732
|
-
await removeDirectoryTree(this.localFS, normalized);
|
|
31283
|
+
await this.writeTombstoneFor(normalized, "directory");
|
|
31284
|
+
await purgeTombstonedTree(this.localFS, normalized);
|
|
30733
31285
|
this.schedulePostDeleteSync();
|
|
30734
|
-
|
|
31286
|
+
log9.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (single directory tombstone)`);
|
|
30735
31287
|
return;
|
|
30736
31288
|
}
|
|
30737
31289
|
await this.writeTombstoneFor(normalized);
|
|
@@ -30770,7 +31322,7 @@ var ZenFSConfig = (() => {
|
|
|
30770
31322
|
try {
|
|
30771
31323
|
await this.syncEngine.syncAll();
|
|
30772
31324
|
} catch (err2) {
|
|
30773
|
-
|
|
31325
|
+
log9.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err2);
|
|
30774
31326
|
}
|
|
30775
31327
|
}
|
|
30776
31328
|
readConflictBackup(conflictId, fileType) {
|
|
@@ -30805,7 +31357,7 @@ var ZenFSConfig = (() => {
|
|
|
30805
31357
|
if (this.dataBackends.has(id)) {
|
|
30806
31358
|
throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
|
|
30807
31359
|
}
|
|
30808
|
-
|
|
31360
|
+
log9.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
|
|
30809
31361
|
const instance = await createBackend({ type, options });
|
|
30810
31362
|
const syncable = backendToSyncableFS(instance, `${type}(${id})`);
|
|
30811
31363
|
const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
|
|
@@ -30816,7 +31368,7 @@ var ZenFSConfig = (() => {
|
|
|
30816
31368
|
direction: SyncDirection.BiDirectional,
|
|
30817
31369
|
conflictStrategy: "source-wins",
|
|
30818
31370
|
pollIntervalMs: this._pollIntervalMs,
|
|
30819
|
-
filter:
|
|
31371
|
+
filter: this.syncFilter,
|
|
30820
31372
|
preSyncHook: async () => {
|
|
30821
31373
|
await this.runTombstonePass("preSync");
|
|
30822
31374
|
},
|
|
@@ -30833,13 +31385,13 @@ var ZenFSConfig = (() => {
|
|
|
30833
31385
|
if (this.features.conflicts) {
|
|
30834
31386
|
this.syncEngine.on(pair.pairId, "conflict", (event) => {
|
|
30835
31387
|
this.archiveConflict(event).catch((err2) => {
|
|
30836
|
-
|
|
31388
|
+
log9.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err2);
|
|
30837
31389
|
});
|
|
30838
31390
|
});
|
|
30839
31391
|
}
|
|
30840
31392
|
this.trackSyncErrors(id, pair.pairId);
|
|
30841
31393
|
this._backends = [...this._backends.filter((b) => b.id !== id), desc];
|
|
30842
|
-
|
|
31394
|
+
log9.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
|
|
30843
31395
|
try {
|
|
30844
31396
|
const stale = (await this.tombstones.list()).find(
|
|
30845
31397
|
(t) => t.path === backendMetaFilePath(id)
|
|
@@ -30847,12 +31399,12 @@ var ZenFSConfig = (() => {
|
|
|
30847
31399
|
if (stale) await this.tombstones.remove(stale);
|
|
30848
31400
|
await writeBackendMetaDescriptor(this.localFS, desc);
|
|
30849
31401
|
} catch (err2) {
|
|
30850
|
-
|
|
31402
|
+
log9.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err2);
|
|
30851
31403
|
}
|
|
30852
31404
|
try {
|
|
30853
31405
|
await this.syncEngine.sync(pair.pairId);
|
|
30854
31406
|
} catch (err2) {
|
|
30855
|
-
|
|
31407
|
+
log9.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err2);
|
|
30856
31408
|
}
|
|
30857
31409
|
this.syncEngine.watch(pair.pairId);
|
|
30858
31410
|
await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends, {
|
|
@@ -30883,7 +31435,7 @@ var ZenFSConfig = (() => {
|
|
|
30883
31435
|
if (backend?.instance?.dispose) {
|
|
30884
31436
|
await backend.instance.dispose();
|
|
30885
31437
|
}
|
|
30886
|
-
|
|
31438
|
+
log9.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
|
|
30887
31439
|
}
|
|
30888
31440
|
listBackends() {
|
|
30889
31441
|
return Array.from(this.dataBackends.values()).map((b) => b.desc);
|
|
@@ -30925,44 +31477,44 @@ var ZenFSConfig = (() => {
|
|
|
30925
31477
|
idbStoreName: options.idbStoreName,
|
|
30926
31478
|
folderPath: options.folderPath
|
|
30927
31479
|
});
|
|
30928
|
-
|
|
31480
|
+
log9.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
|
|
30929
31481
|
const primaryInstance = await createBackend(localPrimary);
|
|
30930
31482
|
const cachedFS = primaryInstance;
|
|
30931
31483
|
if (options.purgeMtimeSidecars !== false) {
|
|
30932
31484
|
try {
|
|
30933
31485
|
const purged = await purgeMtimeSidecars(cachedFS);
|
|
30934
31486
|
if (purged.removed.length > 0) {
|
|
30935
|
-
|
|
31487
|
+
log9.warn(
|
|
30936
31488
|
`[createConfigRepo] purged ${purged.removed.length} leaked .mtime sidecar(s) from local primary:`,
|
|
30937
31489
|
purged.removed
|
|
30938
31490
|
);
|
|
30939
31491
|
}
|
|
30940
31492
|
} catch (err2) {
|
|
30941
|
-
|
|
31493
|
+
log9.warn(`[createConfigRepo] .mtime purge failed:`, err2?.message ?? err2);
|
|
30942
31494
|
}
|
|
30943
31495
|
}
|
|
30944
31496
|
if (options.purgeKeepFiles !== false) {
|
|
30945
31497
|
try {
|
|
30946
31498
|
const purged = await purgeKeepFiles(cachedFS);
|
|
30947
31499
|
if (purged.removed.length > 0) {
|
|
30948
|
-
|
|
31500
|
+
log9.warn(
|
|
30949
31501
|
`[createConfigRepo] purged ${purged.removed.length} leaked .keep placeholder(s) from local primary:`,
|
|
30950
31502
|
purged.removed
|
|
30951
31503
|
);
|
|
30952
31504
|
}
|
|
30953
31505
|
} catch (err2) {
|
|
30954
|
-
|
|
31506
|
+
log9.warn(`[createConfigRepo] .keep purge failed:`, err2?.message ?? err2);
|
|
30955
31507
|
}
|
|
30956
31508
|
}
|
|
30957
31509
|
const cacheOptions = options.cache === false ? void 0 : options.cache ?? {};
|
|
30958
31510
|
try {
|
|
30959
31511
|
await primaryInstance.mkdir(META_DIR);
|
|
30960
|
-
|
|
31512
|
+
log9.log(`[createConfigRepo] /.meta/ ready`);
|
|
30961
31513
|
} catch (err2) {
|
|
30962
31514
|
const msg = err2.message || "";
|
|
30963
31515
|
if (msg.includes("File exists") || msg.includes("EEXIST") || err2.code === "EEXIST") {
|
|
30964
31516
|
} else {
|
|
30965
|
-
|
|
31517
|
+
log9.error(`[createConfigRepo] Failed to ensure /.meta/:`, err2.message);
|
|
30966
31518
|
}
|
|
30967
31519
|
}
|
|
30968
31520
|
try {
|
|
@@ -30973,7 +31525,7 @@ var ZenFSConfig = (() => {
|
|
|
30973
31525
|
} catch {
|
|
30974
31526
|
await ensureParentDir2(primaryInstance, path);
|
|
30975
31527
|
await primaryInstance.writeFile(path, groupTypeBytes);
|
|
30976
|
-
|
|
31528
|
+
log9.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
|
|
30977
31529
|
}
|
|
30978
31530
|
}
|
|
30979
31531
|
if (!await readGroupDescriptor(primaryInstance)) {
|
|
@@ -30981,11 +31533,12 @@ var ZenFSConfig = (() => {
|
|
|
30981
31533
|
schemaVersion: 2,
|
|
30982
31534
|
kind: "config",
|
|
30983
31535
|
id: CONFIG_GROUP_ID,
|
|
31536
|
+
instanceId: newGroupInstanceId(),
|
|
30984
31537
|
features: CONFIG_GROUP_FEATURES
|
|
30985
31538
|
});
|
|
30986
31539
|
}
|
|
30987
31540
|
} catch (err2) {
|
|
30988
|
-
|
|
31541
|
+
log9.warn(`[createConfigRepo] Failed to write group metadata:`, err2.message);
|
|
30989
31542
|
}
|
|
30990
31543
|
const tempRepo = new ConfigRepo(
|
|
30991
31544
|
appId,
|
|
@@ -30999,11 +31552,11 @@ var ZenFSConfig = (() => {
|
|
|
30999
31552
|
);
|
|
31000
31553
|
const oldBackendsMeta = await tempRepo.readMetaFile(BACKENDS_FILE);
|
|
31001
31554
|
if (oldBackendsMeta && oldBackendsMeta.backends?.length > 0) {
|
|
31002
|
-
|
|
31555
|
+
log9.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
|
|
31003
31556
|
await tempRepo.ensureDir(`${BACKENDS_DIR}/.keep`);
|
|
31004
31557
|
for (const desc of oldBackendsMeta.backends) {
|
|
31005
31558
|
if (desc.id === LOCAL_IDB_BACKEND_ID) {
|
|
31006
|
-
|
|
31559
|
+
log9.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
|
|
31007
31560
|
continue;
|
|
31008
31561
|
}
|
|
31009
31562
|
await tempRepo.writeBackendDescriptor(desc);
|
|
@@ -31021,7 +31574,7 @@ var ZenFSConfig = (() => {
|
|
|
31021
31574
|
}
|
|
31022
31575
|
}
|
|
31023
31576
|
}
|
|
31024
|
-
|
|
31577
|
+
log9.log(`[createConfigRepo] Migration complete`);
|
|
31025
31578
|
}
|
|
31026
31579
|
let allBackends = await tempRepo.readAllBackendDescriptors();
|
|
31027
31580
|
if (options.backendInfo) {
|
|
@@ -31039,19 +31592,19 @@ var ZenFSConfig = (() => {
|
|
|
31039
31592
|
type: options.backendInfo.type,
|
|
31040
31593
|
options: options.backendInfo.options
|
|
31041
31594
|
});
|
|
31042
|
-
|
|
31595
|
+
log9.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
|
|
31043
31596
|
allBackends = [...allBackends, { id: replicaId, type: options.backendInfo.type, options: options.backendInfo.options }];
|
|
31044
31597
|
} else if (dupConfig) {
|
|
31045
|
-
|
|
31598
|
+
log9.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
|
|
31046
31599
|
} else {
|
|
31047
|
-
|
|
31600
|
+
log9.log(`[createConfigRepo] Replica ${replicaId} already registered`);
|
|
31048
31601
|
}
|
|
31049
31602
|
}
|
|
31050
|
-
|
|
31603
|
+
log9.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
|
|
31051
31604
|
let nodeId = options.nodeId;
|
|
31052
31605
|
if (!nodeId) {
|
|
31053
31606
|
nodeId = `node-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
31054
|
-
|
|
31607
|
+
log9.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
|
|
31055
31608
|
}
|
|
31056
31609
|
const serializer = createSerializerChain(options.serializer);
|
|
31057
31610
|
const repo = new ConfigRepo(
|
|
@@ -31074,19 +31627,19 @@ var ZenFSConfig = (() => {
|
|
|
31074
31627
|
try {
|
|
31075
31628
|
const mig = await repo.migrateLegacyVersionSidecars();
|
|
31076
31629
|
if (mig.renamed.length === 0 && mig.deleted.length === 0 && mig.remoteDeleted.length === 0) {
|
|
31077
|
-
|
|
31630
|
+
log9.log("[createConfigRepo] no legacy version sidecars to migrate");
|
|
31078
31631
|
}
|
|
31079
31632
|
} catch (err2) {
|
|
31080
|
-
|
|
31633
|
+
log9.warn(`[createConfigRepo] version sidecar migration failed:`, err2?.message ?? err2);
|
|
31081
31634
|
}
|
|
31082
31635
|
}
|
|
31083
31636
|
await repo.load();
|
|
31084
31637
|
if (repo.replicaCount > 0) {
|
|
31085
|
-
|
|
31638
|
+
log9.log("[createConfigRepo] Starting background initial sync + dedup...");
|
|
31086
31639
|
repo.startBackgroundSync();
|
|
31087
31640
|
}
|
|
31088
31641
|
repo.syncMetaToReplicas().catch((err2) => {
|
|
31089
|
-
|
|
31642
|
+
log9.error("[createConfigRepo] background syncMetaToReplicas failed:", err2);
|
|
31090
31643
|
});
|
|
31091
31644
|
return repo;
|
|
31092
31645
|
}
|
|
@@ -31100,11 +31653,11 @@ var ZenFSConfig = (() => {
|
|
|
31100
31653
|
|
|
31101
31654
|
// src/connect.ts
|
|
31102
31655
|
init_backend_registry();
|
|
31103
|
-
var
|
|
31656
|
+
var log10 = createLogger3("connect");
|
|
31104
31657
|
var GROUP_TYPE_FILE2 = "/.config/group-type";
|
|
31105
31658
|
var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
|
|
31106
31659
|
async function detectGroupType(type, options) {
|
|
31107
|
-
|
|
31660
|
+
log10(`detectGroupType: connecting to ${type}...`);
|
|
31108
31661
|
const tempBackend = await createBackend({ type, options });
|
|
31109
31662
|
try {
|
|
31110
31663
|
for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
|
|
@@ -31112,15 +31665,15 @@ var ZenFSConfig = (() => {
|
|
|
31112
31665
|
const raw = await tempBackend.readFile(path, "utf-8");
|
|
31113
31666
|
const groupType = raw.trim();
|
|
31114
31667
|
if (groupType === "config-sync" || groupType === "data-sync") {
|
|
31115
|
-
|
|
31668
|
+
log10(`detectGroupType: detected "${groupType}" at ${path}`);
|
|
31116
31669
|
return groupType;
|
|
31117
31670
|
}
|
|
31118
|
-
|
|
31671
|
+
log10(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
|
|
31119
31672
|
return null;
|
|
31120
31673
|
} catch {
|
|
31121
31674
|
}
|
|
31122
31675
|
}
|
|
31123
|
-
|
|
31676
|
+
log10(`detectGroupType: no group-type file found (new backend)`);
|
|
31124
31677
|
return null;
|
|
31125
31678
|
} finally {
|
|
31126
31679
|
if (tempBackend?.dispose) {
|
|
@@ -31129,7 +31682,7 @@ var ZenFSConfig = (() => {
|
|
|
31129
31682
|
}
|
|
31130
31683
|
}
|
|
31131
31684
|
async function connect(appId, options = {}) {
|
|
31132
|
-
|
|
31685
|
+
log10(`connect: appId=${appId}`);
|
|
31133
31686
|
if (!options.backendInfo) {
|
|
31134
31687
|
const repo2 = await createConfigRepo(appId, {
|
|
31135
31688
|
idbStoreName: options.idbStoreName,
|
|
@@ -31147,12 +31700,12 @@ var ZenFSConfig = (() => {
|
|
|
31147
31700
|
try {
|
|
31148
31701
|
appDataGroups2.push(await repo2.getAppDataGroup(d.id));
|
|
31149
31702
|
} catch (err2) {
|
|
31150
|
-
|
|
31703
|
+
log10(`connect: failed to load app data group "${d.id}":`, err2);
|
|
31151
31704
|
}
|
|
31152
31705
|
}
|
|
31153
31706
|
const dataGroup2 = appDataGroups2[0];
|
|
31154
31707
|
if (!dataGroup2 && descriptors2.length > 0) {
|
|
31155
|
-
|
|
31708
|
+
log10(
|
|
31156
31709
|
`connect: ${descriptors2.length} data group descriptor(s) found but none could be loaded; leaving them untouched (no empty group is created)`
|
|
31157
31710
|
);
|
|
31158
31711
|
}
|
|
@@ -31177,7 +31730,7 @@ var ZenFSConfig = (() => {
|
|
|
31177
31730
|
groupType = detectedType;
|
|
31178
31731
|
} else {
|
|
31179
31732
|
groupType = options.groupType ?? "config-sync";
|
|
31180
|
-
|
|
31733
|
+
log10(`connect: new backend, using groupType="${groupType}"`);
|
|
31181
31734
|
}
|
|
31182
31735
|
const repo = await createConfigRepo(
|
|
31183
31736
|
appId,
|
|
@@ -31206,14 +31759,14 @@ var ZenFSConfig = (() => {
|
|
|
31206
31759
|
try {
|
|
31207
31760
|
appDataGroups.push(await repo.getAppDataGroup(d.id));
|
|
31208
31761
|
} catch (err2) {
|
|
31209
|
-
|
|
31762
|
+
log10(`connect: failed to load app data group "${d.id}":`, err2);
|
|
31210
31763
|
}
|
|
31211
31764
|
}
|
|
31212
31765
|
let dataGroup = appDataGroups[0];
|
|
31213
31766
|
if (groupType === "data-sync") {
|
|
31214
31767
|
if (!dataGroup) {
|
|
31215
31768
|
if (descriptors.length > 0) {
|
|
31216
|
-
|
|
31769
|
+
log10(
|
|
31217
31770
|
`connect: ${descriptors.length} data group descriptor(s) exist but could not be loaded; refusing to create/overwrite "default"`
|
|
31218
31771
|
);
|
|
31219
31772
|
} else {
|