@vrtmrz/livesync-commonlib 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/common/models/fileaccess.definition.d.ts +35 -0
  2. package/dist/common/models/fileaccess.definition.js +11 -0
  3. package/dist/common/typeUtils.d.ts +27 -4
  4. package/dist/interfaces/FileHandler.d.ts +1 -1
  5. package/dist/managers/StorageEventManager/admission.d.ts +50 -0
  6. package/dist/managers/StorageEventManager/admission.js +129 -0
  7. package/dist/managers/StorageEventManager/batching.d.ts +93 -0
  8. package/dist/managers/StorageEventManager/batching.js +97 -0
  9. package/dist/managers/StorageEventManager/operations.d.ts +142 -0
  10. package/dist/managers/StorageEventManager/operations.js +69 -0
  11. package/dist/managers/StorageEventManager/processing.d.ts +63 -0
  12. package/dist/managers/StorageEventManager/processing.js +94 -0
  13. package/dist/managers/StorageEventManager/queue.d.ts +73 -0
  14. package/dist/managers/StorageEventManager/queue.js +113 -0
  15. package/dist/managers/StorageEventManager/retry.d.ts +33 -0
  16. package/dist/managers/StorageEventManager/retry.js +31 -0
  17. package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
  18. package/dist/managers/StorageEventManager/snapshot.js +53 -0
  19. package/dist/managers/StorageEventManager/state.d.ts +155 -0
  20. package/dist/managers/StorageEventManager/state.js +105 -0
  21. package/dist/managers/StorageEventManager/watching.d.ts +93 -0
  22. package/dist/managers/StorageEventManager/watching.js +36 -0
  23. package/dist/managers/StorageEventManager.d.ts +303 -83
  24. package/dist/managers/StorageEventManager.js +457 -547
  25. package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
  26. package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
  27. package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
  28. package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
  29. package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
  30. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
  31. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
  32. package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
  33. package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
  34. package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
  35. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
  36. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
  37. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
  38. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
  39. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
  40. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
  41. package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
  42. package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
  43. package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
  44. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
  45. package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
  46. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
  47. package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
  49. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
  51. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +119 -182
  52. package/dist/serviceModules/ServiceFileHandlerBase.js +182 -1402
  53. package/docs/conflict-resolution.md +3 -1
  54. package/docs/development.md +36 -0
  55. package/docs/offline-scanner.md +5 -1
  56. package/docs/p2p-transport-lifecycle.md +8 -1
  57. package/docs/storage-events-and-reflection.md +203 -19
  58. package/package.json +1 -1
