@vrtmrz/livesync-commonlib 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -2
- package/dist/common/models/fileaccess.definition.d.ts +35 -0
- package/dist/common/models/fileaccess.definition.js +11 -0
- package/dist/common/typeUtils.d.ts +27 -4
- package/dist/interfaces/FileHandler.d.ts +60 -1
- package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
- package/dist/interfaces/FileReflectionProvenance.js +11 -1
- package/dist/managers/StorageEventManager/admission.d.ts +50 -0
- package/dist/managers/StorageEventManager/admission.js +129 -0
- package/dist/managers/StorageEventManager/batching.d.ts +93 -0
- package/dist/managers/StorageEventManager/batching.js +97 -0
- package/dist/managers/StorageEventManager/operations.d.ts +142 -0
- package/dist/managers/StorageEventManager/operations.js +69 -0
- package/dist/managers/StorageEventManager/processing.d.ts +63 -0
- package/dist/managers/StorageEventManager/processing.js +94 -0
- package/dist/managers/StorageEventManager/queue.d.ts +73 -0
- package/dist/managers/StorageEventManager/queue.js +113 -0
- package/dist/managers/StorageEventManager/retry.d.ts +33 -0
- package/dist/managers/StorageEventManager/retry.js +31 -0
- package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
- package/dist/managers/StorageEventManager/snapshot.js +53 -0
- package/dist/managers/StorageEventManager/state.d.ts +155 -0
- package/dist/managers/StorageEventManager/state.js +105 -0
- package/dist/managers/StorageEventManager/watching.d.ts +93 -0
- package/dist/managers/StorageEventManager/watching.js +36 -0
- package/dist/managers/StorageEventManager.d.ts +303 -83
- package/dist/managers/StorageEventManager.js +457 -547
- package/dist/serviceFeatures/offlineScanner/fileStatus.d.ts +61 -0
- package/dist/serviceFeatures/offlineScanner/fileStatus.js +85 -0
- package/dist/serviceFeatures/offlineScanner/files.d.ts +47 -0
- package/dist/serviceFeatures/offlineScanner/files.js +218 -0
- package/dist/serviceFeatures/offlineScanner/metadata.d.ts +56 -0
- package/dist/serviceFeatures/offlineScanner/metadata.js +320 -0
- package/dist/serviceFeatures/offlineScanner/paths.d.ts +20 -0
- package/dist/serviceFeatures/offlineScanner/paths.js +16 -0
- package/dist/serviceFeatures/offlineScanner/scan.d.ts +35 -0
- package/dist/serviceFeatures/offlineScanner/scan.js +358 -0
- package/dist/serviceFeatures/offlineScanner/types.d.ts +134 -0
- package/dist/serviceFeatures/offlineScanner/types.js +66 -0
- package/dist/serviceFeatures/offlineScanner.d.ts +25 -251
- package/dist/serviceFeatures/offlineScanner.js +36 -860
- package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
- package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
- package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
- package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.d.ts +13 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
- package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
- package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
- package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
- package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
- package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
- package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
- package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
- package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
- package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
- package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
- package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
- package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
- package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
- package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
- package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
- package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
- package/dist/serviceModules/ServiceFileHandlerBase.d.ts +141 -183
- package/dist/serviceModules/ServiceFileHandlerBase.js +206 -1397
- package/dist/services/base/KeyValueDBService.d.ts +9 -0
- package/dist/services/base/KeyValueDBService.js +11 -1
- package/docs/conflict-resolution.md +3 -1
- package/docs/development.md +40 -0
- package/docs/offline-scanner.md +26 -1
- package/docs/p2p-transport-lifecycle.md +8 -1
- package/docs/storage-events-and-reflection.md +212 -22
- package/package.json +1 -1
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { withFileEventPaths } from "./locking.js";
|
|
2
|
+
import {
|
|
3
|
+
isCurrentPathSelected,
|
|
4
|
+
getExactCurrentFile,
|
|
5
|
+
canRecordStorageDeletion,
|
|
6
|
+
logRestoredEventValidationFailure,
|
|
7
|
+
isCurrentFileSelected,
|
|
8
|
+
canApplyRestoredDeletion
|
|
9
|
+
} from "./selection.js";
|
|
10
|
+
import { storeFileToDBFromRevision } from "./saving.js";
|
|
11
|
+
import { deleteFileFromDBIfPresent } from "./deletion.js";
|
|
12
|
+
import { renameFileInDBCore } from "./renaming.js";
|
|
13
|
+
import { isFolderInfo } from "./storage.js";
|
|
14
|
+
import { dbToStorageCore } from "./reflection.js";
|
|
15
|
+
import { LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
|
|
16
|
+
import { isReconcileEvent } from "../../common/models/fileaccess.definition.js";
|
|
17
|
+
import { EVENT_CONFLICT_CANCELLED } from "../../events/coreEvents.js";
|
|
18
|
+
import { shouldBeIgnored } from "../../string_and_binary/path.js";
|
|
19
|
+
async function processFileEvent(ctx, item) {
|
|
20
|
+
if (item.restoredFromPreviousRuntime || isReconcileEvent(item)) {
|
|
21
|
+
return await processRestoredFileEvent(ctx, item);
|
|
22
|
+
}
|
|
23
|
+
const eventItem = item.args;
|
|
24
|
+
const type = item.type;
|
|
25
|
+
const path = eventItem.file.path;
|
|
26
|
+
if (type === "RENAME" && !eventItem.oldPath) {
|
|
27
|
+
ctx.host.log(`Rename event for ${path} has no source path`, LOG_LEVEL_VERBOSE);
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
|
|
31
|
+
const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
|
|
32
|
+
return await withFileEventPaths(ctx, eventPaths, async () => {
|
|
33
|
+
if (!await isCurrentPathSelected(ctx, path)) {
|
|
34
|
+
return shouldBeIgnored(path) || !await ctx.vault.isTargetFile(path, { skipCaseCollisionCheck: true });
|
|
35
|
+
}
|
|
36
|
+
switch (type) {
|
|
37
|
+
case "CREATE":
|
|
38
|
+
case "CHANGED": {
|
|
39
|
+
const current = getExactCurrentFile(ctx, await ctx.host.storage().getStub(path), path);
|
|
40
|
+
if (!current || ctx.vault.isFileSizeTooLarge(current.stat.size)) return true;
|
|
41
|
+
return await storeFileToDBFromRevision(ctx, current);
|
|
42
|
+
}
|
|
43
|
+
case "DELETE":
|
|
44
|
+
try {
|
|
45
|
+
if (!await canRecordStorageDeletion(ctx, item)) return true;
|
|
46
|
+
} catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
return await deleteFileFromDBIfPresent(ctx, item.args.file);
|
|
50
|
+
case "RENAME":
|
|
51
|
+
return await renameFileInDBCore(
|
|
52
|
+
ctx,
|
|
53
|
+
item.args.file,
|
|
54
|
+
item.args.oldPath
|
|
55
|
+
);
|
|
56
|
+
case "INTERNAL":
|
|
57
|
+
return false;
|
|
58
|
+
default:
|
|
59
|
+
ctx.host.log(`Unsupported event type: ${type}`, LOG_LEVEL_VERBOSE);
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
async function processRestoredFileEvent(ctx, item) {
|
|
65
|
+
const eventItem = item.args;
|
|
66
|
+
const type = item.type;
|
|
67
|
+
const path = eventItem.file.path;
|
|
68
|
+
if (type === "RENAME" && !eventItem.oldPath) {
|
|
69
|
+
ctx.host.log(`Rename event for ${path} has no source path`, LOG_LEVEL_VERBOSE);
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
|
|
73
|
+
const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
|
|
74
|
+
return await withFileEventPaths(ctx, eventPaths, async (isSameDocument) => {
|
|
75
|
+
let action;
|
|
76
|
+
try {
|
|
77
|
+
action = await planRestoredFileEvent(ctx, item, isSameDocument);
|
|
78
|
+
} catch (ex) {
|
|
79
|
+
logRestoredEventValidationFailure(ctx, path, ex);
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
switch (action.kind) {
|
|
83
|
+
case "none":
|
|
84
|
+
return true;
|
|
85
|
+
case "unresolved":
|
|
86
|
+
return false;
|
|
87
|
+
case "store": {
|
|
88
|
+
const stored = await storeFileToDBFromRevision(ctx, action.file, false, false, void 0, true);
|
|
89
|
+
return stored && action.complete !== false;
|
|
90
|
+
}
|
|
91
|
+
case "delete":
|
|
92
|
+
return await deleteFileFromDBIfPresent(ctx, action.path);
|
|
93
|
+
case "rename":
|
|
94
|
+
return await renameFileInDBCore(ctx, action.file, action.oldPath, true);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
async function planRestoredFileEvent(ctx, item, isSameDocument) {
|
|
99
|
+
const path = item.args.file.path;
|
|
100
|
+
switch (item.type) {
|
|
101
|
+
case "CREATE":
|
|
102
|
+
case "CHANGED": {
|
|
103
|
+
const current = getExactCurrentFile(ctx, await ctx.host.storage().getStub(path), path);
|
|
104
|
+
return current && await isCurrentFileSelected(ctx, current) ? { kind: "store", file: current } : { kind: "none" };
|
|
105
|
+
}
|
|
106
|
+
case "DELETE": {
|
|
107
|
+
if (item.args.renameTarget !== void 0) {
|
|
108
|
+
return await canRecordStorageDeletion(ctx, item) && await canApplyRestoredDeletion(ctx, path) ? { kind: "delete", path } : { kind: "none" };
|
|
109
|
+
}
|
|
110
|
+
const current = await ctx.host.storage().getStub(path);
|
|
111
|
+
return current === null && await canApplyRestoredDeletion(ctx, path) ? { kind: "delete", path } : { kind: "none" };
|
|
112
|
+
}
|
|
113
|
+
case "RENAME":
|
|
114
|
+
return await planRestoredRename(ctx, path, item.args.oldPath, isSameDocument);
|
|
115
|
+
case "INTERNAL":
|
|
116
|
+
return { kind: "none" };
|
|
117
|
+
default:
|
|
118
|
+
ctx.host.log(`Unsupported event type: ${item.type}`, LOG_LEVEL_VERBOSE);
|
|
119
|
+
return { kind: "none" };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async function planRestoredRename(ctx, newPath, oldPath, isSameDocument) {
|
|
123
|
+
if (isSameDocument) return await planSameDocumentRename(ctx, newPath, oldPath);
|
|
124
|
+
return await planCrossDocumentRename(ctx, newPath, oldPath);
|
|
125
|
+
}
|
|
126
|
+
async function processReplicatedDocument(ctx, entry) {
|
|
127
|
+
return await withFileEventPaths(ctx, [ctx.host.getPath(entry)], async () => {
|
|
128
|
+
if (!await ctx.vault.isTargetFile(entry.path)) {
|
|
129
|
+
ctx.host.log(`File ${entry.path} is not the target file`, LOG_LEVEL_VERBOSE);
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
if (ctx.vault.isFileSizeTooLarge(entry.size)) {
|
|
133
|
+
ctx.host.log(`File ${entry.path} is too large (on database) to be processed`, LOG_LEVEL_VERBOSE);
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
if (shouldBeIgnored(entry.path)) {
|
|
137
|
+
ctx.host.log(`File ${entry.path} should be ignored`, LOG_LEVEL_VERBOSE);
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
const path = ctx.host.getPath(entry);
|
|
141
|
+
const targetFile = await ctx.host.storage().getStub(ctx.host.getPathWithoutPrefix(entry));
|
|
142
|
+
if (isFolderInfo(targetFile)) {
|
|
143
|
+
ctx.host.log(`${path} is already exist as the folder`);
|
|
144
|
+
return true;
|
|
145
|
+
} else {
|
|
146
|
+
if (targetFile && ctx.vault.isFileSizeTooLarge(targetFile.stat.size)) {
|
|
147
|
+
ctx.host.log(`File ${targetFile.path} is too large (on storage) to be processed`, LOG_LEVEL_VERBOSE);
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
ctx.host.log(
|
|
151
|
+
`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Started...`,
|
|
152
|
+
LOG_LEVEL_VERBOSE
|
|
153
|
+
);
|
|
154
|
+
ctx.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
|
|
155
|
+
const ret = await dbToStorageCore(ctx, entry, targetFile);
|
|
156
|
+
ctx.host.log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Done`);
|
|
157
|
+
return ret;
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
async function planSameDocumentRename(ctx, newPath, oldPath) {
|
|
162
|
+
const currentTarget = getExactCurrentFile(ctx, await ctx.host.storage().getStub(newPath), newPath);
|
|
163
|
+
if (!currentTarget || !await isCurrentFileSelected(ctx, currentTarget)) {
|
|
164
|
+
return { kind: "none" };
|
|
165
|
+
}
|
|
166
|
+
const entry = await ctx.host.db().fetchEntryMeta(newPath, void 0, true);
|
|
167
|
+
if (entry && !entry.deleted && !entry._deleted && ctx.host.storage().normalisePath(ctx.host.getPath(entry)) === ctx.host.storage().normalisePath(newPath)) {
|
|
168
|
+
return { kind: "store", file: currentTarget };
|
|
169
|
+
}
|
|
170
|
+
return { kind: "rename", file: currentTarget, oldPath };
|
|
171
|
+
}
|
|
172
|
+
async function planCrossDocumentRename(ctx, newPath, oldPath) {
|
|
173
|
+
const currentTargetItem = await ctx.host.storage().getStub(newPath);
|
|
174
|
+
let currentSourceItem = null;
|
|
175
|
+
let sourceWasInspected = true;
|
|
176
|
+
try {
|
|
177
|
+
currentSourceItem = await ctx.host.storage().getStub(oldPath);
|
|
178
|
+
} catch (ex) {
|
|
179
|
+
sourceWasInspected = false;
|
|
180
|
+
logRestoredEventValidationFailure(ctx, oldPath, ex);
|
|
181
|
+
}
|
|
182
|
+
const currentTarget = getExactCurrentFile(ctx, currentTargetItem, newPath);
|
|
183
|
+
if (currentTargetItem !== null) {
|
|
184
|
+
if (!currentTarget || !await isCurrentFileSelected(ctx, currentTarget)) {
|
|
185
|
+
return { kind: "none" };
|
|
186
|
+
}
|
|
187
|
+
if (!sourceWasInspected || currentSourceItem !== null || !await canApplyRestoredDeletion(ctx, oldPath)) {
|
|
188
|
+
return { kind: "store", file: currentTarget, complete: sourceWasInspected };
|
|
189
|
+
}
|
|
190
|
+
const sourceEntry = await ctx.host.db().fetchEntryMeta(oldPath, void 0, true);
|
|
191
|
+
if (!sourceEntry || sourceEntry.deleted || sourceEntry._deleted) {
|
|
192
|
+
return { kind: "store", file: currentTarget };
|
|
193
|
+
}
|
|
194
|
+
return { kind: "rename", file: currentTarget, oldPath };
|
|
195
|
+
}
|
|
196
|
+
if (!sourceWasInspected) return { kind: "unresolved" };
|
|
197
|
+
if (currentSourceItem !== null || !await canApplyRestoredDeletion(ctx, oldPath)) {
|
|
198
|
+
return { kind: "none" };
|
|
199
|
+
}
|
|
200
|
+
return { kind: "delete", path: oldPath };
|
|
201
|
+
}
|
|
202
|
+
export {
|
|
203
|
+
processFileEvent,
|
|
204
|
+
processReplicatedDocument
|
|
205
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { FilePathWithPrefix } from "../../common/types.js";
|
|
2
|
+
import type { FileHandlerContext } from "./context.js";
|
|
3
|
+
/**
|
|
4
|
+
* Serialise related document identities and deliver deferred conflict hooks after unlocking.
|
|
5
|
+
*
|
|
6
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
7
|
+
* @param eventPaths - All storage paths whose document identities must be locked.
|
|
8
|
+
* @param callback - Work performed under the deduplicated, sorted document locks.
|
|
9
|
+
* @typeParam T - The callback result returned after locks are released and deferred hooks have run.
|
|
10
|
+
* @returns The callback result, unless its error or a later conflict-hook error must propagate.
|
|
11
|
+
* @remarks Document IDs are deduplicated and sorted. Conflict hooks run after every lock is released; a callback failure retains precedence over hook failure.
|
|
12
|
+
*/
|
|
13
|
+
export declare function withFileEventPaths<T>(ctx: FileHandlerContext, eventPaths: readonly FilePathWithPrefix[], callback: (isSameDocument: boolean) => Promise<T>): Promise<T>;
|
|
14
|
+
/**
|
|
15
|
+
* Defer conflict hooks within a document lock or deliver them immediately outside it.
|
|
16
|
+
*
|
|
17
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
18
|
+
* @param path - The affected file or provenance path.
|
|
19
|
+
* @param ifOpen - Whether to request only an already-open conflict review.
|
|
20
|
+
* @returns Completion after queueing or immediate hook delivery; immediate lookup or hook failures propagate.
|
|
21
|
+
* @remarks This helper neither sorts identities nor acquires a lock. It appends to an existing per-document deferred queue, or invokes the selected hook immediately when no queue is active.
|
|
22
|
+
*/
|
|
23
|
+
export declare function queueConflictCheckFor(ctx: FileHandlerContext, path: FilePathWithPrefix, ifOpen?: boolean): Promise<void>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { withLocks } from "octagonal-wheels/concurrency/lock";
|
|
2
|
+
async function withFileEventPaths(ctx, eventPaths, callback) {
|
|
3
|
+
const documentIds = await Promise.all(eventPaths.map((eventPath) => ctx.path.path2id(eventPath)));
|
|
4
|
+
const uniqueIds = [...new Set(documentIds)].sort();
|
|
5
|
+
const lockKeys = uniqueIds.map((documentId) => `processFileEvent-${documentId}`);
|
|
6
|
+
const pending = [];
|
|
7
|
+
let result;
|
|
8
|
+
let failed = false;
|
|
9
|
+
let failure;
|
|
10
|
+
try {
|
|
11
|
+
result = await withLocks(lockKeys, async () => {
|
|
12
|
+
for (const id of uniqueIds) ctx.state.deferredConflictChecks.set(id, pending);
|
|
13
|
+
try {
|
|
14
|
+
return await callback(documentIds.length === 2 && documentIds[0] === documentIds[1]);
|
|
15
|
+
} finally {
|
|
16
|
+
for (const id of uniqueIds) ctx.state.deferredConflictChecks.delete(id);
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
} catch (ex) {
|
|
20
|
+
failed = true;
|
|
21
|
+
failure = ex;
|
|
22
|
+
}
|
|
23
|
+
for (const check of pending) {
|
|
24
|
+
try {
|
|
25
|
+
if (check.ifOpen) await ctx.conflict.queueCheckForIfOpen(check.path);
|
|
26
|
+
else await ctx.conflict.queueCheckFor(check.path);
|
|
27
|
+
} catch (ex) {
|
|
28
|
+
if (!failed) {
|
|
29
|
+
failed = true;
|
|
30
|
+
failure = ex;
|
|
31
|
+
}
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (failed) throw failure;
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
async function queueConflictCheckFor(ctx, path, ifOpen = false) {
|
|
39
|
+
const documentId = await ctx.path.path2id(path);
|
|
40
|
+
const pending = ctx.state.deferredConflictChecks.get(documentId);
|
|
41
|
+
if (pending) {
|
|
42
|
+
pending.push({ path, ifOpen });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (ifOpen) await ctx.conflict.queueCheckForIfOpen(path);
|
|
46
|
+
else await ctx.conflict.queueCheckFor(path);
|
|
47
|
+
}
|
|
48
|
+
export {
|
|
49
|
+
queueConflictCheckFor,
|
|
50
|
+
withFileEventPaths
|
|
51
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { FilePathWithPrefix, MetaEntry, UXFileInfoStub } from "../../common/types.js";
|
|
2
|
+
import type { FileHandlerContext, PreservationResult } from "./context.js";
|
|
3
|
+
/**
|
|
4
|
+
* Preserve changed storage before an incoming write can replace its bytes.
|
|
5
|
+
*
|
|
6
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
7
|
+
* @param path - The affected file or provenance path.
|
|
8
|
+
* @param existDoc - The storage file observed before overwrite protection.
|
|
9
|
+
* @param incomingEntry - The database metadata about to be reflected.
|
|
10
|
+
* @param incomingContent - Already decoded incoming bytes, when available.
|
|
11
|
+
* @returns A PreservationResult: preserved:true stops the incoming effect; preserved:false without a snapshot means no safe candidate was established.
|
|
12
|
+
* @remarks The caller holds the document lock. preserved:true also covers a refused preservation write that must still stop overwrite; any returned snapshot requires later revalidation.
|
|
13
|
+
*/
|
|
14
|
+
export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, incomingEntry: MetaEntry, incomingContent?: string | string[] | Blob | ArrayBuffer): Promise<PreservationResult>;
|
|
15
|
+
/**
|
|
16
|
+
* Repeat overwrite protection after a previous storage observation became stale.
|
|
17
|
+
*
|
|
18
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
19
|
+
* @param path - The affected file or provenance path.
|
|
20
|
+
* @param incomingEntry - The database metadata about to be reflected.
|
|
21
|
+
* @param incomingContent - Already decoded incoming bytes, when available.
|
|
22
|
+
* @param allowExistingConflicts - Whether the caller explicitly selected an existing live conflict leaf.
|
|
23
|
+
* @returns A PreservationResult that either stops the incoming effect or supplies a candidate; missing evidence can leave preserved:false without a snapshot.
|
|
24
|
+
* @remarks The caller holds the document lock. This does not authorise overwrite; callers must validate any candidate at the established final check.
|
|
25
|
+
*/
|
|
26
|
+
export declare function recheckIncomingStorage(ctx: FileHandlerContext, path: FilePathWithPrefix, incomingEntry: MetaEntry, incomingContent: string | string[] | Blob | ArrayBuffer | undefined, allowExistingConflicts: boolean): Promise<PreservationResult>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import {
|
|
2
|
+
readProvenanceSnapshot,
|
|
3
|
+
currentStorageSnapshotMatches,
|
|
4
|
+
classifyStorageContent,
|
|
5
|
+
rememberMatchingLeaf,
|
|
6
|
+
finaliseStoredRevision
|
|
7
|
+
} from "./provenance.js";
|
|
8
|
+
import { queueConflictCheckFor } from "./locking.js";
|
|
9
|
+
import { isFolderInfo } from "./storage.js";
|
|
10
|
+
import { LOG_LEVEL_NOTICE } from "octagonal-wheels/common/logger";
|
|
11
|
+
import { isDocContentSame } from "../../common/utils.js";
|
|
12
|
+
async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEntry, incomingContent) {
|
|
13
|
+
const observedProvenance = await readProvenanceSnapshot(ctx, path);
|
|
14
|
+
const readFile = await ctx.host.readFileFromStub(existDoc);
|
|
15
|
+
const snapshot = { file: readFile, revision: observedProvenance };
|
|
16
|
+
if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) {
|
|
17
|
+
return await currentStorageSnapshotMatches(ctx, readFile, observedProvenance) ? { preserved: false, snapshot } : { preserved: false };
|
|
18
|
+
}
|
|
19
|
+
if (!incomingEntry._rev) {
|
|
20
|
+
return { preserved: false };
|
|
21
|
+
}
|
|
22
|
+
const classification = await classifyStorageContent(
|
|
23
|
+
ctx,
|
|
24
|
+
readFile,
|
|
25
|
+
incomingEntry,
|
|
26
|
+
void 0,
|
|
27
|
+
observedProvenance,
|
|
28
|
+
incomingContent ? { _rev: incomingEntry._rev, data: incomingContent } : void 0
|
|
29
|
+
);
|
|
30
|
+
if (!await currentStorageSnapshotMatches(ctx, readFile, observedProvenance)) {
|
|
31
|
+
return { preserved: false };
|
|
32
|
+
}
|
|
33
|
+
if (classification.kind === "unchanged") {
|
|
34
|
+
return { preserved: false, snapshot };
|
|
35
|
+
}
|
|
36
|
+
if (classification.kind === "matching-leaf") {
|
|
37
|
+
await rememberMatchingLeaf(ctx, path, classification.revision, readFile.stat.mtime, readFile.body);
|
|
38
|
+
await queueConflictCheckFor(ctx, path);
|
|
39
|
+
return { preserved: true };
|
|
40
|
+
}
|
|
41
|
+
const storedRevision = classification.kind === "edited" ? await ctx.host.db().storeWithBaseRevision(readFile, classification.revision, true) : await ctx.host.db().storeIndependentRevision(readFile, true);
|
|
42
|
+
if (storedRevision === false) {
|
|
43
|
+
ctx.host.log(`Prevented overwriting unsynchronised local changes for ${path}`, LOG_LEVEL_NOTICE);
|
|
44
|
+
return { preserved: true };
|
|
45
|
+
}
|
|
46
|
+
if (!await finaliseStoredRevision(ctx, readFile, observedProvenance, storedRevision)) {
|
|
47
|
+
return { preserved: false };
|
|
48
|
+
}
|
|
49
|
+
ctx.host.log(`Preserved unsynchronised local changes as a conflict for ${path}`, LOG_LEVEL_NOTICE);
|
|
50
|
+
await queueConflictCheckFor(ctx, path);
|
|
51
|
+
return { preserved: true };
|
|
52
|
+
}
|
|
53
|
+
async function recheckIncomingStorage(ctx, path, incomingEntry, incomingContent, allowExistingConflicts) {
|
|
54
|
+
const current = await ctx.host.storage().getStub(path);
|
|
55
|
+
if (!current || isFolderInfo(current)) return { preserved: false };
|
|
56
|
+
const protection = await preserveUnsyncedStorageAsConflict(ctx, path, current, incomingEntry, incomingContent);
|
|
57
|
+
if (protection.preserved || !protection.snapshot) return protection;
|
|
58
|
+
if (!allowExistingConflicts && !ctx.setting.currentSettings().writeDocumentsIfConflicted && (await ctx.host.db().getConflictedRevs(path)).length > 0) {
|
|
59
|
+
await queueConflictCheckFor(ctx, path, true);
|
|
60
|
+
return { preserved: true };
|
|
61
|
+
}
|
|
62
|
+
return protection;
|
|
63
|
+
}
|
|
64
|
+
export {
|
|
65
|
+
preserveUnsyncedStorageAsConflict,
|
|
66
|
+
recheckIncomingStorage
|
|
67
|
+
};
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import type { FilePathWithPrefix, UXFileInfo } from "../../common/types.js";
|
|
2
|
+
import type { FileReflectionProvenanceRecord } from "../../interfaces/FileReflectionProvenance.js";
|
|
3
|
+
import type { FileHandlerContext } from "./context.js";
|
|
4
|
+
/**
|
|
5
|
+
* Resolve the device-local provenance key using the current path identity policy.
|
|
6
|
+
*
|
|
7
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
8
|
+
* @param path - The affected file or provenance path.
|
|
9
|
+
* @returns The normalised device-local provenance key.
|
|
10
|
+
* @remarks Reads the current path-normalisation setting without accessing or changing the provenance store.
|
|
11
|
+
*/
|
|
12
|
+
export declare function getProvenancePath(ctx: FileHandlerContext, path: FilePathWithPrefix): FilePathWithPrefix;
|
|
13
|
+
/**
|
|
14
|
+
* Read usable revision provenance and conservatively discard only unsupported stale records.
|
|
15
|
+
*
|
|
16
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
17
|
+
* @param path - The affected file or provenance path.
|
|
18
|
+
* @returns The usable record, or undefined when ancestry cannot be established.
|
|
19
|
+
* @remarks May remove a legacy record when its referenced revision is absent or deleted. Inspection errors are logged and yield unknown provenance; host readiness is not retried here.
|
|
20
|
+
*/
|
|
21
|
+
export declare function getProvenance(ctx: FileHandlerContext, path: FilePathWithPrefix): Promise<FileReflectionProvenanceRecord | undefined>;
|
|
22
|
+
/**
|
|
23
|
+
* Hash immutable storage bytes with the per-instance cache when provenance is available.
|
|
24
|
+
*
|
|
25
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
26
|
+
* @param content - The immutable bytes for this provenance observation.
|
|
27
|
+
* @returns Supported hash and size evidence, or an empty object when evidence is unavailable.
|
|
28
|
+
* @remarks Only the per-instance Blob hash cache changes. A hashing failure evicts its cached promise, logs the error, and returns empty evidence without updating a provenance record.
|
|
29
|
+
*/
|
|
30
|
+
export declare function contentEvidence(ctx: FileHandlerContext, content: Blob): Promise<Pick<FileReflectionProvenanceRecord, "contentHash" | "contentSize">>;
|
|
31
|
+
/**
|
|
32
|
+
* Record a saved or reflected revision and its content evidence on this device.
|
|
33
|
+
*
|
|
34
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
35
|
+
* @param path - The affected file or provenance path.
|
|
36
|
+
* @param revision - The observed provenance or selected revision.
|
|
37
|
+
* @param observedStorageMtime - The raw storage timestamp associated with the saved bytes.
|
|
38
|
+
* @param content - The immutable bytes for this provenance observation.
|
|
39
|
+
* @param evidence - Already computed content evidence, when available.
|
|
40
|
+
* @returns Completion after the optional write attempt; provenance-store write errors are logged and suppressed.
|
|
41
|
+
* @remarks No document lock is acquired here. Revision persistence and this optional device-local write are separate; a return does not guarantee durable provenance.
|
|
42
|
+
*/
|
|
43
|
+
export declare function setProvenance(ctx: FileHandlerContext, path: FilePathWithPrefix, revision: string | undefined, observedStorageMtime: number | undefined, content: Blob, evidence?: Pick<FileReflectionProvenanceRecord, "contentHash" | "contentSize">): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Remove a device-local record without hiding a successful database or storage effect.
|
|
46
|
+
*
|
|
47
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
48
|
+
* @param path - The affected file or provenance path.
|
|
49
|
+
* @returns Completion after the optional clear attempt; provenance-store deletion errors are logged and suppressed.
|
|
50
|
+
* @remarks No document lock is acquired here. The caller's database or storage effect is not rolled back if device-local cleanup fails.
|
|
51
|
+
*/
|
|
52
|
+
export declare function deleteProvenance(ctx: FileHandlerContext, path: FilePathWithPrefix): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Find one unambiguous database revision containing the observed storage bytes.
|
|
55
|
+
*
|
|
56
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
57
|
+
* @param file - The supplied storage observation; its body is reused when present.
|
|
58
|
+
* @returns The unique matching revision, or undefined after ambiguity or an inspection failure.
|
|
59
|
+
* @remarks Inspects database history without recording provenance. Lookup failures are logged and treated as unknown origin.
|
|
60
|
+
*/
|
|
61
|
+
export declare function findUniqueContentRevision(ctx: FileHandlerContext, file: UXFileInfo): Promise<string | undefined>;
|
|
62
|
+
/**
|
|
63
|
+
* Prefer the displayed revision before reconstructing provenance from content.
|
|
64
|
+
*
|
|
65
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
66
|
+
* @param file - The supplied storage observation; its body is reused when present.
|
|
67
|
+
* @param preferredPath - The source provenance path used during a rename, when supplied.
|
|
68
|
+
* @returns The displayed or uniquely reconstructed revision, or undefined.
|
|
69
|
+
* @remarks No document lock is acquired here. Callers retain their surrounding operation lock; only device-local provenance and its hash cache may change.
|
|
70
|
+
*/
|
|
71
|
+
export declare function getProvenBaseRevision(ctx: FileHandlerContext, file: UXFileInfo, preferredPath?: FilePathWithPrefix): Promise<string | undefined>;
|
|
72
|
+
/**
|
|
73
|
+
* Classify bytes against recorded ancestry before considering current matching leaves.
|
|
74
|
+
*
|
|
75
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
76
|
+
* @param file - The supplied storage observation; its body is reused when present.
|
|
77
|
+
* @param currentEntry - The current database metadata, or false when no record exists.
|
|
78
|
+
* @param preferredPath - The source provenance path used during a rename, when supplied.
|
|
79
|
+
* @param recorded - The provenance captured with the storage bytes.
|
|
80
|
+
* @param currentLoaded - An already decoded revision body that may avoid a repeated database read.
|
|
81
|
+
* @param requireReadableContent - Whether unreadable recorded live content must reject recovery.
|
|
82
|
+
* @returns The ancestry-based classification; unreadable required content rejects the operation.
|
|
83
|
+
* @remarks No document lock is acquired here. Callers retain their surrounding operation lock; only device-local provenance and its hash cache may change.
|
|
84
|
+
*/
|
|
85
|
+
export declare function classifyStorageContent(ctx: FileHandlerContext, file: UXFileInfo, currentEntry: {
|
|
86
|
+
_rev?: string;
|
|
87
|
+
deleted?: boolean;
|
|
88
|
+
_deleted?: boolean;
|
|
89
|
+
} | false, preferredPath?: FilePathWithPrefix, recorded?: FileReflectionProvenanceRecord, currentLoaded?: {
|
|
90
|
+
_rev?: string;
|
|
91
|
+
data: string | string[] | Blob | ArrayBuffer;
|
|
92
|
+
}, requireReadableContent?: boolean): Promise<StorageContentClassification>;
|
|
93
|
+
/**
|
|
94
|
+
* Attempt to remember a revision already classified as an unambiguous match by the caller.
|
|
95
|
+
*
|
|
96
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
97
|
+
* @param path - The affected file or provenance path.
|
|
98
|
+
* @param revision - The observed provenance or selected revision.
|
|
99
|
+
* @param mtime - The raw storage timestamp observed with the matching bytes.
|
|
100
|
+
* @param content - The immutable bytes for this provenance observation.
|
|
101
|
+
* @param evidence - Already computed content evidence, when available.
|
|
102
|
+
* @returns Completion after a best-effort update when a truthy revision was supplied; undefined revisions do nothing.
|
|
103
|
+
* @remarks This helper neither discovers a match nor validates live-leaf uniqueness. Its caller establishes that evidence, and provenance publication remains optional and best-effort.
|
|
104
|
+
*/
|
|
105
|
+
export declare function rememberMatchingLeaf(ctx: FileHandlerContext, path: FilePathWithPrefix, revision: string | undefined, mtime: number, content: Blob, evidence?: Pick<FileReflectionProvenanceRecord, "contentHash" | "contentSize">): Promise<void>;
|
|
106
|
+
/**
|
|
107
|
+
* Capture an independent raw provenance value for optimistic storage checks.
|
|
108
|
+
*
|
|
109
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
110
|
+
* @param path - The affected file or provenance path.
|
|
111
|
+
* @param requireReadable - Whether a provenance-store read error must propagate.
|
|
112
|
+
* @returns A copied raw record or undefined; required store-read failures propagate.
|
|
113
|
+
* @remarks Does not validate or remove the referenced database revision. An absent store or record, or a suppressed read failure, yields undefined.
|
|
114
|
+
*/
|
|
115
|
+
export declare function readProvenanceSnapshot(ctx: FileHandlerContext, path: FilePathWithPrefix, requireReadable?: boolean): Promise<FileReflectionProvenanceRecord | undefined>;
|
|
116
|
+
/**
|
|
117
|
+
* Recheck exact path, bytes, timestamp, and provenance against one observation.
|
|
118
|
+
*
|
|
119
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
120
|
+
* @param file - The supplied storage observation; its body is reused when present.
|
|
121
|
+
* @param revision - The raw provenance record captured alongside the supplied file.
|
|
122
|
+
* @param requireReadableProvenance - Whether a provenance-store read error must propagate during revalidation.
|
|
123
|
+
* @returns Whether the current observation still matches the captured storage and provenance.
|
|
124
|
+
* @remarks Compares a fresh storage observation with raw provenance without writing records. Storage and comparison errors propagate; the flag controls provenance-read errors only.
|
|
125
|
+
*/
|
|
126
|
+
export declare function currentStorageSnapshotMatches(ctx: FileHandlerContext, file: UXFileInfo, revision: FileReflectionProvenanceRecord | undefined, requireReadableProvenance?: boolean): Promise<boolean>;
|
|
127
|
+
/**
|
|
128
|
+
* Attempt provenance publication for a durable revision after storage revalidation.
|
|
129
|
+
*
|
|
130
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
131
|
+
* @param file - The supplied storage observation; its body is reused when present.
|
|
132
|
+
* @param observedProvenance - The record captured before the database write.
|
|
133
|
+
* @param storedRevision - The durable revision whose provenance may now be published.
|
|
134
|
+
* @param requireReadableProvenance - Whether a provenance-store read error must propagate during revalidation.
|
|
135
|
+
* @returns Whether storage revalidation allowed a provenance-write attempt; true does not guarantee that the optional record was persisted.
|
|
136
|
+
* @remarks The caller holds its document lock. The database write is already durable; storage mismatch returns false, while provenance-store write errors retain setProvenance's best-effort policy.
|
|
137
|
+
*/
|
|
138
|
+
export declare function finaliseStoredRevision(ctx: FileHandlerContext, file: UXFileInfo, observedProvenance: FileReflectionProvenanceRecord | undefined, storedRevision: string, requireReadableProvenance?: boolean): Promise<boolean>;
|
|
139
|
+
/**
|
|
140
|
+
* Recognise supported hash evidence without interpreting it as revision ancestry.
|
|
141
|
+
*
|
|
142
|
+
* @param record - The device-local record to inspect.
|
|
143
|
+
* @returns Whether the record contains a supported hash and a non-negative integral content size.
|
|
144
|
+
* @remarks Narrows both optional evidence fields without reading or changing any service or state.
|
|
145
|
+
*/
|
|
146
|
+
export declare function hasContentHash(record: FileReflectionProvenanceRecord | undefined): record is FileReflectionProvenanceRecord & {
|
|
147
|
+
contentHash: string;
|
|
148
|
+
contentSize: number;
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* Compare the revision and observed content evidence of two device-local records.
|
|
152
|
+
*
|
|
153
|
+
* @param left - The first provenance observation.
|
|
154
|
+
* @param right - The second provenance observation.
|
|
155
|
+
* @returns Whether every stored provenance field is equal.
|
|
156
|
+
* @remarks No document lock is acquired here. Callers retain their surrounding operation lock; only device-local provenance and its hash cache may change.
|
|
157
|
+
*/
|
|
158
|
+
export declare function sameProvenance(left: FileReflectionProvenanceRecord | undefined, right: FileReflectionProvenanceRecord | undefined): boolean;
|
|
159
|
+
/** Recorded ancestry distinguishes unchanged bytes from an edit on the displayed branch. */
|
|
160
|
+
type RecordedStorageClassification = {
|
|
161
|
+
kind: "unchanged";
|
|
162
|
+
revision: string;
|
|
163
|
+
} | {
|
|
164
|
+
kind: "edited";
|
|
165
|
+
revision: string;
|
|
166
|
+
};
|
|
167
|
+
/** Classification used by saving and overwrite preservation without guessing ancestry. */
|
|
168
|
+
export type StorageContentClassification = RecordedStorageClassification | {
|
|
169
|
+
kind: "matching-leaf";
|
|
170
|
+
revision?: string;
|
|
171
|
+
} | {
|
|
172
|
+
kind: "unknown";
|
|
173
|
+
};
|
|
174
|
+
export {};
|