@vrtmrz/livesync-commonlib 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/common/models/diff.definition.d.ts +4 -0
- package/dist/common/utils.d.ts +1 -1
- package/dist/common/utils.doc.d.ts +5 -0
- package/dist/common/utils.doc.js +8 -0
- package/dist/common/utils.js +1 -3
- package/dist/conflicts/filenameCaseConflict.d.ts +8 -0
- package/dist/conflicts/filenameCaseConflict.js +26 -0
- package/dist/conflicts.d.ts +1 -0
- package/dist/conflicts.js +9 -1
- package/dist/interfaces/DatabaseFileAccess.d.ts +12 -1
- package/dist/managers/ConflictManager.d.ts +6 -2
- package/dist/managers/ConflictManager.js +73 -22
- package/dist/managers/EntryManager/EntryManager.d.ts +5 -0
- package/dist/managers/EntryManager/EntryManager.js +5 -0
- package/dist/managers/EntryManager/EntryManagerImpls.d.ts +5 -1
- package/dist/managers/EntryManager/EntryManagerImpls.js +16 -2
- package/dist/managers/LiveSyncManagers.js +2 -1
- package/dist/pouchdb/LiveSyncLocalDB.js +3 -4
- package/dist/replication/index.d.ts +2 -0
- package/dist/replication/index.js +2 -0
- package/dist/replication/replicationResultQueueStore.d.ts +101 -0
- package/dist/replication/replicationResultQueueStore.js +140 -0
- package/dist/serviceFeatures/offlineScanner/files.js +15 -3
- package/dist/serviceFeatures/offlineScanner/scan.js +1 -4
- package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +5 -4
- package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +28 -7
- package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +3 -0
- package/dist/serviceModules/ServiceFileHandlerBase/protection.js +29 -6
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +2 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +29 -10
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +61 -11
- package/dist/serviceModules/ServiceFileHandlerBase/saving.js +32 -8
- package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +2 -8
- package/dist/serviceModules/ServiceFileHandlerBase/storage.js +4 -5
- package/docs/conflict-resolution.md +22 -8
- package/docs/offline-scanner.md +2 -0
- package/docs/storage-events-and-reflection.md +141 -0
- package/package.json +1 -1
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
isReflectionCancelled
|
|
7
7
|
} from "../../interfaces/FileHandler.js";
|
|
8
8
|
import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
|
|
9
|
-
import { infoToStub,
|
|
9
|
+
import { infoToStub, isFileAtExactPath, isFolderInfo } from "./storage.js";
|
|
10
10
|
import {
|
|
11
11
|
captureRenameProvenance,
|
|
12
12
|
commitRenamedProvenance,
|
|
@@ -18,13 +18,19 @@ import {
|
|
|
18
18
|
readProvenanceSnapshot,
|
|
19
19
|
setProvenance
|
|
20
20
|
} from "./provenance.js";
|
|
21
|
-
import { preserveUnsyncedStorageAsConflict, recheckIncomingStorage } from "./protection.js";
|
|
21
|
+
import { preserveUnsyncedStorageAsConflict, preserveUnobservedFilename, recheckIncomingStorage } from "./protection.js";
|
|
22
22
|
import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
|
|
23
|
-
import { createBlob, isDocContentSame, readContent } from "../../common/utils.js";
|
|
23
|
+
import { createBlob, isDeletedEntry, isDocContentSame, readContent } from "../../common/utils.js";
|
|
24
24
|
import { getStoragePathFromUXFileInfo } from "../../common/typeUtils.js";
|
|
25
25
|
import { EVEN } from "../../common/models/shared.const.symbols.js";
|
|
26
26
|
import { tryGetFilePath } from "../../common/utils.doc.js";
|
|
27
27
|
import { getPathNormalizationVersion, normalisePathForIdentity } from "../../common/pathNormalization.js";
|
|
28
|
+
import {
|
|
29
|
+
getParentPath,
|
|
30
|
+
hasFilenameCaseConflict,
|
|
31
|
+
hasSameParentFilenameCaseConflict,
|
|
32
|
+
haveMatchingRevisionPaths
|
|
33
|
+
} from "../../conflicts/filenameCaseConflict.js";
|
|
28
34
|
class IncompleteFileReflectionError extends Error {
|
|
29
35
|
}
|
|
30
36
|
async function dbToStorageWithSpecificRev(ctx, info, rev, force) {
|
|
@@ -70,7 +76,8 @@ async function dbToStorageWithSpecificRevCore(ctx, info, rev, force) {
|
|
|
70
76
|
);
|
|
71
77
|
return false;
|
|
72
78
|
}
|
|
73
|
-
|
|
79
|
+
const entry = await withStoredFilename(ctx, docEntry);
|
|
80
|
+
return !isReflectionCancelled(await applyDatabaseEntryToStorage(ctx, entry, file, force, true));
|
|
74
81
|
}
|
|
75
82
|
async function dbToStorage(ctx, entryInfo, info, force) {
|
|
76
83
|
const path = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
|
|
@@ -105,7 +112,23 @@ async function dbToStorageCore(ctx, entryInfo, info, force, operation) {
|
|
|
105
112
|
ctx.host.log(`File ${pathFromEntryInfo} is not exist on the database`, LOG_LEVEL_VERBOSE);
|
|
106
113
|
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
107
114
|
}
|
|
108
|
-
|
|
115
|
+
const entry = force ? docEntry : await withStoredFilename(ctx, docEntry);
|
|
116
|
+
return await applyDatabaseEntryToStorage(ctx, entry, file, force, false, 0, operation);
|
|
117
|
+
}
|
|
118
|
+
async function withStoredFilename(ctx, entry) {
|
|
119
|
+
const settings = ctx.setting.currentSettings();
|
|
120
|
+
if (settings.handleFilenameCaseSensitive || !entry._rev || isDeletedEntry(entry)) {
|
|
121
|
+
return entry;
|
|
122
|
+
}
|
|
123
|
+
const stored = await ctx.host.db().readRevisionPath?.(entry._id, entry._rev);
|
|
124
|
+
if (stored && hasSameParentFilenameCaseConflict(entry.path, stored, getPathNormalizationVersion(settings))) {
|
|
125
|
+
const target = await ctx.host.db().readEntryMeta(stored, entry._rev, true);
|
|
126
|
+
if (!target || target._id !== entry._id || target._rev !== entry._rev) {
|
|
127
|
+
throw new IncompleteFileReflectionError("Could not confirm the stored filename as a reflection target");
|
|
128
|
+
}
|
|
129
|
+
return target;
|
|
130
|
+
}
|
|
131
|
+
return entry;
|
|
109
132
|
}
|
|
110
133
|
async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0, operation) {
|
|
111
134
|
const mode = file == null ? "create" : "modify";
|
|
@@ -119,12 +142,19 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
|
|
|
119
142
|
return FILE_REFLECTION_POLICY;
|
|
120
143
|
}
|
|
121
144
|
}
|
|
145
|
+
const existOnDB = !isDeletedEntry(docEntry);
|
|
122
146
|
let existDoc = await ctx.host.storage().getStub(path);
|
|
147
|
+
if (existOnDB && !force && !settings.handleFilenameCaseSensitive && file && file.path !== existDoc?.path && hasSameParentFilenameCaseConflict(file.path, path, getPathNormalizationVersion(settings))) {
|
|
148
|
+
const observed = await ctx.host.storage().getStub(file.path);
|
|
149
|
+
if (existDoc && observed && existDoc.path !== observed.path) {
|
|
150
|
+
throw new IncompleteFileReflectionError("Both filename spellings exist in storage");
|
|
151
|
+
}
|
|
152
|
+
existDoc ??= observed;
|
|
153
|
+
}
|
|
123
154
|
if (isFolderInfo(existDoc)) {
|
|
124
155
|
ctx.host.log(`Folder ${path} is already exist on the storage as a folder`, LOG_LEVEL_VERBOSE);
|
|
125
156
|
return FILE_REFLECTION_POLICY;
|
|
126
157
|
}
|
|
127
|
-
const existOnDB = !(docEntry._deleted || docEntry.deleted || false);
|
|
128
158
|
if (!existOnDB && !existDoc) {
|
|
129
159
|
ctx.host.log(`File ${path} seems to be deleted, but already not on storage`, LOG_LEVEL_VERBOSE);
|
|
130
160
|
await deleteProvenance(ctx, path);
|
|
@@ -144,10 +174,13 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
|
|
|
144
174
|
);
|
|
145
175
|
}
|
|
146
176
|
if (existDoc && existDoc.path !== path) {
|
|
147
|
-
const current = await reconcileStoragePath(ctx, existDoc, path, settings);
|
|
177
|
+
const current = await reconcileStoragePath(ctx, existDoc, path, settings, docEntry, force);
|
|
148
178
|
if (current === false) {
|
|
149
179
|
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
150
180
|
}
|
|
181
|
+
if ("status" in current) {
|
|
182
|
+
return current;
|
|
183
|
+
}
|
|
151
184
|
existDoc = current;
|
|
152
185
|
}
|
|
153
186
|
const docRead = await ctx.host.db().readEntryFromMeta(docEntry);
|
|
@@ -203,7 +236,7 @@ async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force
|
|
|
203
236
|
}
|
|
204
237
|
return await applyDatabaseEntryToStorage(
|
|
205
238
|
ctx,
|
|
206
|
-
current,
|
|
239
|
+
await withStoredFilename(ctx, current),
|
|
207
240
|
storage,
|
|
208
241
|
force,
|
|
209
242
|
allowExistingConflicts,
|
|
@@ -282,7 +315,7 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
|
|
|
282
315
|
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
283
316
|
}
|
|
284
317
|
const resolvedForRead = await ctx.host.storage().getStub(path);
|
|
285
|
-
if (!
|
|
318
|
+
if (!isFileAtExactPath(resolvedForRead, observedPath)) {
|
|
286
319
|
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
287
320
|
}
|
|
288
321
|
const readResolved = await ctx.host.readFileFromStub(resolvedForRead);
|
|
@@ -291,7 +324,7 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
|
|
|
291
324
|
}
|
|
292
325
|
}
|
|
293
326
|
const resolvedTarget = await ctx.host.storage().getStub(path);
|
|
294
|
-
if (!
|
|
327
|
+
if (!isFileAtExactPath(resolvedTarget, observedPath) || safeDeletionSnapshot && (resolvedTarget.stat.mtime !== safeDeletionSnapshot.file.stat.mtime || resolvedTarget.stat.size !== safeDeletionSnapshot.file.stat.size)) {
|
|
295
328
|
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
296
329
|
}
|
|
297
330
|
}
|
|
@@ -308,7 +341,7 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
|
|
|
308
341
|
}
|
|
309
342
|
return FILE_REFLECTION_COMPLETED;
|
|
310
343
|
}
|
|
311
|
-
async function reconcileStoragePath(ctx, existDoc, path, settings) {
|
|
344
|
+
async function reconcileStoragePath(ctx, existDoc, path, settings, incoming, force) {
|
|
312
345
|
const [existingDocumentId, targetDocumentId] = await Promise.all([
|
|
313
346
|
ctx.path.path2id(existDoc.path),
|
|
314
347
|
ctx.path.path2id(path)
|
|
@@ -334,10 +367,27 @@ async function reconcileStoragePath(ctx, existDoc, path, settings) {
|
|
|
334
367
|
return false;
|
|
335
368
|
}
|
|
336
369
|
const oldPath = existDoc.path;
|
|
370
|
+
const shouldVerifyLocalSpellingBeforeRename = !force && !settings.writeDocumentsIfConflicted && !settings.handleFilenameCaseSensitive && hasFilenameCaseConflict(oldPath, path, pathNormalizationVersion);
|
|
371
|
+
let recorded;
|
|
372
|
+
if (shouldVerifyLocalSpellingBeforeRename) {
|
|
373
|
+
recorded = await readProvenanceSnapshot(ctx, oldPath, true);
|
|
374
|
+
const recordedName = recorded && await ctx.host.db().readRevisionPath?.(incoming._id, recorded.revision);
|
|
375
|
+
if (!haveMatchingRevisionPaths(oldPath, recordedName, pathNormalizationVersion)) {
|
|
376
|
+
const protection = await preserveUnobservedFilename(ctx, path, existDoc, recorded);
|
|
377
|
+
return protection.preserved ? FILE_REFLECTION_POLICY : false;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
337
380
|
const renameProvenance = await captureRenameProvenance(ctx, oldPath, path);
|
|
338
381
|
if (renameProvenance === false) {
|
|
339
382
|
return false;
|
|
340
383
|
}
|
|
384
|
+
if (recorded) {
|
|
385
|
+
const current = await ctx.host.storage().getStub(oldPath);
|
|
386
|
+
if (!isFileAtExactPath(current, oldPath) || !sameProvenance(renameProvenance?.sourceRecord, recorded)) {
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
existDoc = current;
|
|
390
|
+
}
|
|
341
391
|
const renamedFile = await ctx.host.storage().renameFile(existDoc, path);
|
|
342
392
|
if (!renamedFile) {
|
|
343
393
|
ctx.host.log(`Could not apply the stored filename case: ${oldPath} -> ${path}`, LOG_LEVEL_NOTICE);
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { isReflectionCancelled } from "../../interfaces/FileHandler.js";
|
|
2
2
|
import { ContentReadError } from "../../common/LSError.js";
|
|
3
3
|
import { isFolderInfo, infoToStub } from "./storage.js";
|
|
4
|
+
import { getPathNormalizationVersion } from "../../common/pathNormalization.js";
|
|
5
|
+
import { hasSameParentFilenameCaseConflict, haveMatchingRevisionPaths } from "../../conflicts/filenameCaseConflict.js";
|
|
4
6
|
import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
|
|
5
7
|
import {
|
|
6
8
|
setProvenance,
|
|
@@ -19,7 +21,7 @@ import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/log
|
|
|
19
21
|
import { displayRev, getDocDataAsArray, isDocContentSame, readContent } from "../../common/utils.js";
|
|
20
22
|
import { getStoragePathFromUXFileInfo } from "../../common/typeUtils.js";
|
|
21
23
|
import { EVEN } from "../../common/models/shared.const.symbols.js";
|
|
22
|
-
import { tryGetFilePath } from "../../common/utils.doc.js";
|
|
24
|
+
import { isDeletedEntry, tryGetFilePath } from "../../common/utils.doc.js";
|
|
23
25
|
async function retryCurrentStorage(ctx, path, preferredBasePath, snapshotRetry) {
|
|
24
26
|
if (snapshotRetry >= 2) {
|
|
25
27
|
ctx.host.log(`Storage kept changing while saving ${path}; a fresh event is required`, LOG_LEVEL_NOTICE);
|
|
@@ -73,7 +75,7 @@ async function storeFileToDBWithBaseRevisionCore(ctx, info, baseRevision, create
|
|
|
73
75
|
return false;
|
|
74
76
|
}
|
|
75
77
|
const readFile = await ctx.host.readFileFromStub(file);
|
|
76
|
-
if (!baseEntry
|
|
78
|
+
if (!isDeletedEntry(baseEntry)) {
|
|
77
79
|
const loadedBase = await ctx.host.db().fetchEntry(file, baseRevision, true, true);
|
|
78
80
|
if (loadedBase && await isDocContentSame(getDocDataAsArray(loadedBase.data), readFile.body)) {
|
|
79
81
|
await setProvenance(ctx, file.path, baseRevision, readFile.stat.mtime, readFile.body);
|
|
@@ -115,12 +117,12 @@ async function storeFileToDBFromRevision(ctx, info, force = false, onlyChunks =
|
|
|
115
117
|
}
|
|
116
118
|
const save = await observeStorageSave(ctx, file, preferredBasePath, retryIfStorageChanges);
|
|
117
119
|
const currentEntry = save.currentEntry;
|
|
118
|
-
const currentIsLive = currentEntry && !currentEntry
|
|
120
|
+
const currentIsLive = currentEntry && !isDeletedEntry(currentEntry);
|
|
119
121
|
if (!force && (currentIsLive || retryIfStorageChanges)) {
|
|
120
122
|
return await saveClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges, snapshotRetry);
|
|
121
123
|
}
|
|
122
124
|
if (save.isConflicted) return await saveConflictedStorage(ctx, save, force, preferredBasePath);
|
|
123
|
-
if (!currentEntry || currentEntry
|
|
125
|
+
if (!currentEntry || isDeletedEntry(currentEntry))
|
|
124
126
|
return await createStorageRevision(ctx, save, preferredBasePath);
|
|
125
127
|
return await saveCurrentStorage(ctx, save, currentEntry, force, onlyChunks, preferredBasePath);
|
|
126
128
|
}
|
|
@@ -139,7 +141,7 @@ async function observeStorageSave(ctx, file, preferredBasePath, retryIfStorageCh
|
|
|
139
141
|
}
|
|
140
142
|
async function saveClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges, snapshotRetry) {
|
|
141
143
|
const { entry, currentEntry } = save;
|
|
142
|
-
const currentIsLive = currentEntry && !currentEntry
|
|
144
|
+
const currentIsLive = currentEntry && !isDeletedEntry(currentEntry);
|
|
143
145
|
if (retryIfStorageChanges && currentIsLive && !entry) {
|
|
144
146
|
const revision = currentEntry._rev ? displayRev(currentEntry._rev) : "unknown";
|
|
145
147
|
ctx.host.log(
|
|
@@ -251,12 +253,13 @@ async function saveCurrentStorage(ctx, save, currentEntry, force, onlyChunks, pr
|
|
|
251
253
|
}
|
|
252
254
|
async function observeClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges) {
|
|
253
255
|
const { readFile, observedProvenance, entry, currentEntry } = save;
|
|
256
|
+
const recorded = preferredBasePath ? observedProvenance : await selectProvenanceForStorageFilename(ctx, save);
|
|
254
257
|
const classification = await classifyStorageContent(
|
|
255
258
|
ctx,
|
|
256
259
|
readFile,
|
|
257
260
|
currentEntry,
|
|
258
261
|
preferredBasePath,
|
|
259
|
-
|
|
262
|
+
recorded,
|
|
260
263
|
entry ? { _rev: entry._rev, data: readContent(entry) } : void 0,
|
|
261
264
|
retryIfStorageChanges
|
|
262
265
|
);
|
|
@@ -264,9 +267,30 @@ async function observeClassifiedStorage(ctx, save, preferredBasePath, retryIfSto
|
|
|
264
267
|
const evidence = upgradeCurrentRecord || classification.kind === "matching-leaf" && classification.revision ? await contentEvidence(ctx, readFile.body) : void 0;
|
|
265
268
|
return { classification, upgradeCurrentRecord, evidence };
|
|
266
269
|
}
|
|
270
|
+
function hasLiveRevision(entry) {
|
|
271
|
+
return !!entry && !!entry._rev && !isDeletedEntry(entry);
|
|
272
|
+
}
|
|
273
|
+
async function selectProvenanceForStorageFilename(ctx, save) {
|
|
274
|
+
const { readFile, observedProvenance, currentEntry } = save;
|
|
275
|
+
const settings = ctx.setting.currentSettings();
|
|
276
|
+
const db = ctx.host.db();
|
|
277
|
+
if (!observedProvenance || !hasLiveRevision(currentEntry)) {
|
|
278
|
+
return observedProvenance;
|
|
279
|
+
}
|
|
280
|
+
if (settings.handleFilenameCaseSensitive || !db.readRevisionPath) {
|
|
281
|
+
return observedProvenance;
|
|
282
|
+
}
|
|
283
|
+
const currentName = await db.readRevisionPath(currentEntry._id, currentEntry._rev);
|
|
284
|
+
const version = getPathNormalizationVersion(settings);
|
|
285
|
+
if (!currentName || !hasSameParentFilenameCaseConflict(readFile.path, currentName, version)) {
|
|
286
|
+
return observedProvenance;
|
|
287
|
+
}
|
|
288
|
+
const recordedName = observedProvenance.revision === currentEntry._rev ? currentName : await db.readRevisionPath(currentEntry._id, observedProvenance.revision);
|
|
289
|
+
return haveMatchingRevisionPaths(readFile.path, recordedName, version) ? observedProvenance : void 0;
|
|
290
|
+
}
|
|
267
291
|
function shouldUpgradeSavedRecord(save, classification) {
|
|
268
292
|
const { currentEntry, isConflicted, observedProvenance } = save;
|
|
269
|
-
return classification.kind === "unchanged" && !isConflicted && currentEntry && !currentEntry
|
|
293
|
+
return classification.kind === "unchanged" && !isConflicted && currentEntry && !isDeletedEntry(currentEntry) && classification.revision === currentEntry._rev && !hasContentHash(observedProvenance);
|
|
270
294
|
}
|
|
271
295
|
async function finishUnchangedStorageSave(ctx, save, revision, details, recovery) {
|
|
272
296
|
const { file, readFile, observedProvenance, currentEntry, isConflicted } = save;
|
|
@@ -277,7 +301,7 @@ async function finishUnchangedStorageSave(ctx, save, revision, details, recovery
|
|
|
277
301
|
return await retryCurrentStorage(ctx, file.path, preferredBasePath, snapshotRetry);
|
|
278
302
|
if (isConflicted) {
|
|
279
303
|
await queueConflictCheckFor(ctx, file.path);
|
|
280
|
-
} else if (!currentEntry || currentEntry
|
|
304
|
+
} else if (!currentEntry || isDeletedEntry(currentEntry) || revision !== currentEntry._rev) {
|
|
281
305
|
if (!currentEntry) return false;
|
|
282
306
|
return !isReflectionCancelled(await dbToStorageCore(ctx, file.path, file));
|
|
283
307
|
} else {
|
|
@@ -37,14 +37,6 @@ export declare function readStorageFile(ctx: FileHandlerContext, file: UXFileInf
|
|
|
37
37
|
* @remarks This helper acquires no document lock. Storage and path access retain the dynamic public host seams where the original operation used them.
|
|
38
38
|
*/
|
|
39
39
|
export declare function infoToStub<T extends UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub>(ctx: FileHandlerContext, info: null | T | FilePathWithPrefix | FilePath): Promise<T | UXFileInfoStub | null>;
|
|
40
|
-
/**
|
|
41
|
-
* Extract a parent directory using storage path separators.
|
|
42
|
-
*
|
|
43
|
-
* @param path - The affected file or provenance path.
|
|
44
|
-
* @returns The parent path, or the empty root path.
|
|
45
|
-
* @remarks This helper acquires no document lock. Storage and path access retain the dynamic public host seams where the original operation used them.
|
|
46
|
-
*/
|
|
47
|
-
export declare function getParentPath(path: string): string;
|
|
48
40
|
/**
|
|
49
41
|
* Narrow a nullable storage observation to a folder.
|
|
50
42
|
*
|
|
@@ -53,3 +45,5 @@ export declare function getParentPath(path: string): string;
|
|
|
53
45
|
* @remarks This helper acquires no document lock. Storage and path access retain the dynamic public host seams where the original operation used them.
|
|
54
46
|
*/
|
|
55
47
|
export declare function isFolderInfo(info: UXFileInfoStub | UXFolderInfo | null): info is UXFolderInfo;
|
|
48
|
+
/** Check whether the observed storage item is a file with this exact path spelling. */
|
|
49
|
+
export declare function isFileAtExactPath(info: UXFileInfoStub | UXFolderInfo | null, path: FilePathWithPrefix): info is UXFileInfoStub;
|
|
@@ -20,18 +20,17 @@ async function infoToStub(ctx, info) {
|
|
|
20
20
|
const file = typeof info === "string" ? await ctx.host.storage().getFileStub(info) : info;
|
|
21
21
|
return file;
|
|
22
22
|
}
|
|
23
|
-
function getParentPath(path) {
|
|
24
|
-
const lastSeparator = path.lastIndexOf("/");
|
|
25
|
-
return lastSeparator < 0 ? "" : path.slice(0, lastSeparator);
|
|
26
|
-
}
|
|
27
23
|
function isFolderInfo(info) {
|
|
28
24
|
return info?.isFolder === true;
|
|
29
25
|
}
|
|
26
|
+
function isFileAtExactPath(info, path) {
|
|
27
|
+
return !!info && !isFolderInfo(info) && info.path === path;
|
|
28
|
+
}
|
|
30
29
|
export {
|
|
31
30
|
getFileEntryPath,
|
|
32
31
|
getFileStoragePath,
|
|
33
|
-
getParentPath,
|
|
34
32
|
infoToStub,
|
|
33
|
+
isFileAtExactPath,
|
|
35
34
|
isFolderInfo,
|
|
36
35
|
readStorageFile
|
|
37
36
|
};
|
|
@@ -16,7 +16,7 @@ A1
|
|
|
16
16
|
|
|
17
17
|
`D1` and `C2` are the leaves to compare. Their nearest common ancestor is `A1`, not `B1` or `B2`. Automatic three-way merge may proceed only when the same `available` revision is present in both leaf histories. A matching generation number alone does not establish ancestry.
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
Selecting an existing revision keeps it as a live leaf. A resolver retires the competing leaves it has reviewed. Combining text creates a new content revision. Deleted leaves remain part of the tree until compaction removes their bodies. A stale client can therefore receive the resolved branch and the tombstone for a branch whose old content is still present in its storage.
|
|
20
20
|
|
|
21
21
|
Metadata reads which explicitly include deleted entries also return a current PouchDB `_deleted` winner. An ordinary read still excludes deleted entries, and a request for an unavailable specific revision does not fall back to the current winner. A deleted-winner lookup rechecks the winning revision after fetching its body. If it changes, the lookup follows the new winner for at most three attempts and returns no entry if it cannot establish a stable revision. Incoming file reflection uses the current winner and rechecks it before deleting storage, so an older deletion notification does not override a subsequent restoration. Existing conflict and unsynchronised-edit protection still applies.
|
|
22
22
|
|
|
@@ -44,17 +44,19 @@ After a resolution has propagated, an exact recorded revision can still identify
|
|
|
44
44
|
|
|
45
45
|
## Resolution classes
|
|
46
46
|
|
|
47
|
+
A whole-file logical deletion is a separate revision state. If one leaf is deleted and the other is live, the conservative text merge leaves the choice to the host.
|
|
48
|
+
|
|
47
49
|
| State | Safe automatic action |
|
|
48
50
|
| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
|
|
49
|
-
| Both leaves
|
|
50
|
-
|
|
|
51
|
-
|
|
|
52
|
-
| One side
|
|
51
|
+
| Both leaves have matching names, identical bytes, and the same deletion state | Collapse the duplicate leaf without creating merged content. |
|
|
52
|
+
| Both names match and text or structured data has a shared available base and non-overlapping changes | Perform a conservative three-way merge. |
|
|
53
|
+
| In a three-way text merge, one side removes a line the other leaves unchanged | Keep the line removed from the merged text. |
|
|
54
|
+
| One side removes a line which the other modifies | Retain a manual conflict. |
|
|
53
55
|
| A receiving file matches its exact readable recorded revision | Apply the propagated result under the existing conflict policy. |
|
|
54
56
|
| A receiving file matches its saved content hash and byte length | Apply the propagated result under the existing conflict policy, even after its recorded revision is pruned. |
|
|
55
57
|
| A receiving file differs from its readable recorded revision | Preserve the edit as a child of that revision. |
|
|
56
58
|
| Origin is unknown and no current non-deleted leaf matches | Preserve a fresh independent root for host conflict resolution. |
|
|
57
|
-
| Origin is unknown and current non-deleted leaves already contain the bytes | Avoid duplicate storage; infer provenance only for a unique match. |
|
|
59
|
+
| Origin is unknown and current non-deleted leaves already contain the observed spelling and bytes | Avoid duplicate storage; infer provenance only for a unique match. |
|
|
58
60
|
| A required merge body or common ancestor is missing or compacted | Retain a manual conflict. |
|
|
59
61
|
| Content is binary or otherwise not semantically mergeable | Leave the selection policy to the host; Commonlib cannot infer user intent. |
|
|
60
62
|
|
|
@@ -193,6 +195,18 @@ A1
|
|
|
193
195
|
|
|
194
196
|
`D2` remains a live metadata branch. The host can therefore ask whether to retain `C1` or the deletion. A PouchDB `_deleted` tombstone would remove that decision from the live conflict and is not used for this operation.
|
|
195
197
|
|
|
198
|
+
### Filename case in ordinary synchronisation
|
|
199
|
+
|
|
200
|
+
With case-insensitive document IDs, `Notes/Plan.md` and `Notes/plan.md` can identify the same document. The spelling belongs to each revision. When the receiver can identify the revision and spelling it previously reflected, an incoming case-only rename updates an unchanged file. A local edit based on that recorded revision is preserved as its child.
|
|
201
|
+
|
|
202
|
+
If the actual spelling in storage has no confirmed base, ordinary synchronisation preserves the file before renaming or overwriting it. A live leaf with the same spelling and bytes already represents the file. Otherwise, the file becomes an independent root under the same document ID. A repeated scan leaves the pending choices intact. This also applies when the two spellings contain identical bytes. This protection applies with the default conflict-write policy. Explicit forced reflection and the `writeDocumentsIfConflicted` overwrite setting retain their existing behaviour.
|
|
203
|
+
|
|
204
|
+
Automatic content resolution requires both compared revisions to record the same full path, including case. Path identity version `0` compares the recorded spelling directly. Version `1` applies NFC before comparison. Different or unknown names require a host decision. A successful three-way merge returns the recorded spelling as its save path when that spelling still identifies the reviewed document. If it identifies a different document under the current settings, the save path is the original lookup path. After selection, the host reflects the surviving revision using its recorded spelling, or the document's effective path when no name was recorded.
|
|
205
|
+
|
|
206
|
+
The built-in `DatabaseFileAccess` reads the original spelling directly from revision metadata. Custom adapters can provide `readRevisionPath(documentId, revision)` and honour the filename filter on `readLiveContentRevisions`. Return `undefined` when the revision or its stored path is absent, and propagate I/O errors. The filename filter runs before loading candidate chunks.
|
|
207
|
+
|
|
208
|
+
A host offering concatenation with a choice of filename can use `storeWithLiveBaseRevision(file, displayedWinnerRev)`. Before saving, the host checks that the chosen name still identifies the reviewed document. If the name identifies another document, both revisions remain available. The chosen name goes on a new child of the displayed winner. The two versions can have independent roots. Retire the other reviewed leaf only after the write succeeds. If the displayed parent has advanced, the write is refused and the current versions remain available for review.
|
|
209
|
+
|
|
196
210
|
### Renaming while a conflict is visible
|
|
197
211
|
|
|
198
212
|
For a case-only rename, such as `Note.md` to `note.md`, the renamed entry is written as a child of the displayed revision in the same document tree. The other live branch remains available for resolution.
|
|
@@ -201,9 +215,9 @@ For a cross-path rename, such as `draft.md` to `published.md`, Commonlib stores
|
|
|
201
215
|
|
|
202
216
|
### Reconstructing provenance after local state is unavailable
|
|
203
217
|
|
|
204
|
-
Suppose a local-database reset removed the device-local record, but the storage file still has exactly the bytes held by current non-deleted leaf `C2`. If `C2` is the only
|
|
218
|
+
Suppose a local-database reset removed the device-local record, but the storage file still has exactly the bytes held by current non-deleted leaf `C2`. If `C2` is the only current leaf with that spelling and those bytes, ordinary saving or reflection can reconstruct `C2` as the displayed base and a later edit extends it normally. An unchanged-time scan alone does not guarantee reconstruction.
|
|
205
219
|
|
|
206
|
-
If both current leaves contain the same bytes, ordinary saving avoids duplicate storage without selecting either as provenance. If neither
|
|
220
|
+
If both current leaves contain the same spelling and bytes, ordinary saving avoids duplicate storage without selecting either as provenance. If neither has the observed spelling and bytes, the file is preserved on an independent root. An unproven deletion preserves both existing branches, and a cross-path rename preserves unproven source branches after storing the target. These outcomes may require user review, but they do not guess that the deterministic winner was displayed.
|
|
207
221
|
|
|
208
222
|
### Receiving a resolution while showing the losing branch
|
|
209
223
|
|
package/docs/offline-scanner.md
CHANGED
|
@@ -46,6 +46,8 @@ The tables below cover only paths which remain after identity validation, the ho
|
|
|
46
46
|
|
|
47
47
|
`VaultScanOptions.strictContentCheck` is optional. `initialiseDatabase` accepts `VaultScanOptions` as its optional fifth argument, and `scanVault` accepts it as its optional fourth argument and forwards it. `performFullScan` exposes the same option through `FullScanOptions`. Omitting the option, or setting it to `true`, retains strict content comparison. Only an explicit `false` permits the scanner to pass the `canSkipUnchangedFile` hint to the file handler. Commonlib does not read a host setting or global storage; a host may select this option from a per-installation startup preference.
|
|
48
48
|
|
|
49
|
+
When a live database entry and a storage file have different spellings of the same filename, the scan preserves an untracked spelling before updating either side. A modification time or equal content alone cannot settle the choice. See [Filename case in ordinary synchronisation](conflict-resolution.md#filename-case-in-ordinary-synchronisation).
|
|
50
|
+
|
|
49
51
|
The hint is considered only when the normal freshness comparison reaches `EVEN`, replacing the additional body comparison at that point. It never bypasses `BASE_IS_NEW` or `TARGET_IS_NEW`; those branches retain their timestamp-directed reflection and last-seen bookkeeping. Inside `EVEN`, the hint is allowed only for a tracked file whose raw modification time exactly equals the recorded provenance mtime (not merely a value in the same platform comparison bucket), whose byte size matches the recorded value, whose tracked revision is the current live database revision, and which has no live conflicts or related queued, running, or failed file work. If tracking evidence is missing, or the host cannot establish pending-work state, the existing strict byte-comparison path remains. When the hint is accepted, the pair result is `SKIPPED`; it does not compare or claim equal bytes, write provenance, or introduce Commonlib persistent state. Incoming content, conflict handling, and logical-deletion protection retain their existing rules.
|
|
50
52
|
|
|
51
53
|
A local edit which preserves the tracked modification time and byte size may be missed by a scan using explicit `false`. Existing same-stat edit checks exercise the omitted-option strict path.
|
|
@@ -407,6 +407,147 @@ policy. The storage lookup may be a host index rather than an operating-system
|
|
|
407
407
|
existence check: the observation is made under the application lock, not in
|
|
408
408
|
an atomic filesystem transaction.
|
|
409
409
|
|
|
410
|
+
## Saving replication results in a CLI host
|
|
411
|
+
|
|
412
|
+
The `createReplicationResultQueueStore()` API, introduced in Commonlib 0.8.1, is available from
|
|
413
|
+
`@vrtmrz/livesync-commonlib/replication`. It stores each queued or processing item
|
|
414
|
+
under its own key. It also stores retained reflection failures and retry
|
|
415
|
+
reservations as individual records. Commonlib owns the versioned row format,
|
|
416
|
+
ordered reads, the legacy queue migration, and atomic delta submission. The
|
|
417
|
+
host owns the database connection, the value codec, and the processor's events
|
|
418
|
+
and recovery policy.
|
|
419
|
+
|
|
420
|
+
### Convert an existing CLI JSON file
|
|
421
|
+
|
|
422
|
+
When a scoped `keyvalue-db.json` needs importing, run the conversion on its
|
|
423
|
+
own for that database and Vault. Preserve the existing tagged JSON encoding,
|
|
424
|
+
including `Set`, `Uint8Array`, and `ArrayBuffer`. Use the file whose owner is
|
|
425
|
+
known to match the selected scope. Preserve older files of unknown ownership
|
|
426
|
+
for inspection.
|
|
427
|
+
|
|
428
|
+
Commit the imported KV values and the import receipt in one SQLite transaction.
|
|
429
|
+
Rename the source JSON after that commit. If a prior invocation committed the
|
|
430
|
+
receipt, finish the rename without copying the values again. If the commit
|
|
431
|
+
result is uncertain, close the connection, report failure, and check the
|
|
432
|
+
receipt on the next conversion attempt. Close the connection and exit when
|
|
433
|
+
conversion completes. On the next normal invocation, Commonlib can migrate
|
|
434
|
+
the legacy queue key from SQLite to individual rows.
|
|
435
|
+
|
|
436
|
+
### Connect the CLI-owned SQLite database
|
|
437
|
+
|
|
438
|
+
In LiveSync's `NodeKeyValueDBService`, open the SQLite database selected for the
|
|
439
|
+
current database and Vault. Use the same Fancy-kit 0.2.0 SQLite namespace and
|
|
440
|
+
prefix for the existing `replicationResultProcessorSnapshot` key and the new
|
|
441
|
+
queue prefix.
|
|
442
|
+
|
|
443
|
+
The following bridge uses the CLI's existing tagged JSON encoding for both the
|
|
444
|
+
imported legacy value and new rows. Each `setValue` writes one row.
|
|
445
|
+
|
|
446
|
+
```ts
|
|
447
|
+
import {
|
|
448
|
+
createReplicationResultQueueStore,
|
|
449
|
+
type ReplicationResultQueueBacking,
|
|
450
|
+
} from '@vrtmrz/livesync-commonlib/replication';
|
|
451
|
+
import { createSqliteValueStore } from '@vrtmrz/value-store/node-sqlite';
|
|
452
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
453
|
+
|
|
454
|
+
declare const connection: DatabaseSync;
|
|
455
|
+
declare const cliKvScope: { namespace: string; prefix: string };
|
|
456
|
+
declare function encodeCliValue(value: unknown): string;
|
|
457
|
+
declare function decodeCliValue(value: string): unknown;
|
|
458
|
+
|
|
459
|
+
const kv = createSqliteValueStore(connection, cliKvScope);
|
|
460
|
+
const backing: ReplicationResultQueueBacking = {
|
|
461
|
+
async read(key) {
|
|
462
|
+
const value = await kv.getValue(key);
|
|
463
|
+
return value === null ? undefined : decodeCliValue(value);
|
|
464
|
+
},
|
|
465
|
+
listKeys: (prefix) => kv.listKeys({ prefix }),
|
|
466
|
+
writeBatch: (operations) =>
|
|
467
|
+
kv.writeBatch(
|
|
468
|
+
operations.map((operation) =>
|
|
469
|
+
operation.kind === 'delete'
|
|
470
|
+
? { type: 'delete', key: operation.key }
|
|
471
|
+
: { type: 'setValue', key: operation.key, value: encodeCliValue(operation.value) }
|
|
472
|
+
)
|
|
473
|
+
),
|
|
474
|
+
};
|
|
475
|
+
const results = createReplicationResultQueueStore(backing);
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
Use one writer for the scope. Exclude other writers while `load()` or
|
|
479
|
+
`discard()` reads and changes that scope, and serialise those operations with
|
|
480
|
+
`commit()`. The backing `writeBatch()` must apply the whole batch atomically and
|
|
481
|
+
resolve after commit. The borrowed SQLite adapter starts its own transaction.
|
|
482
|
+
Call it outside any CLI-managed SQL transaction. Settle the submitted writes
|
|
483
|
+
and dispose the value store before closing. Put native connection closure in
|
|
484
|
+
a `finally` block that covers both steps. The CLI selects the SQLite durability
|
|
485
|
+
settings. See the
|
|
486
|
+
[Fancy-kit SQLite contract](https://github.com/vrtmrz/fancy-kit/blob/7bf325dddd6c7000d0ae2990146a538594a67f3b/docs/design/value-store-sqlite.md).
|
|
487
|
+
|
|
488
|
+
### Connect the result processor
|
|
489
|
+
|
|
490
|
+
1. Pass a getter for the current scoped store into `ReplicateResultProcessor`
|
|
491
|
+
from `createReplicationFeature` when the CLI opts in. Use `load()` at the
|
|
492
|
+
existing restore point. It commits any legacy rows and removes the old key in
|
|
493
|
+
the same transaction. The store validates the rows' storage format and returns
|
|
494
|
+
their payloads as `unknown`. Interpret them using the processor's existing
|
|
495
|
+
document and recovery validation. Restore recovery records and reservations
|
|
496
|
+
first. Then pass processing items followed by queued items through the current
|
|
497
|
+
recovery filter and replay rules, ahead of arrivals held during restore. If
|
|
498
|
+
loading fails, keep saves blocked until a load or explicit reset succeeds.
|
|
499
|
+
2. Give every queue occurrence a stable ID and store its order explicitly. Keep
|
|
500
|
+
the ID when a row moves from `queued` to `processing` and use it to delete the
|
|
501
|
+
row on completion. Preserve separate IDs for multiple occurrences even when
|
|
502
|
+
`_id` and `_rev` match. Reserve `legacy:` for migrated IDs. Track changed
|
|
503
|
+
rows at each mutation and submit them at the processor's existing save points.
|
|
504
|
+
Submit a replacement's deletes and insert in the same batch. Commit a retry
|
|
505
|
+
reservation with its changed allowance before dispatch, and commit retirement
|
|
506
|
+
of that reservation with the corresponding result updates. Retain a reflection
|
|
507
|
+
failure before or in the same batch as removal of its processing row.
|
|
508
|
+
3. Record the changes made by replay itself. Carry the loaded ID into each
|
|
509
|
+
surviving occurrence and record its resulting order and phase. Include
|
|
510
|
+
deletions for occurrences dropped by recovery filtering or duplicate
|
|
511
|
+
handling, and for reservations consumed by recovery. Include changes to
|
|
512
|
+
pending records moved to review. For hosts with recovery retries, a saved
|
|
513
|
+
reservation can filter out every runnable item. If replay changed rows,
|
|
514
|
+
request a save even when no work is runnable. Schedule that save after
|
|
515
|
+
restore completes, because the existing save path waits for restore.
|
|
516
|
+
4. Capture the pending delta when a serialised write begins. Mark those changes
|
|
517
|
+
saved only after `commit()` succeeds and keep newer or failed changes pending.
|
|
518
|
+
Preserve the current response timing for ordinary arrivals. A Fancy-kit
|
|
519
|
+
error code can cover both a failed statement and an uncertain commit. If a
|
|
520
|
+
write's outcome remains unclear, check the durable state after reopening the
|
|
521
|
+
same scope before acknowledging or resubmitting the delta. Initialise a new
|
|
522
|
+
store with `load()` before accepting writes. During an in-process reconnect,
|
|
523
|
+
use that read to reconcile the durable state with the existing in-memory queue.
|
|
524
|
+
5. In the pinned LiveSync CLI, `databaseEvents.onResetDatabase` runs before
|
|
525
|
+
database replacement. The `NodeServiceHub` and `NodeKeyValueDBService`
|
|
526
|
+
handlers can remove the runtime directory and the KV file at that point.
|
|
527
|
+
When wiring SQLite, keep the queue rows and legacy key through those early
|
|
528
|
+
handlers, including when the selected database's runtime directory contains
|
|
529
|
+
the SQLite file. Defer retiring that queue until the success event
|
|
530
|
+
`database.onDatabaseReset`. For a `fetch` or `rebuild` startup reset, resolve
|
|
531
|
+
the current scoped store there and await `discard()` before admitting new
|
|
532
|
+
work. Preserve the CLI's existing physical reset scope by retiring old queues
|
|
533
|
+
for every runtime Vault scope of the selected database. While reconstruction
|
|
534
|
+
is incomplete, let read-only commands inspect the database without migrating
|
|
535
|
+
or replaying the result queue. For a live logical reset, commit the delta
|
|
536
|
+
that retains the ordinary items selected by the processor. Use the database
|
|
537
|
+
scope and generation to drop stale mutations. A late completion may delete
|
|
538
|
+
only its own retained row. Keep occurrence IDs unique across reset while old
|
|
539
|
+
callbacks can finish.
|
|
540
|
+
|
|
541
|
+
Validate the CLI wiring by restarting after the first replay delta commits,
|
|
542
|
+
interrupting a write, and failing database replacement after the early reset
|
|
543
|
+
event. For legacy JSON conversion, interrupt the process after commit and
|
|
544
|
+
before renaming the JSON, then verify that the next attempt reuses the receipt.
|
|
545
|
+
Check that a later successful reset lets a new occurrence with the same document
|
|
546
|
+
and revision survive the old occurrence's completion. Compare system write
|
|
547
|
+
bytes on the same Vault and workload to measure SQLite and WAL overhead. The
|
|
548
|
+
Commonlib contract tests measure row operations and the bytes passed through the
|
|
549
|
+
test adapter's encoder.
|
|
550
|
+
|
|
410
551
|
## Verification and scope
|
|
411
552
|
|
|
412
553
|
Focused unit tests cover a current canonical file, absence, lookup failure,
|
package/package.json
CHANGED