@vrtmrz/livesync-commonlib 0.4.0 → 0.4.2
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 +14 -2
- package/dist/common/models/fileaccess.definition.d.ts +35 -0
- package/dist/common/models/fileaccess.definition.js +11 -0
- package/dist/common/typeUtils.d.ts +27 -4
- package/dist/interfaces/FileHandler.d.ts +60 -1
- package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
- package/dist/interfaces/FileReflectionProvenance.js +11 -1
- package/dist/managers/StorageEventManager/admission.d.ts +50 -0
- package/dist/managers/StorageEventManager/admission.js +129 -0
- package/dist/managers/StorageEventManager/batching.d.ts +93 -0
- package/dist/managers/StorageEventManager/batching.js +97 -0
- package/dist/managers/StorageEventManager/operations.d.ts +142 -0
- package/dist/managers/StorageEventManager/operations.js +69 -0
- package/dist/managers/StorageEventManager/processing.d.ts +63 -0
- package/dist/managers/StorageEventManager/processing.js +94 -0
- package/dist/managers/StorageEventManager/queue.d.ts +73 -0
- package/dist/managers/StorageEventManager/queue.js +113 -0
- package/dist/managers/StorageEventManager/retry.d.ts +33 -0
- package/dist/managers/StorageEventManager/retry.js +31 -0
- package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
- package/dist/managers/StorageEventManager/snapshot.js +53 -0
- package/dist/managers/StorageEventManager/state.d.ts +155 -0
- package/dist/managers/StorageEventManager/state.js +105 -0
- package/dist/managers/StorageEventManager/watching.d.ts +93 -0
- package/dist/managers/StorageEventManager/watching.js +36 -0
- package/dist/managers/StorageEventManager.d.ts +303 -83
- package/dist/managers/StorageEventManager.js +457 -547
- package/dist/serviceFeatures/offlineScanner/fileStatus.d.ts +61 -0
- package/dist/serviceFeatures/offlineScanner/fileStatus.js +85 -0
- package/dist/serviceFeatures/offlineScanner/files.d.ts +47 -0
- package/dist/serviceFeatures/offlineScanner/files.js +218 -0
- package/dist/serviceFeatures/offlineScanner/metadata.d.ts +56 -0
- package/dist/serviceFeatures/offlineScanner/metadata.js +320 -0
- package/dist/serviceFeatures/offlineScanner/paths.d.ts +20 -0
- package/dist/serviceFeatures/offlineScanner/paths.js +16 -0
- package/dist/serviceFeatures/offlineScanner/scan.d.ts +35 -0
- package/dist/serviceFeatures/offlineScanner/scan.js +358 -0
- package/dist/serviceFeatures/offlineScanner/types.d.ts +134 -0
- package/dist/serviceFeatures/offlineScanner/types.js +66 -0
- package/dist/serviceFeatures/offlineScanner.d.ts +25 -251
- package/dist/serviceFeatures/offlineScanner.js +36 -860
- package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
- package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
- package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
- package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.d.ts +13 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
- package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
- package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
- package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
- package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
- package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
- package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
- package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
- package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
- package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
- package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
- package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
- package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
- package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
- package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
- package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
- package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
- package/dist/serviceModules/ServiceFileHandlerBase.d.ts +141 -183
- package/dist/serviceModules/ServiceFileHandlerBase.js +206 -1397
- package/dist/services/base/KeyValueDBService.d.ts +9 -0
- package/dist/services/base/KeyValueDBService.js +11 -1
- package/docs/conflict-resolution.md +3 -1
- package/docs/development.md +40 -0
- package/docs/offline-scanner.md +26 -1
- package/docs/p2p-transport-lifecycle.md +8 -1
- package/docs/storage-events-and-reflection.md +212 -22
- package/package.json +1 -1
|
@@ -1,412 +1,39 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
LOG_LEVEL_DEBUG,
|
|
5
|
-
LOG_LEVEL_INFO,
|
|
6
|
-
LOG_LEVEL_NOTICE,
|
|
7
|
-
LOG_LEVEL_VERBOSE,
|
|
8
|
-
isMetaEntry
|
|
9
|
-
} from "../common/types.js";
|
|
10
|
-
import { compareMTime, isAnyNote, isRemediationModeActive } from "../common/utils.js";
|
|
11
|
-
import { shouldBeIgnored, stripAllPrefixes } from "../string_and_binary/path.js";
|
|
12
|
-
import { getPathNormalizationVersion, normalisePathForIdentity } from "../common/pathNormalization.js";
|
|
1
|
+
import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "../common/types.js";
|
|
2
|
+
import { isRemediationModeActive } from "../common/utils.js";
|
|
13
3
|
import { createInstanceLogFunction } from "../services/lib/logUtils.js";
|
|
14
|
-
import { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../common/models/shared.const.symbols.js";
|
|
15
4
|
import { UnresolvedErrorManager } from "../services/base/UnresolvedErrorManager.js";
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
5
|
+
import { collectDeletedFiles } from "./offlineScanner/metadata.js";
|
|
6
|
+
import { synchroniseAllFilesBetweenDBandStorage } from "./offlineScanner/scan.js";
|
|
7
|
+
import { FullScanModes } from "./offlineScanner/types.js";
|
|
19
8
|
import { VaultScanResults } from "../services/base/VaultScanResult.js";
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
if (value.startsWith(ICHeader)) return MetadataDocumentNamespaces.INTERNAL;
|
|
49
|
-
if (value.startsWith(PSCHeader)) return MetadataDocumentNamespaces.PLUGIN_STORAGE;
|
|
50
|
-
return MetadataDocumentNamespaces.NORMAL;
|
|
51
|
-
}
|
|
52
|
-
async function inspectMetadataDocumentIdentity(host, doc) {
|
|
53
|
-
const actualDocumentId = doc._id;
|
|
54
|
-
const declaredPath = getPathFromEntry(host, doc);
|
|
55
|
-
const actualNamespace = getMetadataDocumentNamespace(actualDocumentId);
|
|
56
|
-
const declaredPathNamespace = getMetadataDocumentNamespace(declaredPath);
|
|
57
|
-
if (actualNamespace !== MetadataDocumentNamespaces.NORMAL || declaredPathNamespace !== MetadataDocumentNamespaces.NORMAL) {
|
|
58
|
-
if (actualNamespace === declaredPathNamespace) {
|
|
59
|
-
return {
|
|
60
|
-
status: MetadataDocumentIdentityStatuses.EXCLUDED,
|
|
61
|
-
actualDocumentId,
|
|
62
|
-
declaredPath,
|
|
63
|
-
namespace: actualNamespace
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
return {
|
|
67
|
-
status: MetadataDocumentIdentityStatuses.UNRESOLVED,
|
|
68
|
-
diagnostic: {
|
|
69
|
-
reason: OfflineScanUnresolvedReasons.NAMESPACE_MISMATCH,
|
|
70
|
-
actualDocumentId,
|
|
71
|
-
declaredPath,
|
|
72
|
-
actualNamespace,
|
|
73
|
-
declaredPathNamespace
|
|
74
|
-
}
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
const expectedDocumentId = await host.services.path.path2id(declaredPath);
|
|
78
|
-
if (actualDocumentId !== expectedDocumentId) {
|
|
79
|
-
return {
|
|
80
|
-
status: MetadataDocumentIdentityStatuses.UNRESOLVED,
|
|
81
|
-
diagnostic: {
|
|
82
|
-
reason: OfflineScanUnresolvedReasons.DOCUMENT_ID_MISMATCH,
|
|
83
|
-
actualDocumentId,
|
|
84
|
-
declaredPath,
|
|
85
|
-
expectedDocumentId,
|
|
86
|
-
actualNamespace,
|
|
87
|
-
declaredPathNamespace
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
return {
|
|
92
|
-
status: MetadataDocumentIdentityStatuses.CONSISTENT,
|
|
93
|
-
actualDocumentId,
|
|
94
|
-
declaredPath,
|
|
95
|
-
expectedDocumentId
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
function stableValue(value) {
|
|
99
|
-
if (Array.isArray(value)) return value.map(stableValue);
|
|
100
|
-
if (value === null || typeof value !== "object") return value;
|
|
101
|
-
return Object.fromEntries(
|
|
102
|
-
Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, stableValue(item)])
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
function logicalMetadataPayload(doc) {
|
|
106
|
-
return stableValue({
|
|
107
|
-
path: doc.path,
|
|
108
|
-
ctime: doc.ctime,
|
|
109
|
-
mtime: doc.mtime,
|
|
110
|
-
size: doc.size,
|
|
111
|
-
type: doc.type,
|
|
112
|
-
children: [...doc.children],
|
|
113
|
-
eden: doc.eden ?? {},
|
|
114
|
-
deleted: Boolean(doc.deleted || doc._deleted)
|
|
115
|
-
});
|
|
116
|
-
}
|
|
117
|
-
function isExactMetadataCopy(source, target) {
|
|
118
|
-
return JSON.stringify(logicalMetadataPayload(source)) === JSON.stringify(logicalMetadataPayload(target));
|
|
119
|
-
}
|
|
120
|
-
async function inspectMetadataDocumentIdentities(host) {
|
|
121
|
-
const observations = [];
|
|
122
|
-
for await (const doc of host.services.database.localDatabase.findAllNormalDocs({ conflicts: true }) || []) {
|
|
123
|
-
if (!isMetaEntry(doc)) continue;
|
|
124
|
-
const inspection = await inspectMetadataDocumentIdentity(host, doc);
|
|
125
|
-
observations.push({ doc, inspection });
|
|
126
|
-
}
|
|
127
|
-
const expectedTargetIds = unique(
|
|
128
|
-
observations.flatMap(({ inspection }) => {
|
|
129
|
-
if (inspection.status !== MetadataDocumentIdentityStatuses.UNRESOLVED) return [];
|
|
130
|
-
const { diagnostic } = inspection;
|
|
131
|
-
if (diagnostic.reason !== OfflineScanUnresolvedReasons.DOCUMENT_ID_MISMATCH || diagnostic.expectedDocumentId === void 0) {
|
|
132
|
-
return [];
|
|
133
|
-
}
|
|
134
|
-
return [diagnostic.expectedDocumentId];
|
|
135
|
-
})
|
|
136
|
-
);
|
|
137
|
-
const targetRows = /* @__PURE__ */ new Map();
|
|
138
|
-
if (expectedTargetIds.length > 0) {
|
|
139
|
-
const result = await host.services.database.localDatabase.allDocsRaw({
|
|
140
|
-
keys: expectedTargetIds,
|
|
141
|
-
include_docs: true,
|
|
142
|
-
conflicts: true
|
|
143
|
-
});
|
|
144
|
-
for (const row of result.rows) targetRows.set(row.key, row);
|
|
145
|
-
}
|
|
146
|
-
const settings = host.services.setting.currentSettings();
|
|
147
|
-
const observationsByDocumentId = new Map(observations.map((observation) => [observation.doc._id, observation]));
|
|
148
|
-
const pathClaims = /* @__PURE__ */ new Map();
|
|
149
|
-
const targetClaims = /* @__PURE__ */ new Map();
|
|
150
|
-
for (const { doc, inspection } of observations) {
|
|
151
|
-
const declaredPath = inspection.status === MetadataDocumentIdentityStatuses.UNRESOLVED ? inspection.diagnostic.declaredPath : inspection.declaredPath;
|
|
152
|
-
const declaredNamespace = getMetadataDocumentNamespace(declaredPath);
|
|
153
|
-
if (declaredNamespace === MetadataDocumentNamespaces.NORMAL) {
|
|
154
|
-
const key = convertCase(settings, declaredPath);
|
|
155
|
-
const claims = pathClaims.get(key) ?? /* @__PURE__ */ new Set();
|
|
156
|
-
claims.add(doc._id);
|
|
157
|
-
pathClaims.set(key, claims);
|
|
158
|
-
}
|
|
159
|
-
if (inspection.status === MetadataDocumentIdentityStatuses.UNRESOLVED && inspection.diagnostic.reason === OfflineScanUnresolvedReasons.DOCUMENT_ID_MISMATCH && inspection.diagnostic.expectedDocumentId !== void 0) {
|
|
160
|
-
const claims = targetClaims.get(inspection.diagnostic.expectedDocumentId) ?? /* @__PURE__ */ new Set();
|
|
161
|
-
claims.add(doc._id);
|
|
162
|
-
targetClaims.set(inspection.diagnostic.expectedDocumentId, claims);
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
const entries = [];
|
|
166
|
-
for (const { doc, inspection } of observations) {
|
|
167
|
-
if (inspection.status !== MetadataDocumentIdentityStatuses.UNRESOLVED) continue;
|
|
168
|
-
const { diagnostic } = inspection;
|
|
169
|
-
let repairAvailable = false;
|
|
170
|
-
let targetAlreadyPresent = false;
|
|
171
|
-
let ordinaryPathAvailable = false;
|
|
172
|
-
if (diagnostic.reason === OfflineScanUnresolvedReasons.DOCUMENT_ID_MISMATCH && diagnostic.expectedDocumentId !== void 0) {
|
|
173
|
-
const expectedDocumentId = diagnostic.expectedDocumentId;
|
|
174
|
-
const normalisedPath = convertCase(settings, diagnostic.declaredPath);
|
|
175
|
-
const targetObservation = observationsByDocumentId.get(expectedDocumentId);
|
|
176
|
-
const targetPath = targetObservation?.inspection.status === MetadataDocumentIdentityStatuses.CONSISTENT ? targetObservation.inspection.declaredPath : void 0;
|
|
177
|
-
ordinaryPathAvailable = targetPath !== void 0 && convertCase(settings, targetPath) === normalisedPath && host.services.vault.isValidPath(targetPath) && !shouldBeIgnored(targetPath) && await host.services.vault.isTargetFile(targetPath);
|
|
178
|
-
const row = targetRows.get(expectedDocumentId);
|
|
179
|
-
const target = row?.doc;
|
|
180
|
-
const targetMetadata = target && isMetaEntry(target) ? target : void 0;
|
|
181
|
-
targetAlreadyPresent = Boolean(targetMetadata && isExactMetadataCopy(doc, targetMetadata));
|
|
182
|
-
const targetIsAvailable = !row || row.error === "not_found" || targetAlreadyPresent && !row?.value?.deleted && !targetMetadata?._deleted && !targetMetadata?.deleted && (targetMetadata?._conflicts?.length ?? 0) === 0;
|
|
183
|
-
const samePathClaims = pathClaims.get(normalisedPath) ?? /* @__PURE__ */ new Set();
|
|
184
|
-
const permittedExactPair = targetAlreadyPresent && samePathClaims.size === 2 && samePathClaims.has(doc._id) && samePathClaims.has(expectedDocumentId);
|
|
185
|
-
const pathIsUnambiguous = samePathClaims.size === 1 || permittedExactPair;
|
|
186
|
-
const targetIsUnambiguous = (targetClaims.get(expectedDocumentId)?.size ?? 0) === 1;
|
|
187
|
-
repairAvailable = Boolean(doc._rev) && !doc.deleted && !doc._deleted && (doc._conflicts?.length ?? 0) === 0 && host.services.vault.isValidPath(diagnostic.declaredPath) && await host.services.vault.isTargetFile(diagnostic.declaredPath) && pathIsUnambiguous && targetIsUnambiguous && targetIsAvailable;
|
|
188
|
-
}
|
|
189
|
-
entries.push({
|
|
190
|
-
inspection,
|
|
191
|
-
sourceRevision: doc._rev ?? null,
|
|
192
|
-
logicallyDeleted: Boolean(doc.deleted || doc._deleted),
|
|
193
|
-
conflictRevisions: [...doc._conflicts ?? []],
|
|
194
|
-
repairAvailable,
|
|
195
|
-
targetAlreadyPresent,
|
|
196
|
-
ordinaryPathAvailable
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
return entries;
|
|
200
|
-
}
|
|
201
|
-
function cloneEden(eden) {
|
|
202
|
-
return Object.fromEntries(
|
|
203
|
-
Object.entries(eden ?? {}).map(([id, chunk]) => [id, { data: chunk.data, epoch: chunk.epoch }])
|
|
204
|
-
);
|
|
205
|
-
}
|
|
206
|
-
function createReaddressedMetadata(source, expectedDocumentId) {
|
|
207
|
-
return {
|
|
208
|
-
_id: expectedDocumentId,
|
|
209
|
-
path: source.path,
|
|
210
|
-
ctime: source.ctime,
|
|
211
|
-
mtime: source.mtime,
|
|
212
|
-
size: source.size,
|
|
213
|
-
type: source.type,
|
|
214
|
-
children: [...source.children],
|
|
215
|
-
eden: cloneEden(source.eden),
|
|
216
|
-
...source.deleted === void 0 ? {} : { deleted: source.deleted }
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
async function serializedByMetadataDocumentIds(documentIds, callback) {
|
|
220
|
-
const lockKeys = [...new Set(documentIds)].sort().map((documentId) => `processFileEvent-${documentId}`);
|
|
221
|
-
return await withLocks(lockKeys, callback);
|
|
222
|
-
}
|
|
223
|
-
function findRepairEntry(entries, actualDocumentId) {
|
|
224
|
-
return entries.find(({ inspection }) => inspection.diagnostic.actualDocumentId === actualDocumentId);
|
|
225
|
-
}
|
|
226
|
-
async function repairMetadataDocumentIdentity(host, request) {
|
|
227
|
-
const baseResult = {
|
|
228
|
-
actualDocumentId: request.actualDocumentId,
|
|
229
|
-
expectedDocumentId: request.expectedDocumentId,
|
|
230
|
-
sourceRevision: request.sourceRevision,
|
|
231
|
-
targetCreated: false
|
|
232
|
-
};
|
|
233
|
-
return await serializedByMetadataDocumentIds(
|
|
234
|
-
[request.actualDocumentId, request.expectedDocumentId],
|
|
235
|
-
async () => {
|
|
236
|
-
let targetCreated = false;
|
|
237
|
-
try {
|
|
238
|
-
const entries = await inspectMetadataDocumentIdentities(host);
|
|
239
|
-
const entry = findRepairEntry(entries, request.actualDocumentId);
|
|
240
|
-
if (!entry || entry.sourceRevision !== request.sourceRevision || entry.inspection.diagnostic.reason !== OfflineScanUnresolvedReasons.DOCUMENT_ID_MISMATCH || entry.inspection.diagnostic.expectedDocumentId !== request.expectedDocumentId) {
|
|
241
|
-
return {
|
|
242
|
-
...baseResult,
|
|
243
|
-
status: MetadataDocumentRepairResults.STALE,
|
|
244
|
-
message: "The inspected source revision or expected document ID has changed."
|
|
245
|
-
};
|
|
246
|
-
}
|
|
247
|
-
if (!entry.repairAvailable) {
|
|
248
|
-
return {
|
|
249
|
-
...baseResult,
|
|
250
|
-
status: MetadataDocumentRepairResults.BLOCKED,
|
|
251
|
-
message: "The source no longer satisfies the repair preconditions."
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
const source = await host.services.database.localDatabase.getRaw(request.actualDocumentId, {
|
|
255
|
-
rev: request.sourceRevision,
|
|
256
|
-
conflicts: true
|
|
257
|
-
});
|
|
258
|
-
if (!isMetaEntry(source) || source._rev !== request.sourceRevision) {
|
|
259
|
-
return {
|
|
260
|
-
...baseResult,
|
|
261
|
-
status: MetadataDocumentRepairResults.STALE,
|
|
262
|
-
message: "The source revision changed during repair validation."
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
await clearOfflineScannerLastSeen(host, entry.inspection.diagnostic.declaredPath);
|
|
266
|
-
if (!entry.targetAlreadyPresent) {
|
|
267
|
-
await host.services.database.localDatabase.putRaw(
|
|
268
|
-
createReaddressedMetadata(source, request.expectedDocumentId)
|
|
269
|
-
);
|
|
270
|
-
targetCreated = true;
|
|
271
|
-
}
|
|
272
|
-
const target = await host.services.database.localDatabase.getRaw(
|
|
273
|
-
request.expectedDocumentId,
|
|
274
|
-
{ conflicts: true }
|
|
275
|
-
);
|
|
276
|
-
if (!isMetaEntry(target) || target.deleted || target._deleted || (target._conflicts?.length ?? 0) > 0 || !isExactMetadataCopy(source, target)) {
|
|
277
|
-
return {
|
|
278
|
-
...baseResult,
|
|
279
|
-
targetCreated,
|
|
280
|
-
status: MetadataDocumentRepairResults.FAILED,
|
|
281
|
-
message: "The repair target could not be verified as an exact local copy."
|
|
282
|
-
};
|
|
283
|
-
}
|
|
284
|
-
await host.services.database.localDatabase.removeRaw(request.actualDocumentId, request.sourceRevision);
|
|
285
|
-
return {
|
|
286
|
-
...baseResult,
|
|
287
|
-
targetCreated,
|
|
288
|
-
status: MetadataDocumentRepairResults.COMPLETED
|
|
289
|
-
};
|
|
290
|
-
} catch (error) {
|
|
291
|
-
return {
|
|
292
|
-
...baseResult,
|
|
293
|
-
targetCreated,
|
|
294
|
-
status: MetadataDocumentRepairResults.FAILED,
|
|
295
|
-
message: error instanceof Error ? error.message : `${error}`
|
|
296
|
-
};
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
);
|
|
300
|
-
}
|
|
301
|
-
async function collectDeletedFiles(host, log) {
|
|
302
|
-
const limitDays = host.services.setting.currentSettings().automaticallyDeleteMetadataOfDeletedFiles;
|
|
303
|
-
if (limitDays <= 0) return;
|
|
304
|
-
log(`Checking expired file history`);
|
|
305
|
-
const limit = Date.now() - 86400 * 1e3 * limitDays;
|
|
306
|
-
const notes = [];
|
|
307
|
-
for await (const doc of host.services.database.localDatabase.findAllDocs({ conflicts: true })) {
|
|
308
|
-
if (isAnyNote(doc)) {
|
|
309
|
-
if (doc.deleted && doc.mtime - limit < 0) {
|
|
310
|
-
if (isMetaEntry(doc)) {
|
|
311
|
-
const identity = await inspectMetadataDocumentIdentity(host, doc);
|
|
312
|
-
if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
|
|
313
|
-
log(
|
|
314
|
-
`Expired deletion history has an unresolved Metadata identity and will be left unchanged: ${identity.diagnostic.declaredPath} (${identity.diagnostic.reason})`,
|
|
315
|
-
LOG_LEVEL_INFO
|
|
316
|
-
);
|
|
317
|
-
continue;
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
notes.push({
|
|
321
|
-
path: doc.path,
|
|
322
|
-
mtime: doc.mtime,
|
|
323
|
-
ttl: (doc.mtime - limit) / 1e3 / 86400,
|
|
324
|
-
doc
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
if (notes.length === 0) {
|
|
330
|
-
log("There are no old documents");
|
|
331
|
-
log(`Checking expired file history done`);
|
|
332
|
-
return;
|
|
333
|
-
}
|
|
334
|
-
for (const v of notes) {
|
|
335
|
-
log(`Deletion history expired: ${v.path}`);
|
|
336
|
-
const delDoc = v.doc;
|
|
337
|
-
delDoc._deleted = true;
|
|
338
|
-
await host.services.database.localDatabase.putRaw(delDoc);
|
|
339
|
-
}
|
|
340
|
-
log(`Checking expired file history done`);
|
|
341
|
-
}
|
|
342
|
-
function getPathFromEntry(host, doc) {
|
|
343
|
-
const path = host.services.path.getPath(doc);
|
|
344
|
-
return path;
|
|
345
|
-
}
|
|
346
|
-
async function syncFileBetweenDBandStorage(host, log, file, doc, scanOptions) {
|
|
347
|
-
const docPath = getPathFromEntry(host, doc);
|
|
348
|
-
if (!doc) {
|
|
349
|
-
throw new Error(`Missing doc:${docPath}`);
|
|
350
|
-
}
|
|
351
|
-
const compareResult = host.services.path.compareFileFreshness(file, doc);
|
|
352
|
-
switch (compareResult) {
|
|
353
|
-
case BASE_IS_NEW:
|
|
354
|
-
if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
|
|
355
|
-
log("STORAGE -> DB :" + file.path);
|
|
356
|
-
return await host.serviceModules.fileHandler.storeFileToDB(file) ? FilePairProcessResults.COMPLETED : FilePairProcessResults.FAILED;
|
|
357
|
-
} else {
|
|
358
|
-
log(
|
|
359
|
-
`STORAGE -> DB : ${file.path} has been skipped due to file size exceeding the limit`,
|
|
360
|
-
LOG_LEVEL_NOTICE
|
|
361
|
-
);
|
|
362
|
-
return FilePairProcessResults.SKIPPED;
|
|
363
|
-
}
|
|
364
|
-
case TARGET_IS_NEW:
|
|
365
|
-
if (!host.services.vault.isFileSizeTooLarge(doc.size)) {
|
|
366
|
-
log("STORAGE <- DB :" + docPath);
|
|
367
|
-
if (await host.serviceModules.fileHandler.dbToStorage(doc, stripAllPrefixes(docPath), false)) {
|
|
368
|
-
host.services.context.events.emitEvent("event-file-changed", {
|
|
369
|
-
file: file.path,
|
|
370
|
-
automated: true
|
|
371
|
-
});
|
|
372
|
-
return FilePairProcessResults.COMPLETED;
|
|
373
|
-
} else {
|
|
374
|
-
log(`STORAGE <- DB : Cloud not read ${file.path}, possibly deleted`, LOG_LEVEL_NOTICE);
|
|
375
|
-
return FilePairProcessResults.FAILED;
|
|
376
|
-
}
|
|
377
|
-
} else {
|
|
378
|
-
log(
|
|
379
|
-
`STORAGE <- DB : ${file.path} has been skipped due to file size exceeding the limit`,
|
|
380
|
-
LOG_LEVEL_NOTICE
|
|
381
|
-
);
|
|
382
|
-
return FilePairProcessResults.SKIPPED;
|
|
383
|
-
}
|
|
384
|
-
case EVEN:
|
|
385
|
-
if (host.services.vault.isFileSizeTooLarge(file.stat.size) || host.services.vault.isFileSizeTooLarge(doc.size)) {
|
|
386
|
-
log(`STORAGE ? DB : ${file.path} has been skipped due to file size exceeding the limit`, LOG_LEVEL_NOTICE);
|
|
387
|
-
return FilePairProcessResults.SKIPPED;
|
|
388
|
-
}
|
|
389
|
-
if (scanOptions?.strictContentCheck === false && await host.serviceModules.fileHandler.canSkipUnchangedFile?.(file, doc)) {
|
|
390
|
-
log(`STORAGE ? DB : ${file.path} skipped using unchanged storage and revision metadata`, LOG_LEVEL_DEBUG);
|
|
391
|
-
return FilePairProcessResults.SKIPPED;
|
|
392
|
-
}
|
|
393
|
-
if (doc._rev && await host.serviceModules.fileHandler.tryRecordUntrackedFileRevision(file, doc._rev)) {
|
|
394
|
-
log("STORAGE == DB :" + file.path, LOG_LEVEL_DEBUG);
|
|
395
|
-
return FilePairProcessResults.COMPLETED;
|
|
396
|
-
}
|
|
397
|
-
log("STORAGE ? DB :" + file.path + " Checking content", LOG_LEVEL_DEBUG);
|
|
398
|
-
try {
|
|
399
|
-
return await host.serviceModules.fileHandler.storeFileToDB(file, false, false, { revalidateStorage: true }) ? FilePairProcessResults.COMPLETED : FilePairProcessResults.FAILED;
|
|
400
|
-
} catch (error) {
|
|
401
|
-
log(`STORAGE ? DB : Could not reconcile ${file.path}`, LOG_LEVEL_NOTICE);
|
|
402
|
-
log(error, LOG_LEVEL_VERBOSE);
|
|
403
|
-
return FilePairProcessResults.FAILED;
|
|
404
|
-
}
|
|
405
|
-
default:
|
|
406
|
-
log("STORAGE ?? DB :" + file.path + " Something got weird");
|
|
407
|
-
return FilePairProcessResults.FAILED;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
9
|
+
import {
|
|
10
|
+
FilePairProcessResults,
|
|
11
|
+
MetadataDocumentNamespaces,
|
|
12
|
+
MetadataDocumentIdentityStatuses,
|
|
13
|
+
OfflineScanUnresolvedReasons,
|
|
14
|
+
MetadataDocumentRepairResults,
|
|
15
|
+
FullScanModes as FullScanModes2,
|
|
16
|
+
ExtraOnRemote,
|
|
17
|
+
ExtraOnLocal
|
|
18
|
+
} from "./offlineScanner/types.js";
|
|
19
|
+
import {
|
|
20
|
+
getMetadataDocumentNamespace,
|
|
21
|
+
inspectMetadataDocumentIdentity,
|
|
22
|
+
inspectMetadataDocumentIdentities,
|
|
23
|
+
repairMetadataDocumentIdentity,
|
|
24
|
+
collectDeletedFiles as collectDeletedFiles2
|
|
25
|
+
} from "./offlineScanner/metadata.js";
|
|
26
|
+
import { getPathFromEntry, convertCase } from "./offlineScanner/paths.js";
|
|
27
|
+
import { clearOfflineScannerLastSeen } from "./offlineScanner/fileStatus.js";
|
|
28
|
+
import {
|
|
29
|
+
syncFileBetweenDBandStorage,
|
|
30
|
+
collectFilesOnStorage,
|
|
31
|
+
collectDatabaseFiles,
|
|
32
|
+
updateToDatabase,
|
|
33
|
+
updateToStorage,
|
|
34
|
+
syncStorageAndDatabase
|
|
35
|
+
} from "./offlineScanner/files.js";
|
|
36
|
+
import { getFilePairState, resolveFilePairAction, synchroniseAllFilesBetweenDBandStorage as synchroniseAllFilesBetweenDBandStorage2 } from "./offlineScanner/scan.js";
|
|
410
37
|
function canProceedScan(host, errorManager, log, showingNotice = false, ignoreSuspending = false) {
|
|
411
38
|
const settings = host.services.setting.currentSettings();
|
|
412
39
|
const ERR_NOT_CONFIGURED = "LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.";
|
|
@@ -429,394 +56,6 @@ function canProceedScan(host, errorManager, log, showingNotice = false, ignoreSu
|
|
|
429
56
|
errorManager.clearError(MSG_IN_REMEDIATION);
|
|
430
57
|
return true;
|
|
431
58
|
}
|
|
432
|
-
function convertCase(settings, path) {
|
|
433
|
-
const normalisedPath = normalisePathForIdentity(path, getPathNormalizationVersion(settings));
|
|
434
|
-
if (settings.handleFilenameCaseSensitive) {
|
|
435
|
-
return normalisedPath;
|
|
436
|
-
}
|
|
437
|
-
return normalisedPath.toLowerCase();
|
|
438
|
-
}
|
|
439
|
-
function createComparisonPathLookup(settings, paths) {
|
|
440
|
-
return Object.fromEntries(paths.map((path) => [convertCase(settings, path), path]));
|
|
441
|
-
}
|
|
442
|
-
async function collectFilesOnStorage(host, settings, log) {
|
|
443
|
-
log("Collecting local files on the storage", LOG_LEVEL_VERBOSE);
|
|
444
|
-
const filesStorageSrc = await host.serviceModules.storageAccess.getFiles();
|
|
445
|
-
const _filesStorage = [];
|
|
446
|
-
for (const f of filesStorageSrc) {
|
|
447
|
-
if (shouldBeIgnored(f.path)) continue;
|
|
448
|
-
if (await host.services.vault.isTargetFile(f.path)) {
|
|
449
|
-
_filesStorage.push(f);
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
const storageFileNameMap = Object.fromEntries(_filesStorage.map((e) => [e.path, e]));
|
|
453
|
-
const storageFileNames = Object.keys(storageFileNameMap);
|
|
454
|
-
const storageFileNameCI2CS = createComparisonPathLookup(settings, storageFileNames);
|
|
455
|
-
return { storageFileNameMap, storageFileNames, storageFileNameCI2CS };
|
|
456
|
-
}
|
|
457
|
-
async function collectDatabaseFiles(host, settings, log, showingNotice) {
|
|
458
|
-
log("Collecting local files on the DB", LOG_LEVEL_VERBOSE);
|
|
459
|
-
const _DBEntries = [];
|
|
460
|
-
const unresolvedFileNamesLC = /* @__PURE__ */ new Set();
|
|
461
|
-
const resolvableFileNamesLC = /* @__PURE__ */ new Set();
|
|
462
|
-
let count = 0;
|
|
463
|
-
for await (const doc of host.services.database.localDatabase.findAllNormalDocs({ conflicts: true }) || []) {
|
|
464
|
-
count++;
|
|
465
|
-
if (count % 25 === 0)
|
|
466
|
-
log(
|
|
467
|
-
`Collecting local files on the DB: ${count}`,
|
|
468
|
-
showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
|
|
469
|
-
"syncAll"
|
|
470
|
-
);
|
|
471
|
-
if (!isMetaEntry(doc)) {
|
|
472
|
-
const documentId = doc._id ?? "unknown";
|
|
473
|
-
log(`Invalid Metadata entry: ${documentId}`, LOG_LEVEL_INFO);
|
|
474
|
-
continue;
|
|
475
|
-
}
|
|
476
|
-
const identity = await inspectMetadataDocumentIdentity(host, doc);
|
|
477
|
-
if (identity.status === MetadataDocumentIdentityStatuses.EXCLUDED) {
|
|
478
|
-
continue;
|
|
479
|
-
}
|
|
480
|
-
if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
|
|
481
|
-
const { diagnostic } = identity;
|
|
482
|
-
const unresolvedKey = convertCase(settings, stripAllPrefixes(diagnostic.declaredPath));
|
|
483
|
-
unresolvedFileNamesLC.add(unresolvedKey);
|
|
484
|
-
log(
|
|
485
|
-
`Metadata identity is unresolved and will be left unchanged: ${diagnostic.declaredPath} (${diagnostic.reason})`,
|
|
486
|
-
LOG_LEVEL_INFO
|
|
487
|
-
);
|
|
488
|
-
continue;
|
|
489
|
-
}
|
|
490
|
-
const path = identity.declaredPath;
|
|
491
|
-
if (host.services.vault.isValidPath(path) && !shouldBeIgnored(path) && await host.services.vault.isTargetFile(path)) {
|
|
492
|
-
_DBEntries.push(doc);
|
|
493
|
-
resolvableFileNamesLC.add(convertCase(settings, stripAllPrefixes(path)));
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
const databaseFileNameMap = Object.fromEntries(_DBEntries.map((e) => [getPathFromEntry(host, e), e]));
|
|
497
|
-
const databaseFileNames = Object.keys(databaseFileNameMap);
|
|
498
|
-
const databaseFileNameCI2CS = createComparisonPathLookup(settings, databaseFileNames);
|
|
499
|
-
const quarantinedFileNamesLC = new Set(
|
|
500
|
-
[...unresolvedFileNamesLC].filter((path) => !resolvableFileNamesLC.has(path))
|
|
501
|
-
);
|
|
502
|
-
return {
|
|
503
|
-
databaseFileNameMap,
|
|
504
|
-
databaseFileNames,
|
|
505
|
-
databaseFileNameCI2CS,
|
|
506
|
-
quarantinedFileNamesLC
|
|
507
|
-
};
|
|
508
|
-
}
|
|
509
|
-
async function updateToDatabase(host, log, logLevel, file) {
|
|
510
|
-
if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
|
|
511
|
-
const path = file.path;
|
|
512
|
-
if (!await host.serviceModules.fileHandler.storeFileToDB(file)) {
|
|
513
|
-
return FilePairProcessResults.FAILED;
|
|
514
|
-
}
|
|
515
|
-
host.services.context.events.emitEvent("event-file-changed", { file: path, automated: true });
|
|
516
|
-
return FilePairProcessResults.COMPLETED;
|
|
517
|
-
} else {
|
|
518
|
-
log(`UPDATE DATABASE: ${file.path} has been skipped due to file size exceeding the limit`, logLevel);
|
|
519
|
-
return FilePairProcessResults.SKIPPED;
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
async function updateToStorage(host, log, logLevel, w) {
|
|
523
|
-
const path = getPathFromEntry(host, w);
|
|
524
|
-
if (w && !(w.deleted || w._deleted)) {
|
|
525
|
-
if (!host.services.vault.isFileSizeTooLarge(w.size)) {
|
|
526
|
-
if ((w._conflicts?.length ?? 0) > 0) {
|
|
527
|
-
log(`UPDATE STORAGE: ${path} has conflicts. skipped (x)`, LOG_LEVEL_INFO);
|
|
528
|
-
return FilePairProcessResults.SKIPPED;
|
|
529
|
-
}
|
|
530
|
-
const reflected = await host.serviceModules.fileHandler.dbToStorage(path, null, true);
|
|
531
|
-
if (!reflected) return FilePairProcessResults.FAILED;
|
|
532
|
-
host.services.context.events.emitEvent("event-file-changed", {
|
|
533
|
-
file: path,
|
|
534
|
-
automated: true
|
|
535
|
-
});
|
|
536
|
-
log(`Check or pull from db:${path} OK`);
|
|
537
|
-
return FilePairProcessResults.COMPLETED;
|
|
538
|
-
} else {
|
|
539
|
-
log(`UPDATE STORAGE: ${path} has been skipped due to file size exceeding the limit`, logLevel);
|
|
540
|
-
return FilePairProcessResults.SKIPPED;
|
|
541
|
-
}
|
|
542
|
-
} else if (w) {
|
|
543
|
-
log(`Deletion history skipped: ${path}`, LOG_LEVEL_VERBOSE);
|
|
544
|
-
return FilePairProcessResults.SKIPPED;
|
|
545
|
-
} else {
|
|
546
|
-
log(`entry not found: ${path}`);
|
|
547
|
-
return FilePairProcessResults.FAILED;
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
async function syncStorageAndDatabase(host, log, file, logLevel, doc, scanOptions) {
|
|
551
|
-
if ((doc._conflicts?.length ?? 0) > 0) {
|
|
552
|
-
log(`SYNC DATABASE AND STORAGE: ${file.path} has conflicts. skipped`, LOG_LEVEL_INFO);
|
|
553
|
-
return FilePairProcessResults.SKIPPED;
|
|
554
|
-
}
|
|
555
|
-
if (!host.services.vault.isFileSizeTooLarge(file.stat.size) && !host.services.vault.isFileSizeTooLarge(doc.size)) {
|
|
556
|
-
return await syncFileBetweenDBandStorage(host, log, file, doc, scanOptions);
|
|
557
|
-
} else {
|
|
558
|
-
log(
|
|
559
|
-
`SYNC DATABASE AND STORAGE: ${getPathFromEntry(host, doc)} has been skipped due to file size exceeding the limit`,
|
|
560
|
-
logLevel
|
|
561
|
-
);
|
|
562
|
-
return FilePairProcessResults.SKIPPED;
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
const FullScanModes = {
|
|
566
|
-
// SAFE: "safe",
|
|
567
|
-
DB_APPLY: "db-apply",
|
|
568
|
-
NEWER_WINS: "newer-wins"
|
|
569
|
-
// STORAGE_ONLY: "local-only",
|
|
570
|
-
};
|
|
571
|
-
const ExtraOnRemote = {
|
|
572
|
-
/**
|
|
573
|
-
* Delete database entries if they are missing on storage.
|
|
574
|
-
*/
|
|
575
|
-
DELETE_LOCAL_MISSING: "delete-local-missing"
|
|
576
|
-
/**
|
|
577
|
-
* Apply changes from database to storage.
|
|
578
|
-
*/
|
|
579
|
-
// APPEND_DB_ONLY: "append-db-only",
|
|
580
|
-
};
|
|
581
|
-
const ExtraOnLocal = {
|
|
582
|
-
/**
|
|
583
|
-
* Delete local files if they were deleted on database.
|
|
584
|
-
*/
|
|
585
|
-
DELETE_DB_DELETED: "delete-db-deleted",
|
|
586
|
-
/**
|
|
587
|
-
* Delete local files if they are missing on database or were deleted on database.
|
|
588
|
-
*/
|
|
589
|
-
DELETE_DB_MISSING: "delete-db-missing",
|
|
590
|
-
/**
|
|
591
|
-
* Merge local files to database
|
|
592
|
-
*/
|
|
593
|
-
APPEND_STORAGE_ONLY: "append-storage-only"
|
|
594
|
-
};
|
|
595
|
-
function isDeletedEntry(entry) {
|
|
596
|
-
return entry.deleted || entry._deleted || false;
|
|
597
|
-
}
|
|
598
|
-
function getFilePairState(pair) {
|
|
599
|
-
const { file, doc } = pair;
|
|
600
|
-
if (file && doc) {
|
|
601
|
-
return isDeletedEntry(doc) ? "both-db-deleted" : "both";
|
|
602
|
-
}
|
|
603
|
-
if (file) {
|
|
604
|
-
return "storage-only";
|
|
605
|
-
}
|
|
606
|
-
if (doc) {
|
|
607
|
-
return isDeletedEntry(doc) ? "db-only-deleted" : "db-only";
|
|
608
|
-
}
|
|
609
|
-
throw new Error("Corrupted file pair");
|
|
610
|
-
}
|
|
611
|
-
function shouldDeleteLocalWhenRemoteMissing(options) {
|
|
612
|
-
return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
|
|
613
|
-
}
|
|
614
|
-
function shouldDeleteLocalWhenRemoteDeleted(options) {
|
|
615
|
-
return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_DELETED || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
|
|
616
|
-
}
|
|
617
|
-
function resolveFilePairAction(state, options) {
|
|
618
|
-
switch (options.mode) {
|
|
619
|
-
case FullScanModes.DB_APPLY:
|
|
620
|
-
switch (state) {
|
|
621
|
-
case "both":
|
|
622
|
-
case "db-only":
|
|
623
|
-
return "update-storage";
|
|
624
|
-
case "storage-only":
|
|
625
|
-
return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "skip";
|
|
626
|
-
case "both-db-deleted":
|
|
627
|
-
return shouldDeleteLocalWhenRemoteDeleted(options) ? "delete-local" : "skip";
|
|
628
|
-
case "db-only-deleted":
|
|
629
|
-
return "skip";
|
|
630
|
-
}
|
|
631
|
-
break;
|
|
632
|
-
case FullScanModes.NEWER_WINS:
|
|
633
|
-
switch (state) {
|
|
634
|
-
case "both":
|
|
635
|
-
return "sync-newer";
|
|
636
|
-
case "storage-only":
|
|
637
|
-
return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "update-db";
|
|
638
|
-
case "db-only":
|
|
639
|
-
return "update-storage";
|
|
640
|
-
case "both-db-deleted":
|
|
641
|
-
if (shouldDeleteLocalWhenRemoteDeleted(options)) {
|
|
642
|
-
return "delete-local";
|
|
643
|
-
}
|
|
644
|
-
return options.extraOnLocal === ExtraOnLocal.APPEND_STORAGE_ONLY ? "update-db" : "skip";
|
|
645
|
-
case "db-only-deleted":
|
|
646
|
-
return "skip";
|
|
647
|
-
}
|
|
648
|
-
break;
|
|
649
|
-
}
|
|
650
|
-
return "skip";
|
|
651
|
-
}
|
|
652
|
-
async function processFilePair(host, log, pair, options) {
|
|
653
|
-
const { file, doc } = pair;
|
|
654
|
-
const canonicalPath = doc ? getPathFromEntry(host, doc) : file?.path;
|
|
655
|
-
if (!canonicalPath) {
|
|
656
|
-
throw new Error("Corrupted file pair");
|
|
657
|
-
}
|
|
658
|
-
const path = canonicalPath;
|
|
659
|
-
const fileMapKey = convertCase(host.services.setting.currentSettings(), canonicalPath);
|
|
660
|
-
if (file) {
|
|
661
|
-
updateFileMTimeInMap(host, fileMapKey, file.stat.mtime);
|
|
662
|
-
}
|
|
663
|
-
if (doc && (doc._conflicts?.length ?? 0) > 0) {
|
|
664
|
-
log(`SKIP ${options.mode}: ${path} has conflicts`, LOG_LEVEL_INFO);
|
|
665
|
-
return FilePairProcessResults.SKIPPED;
|
|
666
|
-
}
|
|
667
|
-
const state = getFilePairState(pair);
|
|
668
|
-
let action = resolveFilePairAction(state, options);
|
|
669
|
-
if (options.mode === FullScanModes.NEWER_WINS && state === "db-only" && doc) {
|
|
670
|
-
const lastSeenMTime = getFileMTimeFromMap(fileMapKey);
|
|
671
|
-
if (lastSeenMTime !== void 0) {
|
|
672
|
-
const recency = compareMTime(lastSeenMTime, doc.mtime);
|
|
673
|
-
if (recency === BASE_IS_NEW || recency === EVEN) {
|
|
674
|
-
action = "delete-db";
|
|
675
|
-
log(`NEWER_WINS: Treating missing local file as deletion (${path})`, LOG_LEVEL_VERBOSE);
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
try {
|
|
680
|
-
switch (action) {
|
|
681
|
-
case "update-db":
|
|
682
|
-
if (!file) {
|
|
683
|
-
throw new Error(`Missing storage file for ${path}`);
|
|
684
|
-
}
|
|
685
|
-
return await updateToDatabase(host, log, LOG_LEVEL_INFO, file);
|
|
686
|
-
case "update-storage":
|
|
687
|
-
if (!doc) {
|
|
688
|
-
throw new Error(`Missing database entry for ${path}`);
|
|
689
|
-
}
|
|
690
|
-
const updateStorageResult = await updateToStorage(host, log, LOG_LEVEL_INFO, doc);
|
|
691
|
-
if (updateStorageResult === FilePairProcessResults.COMPLETED) {
|
|
692
|
-
updateFileMTimeInMap(host, fileMapKey, doc.mtime);
|
|
693
|
-
}
|
|
694
|
-
return updateStorageResult;
|
|
695
|
-
case "sync-newer":
|
|
696
|
-
if (!file || !doc) {
|
|
697
|
-
throw new Error(`Cannot compare freshness for ${path}`);
|
|
698
|
-
}
|
|
699
|
-
const syncResult = await syncStorageAndDatabase(host, log, file, LOG_LEVEL_INFO, doc, options);
|
|
700
|
-
if (syncResult === FilePairProcessResults.COMPLETED) {
|
|
701
|
-
updateFileMTimeInMap(host, fileMapKey, Math.max(file.stat.mtime, doc.mtime));
|
|
702
|
-
}
|
|
703
|
-
return syncResult;
|
|
704
|
-
case "delete-local":
|
|
705
|
-
if (!file) {
|
|
706
|
-
log(`DELETE LOCAL: ${path} is already absent from storage`, LOG_LEVEL_VERBOSE);
|
|
707
|
-
return FilePairProcessResults.COMPLETED;
|
|
708
|
-
}
|
|
709
|
-
log(`DELETE LOCAL: ${file.path}`, LOG_LEVEL_INFO);
|
|
710
|
-
await host.serviceModules.storageAccess.delete(file.path, true);
|
|
711
|
-
fileMaps.delete(fileMapKey);
|
|
712
|
-
saveFileStatus(host);
|
|
713
|
-
return FilePairProcessResults.COMPLETED;
|
|
714
|
-
case "delete-db": {
|
|
715
|
-
if (!doc) {
|
|
716
|
-
throw new Error(`Missing database entry for ${path}`);
|
|
717
|
-
}
|
|
718
|
-
log(`DELETE DATABASE: ${path}`, LOG_LEVEL_INFO);
|
|
719
|
-
const dbDeleted = await host.serviceModules.fileHandler.deleteFileFromDB(stripAllPrefixes(path));
|
|
720
|
-
if (dbDeleted) {
|
|
721
|
-
fileMaps.delete(fileMapKey);
|
|
722
|
-
saveFileStatus(host);
|
|
723
|
-
return FilePairProcessResults.COMPLETED;
|
|
724
|
-
} else {
|
|
725
|
-
log(
|
|
726
|
-
`DELETE DATABASE did not delete ${path}; keeping last-seen record to avoid resurrecting the file`,
|
|
727
|
-
LOG_LEVEL_NOTICE
|
|
728
|
-
);
|
|
729
|
-
return FilePairProcessResults.FAILED;
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
case "skip":
|
|
733
|
-
log(`SKIP ${options.mode}: ${path} (${state})`, LOG_LEVEL_VERBOSE);
|
|
734
|
-
return FilePairProcessResults.SKIPPED;
|
|
735
|
-
}
|
|
736
|
-
} catch (ex) {
|
|
737
|
-
log(`Error processing ${path} with action ${action}`, LOG_LEVEL_NOTICE);
|
|
738
|
-
log(ex, LOG_LEVEL_VERBOSE);
|
|
739
|
-
return FilePairProcessResults.FAILED;
|
|
740
|
-
}
|
|
741
|
-
}
|
|
742
|
-
async function synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options) {
|
|
743
|
-
const settings = host.services.setting.currentSettings();
|
|
744
|
-
const showingNotice = options.showingNotice ?? false;
|
|
745
|
-
await loadFileStatus(host);
|
|
746
|
-
const { storageFileNameMap, storageFileNameCI2CS } = await collectFilesOnStorage(host, settings, log);
|
|
747
|
-
const { databaseFileNameMap, databaseFileNameCI2CS, quarantinedFileNamesLC } = await collectDatabaseFiles(
|
|
748
|
-
host,
|
|
749
|
-
settings,
|
|
750
|
-
log,
|
|
751
|
-
showingNotice
|
|
752
|
-
);
|
|
753
|
-
const pairs = [];
|
|
754
|
-
for (const fileNameLC of unique([
|
|
755
|
-
...Object.keys(storageFileNameCI2CS),
|
|
756
|
-
...Object.keys(databaseFileNameCI2CS)
|
|
757
|
-
])) {
|
|
758
|
-
if (quarantinedFileNamesLC.has(fileNameLC)) {
|
|
759
|
-
continue;
|
|
760
|
-
}
|
|
761
|
-
const fileName = fileNameLC in storageFileNameCI2CS ? storageFileNameCI2CS[fileNameLC] : void 0;
|
|
762
|
-
const file = fileName ? storageFileNameMap[fileName] : void 0;
|
|
763
|
-
const databaseName = fileNameLC in databaseFileNameCI2CS ? databaseFileNameCI2CS[fileNameLC] : void 0;
|
|
764
|
-
const doc = databaseName ? databaseFileNameMap[databaseName] : void 0;
|
|
765
|
-
const pair = { file, doc };
|
|
766
|
-
pairs.push(pair);
|
|
767
|
-
}
|
|
768
|
-
log(`Total files to synchronise: ${pairs.length}`, LOG_LEVEL_VERBOSE, "syncAll");
|
|
769
|
-
let completedCount = 0;
|
|
770
|
-
let skippedCount = 0;
|
|
771
|
-
let failedCount = 0;
|
|
772
|
-
let processedCount = 0;
|
|
773
|
-
for await (const { path, result } of withConcurrency(
|
|
774
|
-
pairs,
|
|
775
|
-
async (e) => {
|
|
776
|
-
const path2 = e.file?.path ?? getPathFromEntry(host, e.doc);
|
|
777
|
-
try {
|
|
778
|
-
return { path: path2, result: await processFilePair(host, log, e, options) };
|
|
779
|
-
} catch (ex) {
|
|
780
|
-
log(`Error while synchronising files`, LOG_LEVEL_NOTICE);
|
|
781
|
-
log(ex, LOG_LEVEL_VERBOSE);
|
|
782
|
-
return { path: path2, result: FilePairProcessResults.FAILED };
|
|
783
|
-
}
|
|
784
|
-
},
|
|
785
|
-
10
|
|
786
|
-
)) {
|
|
787
|
-
processedCount++;
|
|
788
|
-
switch (result) {
|
|
789
|
-
case FilePairProcessResults.COMPLETED:
|
|
790
|
-
completedCount++;
|
|
791
|
-
break;
|
|
792
|
-
case FilePairProcessResults.SKIPPED:
|
|
793
|
-
skippedCount++;
|
|
794
|
-
break;
|
|
795
|
-
case FilePairProcessResults.FAILED:
|
|
796
|
-
failedCount++;
|
|
797
|
-
log(
|
|
798
|
-
`Offline scan failed to synchronise ${path} between storage and the local database; this path remains eligible for a later scan.`,
|
|
799
|
-
LOG_LEVEL_VERBOSE
|
|
800
|
-
);
|
|
801
|
-
break;
|
|
802
|
-
}
|
|
803
|
-
if (processedCount % 25 === 0) {
|
|
804
|
-
log(
|
|
805
|
-
`Processing: ${processedCount}/${pairs.length}`,
|
|
806
|
-
showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
|
|
807
|
-
"syncAll"
|
|
808
|
-
);
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
log(
|
|
812
|
-
`Synchronisation completed: ${processedCount} files processed (${completedCount} completed, ${skippedCount} skipped, ${failedCount} failed)`,
|
|
813
|
-
showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
|
|
814
|
-
"syncAll"
|
|
815
|
-
);
|
|
816
|
-
saveFileStatus(host, true);
|
|
817
|
-
if (failedCount === 0) return VaultScanResults.COMPLETED;
|
|
818
|
-
return options.continueOnFileFailure === true ? VaultScanResults.COMPLETED_WITH_FILE_FAILURES : VaultScanResults.FAILED;
|
|
819
|
-
}
|
|
820
59
|
function normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending = false) {
|
|
821
60
|
if (typeof showingNoticeOrOptions === "object") {
|
|
822
61
|
return {
|
|
@@ -830,69 +69,6 @@ function normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending = fal
|
|
|
830
69
|
ignoreSuspending
|
|
831
70
|
};
|
|
832
71
|
}
|
|
833
|
-
let fileMaps = /* @__PURE__ */ new Map();
|
|
834
|
-
const FILE_STATUS_MAP_KEY = "fileStatusMap";
|
|
835
|
-
const FILE_STATUS_MAP_LOCK = "offlineScanner-fileStatusMap";
|
|
836
|
-
async function loadFileStatus(host) {
|
|
837
|
-
await serialized(FILE_STATUS_MAP_LOCK, async () => {
|
|
838
|
-
const kvDB = host.services.keyValueDB.kvDB;
|
|
839
|
-
if (!kvDB?.get) {
|
|
840
|
-
fileMaps = /* @__PURE__ */ new Map();
|
|
841
|
-
return;
|
|
842
|
-
}
|
|
843
|
-
const mapItems = await kvDB.get(FILE_STATUS_MAP_KEY) || {};
|
|
844
|
-
fileMaps = new Map(Object.entries(mapItems));
|
|
845
|
-
});
|
|
846
|
-
}
|
|
847
|
-
async function _saveFileStatus(host) {
|
|
848
|
-
await serialized(FILE_STATUS_MAP_LOCK, async () => {
|
|
849
|
-
const kvDB = host.services.keyValueDB.kvDB;
|
|
850
|
-
if (!kvDB?.set) {
|
|
851
|
-
return;
|
|
852
|
-
}
|
|
853
|
-
await kvDB.set(FILE_STATUS_MAP_KEY, Object.fromEntries(fileMaps));
|
|
854
|
-
});
|
|
855
|
-
}
|
|
856
|
-
async function clearOfflineScannerLastSeen(host, path) {
|
|
857
|
-
const key = convertCase(host.services.setting.currentSettings(), path);
|
|
858
|
-
if (saveFileStatusTimeout !== null) {
|
|
859
|
-
compatGlobal.clearTimeout(saveFileStatusTimeout);
|
|
860
|
-
saveFileStatusTimeout = null;
|
|
861
|
-
}
|
|
862
|
-
await serialized(FILE_STATUS_MAP_LOCK, async () => {
|
|
863
|
-
fileMaps.delete(key);
|
|
864
|
-
const kvDB = host.services.keyValueDB.kvDB;
|
|
865
|
-
if (!kvDB?.set) return;
|
|
866
|
-
const persisted = kvDB.get ? await kvDB.get(FILE_STATUS_MAP_KEY) || {} : Object.fromEntries(fileMaps);
|
|
867
|
-
const next = { ...persisted, ...Object.fromEntries(fileMaps) };
|
|
868
|
-
delete next[key];
|
|
869
|
-
await kvDB.set(FILE_STATUS_MAP_KEY, next);
|
|
870
|
-
});
|
|
871
|
-
}
|
|
872
|
-
let saveFileStatusTimeout = null;
|
|
873
|
-
function saveFileStatus(host, immediate = false) {
|
|
874
|
-
if (immediate) {
|
|
875
|
-
if (saveFileStatusTimeout !== null) compatGlobal.clearTimeout(saveFileStatusTimeout);
|
|
876
|
-
saveFileStatusTimeout = compatGlobal.setTimeout(() => {
|
|
877
|
-
saveFileStatusTimeout = null;
|
|
878
|
-
void _saveFileStatus(host);
|
|
879
|
-
}, 0);
|
|
880
|
-
return;
|
|
881
|
-
}
|
|
882
|
-
if (saveFileStatusTimeout === null) {
|
|
883
|
-
saveFileStatusTimeout = compatGlobal.setTimeout(() => {
|
|
884
|
-
saveFileStatusTimeout = null;
|
|
885
|
-
void _saveFileStatus(host);
|
|
886
|
-
}, 1e3);
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
function updateFileMTimeInMap(host, key, mtime) {
|
|
890
|
-
fileMaps.set(key, mtime);
|
|
891
|
-
saveFileStatus(host);
|
|
892
|
-
}
|
|
893
|
-
function getFileMTimeFromMap(key) {
|
|
894
|
-
return fileMaps.get(key);
|
|
895
|
-
}
|
|
896
72
|
async function performFullScan(host, log, errorManager, showingNoticeOrOptions = false, ignoreSuspending = false) {
|
|
897
73
|
const options = normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending);
|
|
898
74
|
const showingNotice = options.showingNotice ?? false;
|
|
@@ -939,7 +115,7 @@ export {
|
|
|
939
115
|
ExtraOnLocal,
|
|
940
116
|
ExtraOnRemote,
|
|
941
117
|
FilePairProcessResults,
|
|
942
|
-
FullScanModes,
|
|
118
|
+
FullScanModes2 as FullScanModes,
|
|
943
119
|
MetadataDocumentIdentityStatuses,
|
|
944
120
|
MetadataDocumentNamespaces,
|
|
945
121
|
MetadataDocumentRepairResults,
|
|
@@ -948,7 +124,7 @@ export {
|
|
|
948
124
|
canProceedScan,
|
|
949
125
|
clearOfflineScannerLastSeen,
|
|
950
126
|
collectDatabaseFiles,
|
|
951
|
-
collectDeletedFiles,
|
|
127
|
+
collectDeletedFiles2 as collectDeletedFiles,
|
|
952
128
|
collectFilesOnStorage,
|
|
953
129
|
convertCase,
|
|
954
130
|
getFilePairState,
|
|
@@ -962,7 +138,7 @@ export {
|
|
|
962
138
|
resolveFilePairAction,
|
|
963
139
|
syncFileBetweenDBandStorage,
|
|
964
140
|
syncStorageAndDatabase,
|
|
965
|
-
synchroniseAllFilesBetweenDBandStorage,
|
|
141
|
+
synchroniseAllFilesBetweenDBandStorage2 as synchroniseAllFilesBetweenDBandStorage,
|
|
966
142
|
updateToDatabase,
|
|
967
143
|
updateToStorage,
|
|
968
144
|
useOfflineScanner
|