@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
@@ -0,0 +1,40 @@
1
+ import type { FilePathWithPrefix, UXFileInfo, UXFileInfoStub, UXInternalFileInfoStub } from "../../common/types.js";
2
+ import type { StoreFileOptions } from "../../interfaces/FileHandler.js";
3
+ import type { FileHandlerContext } from "./context.js";
4
+ /**
5
+ * Save ordinary storage content under its document lock.
6
+ *
7
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
8
+ * @param info - The supplied file observation or path.
9
+ * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
10
+ * @param onlyChunks - Whether to repair chunks without creating a document revision.
11
+ * @param options - The existing recovery revalidation option for this save.
12
+ * @returns True when current bytes are represented or chunk repair succeeds; false for refused or unstable observations.
13
+ * @remarks Core helpers require the caller's document lock. Ordinary revision writes reuse the captured body; legacy-evidence upgrades retain their validation reads, and recovery permits two fresh retries in addition to validation rereads.
14
+ */
15
+ export declare function storeFileToDB(ctx: FileHandlerContext, info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean, options?: StoreFileOptions): Promise<boolean>;
16
+ /**
17
+ * Save current bytes under one selected live database revision.
18
+ *
19
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
20
+ * @param info - The supplied file observation or path.
21
+ * @param baseRevision - The exact selected live database revision.
22
+ * @param createIfDifferent - Whether differing bytes may create a child of the selected revision.
23
+ * @returns True when matching bytes are certified or a selected-base child is stored; false when the live-base or content condition refuses it.
24
+ * @remarks Core helpers require the caller's document lock. Ordinary revision writes reuse the captured body; legacy-evidence upgrades retain their validation reads, and recovery permits two fresh retries in addition to validation rereads.
25
+ */
26
+ export declare function storeFileToDBWithBaseRevision(ctx: FileHandlerContext, info: UXFileInfoStub | UXFileInfo | FilePathWithPrefix, baseRevision: string, createIfDifferent?: boolean): Promise<boolean>;
27
+ /**
28
+ * Save one observed storage body using provenance and the current revision tree.
29
+ *
30
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
31
+ * @param info - The supplied file observation or path.
32
+ * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
33
+ * @param onlyChunks - Whether to repair chunks without creating a document revision.
34
+ * @param preferredBasePath - The source provenance path used during a rename, when supplied.
35
+ * @param retryIfStorageChanges - Whether recovery revalidates storage and permits bounded rereads.
36
+ * @param snapshotRetry - The number of storage rereads already consumed.
37
+ * @returns True when the observed bytes are represented; false after a refused write or exhausted recovery rechecks.
38
+ * @remarks Core helpers require the caller's document lock. Ordinary revision writes reuse the captured body; legacy-evidence upgrades retain their validation reads, and recovery permits two fresh retries in addition to validation rereads.
39
+ */
40
+ export declare function storeFileToDBFromRevision(ctx: FileHandlerContext, info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean, preferredBasePath?: FilePathWithPrefix, retryIfStorageChanges?: boolean, snapshotRetry?: number): Promise<boolean>;
@@ -0,0 +1,306 @@
1
+ import { isFolderInfo, infoToStub } from "./storage.js";
2
+ import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
3
+ import {
4
+ setProvenance,
5
+ readProvenanceSnapshot,
6
+ getProvenBaseRevision,
7
+ deleteProvenance,
8
+ classifyStorageContent,
9
+ contentEvidence,
10
+ hasContentHash,
11
+ currentStorageSnapshotMatches,
12
+ rememberMatchingLeaf,
13
+ finaliseStoredRevision
14
+ } from "./provenance.js";
15
+ import { dbToStorageCore } from "./reflection.js";
16
+ import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
17
+ import { displayRev, getDocDataAsArray, isDocContentSame, readContent } from "../../common/utils.js";
18
+ import { getStoragePathFromUXFileInfo } from "../../common/typeUtils.js";
19
+ import { EVEN } from "../../common/models/shared.const.symbols.js";
20
+ import { tryGetFilePath } from "../../common/utils.doc.js";
21
+ async function retryCurrentStorage(ctx, path, preferredBasePath, snapshotRetry) {
22
+ if (snapshotRetry >= 2) {
23
+ ctx.host.log(`Storage kept changing while saving ${path}; a fresh event is required`, LOG_LEVEL_NOTICE);
24
+ return false;
25
+ }
26
+ const fresh = await ctx.host.storage().getStub(path);
27
+ if (!fresh || isFolderInfo(fresh)) return false;
28
+ return await storeFileToDBFromRevision(ctx, fresh, false, false, preferredBasePath, true, snapshotRetry + 1);
29
+ }
30
+ async function storeFileToDB(ctx, info, force = false, onlyChunks = false, options = {}) {
31
+ return await withFileEventPaths(
32
+ ctx,
33
+ [getStoragePathFromUXFileInfo(info)],
34
+ () => storeFileToDBFromRevision(ctx, info, force, onlyChunks, void 0, options.revalidateStorage)
35
+ );
36
+ }
37
+ async function storeFileToDBWithBaseRevision(ctx, info, baseRevision, createIfDifferent = true) {
38
+ return await withFileEventPaths(
39
+ ctx,
40
+ [getStoragePathFromUXFileInfo(info)],
41
+ () => storeFileToDBWithBaseRevisionCore(ctx, info, baseRevision, createIfDifferent)
42
+ );
43
+ }
44
+ async function storeFileToDBWithBaseRevisionCore(ctx, info, baseRevision, createIfDifferent) {
45
+ const file = await infoToStub(ctx, info);
46
+ if (file == null) {
47
+ ctx.host.log(`File ${tryGetFilePath(info)} is not exist on the storage`, LOG_LEVEL_VERBOSE);
48
+ return false;
49
+ }
50
+ if (file.isInternal) {
51
+ ctx.host.log(
52
+ `Internal file ${file.path} is not allowed to be stored through the ordinary file handler`,
53
+ LOG_LEVEL_VERBOSE
54
+ );
55
+ return false;
56
+ }
57
+ const [baseEntry, currentEntry, conflictedRevisions] = await Promise.all([
58
+ ctx.host.db().fetchEntryMeta(file, baseRevision, true),
59
+ ctx.host.db().fetchEntryMeta(file, void 0, true),
60
+ ctx.host.db().getConflictedRevs(file)
61
+ ]);
62
+ const liveRevisions = /* @__PURE__ */ new Set([
63
+ ...currentEntry && currentEntry._rev ? [currentEntry._rev] : [],
64
+ ...conflictedRevisions
65
+ ]);
66
+ if (!baseEntry || baseEntry._rev !== baseRevision || !liveRevisions.has(baseRevision)) {
67
+ ctx.host.log(
68
+ `Could not store ${file.path} on revision ${baseRevision}; the selected revision is no longer live`,
69
+ LOG_LEVEL_NOTICE
70
+ );
71
+ return false;
72
+ }
73
+ const readFile = await ctx.host.readFileFromStub(file);
74
+ if (!baseEntry.deleted && !baseEntry._deleted) {
75
+ const loadedBase = await ctx.host.db().fetchEntry(file, baseRevision, true, true);
76
+ if (loadedBase && await isDocContentSame(getDocDataAsArray(loadedBase.data), readFile.body)) {
77
+ await setProvenance(ctx, file.path, baseRevision, readFile.stat.mtime, readFile.body);
78
+ await queueConflictCheckFor(ctx, file.path);
79
+ return true;
80
+ }
81
+ }
82
+ if (!createIfDifferent) {
83
+ ctx.host.log(
84
+ `Could not mark ${file.path} as revision ${baseRevision}; the storage content differs`,
85
+ LOG_LEVEL_NOTICE
86
+ );
87
+ return false;
88
+ }
89
+ const storedRevision = await ctx.host.db().storeWithBaseRevision(readFile, baseRevision, true);
90
+ if (storedRevision === false) {
91
+ return false;
92
+ }
93
+ await setProvenance(ctx, file.path, storedRevision, readFile.stat.mtime, readFile.body);
94
+ await queueConflictCheckFor(ctx, file.path);
95
+ return true;
96
+ }
97
+ async function storeFileToDBFromRevision(ctx, info, force = false, onlyChunks = false, preferredBasePath, retryIfStorageChanges = false, snapshotRetry = 0) {
98
+ const file = await infoToStub(ctx, info);
99
+ if (file == null) {
100
+ ctx.host.log(`File ${tryGetFilePath(info)} is not exist on the storage`, LOG_LEVEL_VERBOSE);
101
+ return false;
102
+ }
103
+ if (file.isInternal) {
104
+ ctx.host.log(
105
+ `Internal file ${file.path} is not allowed to be processed on processFileEvent`,
106
+ LOG_LEVEL_VERBOSE
107
+ );
108
+ return false;
109
+ }
110
+ if (onlyChunks) {
111
+ const readFile = await ctx.host.readFileFromStub(file);
112
+ return await ctx.host.db().createChunks(readFile, force, true);
113
+ }
114
+ const save = await observeStorageSave(ctx, file, preferredBasePath, retryIfStorageChanges);
115
+ const currentEntry = save.currentEntry;
116
+ const currentIsLive = currentEntry && !currentEntry.deleted && !currentEntry._deleted;
117
+ if (!force && (currentIsLive || retryIfStorageChanges)) {
118
+ return await saveClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges, snapshotRetry);
119
+ }
120
+ if (save.isConflicted) return await saveConflictedStorage(ctx, save, force, preferredBasePath);
121
+ if (!currentEntry || currentEntry.deleted || currentEntry._deleted)
122
+ return await createStorageRevision(ctx, save, preferredBasePath);
123
+ return await saveCurrentStorage(ctx, save, currentEntry, force, onlyChunks, preferredBasePath);
124
+ }
125
+ async function observeStorageSave(ctx, file, preferredBasePath, retryIfStorageChanges) {
126
+ const observedProvenance = await readProvenanceSnapshot(
127
+ ctx,
128
+ preferredBasePath ?? file.path,
129
+ retryIfStorageChanges
130
+ );
131
+ const readFile = await ctx.host.readFileFromStub(file);
132
+ const entry = await ctx.host.db().fetchEntry(file, void 0, true, true, !retryIfStorageChanges);
133
+ const currentEntry = entry || await ctx.host.db().fetchEntryMeta(file, void 0, true);
134
+ const conflictedRevs = await ctx.host.db().getConflictedRevs(file);
135
+ const isConflicted = conflictedRevs.length > 0;
136
+ return { file, readFile, observedProvenance, entry, currentEntry, isConflicted };
137
+ }
138
+ async function saveClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges, snapshotRetry) {
139
+ const { entry, currentEntry } = save;
140
+ const currentIsLive = currentEntry && !currentEntry.deleted && !currentEntry._deleted;
141
+ if (retryIfStorageChanges && currentIsLive && !entry) {
142
+ const revision = currentEntry._rev ? displayRev(currentEntry._rev) : "unknown";
143
+ ctx.host.log(
144
+ `Could not reconcile ${save.file.path}: content for current database revision ${revision} is unavailable; this file remains unresolved for a later scan.`,
145
+ LOG_LEVEL_VERBOSE
146
+ );
147
+ return false;
148
+ }
149
+ const details = await observeClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges);
150
+ const recovery = { preferredBasePath, retryIfStorageChanges, snapshotRetry };
151
+ const classification = details.classification;
152
+ if (classification.kind === "unchanged")
153
+ return await finishUnchangedStorageSave(ctx, save, classification.revision, details, recovery);
154
+ if (classification.kind === "matching-leaf")
155
+ return await finishMatchingStorageSave(ctx, save, classification.revision, details, recovery);
156
+ return await storeClassifiedStorageEdit(ctx, save, classification, recovery);
157
+ }
158
+ async function saveConflictedStorage(ctx, save, force, preferredBasePath) {
159
+ const { file, readFile, entry } = save;
160
+ const baseRevision = await getProvenBaseRevision(ctx, readFile, preferredBasePath);
161
+ if (baseRevision) {
162
+ const baseEntry = await ctx.host.db().fetchEntry(file, baseRevision, true, true);
163
+ if (baseEntry && await isDocContentSame(getDocDataAsArray(baseEntry.data), readFile.body) && !force) {
164
+ await setProvenance(ctx, file.path, baseRevision, readFile.stat.mtime, readFile.body);
165
+ ctx.host.log(`File ${file.path} is not changed on its displayed conflict branch`, LOG_LEVEL_VERBOSE);
166
+ return true;
167
+ }
168
+ const storedRevision2 = await ctx.host.db().storeWithBaseRevision(readFile, baseRevision, true);
169
+ if (storedRevision2 === false) return false;
170
+ if (preferredBasePath && preferredBasePath !== file.path) {
171
+ await deleteProvenance(ctx, preferredBasePath);
172
+ }
173
+ await setProvenance(ctx, file.path, storedRevision2, readFile.stat.mtime, readFile.body);
174
+ await queueConflictCheckFor(ctx, file.path);
175
+ return true;
176
+ }
177
+ const currentEntry = entry || await ctx.host.db().fetchEntryMeta(file, void 0, true);
178
+ const currentRevision = currentEntry && currentEntry._rev;
179
+ if (!currentRevision) {
180
+ ctx.host.log(
181
+ `Could not preserve the unknown conflict branch for ${file.path}; no current revision is available`,
182
+ LOG_LEVEL_NOTICE
183
+ );
184
+ await queueConflictCheckFor(ctx, file.path);
185
+ return false;
186
+ }
187
+ const storedRevision = await ctx.host.db().storeAsConflictedRevisionWithResult(readFile, currentRevision, true);
188
+ if (storedRevision === false) {
189
+ ctx.host.log(`Could not preserve the unknown conflict branch for ${file.path}`, LOG_LEVEL_NOTICE);
190
+ await queueConflictCheckFor(ctx, file.path);
191
+ return false;
192
+ }
193
+ if (preferredBasePath && preferredBasePath !== file.path) {
194
+ await deleteProvenance(ctx, preferredBasePath);
195
+ }
196
+ await setProvenance(ctx, file.path, storedRevision, readFile.stat.mtime, readFile.body);
197
+ await queueConflictCheckFor(ctx, file.path);
198
+ return true;
199
+ }
200
+ async function createStorageRevision(ctx, save, preferredBasePath) {
201
+ const { file, readFile, entry } = save;
202
+ const storedRevision = await ctx.host.db().storeWithBaseRevision(readFile, entry ? entry._rev : void 0, true);
203
+ if (storedRevision === false) return false;
204
+ if (preferredBasePath && preferredBasePath !== file.path) {
205
+ await deleteProvenance(ctx, preferredBasePath);
206
+ }
207
+ await setProvenance(ctx, file.path, storedRevision, readFile.stat.mtime, readFile.body);
208
+ return true;
209
+ }
210
+ async function saveCurrentStorage(ctx, save, currentEntry, force, onlyChunks, preferredBasePath) {
211
+ const { file, readFile, entry } = save;
212
+ let shouldApplied = false;
213
+ if (!force && !onlyChunks && entry) {
214
+ if (ctx.path.compareFileFreshness(file, entry) !== EVEN) {
215
+ shouldApplied = true;
216
+ }
217
+ if (!shouldApplied) {
218
+ if (await isDocContentSame(getDocDataAsArray(entry.data), readFile.body)) {
219
+ ctx.path.markChangesAreSame(readFile, readFile.stat.mtime, entry.mtime);
220
+ } else {
221
+ shouldApplied = true;
222
+ }
223
+ }
224
+ if (!shouldApplied) {
225
+ await setProvenance(ctx, file.path, entry._rev, readFile.stat.mtime, readFile.body);
226
+ ctx.host.log(`File ${file.path} is not changed`, LOG_LEVEL_VERBOSE);
227
+ return true;
228
+ }
229
+ }
230
+ const storedRevision = await ctx.host.db().storeWithBaseRevision(readFile, currentEntry._rev, true);
231
+ if (storedRevision === false) return false;
232
+ if (preferredBasePath && preferredBasePath !== file.path) {
233
+ await deleteProvenance(ctx, preferredBasePath);
234
+ }
235
+ await setProvenance(ctx, file.path, storedRevision, readFile.stat.mtime, readFile.body);
236
+ return true;
237
+ }
238
+ async function observeClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges) {
239
+ const { readFile, observedProvenance, entry, currentEntry } = save;
240
+ const classification = await classifyStorageContent(
241
+ ctx,
242
+ readFile,
243
+ currentEntry,
244
+ preferredBasePath,
245
+ observedProvenance,
246
+ entry ? { _rev: entry._rev, data: readContent(entry) } : void 0,
247
+ retryIfStorageChanges
248
+ );
249
+ const upgradeCurrentRecord = shouldUpgradeSavedRecord(save, classification);
250
+ const evidence = upgradeCurrentRecord || classification.kind === "matching-leaf" && classification.revision ? await contentEvidence(ctx, readFile.body) : void 0;
251
+ return { classification, upgradeCurrentRecord, evidence };
252
+ }
253
+ function shouldUpgradeSavedRecord(save, classification) {
254
+ const { currentEntry, isConflicted, observedProvenance } = save;
255
+ return classification.kind === "unchanged" && !isConflicted && currentEntry && !currentEntry.deleted && !currentEntry._deleted && classification.revision === currentEntry._rev && !hasContentHash(observedProvenance);
256
+ }
257
+ async function finishUnchangedStorageSave(ctx, save, revision, details, recovery) {
258
+ const { file, readFile, observedProvenance, currentEntry, isConflicted } = save;
259
+ const { upgradeCurrentRecord, evidence } = details;
260
+ const { preferredBasePath, retryIfStorageChanges, snapshotRetry } = recovery;
261
+ const snapshotMatches = retryIfStorageChanges || upgradeCurrentRecord ? await currentStorageSnapshotMatches(ctx, readFile, observedProvenance, retryIfStorageChanges) : true;
262
+ if (retryIfStorageChanges && !snapshotMatches)
263
+ return await retryCurrentStorage(ctx, file.path, preferredBasePath, snapshotRetry);
264
+ if (isConflicted) {
265
+ await queueConflictCheckFor(ctx, file.path);
266
+ } else if (!currentEntry || currentEntry.deleted || currentEntry._deleted || revision !== currentEntry._rev) {
267
+ if (!currentEntry) return false;
268
+ return await dbToStorageCore(ctx, file.path, file);
269
+ } else {
270
+ if (upgradeCurrentRecord && snapshotMatches) {
271
+ await setProvenance(ctx, file.path, revision, readFile.stat.mtime, readFile.body, evidence);
272
+ }
273
+ ctx.path.markChangesAreSame(readFile, readFile.stat.mtime, currentEntry.mtime);
274
+ }
275
+ return true;
276
+ }
277
+ async function finishMatchingStorageSave(ctx, save, revision, details, recovery) {
278
+ const { file, readFile, observedProvenance, isConflicted } = save;
279
+ const { evidence } = details;
280
+ const { preferredBasePath, retryIfStorageChanges, snapshotRetry } = recovery;
281
+ if (retryIfStorageChanges && !await currentStorageSnapshotMatches(ctx, readFile, observedProvenance, true))
282
+ return await retryCurrentStorage(ctx, file.path, preferredBasePath, snapshotRetry);
283
+ await rememberMatchingLeaf(ctx, file.path, revision, readFile.stat.mtime, readFile.body, evidence);
284
+ if (isConflicted) await queueConflictCheckFor(ctx, file.path);
285
+ return true;
286
+ }
287
+ async function storeClassifiedStorageEdit(ctx, save, classification, recovery) {
288
+ const { file, readFile, observedProvenance, isConflicted } = save;
289
+ const { preferredBasePath, retryIfStorageChanges, snapshotRetry } = recovery;
290
+ if (retryIfStorageChanges && !await currentStorageSnapshotMatches(ctx, readFile, observedProvenance, true))
291
+ return await retryCurrentStorage(ctx, file.path, preferredBasePath, snapshotRetry);
292
+ const storedRevision = classification.kind === "edited" ? await ctx.host.db().storeWithBaseRevision(readFile, classification.revision, true) : await ctx.host.db().storeIndependentRevision(readFile, true);
293
+ if (storedRevision === false) return false;
294
+ if (preferredBasePath && preferredBasePath !== file.path) await deleteProvenance(ctx, preferredBasePath);
295
+ if (retryIfStorageChanges && !await finaliseStoredRevision(ctx, readFile, observedProvenance, storedRevision, true)) {
296
+ return await retryCurrentStorage(ctx, file.path, preferredBasePath, snapshotRetry);
297
+ }
298
+ if (!retryIfStorageChanges) await setProvenance(ctx, file.path, storedRevision, readFile.stat.mtime, readFile.body);
299
+ if (isConflicted || classification.kind === "unknown") await queueConflictCheckFor(ctx, file.path);
300
+ return true;
301
+ }
302
+ export {
303
+ storeFileToDB,
304
+ storeFileToDBFromRevision,
305
+ storeFileToDBWithBaseRevision
306
+ };
@@ -0,0 +1,22 @@
1
+ import type { MetaEntry, UXFileInfo, UXFileInfoStub } from "../../common/types.js";
2
+ import type { FileHandlerContext } from "./context.js";
3
+ /**
4
+ * Offer a metadata-only scan hint without certifying bytes or changing provenance.
5
+ *
6
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
7
+ * @param info - The supplied file observation or path.
8
+ * @param expected - The database metadata expected by this scan.
9
+ * @returns Whether the scan may skip this unchanged metadata observation.
10
+ * @remarks The scan acquires the document lock before certifying evidence. It writes no document revision or storage content; inspection failures return false.
11
+ */
12
+ export declare function canSkipUnchangedFile(ctx: FileHandlerContext, info: UXFileInfoStub, expected: MetaEntry): Promise<boolean>;
13
+ /**
14
+ * Record an unchanged current revision after rechecking storage and database evidence.
15
+ *
16
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
17
+ * @param info - The supplied file observation or path.
18
+ * @param expectedRevision - The exact revision the scan expects to remain current.
19
+ * @returns Whether the exact still-current revision was recorded without writing file content.
20
+ * @remarks The scan acquires the document lock before certifying evidence and may retrieve missing Chunks through the settings-controlled path. It writes no Metadata revision or storage content; inspection failures return false.
21
+ */
22
+ export declare function tryRecordUntrackedFileRevision(ctx: FileHandlerContext, info: UXFileInfoStub | UXFileInfo, expectedRevision: string): Promise<boolean>;
@@ -0,0 +1,93 @@
1
+ import { withFileEventPaths } from "./locking.js";
2
+ import {
3
+ getProvenancePath,
4
+ sameProvenance,
5
+ contentEvidence,
6
+ currentStorageSnapshotMatches,
7
+ hasContentHash
8
+ } from "./provenance.js";
9
+ import { isFolderInfo } from "./storage.js";
10
+ import { LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
11
+ import { isDocContentSame, readContent } from "../../common/utils.js";
12
+ import { getStoragePathFromUXFileInfo } from "../../common/typeUtils.js";
13
+ async function canSkipUnchangedFile(ctx, info, expected) {
14
+ const path = getStoragePathFromUXFileInfo(info);
15
+ const provenance = ctx.provenance;
16
+ if (!provenance || !isUnconflictedScanEntry(expected) || ctx.host.storage().hasPendingFileEvent?.(path) !== false)
17
+ return false;
18
+ try {
19
+ return await withFileEventPaths(ctx, [path], async () => {
20
+ const provenancePath = getProvenancePath(ctx, path);
21
+ const record = await provenance.get(provenancePath);
22
+ if (!scanRecordMatchesFile(record, expected, info)) return false;
23
+ const current = await ctx.host.db().fetchEntryMeta(path, void 0, true);
24
+ if (!isExpectedLiveRevision(current, record.revision)) return false;
25
+ if ((await ctx.host.db().getConflictedRevs(path)).length > 0) return false;
26
+ const stat = await ctx.host.storage().stat(path);
27
+ if (!storageStatMatchesRecord(stat, record)) return false;
28
+ return sameProvenance(await provenance.get(provenancePath), record) && ctx.host.storage().hasPendingFileEvent?.(path) === false;
29
+ });
30
+ } catch (error) {
31
+ ctx.host.log(`Could not inspect unchanged file metadata for ${path}`, LOG_LEVEL_VERBOSE);
32
+ ctx.host.log(error, LOG_LEVEL_VERBOSE);
33
+ return false;
34
+ }
35
+ }
36
+ async function tryRecordUntrackedFileRevision(ctx, info, expectedRevision) {
37
+ if (!ctx.provenance || !expectedRevision) return false;
38
+ const path = getStoragePathFromUXFileInfo(info);
39
+ try {
40
+ return await withFileEventPaths(ctx, [path], async () => {
41
+ const provenance = ctx.provenance;
42
+ const provenancePath = getProvenancePath(ctx, path);
43
+ const existing = await provenance.get(provenancePath);
44
+ const observed = existing ? { ...existing } : void 0;
45
+ if (!canUpgradeScanRecord(observed, expectedRevision)) return false;
46
+ const stub = await ctx.host.storage().getStub(path);
47
+ if (!stub || isFolderInfo(stub) || stub.path !== path) return false;
48
+ const file = await ctx.host.readFileFromStub(stub);
49
+ const current = await ctx.host.db().fetchEntryMeta(path, void 0, true);
50
+ if (!isExpectedLiveRevision(current, expectedRevision)) return false;
51
+ if ((await ctx.host.db().getConflictedRevs(path)).length > 0) return false;
52
+ const entry = await ctx.host.db().fetchEntry(path, expectedRevision, true, true);
53
+ if (!isExpectedLiveRevision(entry, expectedRevision)) return false;
54
+ if (!await isDocContentSame(readContent(entry), file.body)) return false;
55
+ const evidence = await contentEvidence(ctx, file.body);
56
+ if (!evidence.contentHash) return false;
57
+ const latest = await ctx.host.db().fetchEntryMeta(path, void 0, true);
58
+ if (!isExpectedLiveRevision(latest, expectedRevision)) return false;
59
+ if ((await ctx.host.db().getConflictedRevs(path)).length > 0) return false;
60
+ if (!await currentStorageSnapshotMatches(ctx, file, observed)) return false;
61
+ if (!sameProvenance(await provenance.get(provenancePath), observed)) return false;
62
+ await provenance.set(provenancePath, {
63
+ revision: expectedRevision,
64
+ observedStorageMtime: file.stat.mtime,
65
+ ...evidence
66
+ });
67
+ return true;
68
+ });
69
+ } catch (ex) {
70
+ ctx.host.log(`Could not record unchanged file provenance for ${path}`, LOG_LEVEL_VERBOSE);
71
+ ctx.host.log(ex, LOG_LEVEL_VERBOSE);
72
+ return false;
73
+ }
74
+ }
75
+ function isUnconflictedScanEntry(expected) {
76
+ return !!expected._rev && !expected.deleted && !expected._deleted && !expected._conflicts?.length;
77
+ }
78
+ function scanRecordMatchesFile(record, expected, info) {
79
+ return !!record && hasContentHash(record) && record.revision === expected._rev && Number.isFinite(record.observedStorageMtime) && record.observedStorageMtime === info.stat.mtime && record.contentSize === info.stat.size;
80
+ }
81
+ function isExpectedLiveRevision(entry, revision) {
82
+ return !!entry && entry._rev === revision && !entry.deleted && !entry._deleted;
83
+ }
84
+ function storageStatMatchesRecord(stat, record) {
85
+ return !!stat && stat.type === "file" && stat.mtime === record.observedStorageMtime && stat.size === record.contentSize;
86
+ }
87
+ function canUpgradeScanRecord(observed, revision) {
88
+ return !observed || observed.revision === revision && !hasContentHash(observed);
89
+ }
90
+ export {
91
+ canSkipUnchangedFile,
92
+ tryRecordUntrackedFileRevision
93
+ };
@@ -0,0 +1,58 @@
1
+ import type { FileEventItem, FilePathWithPrefix, UXFileInfoStub, UXFolderInfo } from "../../common/types.js";
2
+ import type { FileHandlerContext } from "./context.js";
3
+ /**
4
+ * Validate current absence or an excluded rename target before recording deletion.
5
+ *
6
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
7
+ * @param item - The admitted operation intent and related paths.
8
+ * @returns Whether current storage permits the deletion intent; inspection errors propagate after diagnostics.
9
+ * @remarks Selection reads current storage and settings without acquiring another document lock. Inspection failures remain distinguishable from confirmed absence.
10
+ */
11
+ export declare function canRecordStorageDeletion(ctx: FileHandlerContext, item: FileEventItem): Promise<boolean>;
12
+ /**
13
+ * Accept only a non-folder storage item resolving to the expected path.
14
+ *
15
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
16
+ * @param current - The nullable current storage observation.
17
+ * @param expectedPath - The path the current observation must resolve to.
18
+ * @returns The matching file, or null for folders, aliases, or missing paths.
19
+ * @remarks Selection reads current storage and settings without acquiring another document lock. Inspection failures remain distinguishable from confirmed absence.
20
+ */
21
+ export declare function getExactCurrentFile(ctx: FileHandlerContext, current: UXFileInfoStub | UXFolderInfo | null, expectedPath: FilePathWithPrefix): UXFileInfoStub | null;
22
+ /**
23
+ * Check current path selection and the configured size limit.
24
+ *
25
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
26
+ * @param file - The supplied storage observation; its body is reused when present.
27
+ * @returns Whether the current file satisfies path selection and the existing size limit.
28
+ * @remarks Selection reads current storage and settings without acquiring another document lock. Inspection failures remain distinguishable from confirmed absence.
29
+ */
30
+ export declare function isCurrentFileSelected(ctx: FileHandlerContext, file: UXFileInfoStub): Promise<boolean>;
31
+ /**
32
+ * Apply current host selection and built-in ignore policy in their established order.
33
+ *
34
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
35
+ * @param path - The affected file or provenance path.
36
+ * @returns Whether the current host selection and built-in ignore policy both admit the path.
37
+ * @remarks Selection reads current storage and settings without acquiring another document lock. Inspection failures remain distinguishable from confirmed absence.
38
+ */
39
+ export declare function isCurrentPathSelected(ctx: FileHandlerContext, path: FilePathWithPrefix): Promise<boolean>;
40
+ /**
41
+ * Check recovery deletion selection while retaining validation diagnostics.
42
+ *
43
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
44
+ * @param path - The affected file or provenance path.
45
+ * @returns Whether the current path remains selected; inspection errors propagate after diagnostics.
46
+ * @remarks Selection reads current storage and settings without acquiring another document lock. Inspection failures remain distinguishable from confirmed absence.
47
+ */
48
+ export declare function canApplyRestoredDeletion(ctx: FileHandlerContext, path: FilePathWithPrefix): Promise<boolean>;
49
+ /**
50
+ * Report why saved operation intent remains pending for a later reconciliation.
51
+ *
52
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
53
+ * @param path - The affected file or provenance path.
54
+ * @param ex - The validation error retained in diagnostics.
55
+ * @returns Completion without a value; underlying errors retain the existing propagation policy.
56
+ * @remarks Selection reads current storage and settings without acquiring another document lock. Inspection failures remain distinguishable from confirmed absence.
57
+ */
58
+ export declare function logRestoredEventValidationFailure(ctx: FileHandlerContext, path: FilePathWithPrefix, ex: unknown): void;
@@ -0,0 +1,94 @@
1
+ import { isFolderInfo } from "./storage.js";
2
+ import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
3
+ import { shouldBeIgnored } from "../../string_and_binary/path.js";
4
+ async function canRecordStorageDeletion(ctx, item) {
5
+ const path = item.args.file.path;
6
+ try {
7
+ const current = await ctx.host.storage().getStub(path);
8
+ let excludedRenameTarget = null;
9
+ if (item.args.renameTarget !== void 0) {
10
+ const targetPath = item.args.renameTarget;
11
+ const targetItem = await ctx.host.storage().getStub(targetPath);
12
+ const target = getExactCurrentFile(ctx, targetItem, targetPath);
13
+ if (targetItem !== null && !target) {
14
+ ctx.host.log(
15
+ `Preserved ${path}: the rename target no longer resolves to ${targetPath}`,
16
+ LOG_LEVEL_NOTICE
17
+ );
18
+ return false;
19
+ }
20
+ const targetIsSelected = !shouldBeIgnored(targetPath) && await ctx.vault.isTargetFile(targetPath, { skipCaseCollisionCheck: true }) && !(target && ctx.vault.isFileSizeTooLarge(target.stat.size));
21
+ if (targetIsSelected) {
22
+ ctx.host.log(`Preserved ${path}: rename target ${targetPath} is still selected`, LOG_LEVEL_NOTICE);
23
+ return false;
24
+ }
25
+ excludedRenameTarget = target;
26
+ }
27
+ if (current === null) return true;
28
+ if (isFolderInfo(current)) {
29
+ ctx.host.log(`Preserved ${path}: a current storage item contradicts its deletion event`, LOG_LEVEL_NOTICE);
30
+ return false;
31
+ }
32
+ const [currentId, deletedId] = await Promise.all([ctx.path.path2id(current.path), ctx.path.path2id(path)]);
33
+ if (currentId !== deletedId) return true;
34
+ if (excludedRenameTarget && ctx.host.storage().normalisePath(current.path) !== ctx.host.storage().normalisePath(path) && ctx.host.storage().normalisePath(current.path) === ctx.host.storage().normalisePath(excludedRenameTarget.path)) {
35
+ return true;
36
+ }
37
+ ctx.host.log(`Preserved ${path}: a current storage item contradicts its deletion event`, LOG_LEVEL_NOTICE);
38
+ return false;
39
+ } catch (ex) {
40
+ ctx.host.log(`Could not validate deletion of ${path}; preserved the database entry`, LOG_LEVEL_NOTICE);
41
+ ctx.host.log(ex, LOG_LEVEL_VERBOSE);
42
+ throw ex;
43
+ }
44
+ }
45
+ function getExactCurrentFile(ctx, current, expectedPath) {
46
+ if (current === null || isFolderInfo(current)) {
47
+ return null;
48
+ }
49
+ return ctx.host.storage().normalisePath(current.path) === ctx.host.storage().normalisePath(expectedPath) ? current : null;
50
+ }
51
+ async function isCurrentFileSelected(ctx, file) {
52
+ if (!await isCurrentPathSelected(ctx, file.path)) {
53
+ return false;
54
+ }
55
+ if (ctx.vault.isFileSizeTooLarge(file.stat.size)) {
56
+ ctx.host.log(`File ${file.path} exceeds the current maximum size`, LOG_LEVEL_VERBOSE);
57
+ return false;
58
+ }
59
+ return true;
60
+ }
61
+ async function isCurrentPathSelected(ctx, path) {
62
+ if (!await ctx.vault.isTargetFile(path)) {
63
+ ctx.host.log(`File ${path} is not the target file`, LOG_LEVEL_VERBOSE);
64
+ return false;
65
+ }
66
+ if (shouldBeIgnored(path)) {
67
+ ctx.host.log(`File ${path} should be ignored`, LOG_LEVEL_VERBOSE);
68
+ return false;
69
+ }
70
+ return true;
71
+ }
72
+ async function canApplyRestoredDeletion(ctx, path) {
73
+ try {
74
+ return await isCurrentPathSelected(ctx, path);
75
+ } catch (ex) {
76
+ logRestoredEventValidationFailure(ctx, path, ex);
77
+ throw ex;
78
+ }
79
+ }
80
+ function logRestoredEventValidationFailure(ctx, path, ex) {
81
+ ctx.host.log(
82
+ `Could not validate the saved storage operation for ${path} against current storage; the operation remains pending for recovery`,
83
+ LOG_LEVEL_NOTICE
84
+ );
85
+ ctx.host.log(ex, LOG_LEVEL_VERBOSE);
86
+ }
87
+ export {
88
+ canApplyRestoredDeletion,
89
+ canRecordStorageDeletion,
90
+ getExactCurrentFile,
91
+ isCurrentFileSelected,
92
+ isCurrentPathSelected,
93
+ logRestoredEventValidationFailure
94
+ };