@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
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
const LEGACY_KEY = "replicationResultProcessorSnapshot";
|
|
2
|
+
const QUEUE_PREFIX = "replication-result-queue:";
|
|
3
|
+
const ROW_PREFIX = `${QUEUE_PREFIX}v1:`;
|
|
4
|
+
const ROW_KINDS = ["processing", "queued", "pendingReflection", "recoveryAttempt"];
|
|
5
|
+
const LEGACY_FIELDS = {
|
|
6
|
+
processing: "processing",
|
|
7
|
+
queued: "queued",
|
|
8
|
+
pendingReflection: "pendingReflections",
|
|
9
|
+
recoveryAttempt: "recoveryAttempts"
|
|
10
|
+
};
|
|
11
|
+
function isRecord(value) {
|
|
12
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
function isStoredRow(value) {
|
|
15
|
+
return isRecord(value) && ROW_KINDS.some((kind) => kind === value.kind) && typeof value.id === "string" && value.id.length > 0 && typeof value.order === "number" && Number.isSafeInteger(value.order) && value.order >= 0 && Object.hasOwn(value, "payload") && value.payload !== void 0;
|
|
16
|
+
}
|
|
17
|
+
function rowKey(id) {
|
|
18
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
19
|
+
throw new TypeError("A replication result queue row requires a non-empty ID.");
|
|
20
|
+
}
|
|
21
|
+
return `${ROW_PREFIX}${id}`;
|
|
22
|
+
}
|
|
23
|
+
function upsertRow(value) {
|
|
24
|
+
return { kind: "upsert", key: rowKey(value.id), value };
|
|
25
|
+
}
|
|
26
|
+
function rowsFromLegacyReplicationResultSnapshot(snapshot) {
|
|
27
|
+
if (!isRecord(snapshot)) {
|
|
28
|
+
throw new Error("Invalid legacy replication result queue snapshot.");
|
|
29
|
+
}
|
|
30
|
+
const rows = [];
|
|
31
|
+
for (const kind of ROW_KINDS) {
|
|
32
|
+
const field = LEGACY_FIELDS[kind];
|
|
33
|
+
const records = snapshot[field];
|
|
34
|
+
const optional = kind === "pendingReflection" || kind === "recoveryAttempt";
|
|
35
|
+
if (optional && (records === void 0 || records === null)) {
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (!Array.isArray(records)) {
|
|
39
|
+
throw new Error(`Invalid '${field}' array in the legacy replication result queue snapshot.`);
|
|
40
|
+
}
|
|
41
|
+
for (const [order, payload] of records.entries()) {
|
|
42
|
+
const validPayload = optional ? payload !== void 0 && (kind === "pendingReflection" || payload !== null) : isRecord(payload);
|
|
43
|
+
if (!validPayload) {
|
|
44
|
+
throw new Error(`Invalid '${field}' entry in the legacy replication result queue snapshot.`);
|
|
45
|
+
}
|
|
46
|
+
rows.push({ kind, id: `legacy:${kind}:${order}`, order, payload });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return rows;
|
|
50
|
+
}
|
|
51
|
+
function compareReplicationResultQueueRows(left, right) {
|
|
52
|
+
const order = ROW_KINDS.indexOf(left.kind) - ROW_KINDS.indexOf(right.kind) || left.order - right.order;
|
|
53
|
+
if (order !== 0 || left.id === right.id) {
|
|
54
|
+
return order;
|
|
55
|
+
}
|
|
56
|
+
return left.id < right.id ? -1 : 1;
|
|
57
|
+
}
|
|
58
|
+
async function listQueueKeys(backing) {
|
|
59
|
+
const keys = await backing.listKeys(QUEUE_PREFIX);
|
|
60
|
+
if (keys.some((key) => !key.startsWith(QUEUE_PREFIX))) {
|
|
61
|
+
throw new Error("The replication result queue backing returned keys outside the queue namespace.");
|
|
62
|
+
}
|
|
63
|
+
return keys;
|
|
64
|
+
}
|
|
65
|
+
async function loadReplicationResultQueueRows(backing) {
|
|
66
|
+
const keys = await listQueueKeys(backing);
|
|
67
|
+
const legacySnapshot = await backing.read(LEGACY_KEY);
|
|
68
|
+
if (legacySnapshot !== void 0) {
|
|
69
|
+
if (keys.length > 0) {
|
|
70
|
+
throw new Error("The replication result queue contains both a legacy snapshot and queue rows.");
|
|
71
|
+
}
|
|
72
|
+
const rows2 = rowsFromLegacyReplicationResultSnapshot(legacySnapshot);
|
|
73
|
+
await backing.writeBatch([...rows2.map(upsertRow), { kind: "delete", key: LEGACY_KEY }]);
|
|
74
|
+
return rows2;
|
|
75
|
+
}
|
|
76
|
+
const rows = [];
|
|
77
|
+
for (const key of keys) {
|
|
78
|
+
if (!key.startsWith(ROW_PREFIX)) {
|
|
79
|
+
throw new Error("Unsupported replication result queue row version.");
|
|
80
|
+
}
|
|
81
|
+
const value = await backing.read(key);
|
|
82
|
+
if (!isStoredRow(value) || key !== rowKey(value.id)) {
|
|
83
|
+
throw new Error("Invalid replication result queue row or missing listed value.");
|
|
84
|
+
}
|
|
85
|
+
rows.push(value);
|
|
86
|
+
}
|
|
87
|
+
return rows.sort(compareReplicationResultQueueRows);
|
|
88
|
+
}
|
|
89
|
+
function toReplicationResultQueueWrites(delta) {
|
|
90
|
+
return delta.map((change) => {
|
|
91
|
+
switch (change.kind) {
|
|
92
|
+
case "upsert":
|
|
93
|
+
if (!isStoredRow(change.row)) {
|
|
94
|
+
throw new TypeError("Invalid replication result queue row.");
|
|
95
|
+
}
|
|
96
|
+
return upsertRow(change.row);
|
|
97
|
+
case "delete":
|
|
98
|
+
return { kind: "delete", key: rowKey(change.id) };
|
|
99
|
+
default:
|
|
100
|
+
throw new TypeError("Invalid replication result queue change.");
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
function createReplicationResultQueueStore(backing) {
|
|
105
|
+
let ready = false;
|
|
106
|
+
return {
|
|
107
|
+
async load() {
|
|
108
|
+
ready = false;
|
|
109
|
+
const rows = await loadReplicationResultQueueRows(backing);
|
|
110
|
+
ready = true;
|
|
111
|
+
return rows;
|
|
112
|
+
},
|
|
113
|
+
async commit(delta) {
|
|
114
|
+
if (!ready) {
|
|
115
|
+
throw new Error("Load or discard the replication result queue before committing changes.");
|
|
116
|
+
}
|
|
117
|
+
if (delta.length === 0) {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
await backing.writeBatch(toReplicationResultQueueWrites(delta));
|
|
121
|
+
},
|
|
122
|
+
async discard() {
|
|
123
|
+
ready = false;
|
|
124
|
+
const keys = await listQueueKeys(backing);
|
|
125
|
+
const operations = [...keys, LEGACY_KEY].map((key) => ({
|
|
126
|
+
kind: "delete",
|
|
127
|
+
key
|
|
128
|
+
}));
|
|
129
|
+
await backing.writeBatch(operations);
|
|
130
|
+
ready = true;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
export {
|
|
135
|
+
compareReplicationResultQueueRows,
|
|
136
|
+
createReplicationResultQueueStore,
|
|
137
|
+
loadReplicationResultQueueRows,
|
|
138
|
+
rowsFromLegacyReplicationResultSnapshot,
|
|
139
|
+
toReplicationResultQueueWrites
|
|
140
|
+
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { isReflectionCompleted } from "../../interfaces/FileHandler.js";
|
|
2
|
+
import { isDeletedEntry } from "../../common/utils.doc.js";
|
|
2
3
|
import {
|
|
3
4
|
LOG_LEVEL_DEBUG,
|
|
4
5
|
LOG_LEVEL_INFO,
|
|
@@ -6,11 +7,20 @@ import {
|
|
|
6
7
|
LOG_LEVEL_VERBOSE,
|
|
7
8
|
isMetaEntry
|
|
8
9
|
} from "../../common/types.js";
|
|
10
|
+
import { getPathNormalizationVersion } from "../../common/pathNormalization.js";
|
|
11
|
+
import { hasSameParentFilenameCaseConflict } from "../../conflicts/filenameCaseConflict.js";
|
|
9
12
|
import { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../../common/models/shared.const.symbols.js";
|
|
10
13
|
import { shouldBeIgnored, stripAllPrefixes } from "../../string_and_binary/path.js";
|
|
11
14
|
import { inspectMetadataDocumentIdentity } from "./metadata.js";
|
|
12
15
|
import { getPathFromEntry, convertCase } from "./paths.js";
|
|
13
16
|
import { FilePairProcessResults, MetadataDocumentIdentityStatuses } from "./types.js";
|
|
17
|
+
function shouldCheckFilenameCaseBeforeFreshness(filePath, documentPath, document, services) {
|
|
18
|
+
if (filePath === documentPath || isDeletedEntry(document)) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
const settings = services.setting.currentSettings();
|
|
22
|
+
return !!settings && !settings.handleFilenameCaseSensitive && hasSameParentFilenameCaseConflict(filePath, documentPath, getPathNormalizationVersion(settings));
|
|
23
|
+
}
|
|
14
24
|
async function reflectScannedEntry(host, entry, file, force, options) {
|
|
15
25
|
const target = entry._rev ? { documentId: entry._id, revision: entry._rev } : void 0;
|
|
16
26
|
try {
|
|
@@ -33,7 +43,8 @@ async function syncFileBetweenDBandStorage(host, log, file, doc, scanOptions) {
|
|
|
33
43
|
if (!doc) {
|
|
34
44
|
throw new Error(`Missing doc:${docPath}`);
|
|
35
45
|
}
|
|
36
|
-
const
|
|
46
|
+
const compareFilename = shouldCheckFilenameCaseBeforeFreshness(file.path, docPath, doc, host.services);
|
|
47
|
+
const compareResult = compareFilename ? TARGET_IS_NEW : host.services.path.compareFileFreshness(file, doc);
|
|
37
48
|
switch (compareResult) {
|
|
38
49
|
case BASE_IS_NEW:
|
|
39
50
|
if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
|
|
@@ -47,9 +58,10 @@ async function syncFileBetweenDBandStorage(host, log, file, doc, scanOptions) {
|
|
|
47
58
|
return FilePairProcessResults.SKIPPED;
|
|
48
59
|
}
|
|
49
60
|
case TARGET_IS_NEW:
|
|
50
|
-
if (!host.services.vault.isFileSizeTooLarge(doc.size)) {
|
|
61
|
+
if (!host.services.vault.isFileSizeTooLarge(doc.size) && (!compareFilename || !host.services.vault.isFileSizeTooLarge(file.stat.size))) {
|
|
51
62
|
log("STORAGE <- DB :" + docPath);
|
|
52
|
-
const
|
|
63
|
+
const observed = compareFilename ? file : stripAllPrefixes(docPath);
|
|
64
|
+
const reflection = await reflectScannedEntry(host, doc, observed, false, scanOptions);
|
|
53
65
|
if (reflection === FilePairProcessResults.COMPLETED) {
|
|
54
66
|
host.services.context.events.emitEvent("event-file-changed", {
|
|
55
67
|
file: file.path,
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
LOG_LEVEL_NOTICE,
|
|
7
7
|
LOG_LEVEL_VERBOSE
|
|
8
8
|
} from "../../common/types.js";
|
|
9
|
-
import { compareMTime } from "../../common/utils.js";
|
|
9
|
+
import { compareMTime, isDeletedEntry } from "../../common/utils.js";
|
|
10
10
|
import { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../../common/models/shared.const.symbols.js";
|
|
11
11
|
import { stripAllPrefixes } from "../../string_and_binary/path.js";
|
|
12
12
|
import { VaultScanResults } from "../../services/base/VaultScanResult.js";
|
|
@@ -32,9 +32,6 @@ import {
|
|
|
32
32
|
ExtraOnRemote,
|
|
33
33
|
FilePairProcessResults
|
|
34
34
|
} from "./types.js";
|
|
35
|
-
function isDeletedEntry(entry) {
|
|
36
|
-
return entry.deleted || entry._deleted || false;
|
|
37
|
-
}
|
|
38
35
|
function getFilePairState(pair) {
|
|
39
36
|
const { file, doc } = pair;
|
|
40
37
|
if (file && doc) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { UXFileInfoStub, FilePathWithPrefix, UXFileInfo, MetaEntry, LoadedEntry, FilePath } from "../common/types.js";
|
|
2
|
-
import type { DatabaseFileAccess } from "../interfaces/DatabaseFileAccess.js";
|
|
1
|
+
import type { UXFileInfoStub, FilePathWithPrefix, UXFileInfo, DocumentID, MetaEntry, LoadedEntry, FilePath } from "../common/types.js";
|
|
2
|
+
import type { DatabaseFileAccess, LiveContentFilename } from "../interfaces/DatabaseFileAccess.js";
|
|
3
3
|
import type { StorageAccess } from "../interfaces/StorageAccess.js";
|
|
4
4
|
import type { APIService } from "../services/base/APIService.js";
|
|
5
5
|
import type { DatabaseService } from "../services/base/DatabaseService.js";
|
|
@@ -64,16 +64,17 @@ export declare class ServiceDatabaseFileAccessBase extends ServiceModuleBase<Ser
|
|
|
64
64
|
* A read failure yields no confirmed match. Callers decide whether the result identifies a
|
|
65
65
|
* unique origin; this method does not mutate provenance or hold the revision tree stable.
|
|
66
66
|
*/
|
|
67
|
-
findLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer): Promise<string[]>;
|
|
67
|
+
findLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, filename?: LiveContentFilename): Promise<string[]>;
|
|
68
68
|
/** Select current live leaves, independently of historical ancestor lookup. */
|
|
69
69
|
private selectLiveContentLeaves;
|
|
70
70
|
/** Compare selected leaves using local Chunks only; unreadable content rejects. */
|
|
71
|
-
readLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer): Promise<string[]>;
|
|
71
|
+
readLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, filename?: LiveContentFilename): Promise<string[]>;
|
|
72
72
|
hasContentInRevisionHistory(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, currentRev?: string): Promise<boolean>;
|
|
73
73
|
getConflictedRevs(file: UXFileInfoStub | FilePathWithPrefix): Promise<string[]>;
|
|
74
74
|
readConflictedRevs(file: UXFileInfoStub | FilePathWithPrefix): Promise<string[]>;
|
|
75
75
|
fetch(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, waitForReady?: boolean, skipCheck?: boolean): Promise<UXFileInfo | false>;
|
|
76
76
|
fetchEntryMeta(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, skipCheck?: boolean): Promise<MetaEntry | false>;
|
|
77
|
+
readRevisionPath(documentId: DocumentID, revision: string): Promise<string | undefined>;
|
|
77
78
|
readEntryMeta(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, skipCheck?: boolean): Promise<MetaEntry | false>;
|
|
78
79
|
fetchEntryFromMeta(meta: MetaEntry, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean): Promise<LoadedEntry | false>;
|
|
79
80
|
readEntryFromMeta(meta: MetaEntry, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean): Promise<LoadedEntry | false>;
|
|
@@ -7,6 +7,9 @@ import { EVENT_FILE_SAVED } from "../events/coreEvents.js";
|
|
|
7
7
|
import { getDatabasePathFromUXFileInfo, getStoragePathFromUXFileInfo, isInternalMetadata } from "../common/typeUtils.js";
|
|
8
8
|
import { createBlob, createTextBlob, determineTypeFromBlob, isDocContentSame, readContent } from "../common/utils.js";
|
|
9
9
|
import { ICHeader } from "../common/models/fileaccess.const.js";
|
|
10
|
+
import { isDeletedEntry, tryGetFilePath } from "../common/utils.doc.js";
|
|
11
|
+
import { haveMatchingRevisionPaths } from "../conflicts/filenameCaseConflict.js";
|
|
12
|
+
import { isErrorOfMissingDoc } from "../pouchdb/utils_couchdb.js";
|
|
10
13
|
class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
|
|
11
14
|
events;
|
|
12
15
|
vault;
|
|
@@ -349,16 +352,16 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
|
|
|
349
352
|
* A read failure yields no confirmed match. Callers decide whether the result identifies a
|
|
350
353
|
* unique origin; this method does not mutate provenance or hold the revision tree stable.
|
|
351
354
|
*/
|
|
352
|
-
async findLiveContentRevisions(file, content) {
|
|
355
|
+
async findLiveContentRevisions(file, content, filename) {
|
|
353
356
|
try {
|
|
354
|
-
return await this.readLiveContentRevisions(file, content);
|
|
357
|
+
return await this.readLiveContentRevisions(file, content, filename);
|
|
355
358
|
} catch (error) {
|
|
356
359
|
this._log(error, LOG_LEVEL_VERBOSE);
|
|
357
360
|
return [];
|
|
358
361
|
}
|
|
359
362
|
}
|
|
360
363
|
/** Select current live leaves, independently of historical ancestor lookup. */
|
|
361
|
-
async selectLiveContentLeaves(file) {
|
|
364
|
+
async selectLiveContentLeaves(file, filenameFilter) {
|
|
362
365
|
const filename = getDatabasePathFromUXFileInfo(file);
|
|
363
366
|
const current = await this.readEntryMeta(file, void 0, true);
|
|
364
367
|
if (!current) {
|
|
@@ -379,14 +382,22 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
|
|
|
379
382
|
cause: new Error(`Invalid live revision response for ${filename}`)
|
|
380
383
|
});
|
|
381
384
|
}
|
|
382
|
-
return leaves.flatMap(({ ok }) =>
|
|
385
|
+
return leaves.flatMap(({ ok }) => {
|
|
386
|
+
if (!ok?._rev || isDeletedEntry(ok)) {
|
|
387
|
+
return [];
|
|
388
|
+
}
|
|
389
|
+
if (filenameFilter && !haveMatchingRevisionPaths(tryGetFilePath(ok), filenameFilter.path, filenameFilter.normalizationVersion)) {
|
|
390
|
+
return [];
|
|
391
|
+
}
|
|
392
|
+
return [ok._rev];
|
|
393
|
+
});
|
|
383
394
|
}
|
|
384
395
|
/** Compare selected leaves using local Chunks only; unreadable content rejects. */
|
|
385
|
-
async readLiveContentRevisions(file, content) {
|
|
396
|
+
async readLiveContentRevisions(file, content, filename) {
|
|
386
397
|
if (!await this.checkIsTargetFile(file)) {
|
|
387
398
|
return [];
|
|
388
399
|
}
|
|
389
|
-
const revisions = await this.selectLiveContentLeaves(file);
|
|
400
|
+
const revisions = await this.selectLiveContentLeaves(file, filename);
|
|
390
401
|
const matches = [];
|
|
391
402
|
for (const revision of revisions) {
|
|
392
403
|
const entry = await this.database.localDatabase.readDBEntry(
|
|
@@ -397,7 +408,7 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
|
|
|
397
408
|
true,
|
|
398
409
|
true
|
|
399
410
|
);
|
|
400
|
-
if (entry && !entry
|
|
411
|
+
if (entry && !isDeletedEntry(entry) && await isDocContentSame(readContent(entry), content)) {
|
|
401
412
|
matches.push(revision);
|
|
402
413
|
}
|
|
403
414
|
}
|
|
@@ -450,6 +461,16 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
|
|
|
450
461
|
async fetchEntryMeta(file, rev, skipCheck = false) {
|
|
451
462
|
return await this.readEntryMeta(file, rev, skipCheck);
|
|
452
463
|
}
|
|
464
|
+
async readRevisionPath(documentId, revision) {
|
|
465
|
+
try {
|
|
466
|
+
return tryGetFilePath(await this.database.localDatabase.getRaw(documentId, { rev: revision }));
|
|
467
|
+
} catch (error) {
|
|
468
|
+
if (isErrorOfMissingDoc(error)) {
|
|
469
|
+
return void 0;
|
|
470
|
+
}
|
|
471
|
+
throw new ContentReadError({ documentId, revision, resources: ["local-database"], cause: error });
|
|
472
|
+
}
|
|
473
|
+
}
|
|
453
474
|
async readEntryMeta(file, rev, skipCheck = false) {
|
|
454
475
|
const filename = getDatabasePathFromUXFileInfo(file);
|
|
455
476
|
if (skipCheck && !await this.checkIsTargetFile(file)) {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { FilePathWithPrefix, MetaEntry, UXFileInfoStub } from "../../common/types.js";
|
|
2
2
|
import type { FileHandlerContext, PreservationResult } from "./context.js";
|
|
3
|
+
import type { FileReflectionProvenanceRecord } from "../../interfaces/FileReflectionProvenance.js";
|
|
3
4
|
/** Decoded incoming file body supplied for live-write protection (absent for deletions). */
|
|
4
5
|
type IncomingContent = string | string[] | Blob | ArrayBuffer;
|
|
5
6
|
/**
|
|
@@ -14,6 +15,8 @@ type IncomingContent = string | string[] | Blob | ArrayBuffer;
|
|
|
14
15
|
* @remarks The caller holds the document lock. preserved:true also covers a refused preservation write that must still stop overwrite; any returned snapshot requires later revalidation.
|
|
15
16
|
*/
|
|
16
17
|
export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, incomingEntry: MetaEntry, incomingContent?: IncomingContent): Promise<PreservationResult>;
|
|
18
|
+
/** Preserve an unobserved filename and its bytes before an incoming rename. */
|
|
19
|
+
export declare function preserveUnobservedFilename(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, observedProvenance: FileReflectionProvenanceRecord | undefined): Promise<PreservationResult>;
|
|
17
20
|
/**
|
|
18
21
|
* Repeat overwrite protection after a previous storage observation became stale.
|
|
19
22
|
*
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
readProvenanceSnapshot,
|
|
5
5
|
currentStorageSnapshotMatches,
|
|
6
6
|
classifyStorageContent,
|
|
7
|
+
classifyMatchingFilenameLeaf,
|
|
7
8
|
rememberMatchingLeaf,
|
|
8
9
|
finaliseStoredRevision
|
|
9
10
|
} from "./provenance.js";
|
|
@@ -28,10 +29,11 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
|
|
|
28
29
|
if (!incomingEntry._rev) {
|
|
29
30
|
return { preserved: false };
|
|
30
31
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
32
|
+
return await preserveStorageSnapshot(
|
|
33
|
+
ctx,
|
|
34
|
+
path,
|
|
35
|
+
snapshot,
|
|
36
|
+
() => classifyStorageContent(
|
|
35
37
|
ctx,
|
|
36
38
|
readFile,
|
|
37
39
|
incomingEntry,
|
|
@@ -39,7 +41,27 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
|
|
|
39
41
|
observedProvenance,
|
|
40
42
|
hasIncomingContent(incomingContent) ? { _rev: incomingEntry._rev, data: incomingContent } : void 0,
|
|
41
43
|
false
|
|
42
|
-
)
|
|
44
|
+
)
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
async function preserveUnobservedFilename(ctx, path, existDoc, observedProvenance) {
|
|
48
|
+
const file = await ctx.host.readFileFromStub(existDoc);
|
|
49
|
+
if (file.path !== existDoc.path) {
|
|
50
|
+
return { preserved: false };
|
|
51
|
+
}
|
|
52
|
+
return await preserveStorageSnapshot(
|
|
53
|
+
ctx,
|
|
54
|
+
path,
|
|
55
|
+
{ file, revision: observedProvenance },
|
|
56
|
+
() => classifyMatchingFilenameLeaf(ctx, file)
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
async function preserveStorageSnapshot(ctx, path, snapshot, classify) {
|
|
60
|
+
const { file: readFile, revision: observedProvenance } = snapshot;
|
|
61
|
+
let classification;
|
|
62
|
+
let unavailableRead;
|
|
63
|
+
try {
|
|
64
|
+
classification = await classify();
|
|
43
65
|
} catch (error) {
|
|
44
66
|
if (!(error instanceof ContentReadError)) {
|
|
45
67
|
throw error;
|
|
@@ -54,7 +76,7 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
|
|
|
54
76
|
return { preserved: false, snapshot };
|
|
55
77
|
}
|
|
56
78
|
if (classification.kind === "matching-leaf") {
|
|
57
|
-
await rememberMatchingLeaf(ctx,
|
|
79
|
+
await rememberMatchingLeaf(ctx, readFile.path, classification.revision, readFile.stat.mtime, readFile.body);
|
|
58
80
|
await queueConflictCheckFor(ctx, path);
|
|
59
81
|
return { preserved: true };
|
|
60
82
|
}
|
|
@@ -97,6 +119,7 @@ async function recheckIncomingStorage(ctx, path, incomingEntry, incomingContent,
|
|
|
97
119
|
return protection;
|
|
98
120
|
}
|
|
99
121
|
export {
|
|
122
|
+
preserveUnobservedFilename,
|
|
100
123
|
preserveUnsyncedStorageAsConflict,
|
|
101
124
|
recheckIncomingStorage
|
|
102
125
|
};
|
|
@@ -199,6 +199,8 @@ export type StorageContentClassification = RecordedStorageClassification | {
|
|
|
199
199
|
} | {
|
|
200
200
|
kind: "unknown";
|
|
201
201
|
};
|
|
202
|
+
/** Use existing live-content matches only when the same filename is also recorded. */
|
|
203
|
+
export declare function classifyMatchingFilenameLeaf(ctx: FileHandlerContext, file: UXFileInfo): Promise<StorageContentClassification>;
|
|
202
204
|
/**
|
|
203
205
|
* Confirm the exact displayed revision from current bytes and device-local evidence.
|
|
204
206
|
* @param ctx - Borrowed file-handler capabilities and provenance.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { withFileEventPaths } from "./locking.js";
|
|
2
|
-
import { isFolderInfo } from "./storage.js";
|
|
2
|
+
import { isFileAtExactPath, isFolderInfo } from "./storage.js";
|
|
3
3
|
import { LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
|
|
4
|
-
import { displayRev, isDocContentSame, readContent } from "../../common/utils.js";
|
|
4
|
+
import { displayRev, isDeletedEntry, isDocContentSame, readContent } from "../../common/utils.js";
|
|
5
5
|
import { computeFileContentHash } from "../../common/fileContentHash.js";
|
|
6
6
|
import { getPathNormalizationVersion, normalisePathForIdentity } from "../../common/pathNormalization.js";
|
|
7
7
|
function getProvenancePath(ctx, path) {
|
|
@@ -16,7 +16,7 @@ async function getProvenance(ctx, path) {
|
|
|
16
16
|
const record = await ctx.provenance.get(getProvenancePath(ctx, path));
|
|
17
17
|
if (!record) return void 0;
|
|
18
18
|
const entry = await ctx.host.db().readEntryMeta(path, record.revision, true);
|
|
19
|
-
if (entry && !entry
|
|
19
|
+
if (entry && !isDeletedEntry(entry)) {
|
|
20
20
|
return record;
|
|
21
21
|
}
|
|
22
22
|
if (!hasContentHash(record)) await ctx.provenance.delete(getProvenancePath(ctx, path));
|
|
@@ -169,9 +169,9 @@ async function readProvenanceSnapshot(ctx, path, requireReadable = false) {
|
|
|
169
169
|
}
|
|
170
170
|
async function currentStorageSnapshotMatches(ctx, file, revision, requireReadableProvenance = false) {
|
|
171
171
|
const current = await ctx.host.storage().getStub(file.path);
|
|
172
|
-
if (!
|
|
172
|
+
if (!isFileAtExactPath(current, file.path)) return false;
|
|
173
173
|
const readCurrent = await ctx.host.readFileFromStub(current);
|
|
174
|
-
return readCurrent.stat.mtime === file.stat.mtime && await isDocContentSame(readCurrent.body, file.body) && sameProvenance(await readProvenanceSnapshot(ctx, file.path, requireReadableProvenance), revision);
|
|
174
|
+
return readCurrent.path === file.path && readCurrent.stat.mtime === file.stat.mtime && await isDocContentSame(readCurrent.body, file.body) && sameProvenance(await readProvenanceSnapshot(ctx, file.path, requireReadableProvenance), revision);
|
|
175
175
|
}
|
|
176
176
|
async function finaliseStoredRevision(ctx, file, observedProvenance, storedRevision, requireReadableProvenance = false) {
|
|
177
177
|
const evidence = await contentEvidence(ctx, file.body);
|
|
@@ -200,18 +200,36 @@ async function classifyRecordedStorageContent(ctx, file, path, recorded, recorde
|
|
|
200
200
|
}
|
|
201
201
|
if (!base) {
|
|
202
202
|
const meta = await ctx.host.db().readEntryMeta(file, recordedRevision, true);
|
|
203
|
-
if (requireReadableContent && meta && !meta
|
|
203
|
+
if (requireReadableContent && meta && !isDeletedEntry(meta)) {
|
|
204
204
|
throw new Error(
|
|
205
205
|
`Could not read the recorded file revision ${displayRev(recordedRevision)} for ${file.path}`
|
|
206
206
|
);
|
|
207
207
|
}
|
|
208
|
-
if ((!meta || meta
|
|
208
|
+
if ((!meta || isDeletedEntry(meta)) && !hasContentHash(recorded)) await deleteProvenance(ctx, path);
|
|
209
209
|
}
|
|
210
210
|
return void 0;
|
|
211
211
|
}
|
|
212
212
|
async function classifyLiveStorageContent(ctx, file, currentEntry) {
|
|
213
|
-
const
|
|
214
|
-
if (
|
|
213
|
+
const db = ctx.host.db();
|
|
214
|
+
if (currentEntry && !isDeletedEntry(currentEntry) && !ctx.setting.currentSettings().handleFilenameCaseSensitive && db.readRevisionPath) {
|
|
215
|
+
return await classifyMatchingFilenameLeaf(ctx, file);
|
|
216
|
+
}
|
|
217
|
+
const matches = currentEntry ? await db.readLiveContentRevisions(file, file.body) : [];
|
|
218
|
+
return classifyMatchingLeaves(matches);
|
|
219
|
+
}
|
|
220
|
+
async function classifyMatchingFilenameLeaf(ctx, file) {
|
|
221
|
+
const db = ctx.host.db();
|
|
222
|
+
if (!db.readRevisionPath) {
|
|
223
|
+
return { kind: "unknown" };
|
|
224
|
+
}
|
|
225
|
+
const matches = await db.readLiveContentRevisions(file, file.body, {
|
|
226
|
+
path: file.path,
|
|
227
|
+
normalizationVersion: getPathNormalizationVersion(ctx.setting.currentSettings())
|
|
228
|
+
});
|
|
229
|
+
return classifyMatchingLeaves(matches);
|
|
230
|
+
}
|
|
231
|
+
function classifyMatchingLeaves(matches) {
|
|
232
|
+
if (matches.length > 0) {
|
|
215
233
|
return { kind: "matching-leaf", revision: matches.length === 1 ? matches[0] : void 0 };
|
|
216
234
|
}
|
|
217
235
|
return { kind: "unknown" };
|
|
@@ -235,11 +253,12 @@ async function inspectCurrentFileProvenance(ctx, path, revision) {
|
|
|
235
253
|
return false;
|
|
236
254
|
}
|
|
237
255
|
const current = await ctx.host.db().readEntryMeta(path, void 0, true);
|
|
238
|
-
return !!current && current._rev === revision && !current
|
|
256
|
+
return !!current && current._rev === revision && !isDeletedEntry(current) && await currentStorageSnapshotMatches(ctx, file, recorded, true);
|
|
239
257
|
});
|
|
240
258
|
}
|
|
241
259
|
export {
|
|
242
260
|
captureRenameProvenance,
|
|
261
|
+
classifyMatchingFilenameLeaf,
|
|
243
262
|
classifyStorageContent,
|
|
244
263
|
commitRenamedProvenance,
|
|
245
264
|
contentEvidence,
|