@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.
Files changed (79) hide show
  1. package/README.md +14 -2
  2. package/dist/common/models/fileaccess.definition.d.ts +35 -0
  3. package/dist/common/models/fileaccess.definition.js +11 -0
  4. package/dist/common/typeUtils.d.ts +27 -4
  5. package/dist/interfaces/FileHandler.d.ts +60 -1
  6. package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
  7. package/dist/interfaces/FileReflectionProvenance.js +11 -1
  8. package/dist/managers/StorageEventManager/admission.d.ts +50 -0
  9. package/dist/managers/StorageEventManager/admission.js +129 -0
  10. package/dist/managers/StorageEventManager/batching.d.ts +93 -0
  11. package/dist/managers/StorageEventManager/batching.js +97 -0
  12. package/dist/managers/StorageEventManager/operations.d.ts +142 -0
  13. package/dist/managers/StorageEventManager/operations.js +69 -0
  14. package/dist/managers/StorageEventManager/processing.d.ts +63 -0
  15. package/dist/managers/StorageEventManager/processing.js +94 -0
  16. package/dist/managers/StorageEventManager/queue.d.ts +73 -0
  17. package/dist/managers/StorageEventManager/queue.js +113 -0
  18. package/dist/managers/StorageEventManager/retry.d.ts +33 -0
  19. package/dist/managers/StorageEventManager/retry.js +31 -0
  20. package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
  21. package/dist/managers/StorageEventManager/snapshot.js +53 -0
  22. package/dist/managers/StorageEventManager/state.d.ts +155 -0
  23. package/dist/managers/StorageEventManager/state.js +105 -0
  24. package/dist/managers/StorageEventManager/watching.d.ts +93 -0
  25. package/dist/managers/StorageEventManager/watching.js +36 -0
  26. package/dist/managers/StorageEventManager.d.ts +303 -83
  27. package/dist/managers/StorageEventManager.js +457 -547
  28. package/dist/serviceFeatures/offlineScanner/fileStatus.d.ts +61 -0
  29. package/dist/serviceFeatures/offlineScanner/fileStatus.js +85 -0
  30. package/dist/serviceFeatures/offlineScanner/files.d.ts +47 -0
  31. package/dist/serviceFeatures/offlineScanner/files.js +218 -0
  32. package/dist/serviceFeatures/offlineScanner/metadata.d.ts +56 -0
  33. package/dist/serviceFeatures/offlineScanner/metadata.js +320 -0
  34. package/dist/serviceFeatures/offlineScanner/paths.d.ts +20 -0
  35. package/dist/serviceFeatures/offlineScanner/paths.js +16 -0
  36. package/dist/serviceFeatures/offlineScanner/scan.d.ts +35 -0
  37. package/dist/serviceFeatures/offlineScanner/scan.js +358 -0
  38. package/dist/serviceFeatures/offlineScanner/types.d.ts +134 -0
  39. package/dist/serviceFeatures/offlineScanner/types.js +66 -0
  40. package/dist/serviceFeatures/offlineScanner.d.ts +25 -251
  41. package/dist/serviceFeatures/offlineScanner.js +36 -860
  42. package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
  43. package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
  44. package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
  45. package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
  46. package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
  47. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.d.ts +13 -0
  49. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
  51. package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
  52. package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
  53. package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
  54. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
  55. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
  56. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
  57. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
  58. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
  59. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
  60. package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
  61. package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
  62. package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
  63. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
  64. package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
  65. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
  66. package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
  67. package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
  68. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
  69. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
  70. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +141 -183
  71. package/dist/serviceModules/ServiceFileHandlerBase.js +206 -1397
  72. package/dist/services/base/KeyValueDBService.d.ts +9 -0
  73. package/dist/services/base/KeyValueDBService.js +11 -1
  74. package/docs/conflict-resolution.md +3 -1
  75. package/docs/development.md +40 -0
  76. package/docs/offline-scanner.md +26 -1
  77. package/docs/p2p-transport-lifecycle.md +8 -1
  78. package/docs/storage-events-and-reflection.md +212 -22
  79. package/package.json +1 -1
@@ -1,1471 +1,280 @@
1
- import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
2
- import { withLocks } from "octagonal-wheels/concurrency/lock";
1
+ import { createFileHandlerContext } from "./ServiceFileHandlerBase/context.js";
2
+ import { processFileEvent, processReplicatedDocument } from "./ServiceFileHandlerBase/events.js";
3
+ import { getFileEntryPath, getFileStoragePath, readStorageFile } from "./ServiceFileHandlerBase/storage.js";
4
+ import { canSkipUnchangedFile, tryRecordUntrackedFileRevision } from "./ServiceFileHandlerBase/scanning.js";
5
+ import { storeFileToDB, storeFileToDBWithBaseRevision } from "./ServiceFileHandlerBase/saving.js";
3
6
  import {
4
- createBlob,
5
- getDocDataAsArray,
6
- isDocContentSame,
7
- readContent
8
- } from "../common/utils.js";
9
- import { computeFileContentHash } from "../common/fileContentHash.js";
10
- import { EVENT_CONFLICT_CANCELLED } from "../events/coreEvents.js";
11
- import { shouldBeIgnored, stripAllPrefixes } from "../string_and_binary/path.js";
12
- import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
7
+ deleteFileFromDB,
8
+ deleteRevisionFromDB,
9
+ resolveConflictedByDeletingRevision
10
+ } from "./ServiceFileHandlerBase/deletion.js";
11
+ import { renameFileInDB } from "./ServiceFileHandlerBase/renaming.js";
12
+ import { dbToStorageWithSpecificRev, dbToStorage } from "./ServiceFileHandlerBase/reflection.js";
13
+ import { recoverDatabaseDeletion } from "./ServiceFileHandlerBase/deletionRecovery.js";
14
+ import { createAllChunks } from "./ServiceFileHandlerBase/chunks.js";
13
15
  import { ServiceModuleBase } from "./ServiceModuleBase.js";
