@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.
- 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 +1 -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/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/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 +119 -182
- package/dist/serviceModules/ServiceFileHandlerBase.js +182 -1402
- package/docs/conflict-resolution.md +3 -1
- package/docs/development.md +36 -0
- package/docs/offline-scanner.md +5 -1
- package/docs/p2p-transport-lifecycle.md +8 -1
- package/docs/storage-events-and-reflection.md +203 -19
- package/package.json +1 -1
|
@@ -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 {};
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { isFolderInfo } from "./storage.js";
|
|
2
|
+
import { LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
|
|
3
|
+
import { displayRev, isDocContentSame, readContent } from "../../common/utils.js";
|
|
4
|
+
import { computeFileContentHash } from "../../common/fileContentHash.js";
|
|
5
|
+
import { getPathNormalizationVersion, normalisePathForIdentity } from "../../common/pathNormalization.js";
|
|
6
|
+
function getProvenancePath(ctx, path) {
|
|
7
|
+
return normalisePathForIdentity(
|
|
8
|
+
path,
|
|
9
|
+
getPathNormalizationVersion(ctx.setting.currentSettings())
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
async function getProvenance(ctx, path) {
|
|
13
|
+
if (!ctx.provenance) return void 0;
|
|
14
|
+
try {
|
|
15
|
+
const record = await ctx.provenance.get(getProvenancePath(ctx, path));
|
|
16
|
+
if (!record) return void 0;
|
|
17
|
+
const entry = await ctx.host.db().fetchEntryMeta(path, record.revision, true);
|
|
18
|
+
if (entry && !entry._deleted && !entry.deleted) {
|
|
19
|
+
return record;
|
|
20
|
+
}
|
|
21
|
+
if (!hasContentHash(record)) await ctx.provenance.delete(getProvenancePath(ctx, path));
|
|
22
|
+
} catch (ex) {
|
|
23
|
+
ctx.host.log(`Could not read file reflection provenance for ${path}`, LOG_LEVEL_VERBOSE);
|
|
24
|
+
ctx.host.log(ex, LOG_LEVEL_VERBOSE);
|
|
25
|
+
}
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
async function contentEvidence(ctx, content) {
|
|
29
|
+
if (!ctx.provenance) return {};
|
|
30
|
+
try {
|
|
31
|
+
let hash = ctx.state.contentHashes.get(content);
|
|
32
|
+
if (!hash) {
|
|
33
|
+
hash = computeFileContentHash(content);
|
|
34
|
+
ctx.state.contentHashes.set(content, hash);
|
|
35
|
+
}
|
|
36
|
+
return { contentHash: await hash, contentSize: content.size };
|
|
37
|
+
} catch (ex) {
|
|
38
|
+
ctx.state.contentHashes.delete(content);
|
|
39
|
+
ctx.host.log("Could not hash file reflection content", LOG_LEVEL_VERBOSE);
|
|
40
|
+
ctx.host.log(ex, LOG_LEVEL_VERBOSE);
|
|
41
|
+
return {};
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function setProvenance(ctx, path, revision, observedStorageMtime, content, evidence) {
|
|
45
|
+
if (!ctx.provenance || !revision) return;
|
|
46
|
+
try {
|
|
47
|
+
await ctx.provenance.set(getProvenancePath(ctx, path), {
|
|
48
|
+
revision,
|
|
49
|
+
observedStorageMtime,
|
|
50
|
+
...evidence ?? await contentEvidence(ctx, content)
|
|
51
|
+
});
|
|
52
|
+
} catch (ex) {
|
|
53
|
+
ctx.host.log(`Could not record file reflection provenance for ${path}`, LOG_LEVEL_VERBOSE);
|
|
54
|
+
ctx.host.log(ex, LOG_LEVEL_VERBOSE);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async function deleteProvenance(ctx, path) {
|
|
58
|
+
if (!ctx.provenance) return;
|
|
59
|
+
try {
|
|
60
|
+
await ctx.provenance.delete(getProvenancePath(ctx, path));
|
|
61
|
+
} catch (ex) {
|
|
62
|
+
ctx.host.log(`Could not delete file reflection provenance for ${path}`, LOG_LEVEL_VERBOSE);
|
|
63
|
+
ctx.host.log(ex, LOG_LEVEL_VERBOSE);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async function findUniqueContentRevision(ctx, file) {
|
|
67
|
+
try {
|
|
68
|
+
const revisions = await ctx.host.db().findContentRevisions(file, file.body);
|
|
69
|
+
return revisions.length === 1 ? revisions[0] : void 0;
|
|
70
|
+
} catch (ex) {
|
|
71
|
+
ctx.host.log(`Could not reconstruct file reflection provenance for ${file.path}`, LOG_LEVEL_VERBOSE);
|
|
72
|
+
ctx.host.log(ex, LOG_LEVEL_VERBOSE);
|
|
73
|
+
return void 0;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async function getProvenBaseRevision(ctx, file, preferredPath) {
|
|
77
|
+
const path = preferredPath ?? file.path;
|
|
78
|
+
const recorded = await getProvenance(ctx, path) ?? (preferredPath && preferredPath !== file.path ? await getProvenance(ctx, file.path) : void 0);
|
|
79
|
+
if (recorded) {
|
|
80
|
+
return recorded.revision;
|
|
81
|
+
}
|
|
82
|
+
const matched = await findUniqueContentRevision(ctx, file);
|
|
83
|
+
if (matched) {
|
|
84
|
+
await setProvenance(ctx, path, matched, file.stat.mtime, file.body);
|
|
85
|
+
return matched;
|
|
86
|
+
}
|
|
87
|
+
return void 0;
|
|
88
|
+
}
|
|
89
|
+
async function classifyStorageContent(ctx, file, currentEntry, preferredPath, recorded, currentLoaded, requireReadableContent = false) {
|
|
90
|
+
const path = preferredPath ?? file.path;
|
|
91
|
+
const recordedRevision = recorded?.revision;
|
|
92
|
+
if (recordedRevision) {
|
|
93
|
+
const classification = await classifyRecordedStorageContent(
|
|
94
|
+
ctx,
|
|
95
|
+
file,
|
|
96
|
+
path,
|
|
97
|
+
recorded,
|
|
98
|
+
recordedRevision,
|
|
99
|
+
currentLoaded,
|
|
100
|
+
requireReadableContent
|
|
101
|
+
);
|
|
102
|
+
if (classification) return classification;
|
|
103
|
+
}
|
|
104
|
+
return await classifyLiveStorageContent(ctx, file, currentEntry);
|
|
105
|
+
}
|
|
106
|
+
async function rememberMatchingLeaf(ctx, path, revision, mtime, content, evidence) {
|
|
107
|
+
if (revision) await setProvenance(ctx, path, revision, mtime, content, evidence);
|
|
108
|
+
}
|
|
109
|
+
async function readProvenanceSnapshot(ctx, path, requireReadable = false) {
|
|
110
|
+
try {
|
|
111
|
+
const record = await ctx.provenance?.get(getProvenancePath(ctx, path));
|
|
112
|
+
return record ? { ...record } : void 0;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (requireReadable) throw error;
|
|
115
|
+
return void 0;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function currentStorageSnapshotMatches(ctx, file, revision, requireReadableProvenance = false) {
|
|
119
|
+
const current = await ctx.host.storage().getStub(file.path);
|
|
120
|
+
if (!current || isFolderInfo(current) || current.path !== file.path) return false;
|
|
121
|
+
const readCurrent = await ctx.host.readFileFromStub(current);
|
|
122
|
+
return readCurrent.stat.mtime === file.stat.mtime && await isDocContentSame(readCurrent.body, file.body) && sameProvenance(await readProvenanceSnapshot(ctx, file.path, requireReadableProvenance), revision);
|
|
123
|
+
}
|
|
124
|
+
async function finaliseStoredRevision(ctx, file, observedProvenance, storedRevision, requireReadableProvenance = false) {
|
|
125
|
+
const evidence = await contentEvidence(ctx, file.body);
|
|
126
|
+
if (await currentStorageSnapshotMatches(ctx, file, observedProvenance, requireReadableProvenance)) {
|
|
127
|
+
await setProvenance(ctx, file.path, storedRevision, file.stat.mtime, file.body, evidence);
|
|
128
|
+
return true;
|
|
129
|
+
} else {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function hasContentHash(record) {
|
|
134
|
+
return !!record && typeof record.contentHash === "string" && /^sha256:[0-9a-f]{64}$/.test(record.contentHash) && typeof record.contentSize === "number" && Number.isSafeInteger(record.contentSize) && record.contentSize >= 0;
|
|
135
|
+
}
|
|
136
|
+
function sameProvenance(left, right) {
|
|
137
|
+
return left?.revision === right?.revision && left?.observedStorageMtime === right?.observedStorageMtime && left?.contentHash === right?.contentHash && left?.contentSize === right?.contentSize;
|
|
138
|
+
}
|
|
139
|
+
async function classifyRecordedStorageContent(ctx, file, path, recorded, recordedRevision, currentLoaded, requireReadableContent) {
|
|
140
|
+
if (hasContentHash(recorded) && recorded.contentSize === file.body.size && (await contentEvidence(ctx, file.body)).contentHash === recorded.contentHash) {
|
|
141
|
+
return { kind: "unchanged", revision: recordedRevision };
|
|
142
|
+
}
|
|
143
|
+
const loadedContentIsDecoded = currentLoaded?._rev === recordedRevision;
|
|
144
|
+
const base = loadedContentIsDecoded ? currentLoaded : await ctx.host.db().fetchEntry(file, recordedRevision, true, true, !requireReadableContent);
|
|
145
|
+
if (base && base._rev === recordedRevision && !("deleted" in base && base.deleted) && !("_deleted" in base && base._deleted)) {
|
|
146
|
+
const baseContent = loadedContentIsDecoded ? base.data : readContent(base);
|
|
147
|
+
return await isDocContentSame(baseContent, file.body) ? { kind: "unchanged", revision: recordedRevision } : { kind: "edited", revision: recordedRevision };
|
|
148
|
+
}
|
|
149
|
+
if (!base) {
|
|
150
|
+
const meta = await ctx.host.db().fetchEntryMeta(file, recordedRevision, true);
|
|
151
|
+
if (requireReadableContent && meta && !meta.deleted && !meta._deleted) {
|
|
152
|
+
throw new Error(
|
|
153
|
+
`Could not read the recorded file revision ${displayRev(recordedRevision)} for ${file.path}`
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if ((!meta || meta.deleted || meta._deleted) && !hasContentHash(recorded)) await deleteProvenance(ctx, path);
|
|
157
|
+
}
|
|
158
|
+
return void 0;
|
|
159
|
+
}
|
|
160
|
+
async function classifyLiveStorageContent(ctx, file, currentEntry) {
|
|
161
|
+
const matches = currentEntry ? await ctx.host.db().findLiveContentRevisions(file, file.body) : [];
|
|
162
|
+
if (matches.length) {
|
|
163
|
+
return { kind: "matching-leaf", revision: matches.length === 1 ? matches[0] : void 0 };
|
|
164
|
+
}
|
|
165
|
+
return { kind: "unknown" };
|
|
166
|
+
}
|
|
167
|
+
export {
|
|
168
|
+
classifyStorageContent,
|
|
169
|
+
contentEvidence,
|
|
170
|
+
currentStorageSnapshotMatches,
|
|
171
|
+
deleteProvenance,
|
|
172
|
+
finaliseStoredRevision,
|
|
173
|
+
findUniqueContentRevision,
|
|
174
|
+
getProvenBaseRevision,
|
|
175
|
+
getProvenance,
|
|
176
|
+
getProvenancePath,
|
|
177
|
+
hasContentHash,
|
|
178
|
+
readProvenanceSnapshot,
|
|
179
|
+
rememberMatchingLeaf,
|
|
180
|
+
sameProvenance,
|
|
181
|
+
setProvenance
|
|
182
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { FilePath, FilePathWithPrefix, MetaEntry, UXFileInfo, UXFileInfoStub } from "../../common/types.js";
|
|
2
|
+
import type { FileHandlerContext } from "./context.js";
|
|
3
|
+
/**
|
|
4
|
+
* Reflect one selected live revision under the storage document lock.
|
|
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 rev - The exact selected database revision.
|
|
9
|
+
* @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
|
|
10
|
+
* @returns The selected live leaf reflection result, or false if the selected revision is no longer live.
|
|
11
|
+
* @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
|
|
12
|
+
*/
|
|
13
|
+
export declare function dbToStorageWithSpecificRev(ctx: FileHandlerContext, info: UXFileInfoStub | UXFileInfo | FilePath | FilePathWithPrefix | null, rev: string, force?: boolean): Promise<boolean>;
|
|
14
|
+
/**
|
|
15
|
+
* Fetch and reflect the current database revision under its document lock.
|
|
16
|
+
*
|
|
17
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
18
|
+
* @param entryInfo - Current metadata or a path from which metadata is loaded.
|
|
19
|
+
* @param info - The supplied file observation or path.
|
|
20
|
+
* @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
|
|
21
|
+
* @returns True after reflection or a safe conflict/absence skip; false on unreadable or unsafe observations.
|
|
22
|
+
* @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
|
|
23
|
+
*/
|
|
24
|
+
export declare function dbToStorage(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean): Promise<boolean>;
|
|
25
|
+
/**
|
|
26
|
+
* Fetch current metadata and apply its storage reflection without reacquiring the lock.
|
|
27
|
+
*
|
|
28
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
29
|
+
* @param entryInfo - Current metadata or a path from which metadata is loaded.
|
|
30
|
+
* @param info - The supplied file observation or path.
|
|
31
|
+
* @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
|
|
32
|
+
* @returns True after reflection or a safe conflict/absence skip; false on unreadable or unsafe observations.
|
|
33
|
+
* @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
|
|
34
|
+
*/
|
|
35
|
+
export declare function dbToStorageCore(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean): Promise<boolean>;
|
|
36
|
+
/**
|
|
37
|
+
* Reflect database content while protecting current storage and its provenance.
|
|
38
|
+
*
|
|
39
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
40
|
+
* @param docEntry - The captured database metadata to reflect.
|
|
41
|
+
* @param file - The supplied storage observation; its body is reused when present.
|
|
42
|
+
* @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
|
|
43
|
+
* @param allowExistingConflicts - Whether the caller explicitly selected an existing live conflict leaf.
|
|
44
|
+
* @param incomingRetry - The number of database-advancement rereads already consumed.
|
|
45
|
+
* @returns True after reflection or a policy skip; false when content, path, or current-state validation refuses the effect.
|
|
46
|
+
* @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
|
|
47
|
+
*/
|
|
48
|
+
export declare function applyDatabaseEntryToStorage(ctx: FileHandlerContext, docEntry: MetaEntry, file: UXFileInfoStub | UXFileInfo | null, force?: boolean, allowExistingConflicts?: boolean, incomingRetry?: number): Promise<boolean>;
|