@@ -0,0 +1,344 @@
1
+ import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
2
+ import { infoToStub, isFolderInfo, getParentPath } from "./storage.js";
3
+ import {
4
+ deleteProvenance,
5
+ contentEvidence,
6
+ currentStorageSnapshotMatches,
7
+ sameProvenance,
8
+ readProvenanceSnapshot,
9
+ setProvenance
10
+ } from "./provenance.js";
11
+ import { preserveUnsyncedStorageAsConflict, recheckIncomingStorage } from "./protection.js";
12
+ import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
13
+ import { createBlob, isDocContentSame, readContent } from "../../common/utils.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
+ async function dbToStorageWithSpecificRev(ctx, info, rev, force) {
19
+ if (info == null) {
20
+ ctx.host.log(`Cannot select database revision ${rev} without a file path`, LOG_LEVEL_VERBOSE);
21
+ return false;
22
+ }
23
+ return await withFileEventPaths(
24
+ ctx,
25
+ [getStoragePathFromUXFileInfo(info)],
26
+ () => dbToStorageWithSpecificRevCore(ctx, info, rev, force)
27
+ );
28
+ }
29
+ async function dbToStorageWithSpecificRevCore(ctx, info, rev, force) {
30
+ const file = await infoToStub(ctx, info);
31
+ const databaseTarget = file ?? info;
32
+ const [docEntry, currentEntry, conflictedRevisions] = await Promise.all([
33
+ ctx.host.db().fetchEntryMeta(databaseTarget, rev, true),
34
+ ctx.host.db().fetchEntryMeta(databaseTarget, void 0, true),
35
+ ctx.host.db().getConflictedRevs(databaseTarget)
36
+ ]);
37
+ if (!docEntry) {
38
+ ctx.host.log(`File ${tryGetFilePath(info)} is not exist on the database`, LOG_LEVEL_VERBOSE);
39
+ return false;
40
+ }
41
+ const liveRevisions = /* @__PURE__ */ new Set([
42
+ ...currentEntry && currentEntry._rev ? [currentEntry._rev] : [],
43
+ ...conflictedRevisions
44
+ ]);
45
+ if (!liveRevisions.has(rev)) {
46
+ ctx.host.log(
47
+ `Could not apply ${tryGetFilePath(info)} revision ${rev}; the selected revision is no longer live`,
48
+ LOG_LEVEL_NOTICE
49
+ );
50
+ return false;
51
+ }
52
+ return await applyDatabaseEntryToStorage(ctx, docEntry, file, force, true);
53
+ }
54
+ async function dbToStorage(ctx, entryInfo, info, force) {
55
+ const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
56
+ return await withFileEventPaths(ctx, [pathFromEntryInfo], () => dbToStorageCore(ctx, entryInfo, info, force));
57
+ }
58
+ async function dbToStorageCore(ctx, entryInfo, info, force) {
59
+ const file = await infoToStub(ctx, info);
60
+ const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
61
+ const docEntry = await ctx.host.db().fetchEntryMeta(pathFromEntryInfo, void 0, true);
62
+ if (!docEntry) {
63
+ ctx.host.log(`File ${pathFromEntryInfo} is not exist on the database`, LOG_LEVEL_VERBOSE);
64
+ return false;
65
+ }
66
+ return await applyDatabaseEntryToStorage(ctx, docEntry, file, force);
67
+ }
68
+ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0) {
69
+ const mode = file == null ? "create" : "modify";
70
+ const path = ctx.host.getPath(docEntry);
71
+ const settings = ctx.setting.currentSettings();
72
+ const revs = await ctx.host.db().getConflictedRevs(path);
73
+ if (revs.length > 0 && !allowExistingConflicts) {
74
+ if (settings.writeDocumentsIfConflicted) {
75
+ } else {
76
+ await queueConflictCheckFor(ctx, path, true);
77
+ return true;
78
+ }
79
+ }
80
+ let existDoc = await ctx.host.storage().getStub(path);
81
+ if (isFolderInfo(existDoc)) {
82
+ ctx.host.log(`Folder ${path} is already exist on the storage as a folder`, LOG_LEVEL_VERBOSE);
83
+ return true;
84
+ }
85
+ const existOnDB = !(docEntry._deleted || docEntry.deleted || false);
86
+ if (!existOnDB && !existDoc) {
87
+ ctx.host.log(`File ${path} seems to be deleted, but already not on storage`, LOG_LEVEL_VERBOSE);
88
+ await deleteProvenance(ctx, path);
89
+ return true;
90
+ }
91
+ if (!existOnDB && existDoc)
92
+ return await applyIncomingDeletion(
93
+ ctx,
94
+ docEntry,
95
+ existDoc,
96
+ path,
97
+ settings,
98
+ force,
99
+ allowExistingConflicts,
100
+ incomingRetry
101
+ );
102
+ if (existDoc && existDoc.path !== path) {
103
+ const current = await reconcileStoragePath(ctx, existDoc, path, settings);
104
+ if (current === false) return false;
105
+ existDoc = current;
106
+ }
107
+ const docRead = await ctx.host.db().fetchEntryFromMeta(docEntry);
108
+ if (!docRead) {
109
+ ctx.host.log(`File ${path} is not exist on the database`, LOG_LEVEL_VERBOSE);
110
+ return false;
111
+ }
112
+ const docData = readContent(docRead);
113
+ const reflectedContent = createBlob(docData);
114
+ if (!settings.processSizeMismatchedFiles) {
115
+ if (docRead.size != 0 && docRead.size !== reflectedContent.size) {
116
+ ctx.host.log(
117
+ `File ${path} seems to be corrupted! Writing prevented. (${docRead.size} != ${reflectedContent.size})`,
118
+ LOG_LEVEL_NOTICE
119
+ );
120
+ return false;
121
+ }
122
+ }
123
+ const reflectedEvidence = await contentEvidence(ctx, reflectedContent);
124
+ const write = {
125
+ docEntry,
126
+ docRead,
127
+ docData,
128
+ reflectedContent,
129
+ reflectedEvidence,
130
+ existDoc,
131
+ path,
132
+ settings,
133
+ mode,
134
+ force,
135
+ allowExistingConflicts,
136
+ incomingRetry
137
+ };
138
+ const preparation = await prepareIncomingStorageWrite(ctx, write);
139
+ if (preparation.kind === "complete") return preparation.result;
140
+ return await commitIncomingStorageWrite(ctx, write, preparation.snapshot);
141
+ }
142
+ async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force, allowExistingConflicts, incomingRetry) {
143
+ if (force || allowExistingConflicts) return void 0;
144
+ const current = await ctx.host.db().fetchEntryMeta(path, void 0, true);
145
+ if (!current) return false;
146
+ if (current._rev === incomingEntry._rev) return void 0;
147
+ if (incomingRetry >= 2) {
148
+ ctx.host.log(`Database kept changing while reflecting ${path}`, LOG_LEVEL_NOTICE);
149
+ return false;
150
+ }
151
+ const storage = await ctx.host.storage().getStub(path);
152
+ if (isFolderInfo(storage)) return false;
153
+ return await applyDatabaseEntryToStorage(ctx, current, storage, force, allowExistingConflicts, incomingRetry + 1);
154
+ }
155
+ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, force, allowExistingConflicts, incomingRetry) {
156
+ let safeDeletionSnapshot;
157
+ if (!force && !settings.writeDocumentsIfConflicted) {
158
+ let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry);
159
+ if (protection.preserved) return true;
160
+ if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
161
+ protection = await recheckIncomingStorage(ctx, path, docEntry, void 0, allowExistingConflicts);
162
+ if (protection.preserved) return true;
163
+ if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
164
+ return false;
165
+ }
166
+ }
167
+ safeDeletionSnapshot = protection.snapshot;
168
+ }
169
+ let latest = await reconcileAdvancedIncomingRevision(
170
+ ctx,
171
+ docEntry,
172
+ path,
173
+ force,
174
+ allowExistingConflicts,
175
+ incomingRetry
176
+ );
177
+ if (latest !== void 0) return latest;
178
+ if (safeDeletionSnapshot && !await currentStorageSnapshotMatches(ctx, safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
179
+ const protection = await recheckIncomingStorage(ctx, path, docEntry, void 0, allowExistingConflicts);
180
+ if (protection.preserved) return true;
181
+ if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
182
+ return false;
183
+ }
184
+ safeDeletionSnapshot = protection.snapshot;
185
+ latest = await reconcileAdvancedIncomingRevision(
186
+ ctx,
187
+ docEntry,
188
+ path,
189
+ force,
190
+ allowExistingConflicts,
191
+ incomingRetry
192
+ );
193
+ if (latest !== void 0) return latest;
194
+ if (!await currentStorageSnapshotMatches(ctx, safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
195
+ return false;
196
+ }
197
+ }
198
+ await ctx.host.storage().deleteVaultItem(path);
199
+ await deleteProvenance(ctx, path);
200
+ return true;
201
+ }
202
+ async function reconcileStoragePath(ctx, existDoc, path, settings) {
203
+ const [existingDocumentId, targetDocumentId] = await Promise.all([
204
+ ctx.path.path2id(existDoc.path),
205
+ ctx.path.path2id(path)
206
+ ]);
207
+ if (existingDocumentId !== targetDocumentId) {
208
+ ctx.host.log(
209
+ `Refusing to overwrite ${existDoc.path} while applying the distinct path ${path}`,
210
+ LOG_LEVEL_NOTICE
211
+ );
212
+ return false;
213
+ }
214
+ const pathNormalizationVersion = getPathNormalizationVersion(settings);
215
+ const sameNormalisedPath = pathNormalizationVersion === 1 && normalisePathForIdentity(existDoc.path, pathNormalizationVersion) === normalisePathForIdentity(path, pathNormalizationVersion);
216
+ if (!sameNormalisedPath) {
217
+ const existingParent = getParentPath(existDoc.path);
218
+ const targetParent = getParentPath(path);
219
+ const sameNormalisedParent = pathNormalizationVersion === 1 && normalisePathForIdentity(existingParent, pathNormalizationVersion) === normalisePathForIdentity(targetParent, pathNormalizationVersion);
220
+ if (existingParent !== targetParent && !sameNormalisedParent) {
221
+ ctx.host.log(
222
+ `Refusing to apply a filename case change across differently cased parent directories: ${existDoc.path} -> ${path}`,
223
+ LOG_LEVEL_NOTICE
224
+ );
225
+ return false;
226
+ }
227
+ const renamedFile = await ctx.host.storage().renameFile(existDoc, path);
228
+ if (!renamedFile) {
229
+ ctx.host.log(`Could not apply the stored filename case: ${existDoc.path} -> ${path}`, LOG_LEVEL_NOTICE);
230
+ return false;
231
+ }
232
+ await deleteProvenance(ctx, existDoc.path);
233
+ existDoc = renamedFile;
234
+ }
235
+ return existDoc;
236
+ }
237
+ async function prepareIncomingStorageWrite(ctx, write) {
238
+ const { existDoc, force, allowExistingConflicts, docRead } = write;
239
+ if (allowExistingConflicts && existDoc && !force && await acceptMatchingSelectedContent(ctx, write, existDoc))
240
+ return { kind: "complete", result: true };
241
+ if (existDoc && !force) return await prepareExistingStorageWrite(ctx, write, existDoc);
242
+ ctx.host.log(`File ${docRead.path} ${existDoc ? "(new) " : ""} ${force ? " (forced)" : ""}`, LOG_LEVEL_VERBOSE);
243
+ return { kind: "write", snapshot: void 0 };
244
+ }
245
+ async function commitIncomingStorageWrite(ctx, write, safeSnapshot) {
246
+ const {
247
+ docEntry,
248
+ docRead,
249
+ docData,
250
+ reflectedContent,
251
+ reflectedEvidence,
252
+ path,
253
+ mode,
254
+ force,
255
+ allowExistingConflicts,
256
+ incomingRetry
257
+ } = write;
258
+ await ctx.host.storage().ensureDir(path);
259
+ if (safeSnapshot && !await currentStorageSnapshotMatches(ctx, safeSnapshot.file, safeSnapshot.revision)) {
260
+ const protection = await recheckIncomingStorage(ctx, path, docEntry, docData, allowExistingConflicts);
261
+ if (protection.preserved) return true;
262
+ if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
263
+ return false;
264
+ }
265
+ safeSnapshot = protection.snapshot;
266
+ }
267
+ const latest = await reconcileAdvancedIncomingRevision(
268
+ ctx,
269
+ docEntry,
270
+ path,
271
+ force,
272
+ allowExistingConflicts,
273
+ incomingRetry
274
+ );
275
+ if (latest !== void 0) return latest;
276
+ if (safeSnapshot && !await currentStorageSnapshotMatches(ctx, safeSnapshot.file, safeSnapshot.revision)) {
277
+ return false;
278
+ }
279
+ const ret = await ctx.host.storage().writeFileAuto(path, docData, { ctime: docRead.ctime, mtime: docRead.mtime });
280
+ await ctx.host.storage().touched(path);
281
+ ctx.host.storage().triggerFileEvent(mode, path);
282
+ if (ret && ctx.provenance) {
283
+ const storedStat = await ctx.host.storage().stat(path);
284
+ if (safeSnapshot && !sameProvenance(await readProvenanceSnapshot(ctx, path), safeSnapshot.revision)) {
285
+ return ret;
286
+ }
287
+ await setProvenance(ctx, path, docEntry._rev, storedStat?.mtime, reflectedContent, reflectedEvidence);
288
+ }
289
+ return ret;
290
+ }
291
+ async function acceptMatchingSelectedContent(ctx, write, current) {
292
+ const { docEntry, docRead, docData, reflectedContent, reflectedEvidence, path } = write;
293
+ const existDoc = current;
294
+ const readFile = await ctx.host.readFileFromStub(existDoc);
295
+ if (await isDocContentSame(docData, readFile.body)) {
296
+ await setProvenance(ctx, path, docEntry._rev, existDoc.stat.mtime, reflectedContent, reflectedEvidence);
297
+ ctx.path.markChangesAreSame(docRead, docRead.mtime, existDoc.stat.mtime);
298
+ return true;
299
+ }
300
+ return false;
301
+ }
302
+ async function prepareExistingStorageWrite(ctx, write, current) {
303
+ const { docEntry, docRead, docData, reflectedContent, reflectedEvidence, path } = write;
304
+ const existDoc = current;
305
+ let shouldApplied = false;
306
+ const freshness = ctx.path.compareFileFreshness(existDoc, docEntry);
307
+ if (freshness !== EVEN) {
308
+ shouldApplied = true;
309
+ }
310
+ if (!shouldApplied) {
311
+ const readFile = await ctx.host.readFileFromStub(existDoc);
312
+ if (await isDocContentSame(docData, readFile.body)) {
313
+ shouldApplied = false;
314
+ ctx.path.markChangesAreSame(docRead, docRead.mtime, existDoc.stat.mtime);
315
+ } else {
316
+ shouldApplied = true;
317
+ }
318
+ }
319
+ if (!shouldApplied) {
320
+ await setProvenance(ctx, path, docEntry._rev, existDoc.stat.mtime, reflectedContent, reflectedEvidence);
321
+ ctx.host.log(`File ${docRead.path} is not changed`, LOG_LEVEL_VERBOSE);
322
+ return { kind: "complete", result: true };
323
+ }
324
+ return await prepareIncomingStorageProtection(ctx, write, current);
325
+ }
326
+ async function prepareIncomingStorageProtection(ctx, write, current) {
327
+ const { docEntry, docData, path, settings, force, allowExistingConflicts } = write;
328
+ const existDoc = current;
329
+ if (force || settings.writeDocumentsIfConflicted) return { kind: "write", snapshot: void 0 };
330
+ let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry, docData);
331
+ if (protection.preserved) return { kind: "complete", result: true };
332
+ if (!protection.snapshot) {
333
+ protection = await recheckIncomingStorage(ctx, path, docEntry, docData, allowExistingConflicts);
334
+ if (protection.preserved) return { kind: "complete", result: true };
335
+ if (!protection.snapshot) return { kind: "complete", result: false };
336
+ }
337
+ return { kind: "write", snapshot: protection.snapshot };
338
+ }
339
+ export {
340
+ applyDatabaseEntryToStorage,
341
+ dbToStorage,
342
+ dbToStorageCore,
343
+ dbToStorageWithSpecificRev
344
+ };
@@ -0,0 +1,23 @@
1
+ import type { FilePath, FilePathWithPrefix, UXFileInfo, UXFileInfoStub } from "../../common/types.js";
2
+ import type { FileHandlerContext } from "./context.js";
3
+ /**
4
+ * Record a rename under both source and destination document locks.
5
+ *
6
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
7
+ * @param info - The destination file observation, optionally already containing its body.
8
+ * @param oldPath - The rename source path whose branch must be preserved or deleted safely.
9
+ * @returns True after target/source handling or conservative source preservation; false on target collision or refused work.
10
+ * @remarks Core operations require source and destination document locks as applicable. Unknown conflict ancestry is preserved for review rather than guessed.
11
+ */
12
+ export declare function renameFileInDB(ctx: FileHandlerContext, info: UXFileInfoStub | UXFileInfo, oldPath: FilePath | FilePathWithPrefix): Promise<boolean>;
13
+ /**
14
+ * Save a rename target before applying its guarded source deletion.
15
+ *
16
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
17
+ * @param info - The destination file observation, optionally already containing its body.
18
+ * @param oldPath - The rename source path whose branch must be preserved or deleted safely.
19
+ * @param retryIfStorageChanges - Whether recovery revalidates storage and permits bounded rereads.
20
+ * @returns True after target/source handling or conservative source preservation; false on target collision or refused work.
21
+ * @remarks Core operations require source and destination document locks as applicable. Unknown conflict ancestry is preserved for review rather than guessed.
22
+ */
23
+ export declare function renameFileInDBCore(ctx: FileHandlerContext, info: UXFileInfoStub | UXFileInfo, oldPath: FilePath | FilePathWithPrefix, retryIfStorageChanges?: boolean): Promise<boolean>;
@@ -0,0 +1,77 @@
1
+ import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
2
+ import { storeFileToDBFromRevision } from "./saving.js";
3
+ import { getProvenance, deleteProvenance } from "./provenance.js";
4
+ import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
5
+ import { getStoragePathFromUXFileInfo } from "../../common/typeUtils.js";
6
+ async function renameFileInDB(ctx, info, oldPath) {
7
+ const newPath = getStoragePathFromUXFileInfo(info);
8
+ return await withFileEventPaths(
9
+ ctx,
10
+ [oldPath, newPath],
11
+ () => renameFileInDBCore(ctx, info, oldPath)
12
+ );
13
+ }
14
+ async function renameFileInDBCore(ctx, info, oldPath, retryIfStorageChanges = false) {
15
+ const newPath = getStoragePathFromUXFileInfo(info);
16
+ const [oldDocumentId, newDocumentId] = await Promise.all([ctx.path.path2id(oldPath), ctx.path.path2id(newPath)]);
17
+ if (oldDocumentId === newDocumentId) {
18
+ ctx.host.log(`Updating the stored path for case-only rename: ${oldPath} -> ${newPath}`, LOG_LEVEL_VERBOSE);
19
+ return await storeFileToDBFromRevision(
20
+ ctx,
21
+ info,
22
+ true,
23
+ false,
24
+ oldPath,
25
+ retryIfStorageChanges
26
+ );
27
+ }
28
+ const oldEntry = await ctx.host.db().fetchEntryMeta(oldPath, void 0, true);
29
+ const newEntry = await ctx.host.db().fetchEntryMeta(newPath, void 0, true);
30
+ if (newEntry && !newEntry.deleted && !newEntry._deleted) {
31
+ ctx.host.log(
32
+ `Refusing to overwrite the existing database entry while renaming ${oldPath} to ${newPath}`,
33
+ LOG_LEVEL_NOTICE
34
+ );
35
+ return false;
36
+ }
37
+ if (!await storeFileToDBFromRevision(ctx, info, true, false, void 0, retryIfStorageChanges)) {
38
+ ctx.host.log(`Failed to store rename target; preserving source in the database: ${oldPath}`, LOG_LEVEL_NOTICE);
39
+ return false;
40
+ }
41
+ if (!oldEntry || oldEntry.deleted || oldEntry._deleted) {
42
+ ctx.host.log(`Rename source is not present in the database: ${oldPath}`, LOG_LEVEL_VERBOSE);
43
+ return true;
44
+ }
45
+ return await deleteRenamedSource(ctx, info, oldPath, newPath);
46
+ }
47
+ async function deleteRenamedSource(ctx, info, oldPath, newPath) {
48
+ const oldConflicts = await ctx.host.db().getConflictedRevs(oldPath);
49
+ if (oldConflicts.length > 0) {
50
+ let baseRevision = (await getProvenance(ctx, oldPath))?.revision;
51
+ if (!baseRevision) {
52
+ const readFile = await ctx.host.readFileFromStub(info);
53
+ const revisions = await ctx.host.db().findContentRevisions(oldPath, readFile.body);
54
+ baseRevision = revisions.length === 1 ? revisions[0] : void 0;
55
+ }
56
+ if (!baseRevision) {
57
+ ctx.host.log(
58
+ `Renamed ${oldPath} to ${newPath}, but preserved every conflicted source branch because the displayed source revision is unknown`,
59
+ LOG_LEVEL_NOTICE
60
+ );
61
+ await queueConflictCheckFor(ctx, oldPath);
62
+ return true;
63
+ }
64
+ const storedRevision = await ctx.host.db().storeDeletionWithBaseRevision(oldPath, baseRevision);
65
+ if (storedRevision === false) return false;
66
+ await deleteProvenance(ctx, oldPath);
67
+ await queueConflictCheckFor(ctx, oldPath);
68
+ return true;
69
+ }
70
+ const deleted = await ctx.host.db().delete(oldPath);
71
+ if (deleted) await deleteProvenance(ctx, oldPath);
72
+ return deleted;
73
+ }
74
+ export {
75
+ renameFileInDB,
76
+ renameFileInDBCore
77
+ };
@@ -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>;