14
- import { getStoragePathFromUXFileInfo } from "../common/typeUtils.js";
15
- import { EVEN } from "../common/models/shared.const.symbols.js";
16
- import { tryGetFilePath } from "../common/utils.doc.js";
17
- import { getPathNormalizationVersion, normalisePathForIdentity } from "../common/pathNormalization.js";
18
- function getParentPath(path) {
19
- const lastSeparator = path.lastIndexOf("/");
20
- return lastSeparator < 0 ? "" : path.slice(0, lastSeparator);
21
- }
22
- function isFolderInfo(info) {
23
- return info?.isFolder === true;
24
- }
25
- function hasContentHash(record) {
26
- return !!record && typeof record.contentHash === "string" && /^sha256:[0-9a-f]{64}$/.test(record.contentHash) && Number.isSafeInteger(record.contentSize) && record.contentSize >= 0;
27
- }
28
- function sameProvenance(left, right) {
29
- return left?.revision === right?.revision && left?.observedStorageMtime === right?.observedStorageMtime && left?.contentHash === right?.contentHash && left?.contentSize === right?.contentSize;
30
- }
16
+ import {} from "./ServiceFileHandlerBase/context.js";
31
17
  class ServiceFileHandlerBase extends ServiceModuleBase {
32
- events;
18
+ /** Database service captured at construction; the public getter remains virtual. */
33
19
  databaseFileAccess;
20
+ /** Storage service captured at construction; the public getter remains virtual. */
34
21
  storageAccess;
35
- conflict;
36
- path;
37
- setting;
38
- vault;
39
- fileReflectionProvenance;
40
- contentHashes = /* @__PURE__ */ new WeakMap();
41
- deferredConflictChecks = /* @__PURE__ */ new Map();
22
+ /** Captured services, per-instance state, and the dynamic public host boundary. */
23
+ context;
24
+ /**
25
+ * Capture services and register the existing storage and replication handlers.
26
+ * @param services - Host-owned services, copied by value into this facade and its context.
27
+ * @remarks Replication registration binds the current subclass method at construction,
28
+ * retaining the original callback capture semantics. No database or storage I/O starts here.
29
+ */
42
30
  constructor(services) {
43
31
  super(services);
44
- this.events = services.events;
45
32
  this.databaseFileAccess = services.databaseFileAccess;
46
33
  this.storageAccess = services.storageAccess;
47
- this.conflict = services.conflict;
48
- this.path = services.path;
49
- this.setting = services.setting;
50
- this.vault = services.vault;
51
- this.fileReflectionProvenance = services.fileReflectionProvenance;
52
- services.fileProcessing.processFileEvent.addHandler(this._anyHandlerProcessesFileEvent.bind(this), 100);
34
+ this.context = createFileHandlerContext(services, {
35
+ /**
36
+ * Resolve the virtual database service at its original access site.
37
+ * @returns The current database getter result.
38
+ * @remarks No service property is cached through this seam.
39
+ */
40
+ db: () => this.db,
41
+ /**
42
+ * Resolve the virtual storage service at its original access site.
43
+ * @returns The current storage getter result.
44
+ * @remarks No service property is cached through this seam.
45
+ */
46
+ storage: () => this.storage,
47
+ /**
48
+ * Deliver diagnostics through the current public logger.
49
+ * @param args - Original logging arguments, including optional key arity.
50
+ * @returns Completion without a value.
51
+ * @remarks A later logger replacement remains visible.
52
+ */
53
+ log: (...args) => this._log(...args),
54
+ /**
55
+ * Resolve the metadata path through the current host override.
56
+ * @param entry - Database metadata being processed.
57
+ * @returns The current host path.
58
+ * @remarks This does not acquire a document lock.
59
+ */
60
+ getPath: (entry) => this.getPath(entry),
61
+ /**
62
+ * Resolve the storage path through its independent host override.
63
+ * @param entry - Database metadata being processed.
64
+ * @returns The current unprefixed host path.
65
+ * @remarks The original independence from getPath is preserved.
66
+ */
67
+ getPathWithoutPrefix: (entry) => this.getPathWithoutPrefix(entry),
68
+ /**
69
+ * Acquire content through the current public reader.
70
+ * @param file - The original file observation.
71
+ * @returns Its supplied or current body.
72
+ * @remarks The caller retains its existing document lock and read count.
73
+ */
74
+ readFileFromStub: (file) => this.readFileFromStub(file),
75
+ /**
76
+ * Invoke the current public save override for chunk repair.
77
+ * @param args - Original save arguments, retaining omitted optional arguments.
78
+ * @returns The host save result.
79
+ * @remarks The public method retains document-lock ownership.
80
+ */
81
+ storeFileToDB: (...args) => this.storeFileToDB(...args)
82
+ });
83
+ services.fileProcessing.processFileEvent.addHandler((item) => processFileEvent(this.context, item), 100);
53
84
  services.replication.processSynchroniseResult.addHandler(this._anyProcessReplicatedDoc.bind(this), 100);
54
85
  }
86
+ /**
87
+ * Expose the database service captured when the facade was constructed.
88
+ * @returns The captured database access service.
89
+ * @remarks Responsibility functions resolve this virtual getter at each original access site.
90
+ */
55
91
  get db() {
56
92
  return this.databaseFileAccess;
57
93
  }
58
- get storage() {
59
- return this.storageAccess;
60
- }
61
- getProvenancePath(path) {
62
- return normalisePathForIdentity(
63
- path,
64
- getPathNormalizationVersion(this.setting.currentSettings())
65
- );
66
- }
67
- async getProvenance(path) {
68
- if (!this.fileReflectionProvenance) return void 0;
69
- try {
70
- const record = await this.fileReflectionProvenance.get(this.getProvenancePath(path));
71
- if (!record) return void 0;
72
- const entry = await this.db.fetchEntryMeta(path, record.revision, true);
73
- if (entry && !entry._deleted && !entry.deleted) {
74
- return record;
75
- }
76
- if (!hasContentHash(record)) await this.fileReflectionProvenance.delete(this.getProvenancePath(path));
77
- } catch (ex) {
78
- this._log(`Could not read file reflection provenance for ${path}`, LOG_LEVEL_VERBOSE);
79
- this._log(ex, LOG_LEVEL_VERBOSE);
80
- }
81
- return void 0;
82
- }
83
- async contentEvidence(content) {
84
- if (!this.fileReflectionProvenance) return {};
85
- try {
86
- let hash = this.contentHashes.get(content);
87
- if (!hash) {
88
- hash = computeFileContentHash(content);
89
- this.contentHashes.set(content, hash);
90
- }
91
- return { contentHash: await hash, contentSize: content.size };
92
- } catch (ex) {
93
- this.contentHashes.delete(content);
94
- this._log("Could not hash file reflection content", LOG_LEVEL_VERBOSE);
95
- this._log(ex, LOG_LEVEL_VERBOSE);
96
- return {};
97
- }
98
- }
99
- async setProvenance(path, revision, observedStorageMtime, content, evidence) {
100
- if (!this.fileReflectionProvenance || !revision) return;
101
- try {
102
- await this.fileReflectionProvenance.set(this.getProvenancePath(path), {
103
- revision,
104
- observedStorageMtime,
105
- ...evidence ?? await this.contentEvidence(content)
106
- });
107
- } catch (ex) {
108
- this._log(`Could not record file reflection provenance for ${path}`, LOG_LEVEL_VERBOSE);
109
- this._log(ex, LOG_LEVEL_VERBOSE);
110
- }
111
- }
112
- async deleteProvenance(path) {
113
- if (!this.fileReflectionProvenance) return;
114
- try {
115
- await this.fileReflectionProvenance.delete(this.getProvenancePath(path));
116
- } catch (ex) {
117
- this._log(`Could not delete file reflection provenance for ${path}`, LOG_LEVEL_VERBOSE);
118
- this._log(ex, LOG_LEVEL_VERBOSE);
119
- }
120
- }
121
- async findUniqueContentRevision(file) {
122
- try {
123
- const revisions = await this.db.findContentRevisions(file, file.body);
124
- return revisions.length === 1 ? revisions[0] : void 0;
125
- } catch (ex) {
126
- this._log(`Could not reconstruct file reflection provenance for ${file.path}`, LOG_LEVEL_VERBOSE);
127
- this._log(ex, LOG_LEVEL_VERBOSE);
128
- return void 0;
129
- }
130
- }
131
- async getProvenBaseRevision(file, preferredPath) {
132
- const path = preferredPath ?? file.path;
133
- const recorded = await this.getProvenance(path) ?? (preferredPath && preferredPath !== file.path ? await this.getProvenance(file.path) : void 0);
134
- if (recorded) {
135
- return recorded.revision;
136
- }
137
- const matched = await this.findUniqueContentRevision(file);
138
- if (matched) {
139
- await this.setProvenance(path, matched, file.stat.mtime, file.body);
140
- return matched;
141
- }
142
- return void 0;
143
- }
144
94
  /**
145
- * Classify a storage read against its displayed database branch.
146
- *
147
- * A recorded revision identifies the branch and therefore takes precedence
148
- * over byte matches. Without a readable base, only current live leaves are
149
- * considered. Any match avoids a duplicate write, but only a unique match
150
- * identifies provenance; no match is `unknown`.
151
- * `preferredPath` selects the provenance key during a rename, and
152
- * `currentLoaded` supplies an already decoded candidate body when available.
153
- * A valid saved content hash can prove unchanged bytes after revision
154
- * pruning. It cannot reconstruct ancestry for an edited file.
95
+ * Expose the storage service captured when the facade was constructed.
96
+ * @returns The captured storage access service.
97
+ * @remarks Responsibility functions resolve this virtual getter at each original access site.
155
98
  */
156
- async classifyStorageContent(file, currentEntry, preferredPath, recorded, currentLoaded, requireReadableContent = false) {
157
- const path = preferredPath ?? file.path;
158
- const recordedRevision = recorded?.revision;
159
- if (recordedRevision) {
160
- if (hasContentHash(recorded) && recorded.contentSize === file.body.size && (await this.contentEvidence(file.body)).contentHash === recorded.contentHash) {
161
- return { kind: "unchanged", revision: recordedRevision };
162
- }
163
- const loadedContentIsDecoded = currentLoaded?._rev === recordedRevision;
164
- const base = loadedContentIsDecoded ? currentLoaded : await this.db.fetchEntry(file, recordedRevision, true, true, true);
165
- if (base && base._rev === recordedRevision && !("deleted" in base && base.deleted) && !("_deleted" in base && base._deleted)) {
166
- const baseContent = loadedContentIsDecoded ? base.data : readContent(base);
167
- return await isDocContentSame(baseContent, file.body) ? { kind: "unchanged", revision: recordedRevision } : { kind: "edited", revision: recordedRevision };
168
- }
169
- if (!base) {
170
- const meta = await this.db.fetchEntryMeta(file, recordedRevision, true);
171
- if (requireReadableContent && meta && !meta.deleted && !meta._deleted) {
172
- throw new Error(`Could not read the recorded file revision for ${file.path}`);
173
- }
174
- if ((!meta || meta.deleted || meta._deleted) && !hasContentHash(recorded)) await this.deleteProvenance(path);
175
- }
176
- }
177
- const matches = currentEntry ? await this.db.findLiveContentRevisions(file, file.body) : [];
178
- if (matches.length) {
179
- return { kind: "matching-leaf", revision: matches.length === 1 ? matches[0] : void 0 };
180
- }
181
- return { kind: "unknown" };
182
- }
183
- /** Record provenance only when storage matches one unambiguous live leaf. */
184
- async rememberMatchingLeaf(path, revision, mtime, content, evidence) {
185
- if (revision) await this.setProvenance(path, revision, mtime, content, evidence);
99
+ get storage() {
100
+ return this.storageAccess;
186
101
  }
187
102
  /**
188
- * Read the raw provenance value used by an optimistic storage snapshot.
189
- * Unlike `getProvenance`, this does not validate or remove the referenced
190
- * database revision. Recovery callers require a readable value so a store
191
- * failure cannot be mistaken for absent provenance.
103
+ * Resolve an entry through the captured host path service.
104
+ * @param entry - The database metadata being processed.
105
+ * @returns The path reported by the captured path service.
106
+ * @remarks Resolve through the path service captured at construction. This synchronous method acquires no document lock.
192
107
  */
193
- async readProvenanceSnapshot(path, requireReadable = false) {
194
- try {
195
- const record = await this.fileReflectionProvenance?.get(this.getProvenancePath(path));
196
- return record ? { ...record } : void 0;
197
- } catch (error) {
198
- if (requireReadable) throw error;
199
- return void 0;
200
- }
108
+ getPath(entry) {
109
+ return getFileEntryPath(this.context, entry);
201
110
  }
202
111
  /**
203
- * Check that storage still has the same path, bytes, timestamp, and
204
- * provenance as a previously captured snapshot.
112
+ * Resolve a storage path through the path service and remove its namespace prefix.
113
+ * @param entry - The database metadata being processed.
114
+ * @returns The path without a storage namespace prefix.
115
+ * @remarks Resolve through the captured path service independently of getPath overrides, then strip the namespace. No document lock is acquired.
205
116
  */
206
- async currentStorageSnapshotMatches(file, revision, requireReadableProvenance = false) {
207
- const current = await this.storage.getStub(file.path);
208
- if (!current || isFolderInfo(current) || current.path !== file.path) return false;
209
- const readCurrent = await this.readFileFromStub(current);
210
- return readCurrent.stat.mtime === file.stat.mtime && await isDocContentSame(readCurrent.body, file.body) && sameProvenance(await this.readProvenanceSnapshot(file.path, requireReadableProvenance), revision);
117
+ getPathWithoutPrefix(entry) {
118
+ return getFileStoragePath(this.context, entry);
211
119
  }
212
120
  /**
213
- * Publish provenance after a durable database write if storage is unchanged.
214
- * A failed revalidation leaves the database revision stored and asks the
215
- * caller to reread storage before proceeding.
121
+ * Reuse a supplied body or acquire the current content through storage.
122
+ * @param file - The supplied storage observation; its body is reused when present.
123
+ * @returns The supplied or acquired complete file; missing content rejects the operation.
124
+ * @remarks This public reader acquires no document lock. It reuses a supplied body or reads storage, and missing/read failures reject its promise.
216
125
  */
217
- async finaliseStoredRevision(file, observedProvenance, storedRevision, requireReadableProvenance = false) {
218
- const evidence = await this.contentEvidence(file.body);
219
- if (await this.currentStorageSnapshotMatches(file, observedProvenance, requireReadableProvenance)) {
220
- await this.setProvenance(file.path, storedRevision, file.stat.mtime, file.body, evidence);
221
- return true;
222
- } else {
223
- return false;
224
- }
126
+ async readFileFromStub(file) {
127
+ return await readStorageFile(this.context, file);
225
128
  }
226
129
  /**
227
- * Reread storage after a restored startup snapshot changed and retry a save.
228
- * The bounded counter prevents an unstable file from causing an endless
229
- * startup loop; the next event or scan can reconcile a final refusal.
130
+ * Offer a metadata-only scan hint without certifying bytes or changing provenance.
131
+ * @param info - The supplied file observation or path.
132
+ * @param expected - The database metadata expected by this scan.
133
+ * @returns Whether the scan may skip this unchanged metadata observation.
134
+ * @remarks Acquire the document lock while checking a metadata-only hint. No revision or file content is written; inspection failures are logged and return false.
230
135
  */
231
- async retryCurrentStorage(path, preferredBasePath, snapshotRetry) {
232
- if (snapshotRetry >= 2) {
233
- this._log(`Storage kept changing while saving ${path}; a fresh event is required`, LOG_LEVEL_NOTICE);
234
- return false;
235
- }
236
- const fresh = await this.storage.getStub(path);
237
- if (!fresh || isFolderInfo(fresh)) return false;
238
- return await this.storeFileToDBFromRevision(fresh, false, false, preferredBasePath, true, snapshotRetry + 1);
239
- }
240
- getPath(entry) {
241
- return this.path.getPath(entry);
242
- }
243
- getPathWithoutPrefix(entry) {
244
- return stripAllPrefixes(this.path.getPath(entry));
245
- }
246
- async readFileFromStub(file) {
247
- if ("body" in file && file.body) {
248
- return file;
249
- }
250
- const readFile = await this.storage.readStubContent(file);
251
- if (!readFile) {
252
- throw new Error(`File ${file.path} is not exist on the storage`);
253
- }
254
- return readFile;
255
- }
256
136
  async canSkipUnchangedFile(info, expected) {
257
- const path = getStoragePathFromUXFileInfo(info);
258
- const provenance = this.fileReflectionProvenance;
259
- if (!provenance || !expected._rev || expected.deleted || expected._deleted || expected._conflicts?.length || this.storage.hasPendingFileEvent?.(path) !== false) return false;
260
- try {
261
- return await this.serializedByFileEventPaths([path], async () => {
262
- const provenancePath = this.getProvenancePath(path);
263
- const record = await provenance.get(provenancePath);
264
- if (!record || !hasContentHash(record) || record.revision !== expected._rev || !Number.isFinite(record.observedStorageMtime) || record.observedStorageMtime !== info.stat.mtime || record.contentSize !== info.stat.size) return false;
265
- const current = await this.db.fetchEntryMeta(path, void 0, true);
266
- if (!current || current._rev !== record.revision || current.deleted || current._deleted || (await this.db.getConflictedRevs(path)).length > 0) return false;
267
- const stat = await this.storage.stat(path);
268
- if (!stat || stat.type !== "file" || stat.mtime !== record.observedStorageMtime || stat.size !== record.contentSize) return false;
269
- return sameProvenance(await provenance.get(provenancePath), record) && this.storage.hasPendingFileEvent?.(path) === false;
270
- });
271
- } catch (error) {
272
- this._log(`Could not inspect unchanged file metadata for ${path}`, LOG_LEVEL_VERBOSE);
273
- this._log(error, LOG_LEVEL_VERBOSE);
274
- return false;
275
- }
276
- }
277
- async tryRecordUntrackedFileRevision(info, expectedRevision) {
278
- if (!this.fileReflectionProvenance || !expectedRevision) return false;
279
- const path = getStoragePathFromUXFileInfo(info);
280
- try {
281
- return await this.serializedByFileEventPaths([path], async () => {
282
- const provenance = this.fileReflectionProvenance;
283
- const provenancePath = this.getProvenancePath(path);
284
- const existing = await provenance.get(provenancePath);
285
- const observed = existing ? { ...existing } : void 0;
286
- if (observed && (observed.revision !== expectedRevision || hasContentHash(observed))) return false;
287
- const stub = await this.storage.getStub(path);
288
- if (!stub || isFolderInfo(stub) || stub.path !== path) return false;
289
- const file = await this.readFileFromStub(stub);
290
- const current = await this.db.fetchEntryMeta(path, void 0, true);
291
- if (!current || current._rev !== expectedRevision || current.deleted || current._deleted) return false;
292
- if ((await this.db.getConflictedRevs(path)).length > 0) return false;
293
- const entry = await this.db.fetchEntry(path, expectedRevision, true, true, true);
294
- if (!entry || entry._rev !== expectedRevision || entry.deleted || entry._deleted) return false;
295
- if (!await isDocContentSame(readContent(entry), file.body)) return false;
296
- const evidence = await this.contentEvidence(file.body);
297
- if (!evidence.contentHash) return false;
298
- const latest = await this.db.fetchEntryMeta(path, void 0, true);
299
- if (!latest || latest._rev !== expectedRevision || latest.deleted || latest._deleted) return false;
300
- if ((await this.db.getConflictedRevs(path)).length > 0) return false;
301
- if (!await this.currentStorageSnapshotMatches(file, observed)) return false;
302
- if (!sameProvenance(await provenance.get(provenancePath), observed)) return false;
303
- await provenance.set(provenancePath, { revision: expectedRevision, observedStorageMtime: file.stat.mtime, ...evidence });
304
- return true;
305
- });
306
- } catch (ex) {
307
- this._log(`Could not record unchanged file provenance for ${path}`, LOG_LEVEL_VERBOSE);
308
- this._log(ex, LOG_LEVEL_VERBOSE);
309
- return false;
310
- }
311
- }
312
- async infoToStub(info) {
313
- if (info == null) return null;
314
- const file = typeof info === "string" ? await this.storage.getFileStub(info) : info;
315
- return file;
316
- }
317
- async storeFileToDB(info, force = false, onlyChunks = false, options = {}) {
318
- return await this.serializedByFileEventPaths(
319
- [getStoragePathFromUXFileInfo(info)],
320
- () => this.storeFileToDBFromRevision(info, force, onlyChunks, void 0, options.revalidateStorage)
321
- );
322
- }
323
- async storeFileToDBWithBaseRevision(info, baseRevision, createIfDifferent = true) {
324
- return await this.serializedByFileEventPaths(
325
- [getStoragePathFromUXFileInfo(info)],
326
- () => this.storeFileToDBWithBaseRevisionCore(info, baseRevision, createIfDifferent)
327
- );
137
+ return await canSkipUnchangedFile(this.context, info, expected);
328
138
  }
329
139
  /**
330
- * Store current storage content below an exact live revision. A differing
331
- * body is rejected when `createIfDifferent` is false; callers hold the
332
- * document lock for this core operation.
140
+ * Check the host's explicit deletion-recovery capability without store access.
141
+ * @returns Whether complete provenance-key enumeration is available.
142
+ * @remarks This pure capability check never enumerates keys or reads provenance values.
333
143
  */
334
- async storeFileToDBWithBaseRevisionCore(info, baseRevision, createIfDifferent) {
335
- const file = await this.infoToStub(info);
336
- if (file == null) {
337
- this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, LOG_LEVEL_VERBOSE);
338
- return false;
339
- }
340
- if (file.isInternal) {
341
- this._log(
342
- `Internal file ${file.path} is not allowed to be stored through the ordinary file handler`,
343
- LOG_LEVEL_VERBOSE
344
- );
345
- return false;
346
- }
347
- const [baseEntry, currentEntry, conflictedRevisions] = await Promise.all([
348
- this.db.fetchEntryMeta(file, baseRevision, true),
349
- this.db.fetchEntryMeta(file, void 0, true),
350
- this.db.getConflictedRevs(file)
351
- ]);
352
- const liveRevisions = /* @__PURE__ */ new Set([
353
- ...currentEntry && currentEntry._rev ? [currentEntry._rev] : [],
354
- ...conflictedRevisions
355
- ]);
356
- if (!baseEntry || baseEntry._rev !== baseRevision || !liveRevisions.has(baseRevision)) {
357
- this._log(
358
- `Could not store ${file.path} on revision ${baseRevision}; the selected revision is no longer live`,
359
- LOG_LEVEL_NOTICE
360
- );
361
- return false;
362
- }
363
- const readFile = await this.readFileFromStub(file);
364
- if (!baseEntry.deleted && !baseEntry._deleted) {
365
- const loadedBase = await this.db.fetchEntry(file, baseRevision, true, true);
366
- if (loadedBase && await isDocContentSame(getDocDataAsArray(loadedBase.data), readFile.body)) {
367
- await this.setProvenance(file.path, baseRevision, readFile.stat.mtime, readFile.body);
368
- await this.queueConflictCheckFor(file.path);
369
- return true;
370
- }
371
- }
372
- if (!createIfDifferent) {
373
- this._log(
374
- `Could not mark ${file.path} as revision ${baseRevision}; the storage content differs`,
375
- LOG_LEVEL_NOTICE
376
- );
377
- return false;
378
- }
379
- const storedRevision = await this.db.storeWithBaseRevision(readFile, baseRevision, true);
380
- if (storedRevision === false) {
381
- return false;
382
- }
383
- await this.setProvenance(file.path, storedRevision, readFile.stat.mtime, readFile.body);
384
- await this.queueConflictCheckFor(file.path);
385
- return true;
144
+ supportsDeletionRecovery() {
145
+ return !!this.context.provenance?.listPaths;
386
146
  }
387
147
  /**
388
- * Save one storage snapshot while the caller holds its document lock.
389
- * Ordinary saves read once inside the lock and leave retries disabled.
390
- * Restored start-up events and recovery scans retain bounded rereads
391
- * because a watcher event may not cover a concurrent edit.
148
+ * Enumerate the host's existing provenance keys for absent-file cleanup discovery.
149
+ * @returns Complete namespace-scoped provenance paths; host access errors propagate.
150
+ * @remarks Unsupported hosts reject. This operation reads keys without loading bodies or records.
392
151
  */
393
- async storeFileToDBFromRevision(info, force = false, onlyChunks = false, preferredBasePath, retryIfStorageChanges = false, snapshotRetry = 0) {
394
- const file = await this.infoToStub(info);
395
- if (file == null) {
396
- this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, LOG_LEVEL_VERBOSE);
397
- return false;
398
- }
399
- if (file.isInternal) {
400
- this._log(
401
- `Internal file ${file.path} is not allowed to be processed on processFileEvent`,
402
- LOG_LEVEL_VERBOSE
403
- );
404
- return false;
405
- }
406
- if (onlyChunks) {
407
- const readFile2 = await this.readFileFromStub(file);
408
- return await this.db.createChunks(readFile2, force, true);
409
- }
410
- const observedProvenance = await this.readProvenanceSnapshot(
411
- preferredBasePath ?? file.path,
412
- retryIfStorageChanges
413
- );
414
- const readFile = await this.readFileFromStub(file);
415
- const entry = await this.db.fetchEntry(file, void 0, true, true, true);
416
- const currentEntry = entry || await this.db.fetchEntryMeta(file, void 0, true);
417
- const conflictedRevs = await this.db.getConflictedRevs(file);
418
- const isConflicted = conflictedRevs.length > 0;
419
- const currentIsLive = currentEntry && !currentEntry.deleted && !currentEntry._deleted;
420
- if (!force && (currentIsLive || retryIfStorageChanges)) {
421
- if (retryIfStorageChanges && currentIsLive && !entry) return false;
422
- const classification = await this.classifyStorageContent(
423
- readFile,
424
- currentEntry,
425
- preferredBasePath,
426
- observedProvenance,
427
- entry ? { _rev: entry._rev, data: readContent(entry) } : void 0,
428
- retryIfStorageChanges
429
- );
430
- const upgradeCurrentRecord = classification.kind === "unchanged" && !isConflicted && currentEntry && !currentEntry.deleted && !currentEntry._deleted && classification.revision === currentEntry._rev && !hasContentHash(observedProvenance);
431
- const evidence = upgradeCurrentRecord || classification.kind === "matching-leaf" && classification.revision ? await this.contentEvidence(readFile.body) : void 0;
432
- const snapshotMatches = retryIfStorageChanges || upgradeCurrentRecord ? await this.currentStorageSnapshotMatches(readFile, observedProvenance, retryIfStorageChanges) : true;
433
- if (retryIfStorageChanges && !snapshotMatches) {
434
- return await this.retryCurrentStorage(file.path, preferredBasePath, snapshotRetry);
435
- }
436
- if (classification.kind === "unchanged") {
437
- if (isConflicted) {
438
- await this.queueConflictCheckFor(file.path);
439
- } else if (!currentEntry || currentEntry.deleted || currentEntry._deleted || classification.revision !== currentEntry._rev) {
440
- if (!currentEntry) return false;
441
- return await this.dbToStorageCore(file.path, file);
442
- } else {
443
- if (upgradeCurrentRecord && snapshotMatches) {
444
- await this.setProvenance(file.path, classification.revision, readFile.stat.mtime, readFile.body, evidence);
445
- }
446
- this.path.markChangesAreSame(readFile, readFile.stat.mtime, currentEntry.mtime);
447
- }
448
- return true;
449
- }
450
- if (classification.kind === "matching-leaf") {
451
- await this.rememberMatchingLeaf(file.path, classification.revision, readFile.stat.mtime, readFile.body, evidence);
452
- if (isConflicted) await this.queueConflictCheckFor(file.path);
453
- return true;
454
- }
455
- const storedRevision2 = classification.kind === "edited" ? await this.db.storeWithBaseRevision(readFile, classification.revision, true) : await this.db.storeIndependentRevision(readFile, true);
456
- if (storedRevision2 === false) return false;
457
- if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
458
- if (retryIfStorageChanges && !await this.finaliseStoredRevision(readFile, observedProvenance, storedRevision2, true)) {
459
- return await this.retryCurrentStorage(file.path, preferredBasePath, snapshotRetry);
460
- }
461
- if (!retryIfStorageChanges) await this.setProvenance(file.path, storedRevision2, readFile.stat.mtime, readFile.body);
462
- if (isConflicted || classification.kind === "unknown") await this.queueConflictCheckFor(file.path);
463
- return true;
464
- }
465
- if (isConflicted) {
466
- const baseRevision = await this.getProvenBaseRevision(readFile, preferredBasePath);
467
- if (baseRevision) {
468
- const baseEntry = await this.db.fetchEntry(file, baseRevision, true, true);
469
- if (baseEntry && await isDocContentSame(getDocDataAsArray(baseEntry.data), readFile.body) && !force) {
470
- await this.setProvenance(file.path, baseRevision, readFile.stat.mtime, readFile.body);
471
- this._log(`File ${file.path} is not changed on its displayed conflict branch`, LOG_LEVEL_VERBOSE);
472
- return true;
473
- }
474
- const storedRevision3 = await this.db.storeWithBaseRevision(readFile, baseRevision, true);
475
- if (storedRevision3 === false) return false;
476
- if (preferredBasePath && preferredBasePath !== file.path) {
477
- await this.deleteProvenance(preferredBasePath);
478
- }
479
- await this.setProvenance(file.path, storedRevision3, readFile.stat.mtime, readFile.body);
480
- await this.queueConflictCheckFor(file.path);
481
- return true;
482
- }
483
- const currentEntry2 = entry || await this.db.fetchEntryMeta(file, void 0, true);
484
- const currentRevision = currentEntry2 && currentEntry2._rev;
485
- if (!currentRevision) {
486
- this._log(
487
- `Could not preserve the unknown conflict branch for ${file.path}; no current revision is available`,
488
- LOG_LEVEL_NOTICE
489
- );
490
- await this.queueConflictCheckFor(file.path);
491
- return false;
492
- }
493
- const storedRevision2 = await this.db.storeAsConflictedRevisionWithResult(readFile, currentRevision, true);
494
- if (storedRevision2 === false) {
495
- this._log(`Could not preserve the unknown conflict branch for ${file.path}`, LOG_LEVEL_NOTICE);
496
- await this.queueConflictCheckFor(file.path);
497
- return false;
498
- }
499
- if (preferredBasePath && preferredBasePath !== file.path) {
500
- await this.deleteProvenance(preferredBasePath);
501
- }
502
- await this.setProvenance(file.path, storedRevision2, readFile.stat.mtime, readFile.body);
503
- await this.queueConflictCheckFor(file.path);
504
- return true;
505
- }
506
- if (!currentEntry || currentEntry.deleted || currentEntry._deleted) {
507
- const storedRevision2 = await this.db.storeWithBaseRevision(readFile, entry && entry._rev, true);
508
- if (storedRevision2 === false) return false;
509
- if (preferredBasePath && preferredBasePath !== file.path) {
510
- await this.deleteProvenance(preferredBasePath);
511
- }
512
- await this.setProvenance(file.path, storedRevision2, readFile.stat.mtime, readFile.body);
513
- return true;
514
- }
515
- let shouldApplied = false;
516
- if (!force && !onlyChunks && entry) {
517
- if (this.path.compareFileFreshness(file, entry) !== EVEN) {
518
- shouldApplied = true;
519
- }
520
- if (!shouldApplied) {
521
- if (await isDocContentSame(getDocDataAsArray(entry.data), readFile.body)) {
522
- this.path.markChangesAreSame(readFile, readFile.stat.mtime, entry.mtime);
523
- } else {
524
- shouldApplied = true;
525
- }
526
- }
527
- if (!shouldApplied) {
528
- await this.setProvenance(file.path, entry._rev, readFile.stat.mtime, readFile.body);
529
- this._log(`File ${file.path} is not changed`, LOG_LEVEL_VERBOSE);
530
- return true;
531
- }
532
- }
533
- const storedRevision = await this.db.storeWithBaseRevision(readFile, currentEntry._rev, true);
534
- if (storedRevision === false) return false;
535
- if (preferredBasePath && preferredBasePath !== file.path) {
536
- await this.deleteProvenance(preferredBasePath);
537
- }
538
- await this.setProvenance(file.path, storedRevision, readFile.stat.mtime, readFile.body);
539
- return true;
540
- }
541
- async deleteFileFromDB(info) {
542
- return await this.serializedByFileEventPaths(
543
- [getStoragePathFromUXFileInfo(info)],
544
- () => this.deleteFileFromDBCore(info)
545
- );
546
- }
547
- /** Complete a validated storage deletion when its database effect is already represented. */
548
- async deleteFileFromDBIfPresent(info) {
549
- const entry = await this.db.fetchEntryMeta(info, void 0, true);
550
- if (!entry || entry.deleted || entry._deleted) return true;
551
- return await this.deleteFileFromDBCore(info);
152
+ async listDeletionRecoveryPaths() {
153
+ if (!this.context.provenance?.listPaths) throw new Error("Deletion recovery is unavailable for this host");
154
+ return await this.context.provenance.listPaths();
552
155
  }
553
156
  /**
554
- * Record a storage deletion under the caller's document lock, preserving
555
- * the displayed conflict branch when its provenance is known.
157
+ * Recover one exact database deletion while preserving unproved or changed local content.
158
+ * @param expected - The current logical deletion selected by the ordinary scanner.
159
+ * @param cleanupOnly - Require an absent file and clear only stale device-local bookkeeping.
160
+ * @returns Separate observed file, provenance, and completion outcomes.
161
+ * @remarks The responsibility acquires a shared recovery permit before its document lock;
162
+ * verification failures are reported without changing normal incoming or save policy.
556
163
  */
557
- async deleteFileFromDBCore(info) {
558
- const file = await this.infoToStub(info);
559
- const path = typeof info === "string" ? info : tryGetFilePath(info);
560
- if (file == null) {
561
- if (path === void 0) {
562
- this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, LOG_LEVEL_VERBOSE);
563
- return false;
564
- }
565
- const entryByPath = await this.db.fetchEntry(path, void 0, true, true);
566
- if (!entryByPath || entryByPath.deleted || entryByPath._deleted) {
567
- this._log(
568
- `File ${path} is not exist on the storage nor the database (or already deleted)`,
569
- LOG_LEVEL_VERBOSE
570
- );
571
- return false;
572
- }
573
- const conflictedRevs2 = await this.db.getConflictedRevs(path);
574
- if (conflictedRevs2.length > 0) {
575
- const provenance = await this.getProvenance(path);
576
- if (!provenance) {
577
- this._log(
578
- `The deleted storage file ${path} has conflicts, but its displayed revision is unknown; preserving every database branch`,
579
- LOG_LEVEL_NOTICE
580
- );
581
- await this.queueConflictCheckFor(path);
582
- return true;
583
- }
584
- const storedRevision = await this.db.storeDeletionWithBaseRevision(path, provenance.revision);
585
- if (storedRevision === false) return false;
586
- await this.deleteProvenance(path);
587
- await this.queueConflictCheckFor(path);
588
- return true;
589
- }
590
- this._log(`File ${path} is missing on storage; deleting from the database by path`, LOG_LEVEL_INFO);
591
- const deleted2 = await this.db.delete(path);
592
- if (deleted2) await this.deleteProvenance(path);
593
- return deleted2;
594
- }
595
- if (file.isInternal) {
596
- this._log(
597
- `Internal file ${file.path} is not allowed to be processed on processFileEvent`,
598
- LOG_LEVEL_VERBOSE
599
- );
600
- return false;
601
- }
602
- const entry = await this.db.fetchEntry(file, void 0, true, true);
603
- if (!entry || entry.deleted || entry._deleted) {
604
- this._log(`File ${file.path} is not exist or already deleted on the database`, LOG_LEVEL_VERBOSE);
605
- return false;
606
- }
607
- const conflictedRevs = await this.db.getConflictedRevs(file);
608
- if (conflictedRevs.length > 0) {
609
- let baseRevision = (await this.getProvenance(file.path))?.revision;
610
- if (!baseRevision) {
611
- try {
612
- const readFile = await this.readFileFromStub(file);
613
- baseRevision = await this.findUniqueContentRevision(readFile);
614
- } catch {
615
- }
616
- }
617
- if (!baseRevision) {
618
- this._log(
619
- `The deleted storage file ${file.path} has conflicts, but its displayed revision is unknown; preserving every database branch`,
620
- LOG_LEVEL_NOTICE
621
- );
622
- await this.queueConflictCheckFor(file.path);
623
- return true;
624
- }
625
- const storedRevision = await this.db.storeDeletionWithBaseRevision(file.path, baseRevision);
626
- if (storedRevision === false) return false;
627
- await this.deleteProvenance(file.path);
628
- await this.queueConflictCheckFor(file.path);
629
- return true;
630
- }
631
- const deleted = await this.db.delete(file);
632
- if (deleted) await this.deleteProvenance(file.path);
633
- return deleted;
634
- }
635
- async renameFileInDB(info, oldPath) {
636
- const newPath = getStoragePathFromUXFileInfo(info);
637
- return await this.serializedByFileEventPaths(
638
- [oldPath, newPath],
639
- () => this.renameFileInDBCore(info, oldPath)
640
- );
164
+ async recoverDatabaseDeletion(expected, cleanupOnly = false) {
165
+ return await recoverDatabaseDeletion(this.context, expected, cleanupOnly);
641
166
  }
642
167
  /**
643
- * Record a rename under the caller's source and target locks. Case-only
644
- * renames retain the source provenance while other renames handle the
645
- * source conflict before deleting its old path.
168
+ * Record an unchanged current revision after rechecking storage and database evidence.
169
+ * @param info - The supplied file observation or path.
170
+ * @param expectedRevision - The exact revision the scan expects to remain current.
171
+ * @returns Whether the exact still-current revision was recorded without writing file content.
172
+ * @remarks Acquire the document lock before attempting an evidence-only provenance update. Missing Chunks follow the settings-controlled retrieval policy. No Metadata revision or file content is written; inspection/store failures are logged and return false.
646
173
  */
647
- async renameFileInDBCore(info, oldPath, retryIfStorageChanges = false) {
648
- const newPath = getStoragePathFromUXFileInfo(info);
649
- const [oldDocumentId, newDocumentId] = await Promise.all([
650
- this.path.path2id(oldPath),
651
- this.path.path2id(newPath)
652
- ]);
653
- if (oldDocumentId === newDocumentId) {
654
- this._log(`Updating the stored path for case-only rename: ${oldPath} -> ${newPath}`, LOG_LEVEL_VERBOSE);
655
- return await this.storeFileToDBFromRevision(
656
- info,
657
- true,
658
- false,
659
- oldPath,
660
- retryIfStorageChanges
661
- );
662
- }
663
- const oldEntry = await this.db.fetchEntryMeta(oldPath, void 0, true);
664
- const newEntry = await this.db.fetchEntryMeta(newPath, void 0, true);
665
- if (newEntry && !newEntry.deleted && !newEntry._deleted) {
666
- this._log(
667
- `Refusing to overwrite the existing database entry while renaming ${oldPath} to ${newPath}`,
668
- LOG_LEVEL_NOTICE
669
- );
670
- return false;
671
- }
672
- if (!await this.storeFileToDBFromRevision(info, true, false, void 0, retryIfStorageChanges)) {
673
- this._log(`Failed to store rename target; preserving source in the database: ${oldPath}`, LOG_LEVEL_NOTICE);
674
- return false;
675
- }
676
- if (!oldEntry || oldEntry.deleted || oldEntry._deleted) {
677
- this._log(`Rename source is not present in the database: ${oldPath}`, LOG_LEVEL_VERBOSE);
678
- return true;
679
- }
680
- const oldConflicts = await this.db.getConflictedRevs(oldPath);
681
- if (oldConflicts.length > 0) {
682
- let baseRevision = (await this.getProvenance(oldPath))?.revision;
683
- if (!baseRevision) {
684
- const readFile = await this.readFileFromStub(info);
685
- const revisions = await this.db.findContentRevisions(oldPath, readFile.body);
686
- baseRevision = revisions.length === 1 ? revisions[0] : void 0;
687
- }
688
- if (!baseRevision) {
689
- this._log(
690
- `Renamed ${oldPath} to ${newPath}, but preserved every conflicted source branch because the displayed source revision is unknown`,
691
- LOG_LEVEL_NOTICE
692
- );
693
- await this.queueConflictCheckFor(oldPath);
694
- return true;
695
- }
696
- const storedRevision = await this.db.storeDeletionWithBaseRevision(
697
- oldPath,
698
- baseRevision
699
- );
700
- if (storedRevision === false) return false;
701
- await this.deleteProvenance(oldPath);
702
- await this.queueConflictCheckFor(oldPath);
703
- return true;
704
- }
705
- const deleted = await this.db.delete(oldPath);
706
- if (deleted) await this.deleteProvenance(oldPath);
707
- return deleted;
708
- }
709
- async deleteRevisionFromDB(info, rev) {
710
- return await this.serializedByFileEventPaths(
711
- [getStoragePathFromUXFileInfo(info)],
712
- () => this.deleteRevisionFromDBCore(info, rev)
713
- );
714
- }
715
- /** Delete one selected revision and clear matching provenance under the caller's document lock. */
716
- async deleteRevisionFromDBCore(info, rev) {
717
- const path = getStoragePathFromUXFileInfo(info);
718
- const provenance = await this.getProvenance(path);
719
- const deleted = await this.db.delete(info, rev);
720
- if (deleted && provenance?.revision === rev) {
721
- await this.deleteProvenance(path);
722
- }
723
- return deleted;
724
- }
725
- async resolveConflictedByDeletingRevision(info, rev) {
726
- return await this.serializedByFileEventPaths(
727
- [getStoragePathFromUXFileInfo(info)],
728
- () => this.resolveConflictedByDeletingRevisionCore(info, rev)
729
- );
174
+ async tryRecordUntrackedFileRevision(info, expectedRevision) {
175
+ return await tryRecordUntrackedFileRevision(this.context, info, expectedRevision);
730
176
  }
731
177
  /**
732
- * Apply the legacy resolve-by-delete sequence while holding one document
733
- * lock; metadata is captured before the selected revision is removed.
178
+ * Save ordinary storage content under its document lock.
179
+ * @param info - The supplied file observation or path.
180
+ * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
181
+ * @param onlyChunks - Whether to repair chunks without creating a document revision.
182
+ * @param options - The existing recovery revalidation option for this save.
183
+ * @returns True when current bytes are represented or chunk repair succeeds; false for refused or unstable observations.
184
+ * @remarks Acquire the document lock and retain deferred post-lock conflict hooks. Ordinary revision writes reuse the captured body; legacy-evidence upgrades and recovery retain their existing validation reads. Provenance publication is best-effort.
734
185
  */
735
- async resolveConflictedByDeletingRevisionCore(info, rev) {
736
- const path = getStoragePathFromUXFileInfo(info);
737
- const file = await this.infoToStub(info);
738
- const docEntry = await this.db.fetchEntryMeta(file ?? info, rev, true);
739
- if (!docEntry) {
740
- this._log(`Failed to read the conflicted revision ${rev} of ${path}`, LOG_LEVEL_VERBOSE);
741
- return false;
742
- }
743
- if (!await this.deleteRevisionFromDBCore(info, rev)) {
744
- this._log(`Failed to delete the conflicted revision ${rev} of ${path}`, LOG_LEVEL_VERBOSE);
745
- return false;
746
- }
747
- if (!await this.applyDatabaseEntryToStorage(docEntry, file, true)) {
748
- this._log(`Failed to apply the resolved revision ${rev} of ${path} to the storage`, LOG_LEVEL_VERBOSE);
749
- return false;
750
- }
751
- await this.deleteProvenance(path);
752
- }
753
- async dbToStorageWithSpecificRev(info, rev, force) {
754
- if (info == null) {
755
- this._log(`Cannot select database revision ${rev} without a file path`, LOG_LEVEL_VERBOSE);
756
- return false;
757
- }
758
- return await this.serializedByFileEventPaths(
759
- [getStoragePathFromUXFileInfo(info)],
760
- () => this.dbToStorageWithSpecificRevCore(info, rev, force)
761
- );
186
+ async storeFileToDB(info, force = false, onlyChunks = false, options = {}) {
187
+ return await storeFileToDB(this.context, info, force, onlyChunks, options);
762
188
  }
763
189
  /**
764
- * Reflect a selected live revision under the caller's document lock.
765
- * The public wrapper performs the same lock acquisition before entering here.
190
+ * Save current bytes under one selected live database revision.
191
+ * @param info - The supplied file observation or path.
192
+ * @param baseRevision - The exact selected live database revision.
193
+ * @param createIfDifferent - Whether differing bytes may create a child of the selected revision.
194
+ * @returns True when matching bytes are certified or a selected-base child is stored; false when the live-base or content condition refuses it.
195
+ * @remarks Acquire the document lock and reject a selected base that is no longer live. Matching bytes or a new selected-base child may complete; provenance publication is best-effort.
766
196
  */
767
- async dbToStorageWithSpecificRevCore(info, rev, force) {
768
- const file = await this.infoToStub(info);
769
- const databaseTarget = file ?? info;
770
- const [docEntry, currentEntry, conflictedRevisions] = await Promise.all([
771
- this.db.fetchEntryMeta(databaseTarget, rev, true),
772
- this.db.fetchEntryMeta(databaseTarget, void 0, true),
773
- this.db.getConflictedRevs(databaseTarget)
774
- ]);
775
- if (!docEntry) {
776
- this._log(`File ${tryGetFilePath(info)} is not exist on the database`, LOG_LEVEL_VERBOSE);
777
- return false;
778
- }
779
- const liveRevisions = /* @__PURE__ */ new Set([
780
- ...currentEntry && currentEntry._rev ? [currentEntry._rev] : [],
781
- ...conflictedRevisions
782
- ]);
783
- if (!liveRevisions.has(rev)) {
784
- this._log(
785
- `Could not apply ${tryGetFilePath(info)} revision ${rev}; the selected revision is no longer live`,
786
- LOG_LEVEL_NOTICE
787
- );
788
- return false;
789
- }
790
- return await this.applyDatabaseEntryToStorage(docEntry, file, force, true);
791
- }
792
- async dbToStorage(entryInfo, info, force) {
793
- const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : this.getPath(entryInfo);
794
- return await this.serializedByFileEventPaths(
795
- [pathFromEntryInfo],
796
- () => this.dbToStorageCore(entryInfo, info, force)
797
- );
798
- }
799
- /** Fetch the current metadata and reflect it while the caller holds its lock. */
800
- async dbToStorageCore(entryInfo, info, force) {
801
- const file = await this.infoToStub(info);
802
- const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : this.getPath(entryInfo);
803
- const docEntry = await this.db.fetchEntryMeta(pathFromEntryInfo, void 0, true);
804
- if (!docEntry) {
805
- this._log(`File ${pathFromEntryInfo} is not exist on the database`, LOG_LEVEL_VERBOSE);
806
- return false;
807
- }
808
- return await this.applyDatabaseEntryToStorage(docEntry, file, force);
197
+ async storeFileToDBWithBaseRevision(info, baseRevision, createIfDifferent = true) {
198
+ return await storeFileToDBWithBaseRevision(this.context, info, baseRevision, createIfDifferent);
809
199
  }
810
200
  /**
811
- * Reflect one database revision while protecting concurrent storage edits.
812
- * Overwrite and deletion paths preserve changed bytes first, then revalidate
813
- * their snapshot and the current database revision immediately before the
814
- * destructive operation.
201
+ * Record a storage deletion under the corresponding document lock.
202
+ * @param info - The supplied file observation or path.
203
+ * @returns True after deletion or conservative conflict preservation; false for absent/deleted records or a refused write.
204
+ * @remarks Acquire the source document lock. Unknown conflict ancestry is preserved for review; database errors reject and optional provenance cleanup remains best-effort.
815
205
  */
816
- async applyDatabaseEntryToStorage(docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0) {
817
- const mode = file == null ? "create" : "modify";
818
- const path = this.getPath(docEntry);
819
- const settings = this.setting.currentSettings();
820
- const revs = await this.db.getConflictedRevs(path);
821
- if (revs.length > 0 && !allowExistingConflicts) {
822
- if (settings.writeDocumentsIfConflicted) {
823
- } else {
824
- await this.queueConflictCheckFor(path, true);
825
- return true;
826
- }
827
- }
828
- let existDoc = await this.storage.getStub(path);
829
- if (isFolderInfo(existDoc)) {
830
- this._log(`Folder ${path} is already exist on the storage as a folder`, LOG_LEVEL_VERBOSE);
831
- return true;
832
- }
833
- const existOnDB = !(docEntry._deleted || docEntry.deleted || false);
834
- if (!existOnDB && !existDoc) {
835
- this._log(`File ${path} seems to be deleted, but already not on storage`, LOG_LEVEL_VERBOSE);
836
- await this.deleteProvenance(path);
837
- return true;
838
- }
839
- if (!existOnDB && existDoc) {
840
- let safeDeletionSnapshot;
841
- if (!force && !settings.writeDocumentsIfConflicted) {
842
- let protection = await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry);
843
- if (protection.preserved) return true;
844
- if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) {
845
- protection = await this.recheckIncomingStorage(path, docEntry, void 0, allowExistingConflicts);
846
- if (protection.preserved) return true;
847
- if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) {
848
- return false;
849
- }
850
- }
851
- safeDeletionSnapshot = protection.snapshot;
852
- }
853
- let latest2 = await this.reconcileAdvancedIncomingRevision(
854
- docEntry,
855
- path,
856
- force,
857
- allowExistingConflicts,
858
- incomingRetry
859
- );
860
- if (latest2 !== void 0) return latest2;
861
- if (safeDeletionSnapshot && !await this.currentStorageSnapshotMatches(safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
862
- const protection = await this.recheckIncomingStorage(path, docEntry, void 0, allowExistingConflicts);
863
- if (protection.preserved) return true;
864
- if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) {
865
- return false;
866
- }
867
- safeDeletionSnapshot = protection.snapshot;
868
- latest2 = await this.reconcileAdvancedIncomingRevision(
869
- docEntry,
870
- path,
871
- force,
872
- allowExistingConflicts,
873
- incomingRetry
874
- );
875
- if (latest2 !== void 0) return latest2;
876
- if (!await this.currentStorageSnapshotMatches(safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
877
- return false;
878
- }
879
- }
880
- await this.storage.deleteVaultItem(path);
881
- await this.deleteProvenance(path);
882
- return true;
883
- }
884
- if (existDoc && existDoc.path !== path) {
885
- const [existingDocumentId, targetDocumentId] = await Promise.all([
886
- this.path.path2id(existDoc.path),
887
- this.path.path2id(path)
888
- ]);
889
- if (existingDocumentId !== targetDocumentId) {
890
- this._log(
891
- `Refusing to overwrite ${existDoc.path} while applying the distinct path ${path}`,
892
- LOG_LEVEL_NOTICE
893
- );
894
- return false;
895
- }
896
- const pathNormalizationVersion = getPathNormalizationVersion(settings);
897
- const sameNormalisedPath = pathNormalizationVersion === 1 && normalisePathForIdentity(existDoc.path, pathNormalizationVersion) === normalisePathForIdentity(path, pathNormalizationVersion);
898
- if (!sameNormalisedPath) {
899
- const existingParent = getParentPath(existDoc.path);
900
- const targetParent = getParentPath(path);
901
- const sameNormalisedParent = pathNormalizationVersion === 1 && normalisePathForIdentity(existingParent, pathNormalizationVersion) === normalisePathForIdentity(targetParent, pathNormalizationVersion);
902
- if (existingParent !== targetParent && !sameNormalisedParent) {
903
- this._log(
904
- `Refusing to apply a filename case change across differently cased parent directories: ${existDoc.path} -> ${path}`,
905
- LOG_LEVEL_NOTICE
906
- );
907
- return false;
908
- }
909
- const renamedFile = await this.storage.renameFile(existDoc, path);
910
- if (!renamedFile) {
911
- this._log(
912
- `Could not apply the stored filename case: ${existDoc.path} -> ${path}`,
913
- LOG_LEVEL_NOTICE
914
- );
915
- return false;
916
- }
917
- await this.deleteProvenance(existDoc.path);
918
- existDoc = renamedFile;
919
- }
920
- }
921
- const docRead = await this.db.fetchEntryFromMeta(docEntry);
922
- if (!docRead) {
923
- this._log(`File ${path} is not exist on the database`, LOG_LEVEL_VERBOSE);
924
- return false;
925
- }
926
- const docData = readContent(docRead);
927
- const reflectedContent = createBlob(docData);
928
- if (!settings.processSizeMismatchedFiles) {
929
- if (docRead.size != 0 && docRead.size !== reflectedContent.size) {
930
- this._log(
931
- `File ${path} seems to be corrupted! Writing prevented. (${docRead.size} != ${reflectedContent.size})`,
932
- LOG_LEVEL_NOTICE
933
- );
934
- return false;
935
- }
936
- }
937
- const reflectedEvidence = await this.contentEvidence(reflectedContent);
938
- if (allowExistingConflicts && existDoc && !force) {
939
- const readFile = await this.readFileFromStub(existDoc);
940
- if (await isDocContentSame(docData, readFile.body)) {
941
- await this.setProvenance(path, docEntry._rev, existDoc.stat.mtime, reflectedContent, reflectedEvidence);
942
- this.path.markChangesAreSame(docRead, docRead.mtime, existDoc.stat.mtime);
943
- return true;
944
- }
945
- }
946
- let safeSnapshot;
947
- if (existDoc && !force) {
948
- let shouldApplied = false;
949
- const freshness = this.path.compareFileFreshness(existDoc, docEntry);
950
- if (freshness !== EVEN) {
951
- shouldApplied = true;
952
- }
953
- if (!shouldApplied) {
954
- const readFile = await this.readFileFromStub(existDoc);
955
- if (await isDocContentSame(docData, readFile.body)) {
956
- shouldApplied = false;
957
- this.path.markChangesAreSame(docRead, docRead.mtime, existDoc.stat.mtime);
958
- } else {
959
- shouldApplied = true;
960
- }
961
- }
962
- if (!shouldApplied) {
963
- await this.setProvenance(path, docEntry._rev, existDoc.stat.mtime, reflectedContent, reflectedEvidence);
964
- this._log(`File ${docRead.path} is not changed`, LOG_LEVEL_VERBOSE);
965
- return true;
966
- }
967
- if (!force && !settings.writeDocumentsIfConflicted) {
968
- let protection = await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry, docData);
969
- if (protection.preserved) return true;
970
- if (!protection.snapshot) {
971
- protection = await this.recheckIncomingStorage(path, docEntry, docData, allowExistingConflicts);
972
- if (protection.preserved) return true;
973
- if (!protection.snapshot) return false;
974
- }
975
- safeSnapshot = protection.snapshot;
976
- }
977
- } else {
978
- this._log(
979
- `File ${docRead.path} ${existDoc ? "(new) " : ""} ${force ? " (forced)" : ""}`,
980
- LOG_LEVEL_VERBOSE
981
- );
982
- }
983
- await this.storage.ensureDir(path);
984
- if (safeSnapshot && !await this.currentStorageSnapshotMatches(safeSnapshot.file, safeSnapshot.revision)) {
985
- const protection = await this.recheckIncomingStorage(path, docEntry, docData, allowExistingConflicts);
986
- if (protection.preserved) return true;
987
- if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) {
988
- return false;
989
- }
990
- safeSnapshot = protection.snapshot;
991
- }
992
- const latest = await this.reconcileAdvancedIncomingRevision(
993
- docEntry,
994
- path,
995
- force,
996
- allowExistingConflicts,
997
- incomingRetry
998
- );
999
- if (latest !== void 0) return latest;
1000
- if (safeSnapshot && !await this.currentStorageSnapshotMatches(safeSnapshot.file, safeSnapshot.revision)) {
1001
- return false;
1002
- }
1003
- const ret = await this.storage.writeFileAuto(path, docData, { ctime: docRead.ctime, mtime: docRead.mtime });
1004
- await this.storage.touched(path);
1005
- this.storage.triggerFileEvent(mode, path);
1006
- if (ret && this.fileReflectionProvenance) {
1007
- const storedStat = await this.storage.stat(path);
1008
- if (safeSnapshot && !sameProvenance(await this.readProvenanceSnapshot(path), safeSnapshot.revision)) {
1009
- return ret;
1010
- }
1011
- await this.setProvenance(path, docEntry._rev, storedStat?.mtime, reflectedContent, reflectedEvidence);
1012
- }
1013
- return ret;
206
+ async deleteFileFromDB(info) {
207
+ return await deleteFileFromDB(this.context, info);
1014
208
  }
1015
209
  /**
1016
- * Preserve storage bytes before an incoming reflection can replace them.
1017
- *
1018
- * The initial read and provenance form one candidate snapshot. Classification
1019
- * gives a recorded branch priority, deduplicates matching live leaves, or
1020
- * creates an independent root for unknown origin. Optional `incomingContent` avoids
1021
- * re-reading an already loaded incoming body. Storage is revalidated before
1022
- * and after the database write; `preserved: true` stops the incoming write,
1023
- * while a returned `snapshot` lets the caller continue only after revalidation.
210
+ * Record a rename under both source and destination document locks.
211
+ * @param info - The destination file observation, optionally already containing its body.
212
+ * @param oldPath - The rename source path whose branch must be preserved or deleted safely.
213
+ * @returns True after target/source handling or conservative source preservation; false on target collision or refused work.
214
+ * @remarks Acquire deduplicated source and target document locks. Save the target before guarded source cleanup; unknown source ancestry is preserved for review.
1024
215
  */
1025
- async preserveUnsyncedStorageAsConflict(path, existDoc, incomingEntry, incomingContent) {
1026
- const observedProvenance = await this.readProvenanceSnapshot(path);
1027
- const readFile = await this.readFileFromStub(existDoc);
1028
- const snapshot = { file: readFile, revision: observedProvenance };
1029
- if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) {
1030
- return await this.currentStorageSnapshotMatches(readFile, observedProvenance) ? { preserved: false, snapshot } : { preserved: false };
1031
- }
1032
- if (!incomingEntry._rev) {
1033
- return { preserved: false };
1034
- }
1035
- const classification = await this.classifyStorageContent(
1036
- readFile,
1037
- incomingEntry,
1038
- void 0,
1039
- observedProvenance,
1040
- incomingContent ? { _rev: incomingEntry._rev, data: incomingContent } : void 0
1041
- );
1042
- if (!await this.currentStorageSnapshotMatches(readFile, observedProvenance)) {
1043
- return { preserved: false };
1044
- }
1045
- if (classification.kind === "unchanged") {
1046
- return { preserved: false, snapshot };
1047
- }
1048
- if (classification.kind === "matching-leaf") {
1049
- await this.rememberMatchingLeaf(path, classification.revision, readFile.stat.mtime, readFile.body);
1050
- await this.queueConflictCheckFor(path);
1051
- return { preserved: true };
1052
- }
1053
- const storedRevision = classification.kind === "edited" ? await this.db.storeWithBaseRevision(readFile, classification.revision, true) : await this.db.storeIndependentRevision(readFile, true);
1054
- if (storedRevision === false) {
1055
- this._log(`Prevented overwriting unsynchronised local changes for ${path}`, LOG_LEVEL_NOTICE);
1056
- return { preserved: true };
1057
- }
1058
- if (!await this.finaliseStoredRevision(readFile, observedProvenance, storedRevision)) {
1059
- return { preserved: false };
1060
- }
1061
- this._log(`Preserved unsynchronised local changes as a conflict for ${path}`, LOG_LEVEL_NOTICE);
1062
- await this.queueConflictCheckFor(path);
1063
- return { preserved: true };
216
+ async renameFileInDB(info, oldPath) {
217
+ return await renameFileInDB(this.context, info, oldPath);
1064
218
  }
1065
219
  /**
1066
- * Repeat overwrite protection from a fresh storage read after a snapshot
1067
- * becomes stale. Existing conflicts may defer reflection and request an
1068
- * open-only check while leaving the current storage untouched.
220
+ * Delete a selected revision under its document lock.
221
+ * @param info - The supplied file observation or path.
222
+ * @param rev - The exact selected database revision.
223
+ * @returns The database deletion result; matching provenance is cleared only after success.
224
+ * @remarks Acquire the document lock and delete the selected revision. Matching provenance clearing is attempted best-effort only after successful deletion.
1069
225
  */
1070
- async recheckIncomingStorage(path, incomingEntry, incomingContent, allowExistingConflicts) {
1071
- const current = await this.storage.getStub(path);
1072
- if (!current || isFolderInfo(current)) return { preserved: false };
1073
- const protection = await this.preserveUnsyncedStorageAsConflict(path, current, incomingEntry, incomingContent);
1074
- if (protection.preserved || !protection.snapshot) return protection;
1075
- if (!allowExistingConflicts && !this.setting.currentSettings().writeDocumentsIfConflicted && (await this.db.getConflictedRevs(path)).length > 0) {
1076
- await this.queueConflictCheckFor(path, true);
1077
- return { preserved: true };
1078
- }
1079
- return protection;
226
+ async deleteRevisionFromDB(info, rev) {
227
+ return await deleteRevisionFromDB(this.context, info, rev);
1080
228
  }
1081
229
  /**
1082
- * Re-read database metadata immediately before reflecting an incoming entry.
1083
- * If the current revision advanced, recurse with fresh storage; force and
1084
- * explicitly allowed conflict writes retain the caller's selected entry.
1085
- * `incomingRetry` bounds repeated database churn.
230
+ * Run the legacy delete-and-reflect resolution under one document lock.
231
+ * @param info - The supplied file observation or path.
232
+ * @param rev - The exact selected database revision.
233
+ * @returns False on refusal; the existing undefined result on successful legacy completion.
234
+ * @remarks Acquire the document lock for the existing metadata-capture, deletion, reflection, and best-effort-provenance-clear sequence. Operation errors retain precedence over post-lock hook errors.
1086
235
  */
1087
- async reconcileAdvancedIncomingRevision(incomingEntry, path, force, allowExistingConflicts, incomingRetry) {
1088
- if (force || allowExistingConflicts) return void 0;
1089
- const current = await this.db.fetchEntryMeta(path, void 0, true);
1090
- if (!current) return false;
1091
- if (current._rev === incomingEntry._rev) return void 0;
1092
- if (incomingRetry >= 2) {
1093
- this._log(`Database kept changing while reflecting ${path}`, LOG_LEVEL_NOTICE);
1094
- return false;
1095
- }
1096
- const storage = await this.storage.getStub(path);
1097
- if (isFolderInfo(storage)) return false;
1098
- return await this.applyDatabaseEntryToStorage(current, storage, force, allowExistingConflicts, incomingRetry + 1);
1099
- }
1100
- async _anyHandlerProcessesFileEvent(item) {
1101
- if (item.restoredFromPreviousRuntime) {
1102
- return await this._processRestoredFileEvent(item);
1103
- }
1104
- const eventItem = item.args;
1105
- const type = item.type;
1106
- const path = eventItem.file.path;
1107
- if (type === "RENAME" && !eventItem.oldPath) {
1108
- this._log(`Rename event for ${path} has no source path`, LOG_LEVEL_VERBOSE);
1109
- return false;
1110
- }
1111
- const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
1112
- const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
1113
- return await this.serializedByFileEventPaths(eventPaths, async () => {
1114
- if (!await this.isCurrentPathSelected(path)) {
1115
- return shouldBeIgnored(path) || !await this.vault.isTargetFile(path, { skipCaseCollisionCheck: true });
1116
- }
1117
- switch (type) {
1118
- case "CREATE":
1119
- case "CHANGED": {
1120
- const current = this.getExactCurrentFile(await this.storage.getStub(path), path);
1121
- if (!current || this.vault.isFileSizeTooLarge(current.stat.size)) return true;
1122
- return await this.storeFileToDBFromRevision(current);
1123
- }
1124
- case "DELETE":
1125
- try {
1126
- if (!await this.canRecordStorageDeletion(item)) return true;
1127
- } catch {
1128
- return false;
1129
- }
1130
- return await this.deleteFileFromDBIfPresent(item.args.file);
1131
- case "RENAME":
1132
- return await this.renameFileInDBCore(
1133
- item.args.file,
1134
- item.args.oldPath
1135
- );
1136
- case "INTERNAL":
1137
- return false;
1138
- default:
1139
- this._log(`Unsupported event type: ${type}`, LOG_LEVEL_VERBOSE);
1140
- return false;
1141
- }
1142
- });
1143
- }
1144
- async canRecordStorageDeletion(item) {
1145
- const path = item.args.file.path;
1146
- try {
1147
- const current = await this.storage.getStub(path);
1148
- let excludedRenameTarget = null;
1149
- if (item.args.renameTarget !== void 0) {
1150
- const targetPath = item.args.renameTarget;
1151
- const targetItem = await this.storage.getStub(targetPath);
1152
- const target = this.getExactCurrentFile(targetItem, targetPath);
1153
- if (targetItem !== null && !target) {
1154
- this._log(`Preserved ${path}: the rename target no longer resolves to ${targetPath}`, LOG_LEVEL_NOTICE);
1155
- return false;
1156
- }
1157
- const targetIsSelected = !shouldBeIgnored(targetPath) && await this.vault.isTargetFile(targetPath, { skipCaseCollisionCheck: true }) && !(target && this.vault.isFileSizeTooLarge(target.stat.size));
1158
- if (targetIsSelected) {
1159
- this._log(`Preserved ${path}: rename target ${targetPath} is still selected`, LOG_LEVEL_NOTICE);
1160
- return false;
1161
- }
1162
- excludedRenameTarget = target;
1163
- }
1164
- if (current === null) return true;
1165
- if (!isFolderInfo(current)) {
1166
- const [currentId, deletedId] = await Promise.all([
1167
- this.path.path2id(current.path),
1168
- this.path.path2id(path)
1169
- ]);
1170
- if (currentId !== deletedId) return true;
1171
- if (excludedRenameTarget && this.storage.normalisePath(current.path) !== this.storage.normalisePath(path) && this.storage.normalisePath(current.path) === this.storage.normalisePath(excludedRenameTarget.path)) {
1172
- return true;
1173
- }
1174
- }
1175
- this._log(`Preserved ${path}: a current storage item contradicts its deletion event`, LOG_LEVEL_NOTICE);
1176
- return false;
1177
- } catch (ex) {
1178
- this._log(`Could not validate deletion of ${path}; preserved the database entry`, LOG_LEVEL_NOTICE);
1179
- this._log(ex, LOG_LEVEL_VERBOSE);
1180
- throw ex;
1181
- }
236
+ async resolveConflictedByDeletingRevision(info, rev) {
237
+ return await resolveConflictedByDeletingRevision(this.context, info, rev);
1182
238
  }
1183
239
  /**
1184
- * Serialise work by every document ID represented by the supplied paths.
1185
- * IDs are deduplicated and sorted so aliases take one lock and cross-document renames have one order.
1186
- * The callback runs under those locks and must use core methods; conflict
1187
- * hooks requested inside it are deferred until all locks have been released.
240
+ * Reflect one selected live revision under the storage document lock.
241
+ * @param info - The supplied file observation or path.
242
+ * @param rev - The exact selected database revision.
243
+ * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
244
+ * @returns The selected live leaf reflection result, or false if the selected revision is no longer live.
245
+ * @remarks Acquire the document lock and validate that the selected revision remains live before protected reflection. Refusals return false; operation errors reject.
1188
246
  */
1189
- async serializedByFileEventPaths(eventPaths, callback) {
1190
- const documentIds = await Promise.all(eventPaths.map((eventPath) => this.path.path2id(eventPath)));
1191
- const uniqueIds = [...new Set(documentIds)].sort();
1192
- const lockKeys = uniqueIds.map((documentId) => `processFileEvent-${documentId}`);
1193
- const pending = [];
1194
- let result;
1195
- let failed = false;
1196
- let failure;
1197
- try {
1198
- result = await withLocks(lockKeys, async () => {
1199
- for (const id of uniqueIds) this.deferredConflictChecks.set(id, pending);
1200
- try {
1201
- return await callback(documentIds.length === 2 && documentIds[0] === documentIds[1]);
1202
- } finally {
1203
- for (const id of uniqueIds) this.deferredConflictChecks.delete(id);
1204
- }
1205
- });
1206
- } catch (ex) {
1207
- failed = true;
1208
- failure = ex;
1209
- }
1210
- for (const check of pending) {
1211
- try {
1212
- if (check.ifOpen) await this.conflict.queueCheckForIfOpen(check.path);
1213
- else await this.conflict.queueCheckFor(check.path);
1214
- } catch (ex) {
1215
- if (!failed) {
1216
- failed = true;
1217
- failure = ex;
1218
- }
1219
- break;
1220
- }
1221
- }
1222
- if (failed) throw failure;
1223
- return result;
247
+ async dbToStorageWithSpecificRev(info, rev, force) {
248
+ return await dbToStorageWithSpecificRev(this.context, info, rev, force);
1224
249
  }
1225
250
  /**
1226
- * Queue a conflict hook while its document lock is held, or run it directly
1227
- * when no matching lock is active. Preserve `ifOpen` across deferral.
251
+ * Fetch and reflect the current database revision under its document lock.
252
+ * @param entryInfo - Current metadata or a path from which metadata is loaded.
253
+ * @param info - The supplied file observation or path.
254
+ * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
255
+ * @returns True after reflection or a safe conflict/absence skip; false on unreadable or unsafe observations.
256
+ * @remarks Acquire the document lock before fetching current metadata and protected reflection. Safe skips may return true without writing a file; operation errors reject.
1228
257
  */
1229
- async queueConflictCheckFor(path, ifOpen = false) {
1230
- const documentId = await this.path.path2id(path);
1231
- const pending = this.deferredConflictChecks.get(documentId);
1232
- if (pending) {
1233
- pending.push({ path, ifOpen });
1234
- return;
1235
- }
1236
- if (ifOpen) await this.conflict.queueCheckForIfOpen(path);
1237
- else await this.conflict.queueCheckFor(path);
258
+ async dbToStorage(entryInfo, info, force) {
259
+ return await dbToStorage(this.context, entryInfo, info, force);
1238
260
  }
1239
261
  /**
1240
- * Revalidate a persisted storage operation against the current storage state.
1241
- *
1242
- * Snapshot entries preserve operation intent and ordering only. Their file
1243
- * stub, timestamps, and existence assumptions can be stale after a restart.
1244
- * Current inclusion is therefore read from storage, while destructive work
1245
- * is allowed only after current absence has been observed. Store and rename
1246
- * actions use the fresh reread with bounded retry because no later watcher
1247
- * event is guaranteed after startup reconciliation.
262
+ * Select and reflect a replicated document while retaining host override dispatch.
263
+ * @param entry - The database metadata being processed.
264
+ * @returns Whether replication reflection completed; excluded or unsafe documents retain a false result.
265
+ * @remarks Acquire the related document lock before selection and reflection. Constructor registration captures the current subclass override with bind; internal public seams remain live at use time.
1248
266
  */
1249
- async _processRestoredFileEvent(item) {
1250
- const eventItem = item.args;
1251
- const type = item.type;
1252
- const path = eventItem.file.path;
1253
- if (type === "RENAME" && !eventItem.oldPath) {
1254
- this._log(`Rename event for ${path} has no source path`, LOG_LEVEL_VERBOSE);
1255
- return true;
1256
- }
1257
- const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
1258
- const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
1259
- return await this.serializedByFileEventPaths(eventPaths, async (isSameDocument) => {
1260
- let action;
1261
- try {
1262
- action = await this._planRestoredFileEvent(item, isSameDocument);
1263
- } catch (ex) {
1264
- this.logRestoredEventValidationFailure(path, ex);
1265
- return false;
1266
- }
1267
- switch (action.kind) {
1268
- case "none":
1269
- return true;
1270
- case "unresolved":
1271
- return false;
1272
- case "store": {
1273
- const stored = await this.storeFileToDBFromRevision(action.file, false, false, void 0, true);
1274
- return stored && action.complete !== false;
1275
- }
1276
- case "delete":
1277
- return await this.deleteFileFromDBIfPresent(action.path);
1278
- case "rename":
1279
- return await this.renameFileInDBCore(action.file, action.oldPath, true);
1280
- }
1281
- });
1282
- }
1283
- async _planRestoredFileEvent(item, isSameDocument) {
1284
- const path = item.args.file.path;
1285
- switch (item.type) {
1286
- case "CREATE":
1287
- case "CHANGED": {
1288
- const current = this.getExactCurrentFile(await this.storage.getStub(path), path);
1289
- return current && await this.isCurrentFileSelected(current) ? { kind: "store", file: current } : { kind: "none" };
1290
- }
1291
- case "DELETE": {
1292
- if (item.args.renameTarget !== void 0) {
1293
- return await this.canRecordStorageDeletion(item) && await this.canApplyRestoredDeletion(path) ? { kind: "delete", path } : { kind: "none" };
1294
- }
1295
- const current = await this.storage.getStub(path);
1296
- return current === null && await this.canApplyRestoredDeletion(path) ? { kind: "delete", path } : { kind: "none" };
1297
- }
1298
- case "RENAME":
1299
- return await this._planRestoredRename(path, item.args.oldPath, isSameDocument);
1300
- case "INTERNAL":
1301
- return { kind: "none" };
1302
- default:
1303
- this._log(`Unsupported event type: ${item.type}`, LOG_LEVEL_VERBOSE);
1304
- return { kind: "none" };
1305
- }
1306
- }
1307
- async _planRestoredRename(newPath, oldPath, isSameDocument) {
1308
- if (isSameDocument) {
1309
- const currentTarget2 = this.getExactCurrentFile(await this.storage.getStub(newPath), newPath);
1310
- if (!currentTarget2 || !await this.isCurrentFileSelected(currentTarget2)) {
1311
- return { kind: "none" };
1312
- }
1313
- const entry = await this.db.fetchEntryMeta(newPath, void 0, true);
1314
- if (entry && !entry.deleted && !entry._deleted && this.storage.normalisePath(this.getPath(entry)) === this.storage.normalisePath(newPath)) {
1315
- return { kind: "store", file: currentTarget2 };
1316
- }
1317
- return { kind: "rename", file: currentTarget2, oldPath };
1318
- }
1319
- const currentTargetItem = await this.storage.getStub(newPath);
1320
- let currentSourceItem = null;
1321
- let sourceWasInspected = true;
1322
- try {
1323
- currentSourceItem = await this.storage.getStub(oldPath);
1324
- } catch (ex) {
1325
- sourceWasInspected = false;
1326
- this.logRestoredEventValidationFailure(oldPath, ex);
1327
- }
1328
- const currentTarget = this.getExactCurrentFile(currentTargetItem, newPath);
1329
- if (currentTargetItem !== null) {
1330
- if (!currentTarget || !await this.isCurrentFileSelected(currentTarget)) {
1331
- return { kind: "none" };
1332
- }
1333
- if (!sourceWasInspected || currentSourceItem !== null || !await this.canApplyRestoredDeletion(oldPath)) {
1334
- return { kind: "store", file: currentTarget, complete: sourceWasInspected };
1335
- }
1336
- const sourceEntry = await this.db.fetchEntryMeta(oldPath, void 0, true);
1337
- if (!sourceEntry || sourceEntry.deleted || sourceEntry._deleted) {
1338
- return { kind: "store", file: currentTarget };
1339
- }
1340
- return { kind: "rename", file: currentTarget, oldPath };
1341
- }
1342
- if (!sourceWasInspected) return { kind: "unresolved" };
1343
- if (currentSourceItem !== null || !await this.canApplyRestoredDeletion(oldPath)) {
1344
- return { kind: "none" };
1345
- }
1346
- return { kind: "delete", path: oldPath };
1347
- }
1348
- getExactCurrentFile(current, expectedPath) {
1349
- if (current === null || isFolderInfo(current)) {
1350
- return null;
1351
- }
1352
- return this.storage.normalisePath(current.path) === this.storage.normalisePath(expectedPath) ? current : null;
1353
- }
1354
- async isCurrentFileSelected(file) {
1355
- if (!await this.isCurrentPathSelected(file.path)) {
1356
- return false;
1357
- }
1358
- if (this.vault.isFileSizeTooLarge(file.stat.size)) {
1359
- this._log(`File ${file.path} exceeds the current maximum size`, LOG_LEVEL_VERBOSE);
1360
- return false;
1361
- }
1362
- return true;
1363
- }
1364
- async isCurrentPathSelected(path) {
1365
- if (!await this.vault.isTargetFile(path)) {
1366
- this._log(`File ${path} is not the target file`, LOG_LEVEL_VERBOSE);
1367
- return false;
1368
- }
1369
- if (shouldBeIgnored(path)) {
1370
- this._log(`File ${path} should be ignored`, LOG_LEVEL_VERBOSE);
1371
- return false;
1372
- }
1373
- return true;
1374
- }
1375
- async canApplyRestoredDeletion(path) {
1376
- try {
1377
- return await this.isCurrentPathSelected(path);
1378
- } catch (ex) {
1379
- this.logRestoredEventValidationFailure(path, ex);
1380
- throw ex;
1381
- }
1382
- }
1383
- logRestoredEventValidationFailure(path, ex) {
1384
- this._log(
1385
- `Could not validate the saved storage operation for ${path} against current storage; the operation remains pending for recovery`,
1386
- LOG_LEVEL_NOTICE
1387
- );
1388
- this._log(ex, LOG_LEVEL_VERBOSE);
1389
- }
1390
267
  async _anyProcessReplicatedDoc(entry) {
1391
- return await this.serializedByFileEventPaths([this.getPath(entry)], async () => {
1392
- if (!await this.vault.isTargetFile(entry.path)) {
1393
- this._log(`File ${entry.path} is not the target file`, LOG_LEVEL_VERBOSE);
1394
- return false;
1395
- }
1396
- if (this.vault.isFileSizeTooLarge(entry.size)) {
1397
- this._log(`File ${entry.path} is too large (on database) to be processed`, LOG_LEVEL_VERBOSE);
1398
- return false;
1399
- }
1400
- if (shouldBeIgnored(entry.path)) {
1401
- this._log(`File ${entry.path} should be ignored`, LOG_LEVEL_VERBOSE);
1402
- return false;
1403
- }
1404
- const path = this.getPath(entry);
1405
- const targetFile = await this.storage.getStub(this.getPathWithoutPrefix(entry));
1406
- if (isFolderInfo(targetFile)) {
1407
- this._log(`${path} is already exist as the folder`);
1408
- return true;
1409
- } else {
1410
- if (targetFile && this.vault.isFileSizeTooLarge(targetFile.stat.size)) {
1411
- this._log(`File ${targetFile.path} is too large (on storage) to be processed`, LOG_LEVEL_VERBOSE);
1412
- return false;
1413
- }
1414
- this._log(
1415
- `Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Started...`,
1416
- LOG_LEVEL_VERBOSE
1417
- );
1418
- this.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
1419
- const ret = await this.dbToStorageCore(entry, targetFile);
1420
- this._log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Done`);
1421
- return ret;
1422
- }
1423
- });
268
+ return await processReplicatedDocument(this.context, entry);
1424
269
  }
270
+ /**
271
+ * Repair missing chunks with at most ten acquired file operations at a time.
272
+ * @param showingNotice - Whether progress uses notice-level messages instead of informational messages.
273
+ * @returns Completion after all selected tasks settle. Per-file save errors are logged and swallowed; listing, selection, acquisition, progress, or logger failures can still reject.
274
+ * @remarks Each file uses the dynamic public save seam and its document lock. Up to ten permits are acquired; progress remains before the original guarded body, preserving its existing cleanup semantics.
275
+ */
1425
276
  async createAllChunks(showingNotice) {
1426
- this._log("Collecting local files on the storage", LOG_LEVEL_VERBOSE);
1427
- const semaphore = Semaphore(10);
1428
- let processed = 0;
1429
- const filesStorageSrc = await this.storage.getFiles();
1430
- const incProcessed = () => {
1431
- processed++;
1432
- if (processed % 25 == 0)
1433
- this._log(
1434
- `Creating missing chunks: ${processed} of ${total} files`,
1435
- showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
1436
- "chunkCreation"
1437
- );
1438
- };
1439
- const total = filesStorageSrc.length;
1440
- const procAllChunks = filesStorageSrc.map(async (file) => {
1441
- if (!await this.vault.isTargetFile(file)) {
1442
- incProcessed();
1443
- return true;
1444
- }
1445
- if (this.vault.isFileSizeTooLarge(file.stat.size)) {
1446
- incProcessed();
1447
- return true;
1448
- }
1449
- if (shouldBeIgnored(file.path)) {
1450
- incProcessed();
1451
- return true;
1452
- }
1453
- const release = await semaphore.acquire();
1454
- incProcessed();
1455
- try {
1456
- await this.storeFileToDB(file, false, true);
1457
- } catch (ex) {
1458
- this._log(ex, LOG_LEVEL_VERBOSE);
1459
- } finally {
1460
- release();
1461
- }
1462
- });
1463
- await Promise.all(procAllChunks);
1464
- this._log(
1465
- `Creating chunks Done: ${processed} of ${total} files`,
1466
- showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
1467
- "chunkCreation"
1468
- );
277
+ return await createAllChunks(this.context, showingNotice);
1469
278
  }
1470
279
  }
1471
280
  export {