@vrtmrz/livesync-commonlib 0.6.1 → 0.8.0
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 +29 -19
- package/dist/common/models/shared.definition.d.ts +10 -1
- package/dist/common/models/shared.definition.js +4 -3
- package/dist/events/coreEvents.d.ts +3 -0
- package/dist/events/coreEvents.js +2 -0
- package/dist/interfaces/FileReflectionProvenance.js +1 -0
- package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
- package/dist/managers/EntryManager/EntryManager.d.ts +1 -1
- package/dist/managers/EntryManager/EntryManager.js +2 -2
- package/dist/managers/EntryManager/EntryManagerImpls.d.ts +1 -1
- package/dist/managers/EntryManager/EntryManagerImpls.js +80 -8
- package/dist/managers/StorageEventManager/admission.d.ts +16 -3
- package/dist/managers/StorageEventManager/admission.js +18 -4
- package/dist/managers/StorageEventManager/processing.d.ts +2 -2
- package/dist/managers/StorageEventManager/processing.js +3 -3
- package/dist/managers/StorageEventManager/queue.d.ts +23 -14
- package/dist/managers/StorageEventManager/queue.js +70 -30
- package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
- package/dist/managers/StorageEventManager/snapshot.js +74 -0
- package/dist/managers/StorageEventManager/state.d.ts +27 -5
- package/dist/managers/StorageEventManager/state.js +9 -7
- package/dist/managers/StorageEventManager.d.ts +8 -0
- package/dist/managers/StorageEventManager.js +136 -18
- package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
- package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
- package/dist/managers/adapters/index.d.ts +1 -1
- package/dist/pouchdb/LiveSyncLocalDB.d.ts +1 -1
- package/dist/pouchdb/LiveSyncLocalDB.js +2 -2
- package/dist/replication/LiveSyncAbstractReplicator.d.ts +7 -0
- package/dist/replication/LiveSyncAbstractReplicator.js +5 -2
- package/dist/replication/ReplicatorInstance.d.ts +3 -0
- package/dist/replication/ReplicatorProvider.d.ts +23 -2
- package/dist/replication/ReplicatorProvider.js +10 -0
- package/dist/replication/SyncParamsHandler.js +26 -25
- package/dist/replication/couchdb/LiveSyncReplicator.d.ts +14 -2
- package/dist/replication/couchdb/LiveSyncReplicator.js +247 -122
- package/dist/replication/index.d.ts +4 -2
- package/dist/replication/index.js +6 -0
- package/dist/replication/remoteTransportFailure.d.ts +24 -0
- package/dist/replication/remoteTransportFailure.js +80 -0
- package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +1 -1
- package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +2 -2
- package/dist/replication/trystero/TrysteroRpcRoom.d.ts +14 -0
- package/dist/replication/trystero/TrysteroRpcRoom.js +168 -0
- package/dist/replication/trystero/rpcCompat.d.ts +1 -0
- package/dist/replication/trystero/rpcCompat.js +15 -0
- package/dist/rpc/RpcRoom.d.ts +1 -0
- package/dist/rpc/RpcRoom.js +21 -9
- package/dist/rpc/RpcSession.d.ts +8 -13
- package/dist/rpc/RpcSession.js +14 -35
- package/dist/rpc/commonlibRpcRoom.d.ts +1 -0
- package/dist/rpc/commonlibRpcRoom.js +4 -0
- package/dist/rpc/errors.d.ts +9 -3
- package/dist/rpc/errors.js +13 -16
- package/dist/rpc/index.d.ts +10 -1
- package/dist/rpc/index.js +2 -1
- package/dist/rpc/pouchdb/RpcPouchDBProxy.d.ts +1 -1
- package/dist/rpc/pouchdb/RpcPouchDBServer.d.ts +1 -1
- package/dist/serviceFeatures/targetFilter.d.ts +3 -1
- package/dist/serviceFeatures/targetFilter.js +2 -2
- package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +5 -2
- package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -4
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +28 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +53 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +59 -3
- package/dist/services/base/IService.d.ts +9 -6
- package/dist/services/base/KeyValueDBService.d.ts +6 -6
- package/dist/services/base/ReadinessEvaluator.d.ts +7 -6
- package/dist/services/base/ReadinessEvaluator.js +4 -2
- package/dist/services/base/RemoteConnection.d.ts +4 -0
- package/dist/services/base/RemoteService.d.ts +5 -3
- package/dist/services/base/RemoteService.js +85 -33
- package/dist/services/base/ReplicationService.d.ts +10 -2
- package/dist/services/base/ReplicationService.js +13 -7
- package/dist/services/base/ReplicationService.readiness.d.ts +14 -4
- package/dist/services/base/ReplicationService.readiness.js +29 -2
- package/dist/services/base/ReplicationService.typedReplication.d.ts +5 -2
- package/dist/services/base/ReplicationService.typedReplication.js +67 -6
- package/dist/services/base/ReplicationStaticsOwner.d.ts +18 -0
- package/dist/services/base/ReplicationStaticsOwner.js +33 -0
- package/dist/services/base/ReplicatorService.d.ts +2 -10
- package/dist/services/base/ReplicatorService.js +6 -3
- package/dist/services/base/VaultService.d.ts +1 -0
- package/dist/string_and_binary/chunks.d.ts +1 -1
- package/dist/string_and_binary/chunks.js +63 -50
- package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
- package/dist/worker/WorkerPushStreamProducer.js +299 -0
- package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
- package/dist/worker/WorkerPushStreamReader.js +179 -0
- package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
- package/dist/worker/backgroundWorkerRpcContract.js +24 -0
- package/dist/worker/bg.worker.js +2 -14
- package/dist/worker/bg.worker.splitting.d.ts +3 -6
- package/dist/worker/bg.worker.splitting.js +65 -30
- package/dist/worker/bgWorker.d.ts +9 -11
- package/dist/worker/bgWorker.direct.d.ts +5 -28
- package/dist/worker/bgWorker.direct.js +32 -2
- package/dist/worker/bgWorker.errors.d.ts +1 -0
- package/dist/worker/bgWorker.errors.js +12 -0
- package/dist/worker/bgWorker.js +718 -268
- package/dist/worker/bgWorker.splitting.d.ts +12 -27
- package/dist/worker/bgWorker.splitting.js +114 -110
- package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
- package/dist/worker/outOfBandCancelIterator.js +8 -0
- package/dist/worker/serveBackgroundWorker.d.ts +3 -0
- package/dist/worker/serveBackgroundWorker.js +35 -0
- package/dist/worker/splitConnectionTracker.d.ts +25 -0
- package/dist/worker/splitConnectionTracker.js +73 -0
- package/dist/worker/splitGate.d.ts +19 -0
- package/dist/worker/splitGate.js +71 -0
- package/dist/worker/universalTypes.d.ts +1 -19
- package/dist/worker/universalTypes.js +0 -4
- package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
- package/dist/worker/workerPushStreamProtocol.js +143 -0
- package/docs/development.md +75 -32
- package/docs/p2p-transport-lifecycle.md +2 -3
- package/docs/storage-events-and-reflection.md +40 -5
- package/package.json +3 -2
- package/dist/worker/bg.common.d.ts +0 -2
- package/dist/worker/bg.common.js +0 -6
- package/dist/worker/bg.worker.encryption.d.ts +0 -7
- package/dist/worker/bg.worker.encryption.js +0 -30
- package/dist/worker/bgWorker.encryption.d.ts +0 -22
- package/dist/worker/bgWorker.encryption.js +0 -40
|
@@ -38,7 +38,7 @@ export declare class RpcPouchDBProxy extends EventEmitter {
|
|
|
38
38
|
};
|
|
39
39
|
private readonly session;
|
|
40
40
|
private readonly ns;
|
|
41
|
-
constructor(session: RpcSession, name: string, ns?: string);
|
|
41
|
+
constructor(session: Pick<RpcSession, "call">, name: string, ns?: string);
|
|
42
42
|
/**
|
|
43
43
|
* Invoke an RPC method and reconstruct PouchDB error shapes on the response.
|
|
44
44
|
*
|
|
@@ -13,4 +13,4 @@ import type { RpcRoom } from "../RpcRoom.js";
|
|
|
13
13
|
* @param db The PouchDB database instance to expose.
|
|
14
14
|
* @param ns Method namespace prefix (default: `'pdb'`).
|
|
15
15
|
*/
|
|
16
|
-
export declare function exposeDB(room: RpcRoom, db: PouchDB.Database<object>, ns?: string): void;
|
|
16
|
+
export declare function exposeDB(room: Pick<RpcRoom, "register">, db: PouchDB.Database<object>, ns?: string): void;
|
|
@@ -15,7 +15,9 @@ export declare function isAcceptedInFilenameDuplicationFactory(host: NecessarySe
|
|
|
15
15
|
* Local database responsible for non-internal files, syncOnlyRegEx, syncIgnoreRegEx
|
|
16
16
|
* This possibly should be separated.
|
|
17
17
|
*/
|
|
18
|
-
export declare function isAcceptedByLocalDBFactory(host: NecessaryServices<"database" | "databaseEvents", never>, log: LogFunction): (file: string | UXFileInfoStub
|
|
18
|
+
export declare function isAcceptedByLocalDBFactory(host: NecessaryServices<"database" | "databaseEvents", never>, log: LogFunction): (file: string | UXFileInfoStub, options?: {
|
|
19
|
+
internalFileEvent?: boolean;
|
|
20
|
+
}) => Promise<boolean>;
|
|
19
21
|
/**
|
|
20
22
|
* Factory function to create the isAcceptedByIgnoreFiles handler.
|
|
21
23
|
* This handler checks if a file is ignored based on the ignore files specified in the settings.
|
|
@@ -39,10 +39,10 @@ function isAcceptedByLocalDBFactory(host, log) {
|
|
|
39
39
|
isReady = promiseWithResolvers();
|
|
40
40
|
return Promise.resolve(true);
|
|
41
41
|
});
|
|
42
|
-
return async (file) => {
|
|
42
|
+
return async (file, options) => {
|
|
43
43
|
await isReady.promise;
|
|
44
44
|
const filepath = getStoragePathFromUXFileInfo(file);
|
|
45
|
-
if (!await Promise.resolve(database.localDatabase.isTargetFile(filepath))) {
|
|
45
|
+
if (!await Promise.resolve(database.localDatabase.isTargetFile(filepath, options?.internalFileEvent))) {
|
|
46
46
|
log("File is not target by local DB: " + filepath);
|
|
47
47
|
return false;
|
|
48
48
|
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { FilePathWithPrefix, MetaEntry, UXFileInfoStub } from "../../common/types.js";
|
|
2
2
|
import type { FileHandlerContext, PreservationResult } from "./context.js";
|
|
3
|
+
/** Decoded incoming file body supplied for live-write protection (absent for deletions). */
|
|
4
|
+
type IncomingContent = string | string[] | Blob | ArrayBuffer;
|
|
3
5
|
/**
|
|
4
6
|
* Preserve changed storage before an incoming write can replace its bytes.
|
|
5
7
|
*
|
|
@@ -11,7 +13,7 @@ import type { FileHandlerContext, PreservationResult } from "./context.js";
|
|
|
11
13
|
* @returns A PreservationResult: preserved:true stops the incoming effect; preserved:false without a snapshot means no safe candidate was established.
|
|
12
14
|
* @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
15
|
*/
|
|
14
|
-
export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, incomingEntry: MetaEntry, incomingContent?:
|
|
16
|
+
export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, incomingEntry: MetaEntry, incomingContent?: IncomingContent): Promise<PreservationResult>;
|
|
15
17
|
/**
|
|
16
18
|
* Repeat overwrite protection after a previous storage observation became stale.
|
|
17
19
|
*
|
|
@@ -23,4 +25,5 @@ export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContex
|
|
|
23
25
|
* @returns A PreservationResult that either stops the incoming effect or supplies a candidate; missing evidence can leave preserved:false without a snapshot.
|
|
24
26
|
* @remarks The caller holds the document lock. This does not authorise overwrite; callers must validate any candidate at the established final check.
|
|
25
27
|
*/
|
|
26
|
-
export declare function recheckIncomingStorage(ctx: FileHandlerContext, path: FilePathWithPrefix, incomingEntry: MetaEntry, incomingContent:
|
|
28
|
+
export declare function recheckIncomingStorage(ctx: FileHandlerContext, path: FilePathWithPrefix, incomingEntry: MetaEntry, incomingContent: IncomingContent | undefined, allowExistingConflicts: boolean): Promise<PreservationResult>;
|
|
29
|
+
export {};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ContentReadError } from "../../common/LSError.js";
|
|
2
2
|
import {
|
|
3
|
+
getProvenancePath,
|
|
3
4
|
readProvenanceSnapshot,
|
|
4
5
|
currentStorageSnapshotMatches,
|
|
5
6
|
classifyStorageContent,
|
|
@@ -10,11 +11,18 @@ import { queueConflictCheckFor } from "./locking.js";
|
|
|
10
11
|
import { isFolderInfo } from "./storage.js";
|
|
11
12
|
import { LOG_LEVEL_NOTICE } from "octagonal-wheels/common/logger";
|
|
12
13
|
import { isDocContentSame } from "../../common/utils.js";
|
|
14
|
+
function hasIncomingContent(content) {
|
|
15
|
+
return content !== void 0;
|
|
16
|
+
}
|
|
13
17
|
async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEntry, incomingContent) {
|
|
14
|
-
const
|
|
18
|
+
const observedPath = existDoc.path;
|
|
19
|
+
const observedProvenance = await readProvenanceSnapshot(ctx, observedPath);
|
|
15
20
|
const readFile = await ctx.host.readFileFromStub(existDoc);
|
|
21
|
+
if (readFile.path !== observedPath) {
|
|
22
|
+
return { preserved: false };
|
|
23
|
+
}
|
|
16
24
|
const snapshot = { file: readFile, revision: observedProvenance };
|
|
17
|
-
if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) {
|
|
25
|
+
if (hasIncomingContent(incomingContent) && await isDocContentSame(incomingContent, readFile.body)) {
|
|
18
26
|
return await currentStorageSnapshotMatches(ctx, readFile, observedProvenance) ? { preserved: false, snapshot } : { preserved: false };
|
|
19
27
|
}
|
|
20
28
|
if (!incomingEntry._rev) {
|
|
@@ -29,7 +37,7 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
|
|
|
29
37
|
incomingEntry,
|
|
30
38
|
void 0,
|
|
31
39
|
observedProvenance,
|
|
32
|
-
incomingContent ? { _rev: incomingEntry._rev, data: incomingContent } : void 0,
|
|
40
|
+
hasIncomingContent(incomingContent) ? { _rev: incomingEntry._rev, data: incomingContent } : void 0,
|
|
33
41
|
false
|
|
34
42
|
);
|
|
35
43
|
} catch (error) {
|
|
@@ -46,7 +54,7 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
|
|
|
46
54
|
return { preserved: false, snapshot };
|
|
47
55
|
}
|
|
48
56
|
if (classification.kind === "matching-leaf") {
|
|
49
|
-
await rememberMatchingLeaf(ctx,
|
|
57
|
+
await rememberMatchingLeaf(ctx, observedPath, classification.revision, readFile.stat.mtime, readFile.body);
|
|
50
58
|
await queueConflictCheckFor(ctx, path);
|
|
51
59
|
return { preserved: true };
|
|
52
60
|
}
|
|
@@ -68,6 +76,18 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
|
|
|
68
76
|
async function recheckIncomingStorage(ctx, path, incomingEntry, incomingContent, allowExistingConflicts) {
|
|
69
77
|
const current = await ctx.host.storage().getStub(path);
|
|
70
78
|
if (!current || isFolderInfo(current)) return { preserved: false };
|
|
79
|
+
if (current.path !== path) {
|
|
80
|
+
const [currentDocumentId, targetDocumentId] = await Promise.all([
|
|
81
|
+
ctx.path.path2id(current.path),
|
|
82
|
+
ctx.path.path2id(path)
|
|
83
|
+
]);
|
|
84
|
+
if (currentDocumentId !== targetDocumentId) {
|
|
85
|
+
return { preserved: false };
|
|
86
|
+
}
|
|
87
|
+
if (hasIncomingContent(incomingContent) && getProvenancePath(ctx, current.path) !== getProvenancePath(ctx, path)) {
|
|
88
|
+
return { preserved: false };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
71
91
|
const protection = await preserveUnsyncedStorageAsConflict(ctx, path, current, incomingEntry, incomingContent);
|
|
72
92
|
if (protection.preserved || !protection.snapshot) return protection;
|
|
73
93
|
if (!allowExistingConflicts && !ctx.setting.currentSettings().writeDocumentsIfConflicted && (await ctx.host.db().readConflictedRevs(path)).length > 0) {
|
|
@@ -50,6 +50,34 @@ export declare function setProvenance(ctx: FileHandlerContext, path: FilePathWit
|
|
|
50
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
51
|
*/
|
|
52
52
|
export declare function deleteProvenance(ctx: FileHandlerContext, path: FilePathWithPrefix): Promise<void>;
|
|
53
|
+
/** Pre-rename provenance snapshot for source and target spellings under the same document lock. */
|
|
54
|
+
export interface RenameProvenanceSnapshot {
|
|
55
|
+
readonly oldPath: FilePathWithPrefix;
|
|
56
|
+
readonly oldKey: FilePathWithPrefix;
|
|
57
|
+
readonly expectedNewKey: FilePathWithPrefix;
|
|
58
|
+
readonly sourceRecord: FileReflectionProvenanceRecord | undefined;
|
|
59
|
+
readonly destinationBefore: FileReflectionProvenanceRecord | undefined;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Capture source and destination provenance strictly before a physical case-only rename.
|
|
63
|
+
*
|
|
64
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
65
|
+
* @param oldPath - The physical path observed before renaming.
|
|
66
|
+
* @param targetPath - The incoming canonical path requested for the rename.
|
|
67
|
+
* @returns The captured snapshot, or undefined when provenance is disabled or keys already match; returns false on a read or pre-rename stale-destination cleanup failure.
|
|
68
|
+
* @remarks When the source has no provenance and a stale record already occupies the destination key, that stale record is removed before mutating storage so a post-rename retry cannot inherit it.
|
|
69
|
+
*/
|
|
70
|
+
export declare function captureRenameProvenance(ctx: FileHandlerContext, oldPath: FilePathWithPrefix, targetPath: FilePathWithPrefix): Promise<RenameProvenanceSnapshot | undefined | false>;
|
|
71
|
+
/**
|
|
72
|
+
* Transfer or reconcile destination provenance after a verified physical case-only rename.
|
|
73
|
+
*
|
|
74
|
+
* @param ctx - The captured services, per-instance state, and dynamic host seams.
|
|
75
|
+
* @param snapshot - The pre-rename source and destination provenance observations.
|
|
76
|
+
* @param newPath - The physical path returned by the storage rename.
|
|
77
|
+
* @returns True if provenance is now consistent with the renamed file; false if an intervening host update or store error prevents safe continuation.
|
|
78
|
+
* @remarks Performs an optimistic check against the pre-rename destination snapshot (read and write are separate operations) to preserve concurrent out-of-lock destination updates. Deletes the old key best-effort only after the new key write succeeds.
|
|
79
|
+
*/
|
|
80
|
+
export declare function commitRenamedProvenance(ctx: FileHandlerContext, snapshot: RenameProvenanceSnapshot, newPath: FilePathWithPrefix): Promise<boolean>;
|
|
53
81
|
/**
|
|
54
82
|
* Find one unambiguous database revision containing the observed storage bytes.
|
|
55
83
|
*
|
|
@@ -64,6 +64,57 @@ async function deleteProvenance(ctx, path) {
|
|
|
64
64
|
ctx.host.log(ex, LOG_LEVEL_VERBOSE);
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
|
+
async function captureRenameProvenance(ctx, oldPath, targetPath) {
|
|
68
|
+
if (!ctx.provenance) return void 0;
|
|
69
|
+
const oldKey = getProvenancePath(ctx, oldPath);
|
|
70
|
+
const expectedNewKey = getProvenancePath(ctx, targetPath);
|
|
71
|
+
if (oldKey === expectedNewKey) return void 0;
|
|
72
|
+
try {
|
|
73
|
+
const sourceRecord = await readProvenanceSnapshot(ctx, oldPath, true);
|
|
74
|
+
let destinationBefore = await readProvenanceSnapshot(ctx, targetPath, true);
|
|
75
|
+
if (!sourceRecord && destinationBefore !== void 0) {
|
|
76
|
+
await ctx.provenance.delete(expectedNewKey);
|
|
77
|
+
destinationBefore = void 0;
|
|
78
|
+
}
|
|
79
|
+
return { oldPath, oldKey, expectedNewKey, sourceRecord, destinationBefore };
|
|
80
|
+
} catch (ex) {
|
|
81
|
+
ctx.host.log(
|
|
82
|
+
`Could not prepare file reflection provenance before renaming ${oldPath} -> ${targetPath}`,
|
|
83
|
+
LOG_LEVEL_VERBOSE
|
|
84
|
+
);
|
|
85
|
+
ctx.host.log(ex, LOG_LEVEL_VERBOSE);
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function commitRenamedProvenance(ctx, snapshot, newPath) {
|
|
90
|
+
if (!ctx.provenance) return true;
|
|
91
|
+
const newKey = getProvenancePath(ctx, newPath);
|
|
92
|
+
if (newKey !== snapshot.expectedNewKey) return false;
|
|
93
|
+
if (snapshot.oldKey === newKey) return true;
|
|
94
|
+
try {
|
|
95
|
+
const destinationAfter = await readProvenanceSnapshot(ctx, newPath, true);
|
|
96
|
+
if (!sameProvenance(destinationAfter, snapshot.destinationBefore)) {
|
|
97
|
+
ctx.host.log(
|
|
98
|
+
`Preserving concurrent file reflection provenance update for ${newPath} after rename from ${snapshot.oldPath}`,
|
|
99
|
+
LOG_LEVEL_VERBOSE
|
|
100
|
+
);
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
if (snapshot.sourceRecord) {
|
|
104
|
+
await ctx.provenance.set(newKey, snapshot.sourceRecord);
|
|
105
|
+
await deleteProvenance(ctx, snapshot.oldPath);
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
return true;
|
|
109
|
+
} catch (ex) {
|
|
110
|
+
ctx.host.log(
|
|
111
|
+
`Could not update file reflection provenance after renaming ${snapshot.oldPath} -> ${newPath}`,
|
|
112
|
+
LOG_LEVEL_VERBOSE
|
|
113
|
+
);
|
|
114
|
+
ctx.host.log(ex, LOG_LEVEL_VERBOSE);
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
67
118
|
async function findUniqueContentRevision(ctx, file) {
|
|
68
119
|
try {
|
|
69
120
|
const revisions = await ctx.host.db().findContentRevisions(file, file.body);
|
|
@@ -188,7 +239,9 @@ async function inspectCurrentFileProvenance(ctx, path, revision) {
|
|
|
188
239
|
});
|
|
189
240
|
}
|
|
190
241
|
export {
|
|
242
|
+
captureRenameProvenance,
|
|
191
243
|
classifyStorageContent,
|
|
244
|
+
commitRenamedProvenance,
|
|
192
245
|
contentEvidence,
|
|
193
246
|
currentStorageSnapshotMatches,
|
|
194
247
|
deleteProvenance,
|
|
@@ -8,7 +8,10 @@ import {
|
|
|
8
8
|
import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
|
|
9
9
|
import { infoToStub, isFolderInfo, getParentPath } from "./storage.js";
|
|
10
10
|
import {
|
|
11
|
+
captureRenameProvenance,
|
|
12
|
+
commitRenamedProvenance,
|
|
11
13
|
deleteProvenance,
|
|
14
|
+
getProvenancePath,
|
|
12
15
|
contentEvidence,
|
|
13
16
|
currentStorageSnapshotMatches,
|
|
14
17
|
sameProvenance,
|
|
@@ -209,6 +212,19 @@ async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force
|
|
|
209
212
|
);
|
|
210
213
|
}
|
|
211
214
|
async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, force, allowExistingConflicts, incomingRetry, operation) {
|
|
215
|
+
if (existDoc.path !== path) {
|
|
216
|
+
const [existingDocumentId, targetDocumentId] = await Promise.all([
|
|
217
|
+
ctx.path.path2id(existDoc.path),
|
|
218
|
+
ctx.path.path2id(path)
|
|
219
|
+
]);
|
|
220
|
+
if (existingDocumentId !== targetDocumentId) {
|
|
221
|
+
ctx.host.log(
|
|
222
|
+
`Refusing to delete ${existDoc.path} while applying deletion for the distinct path ${path}`,
|
|
223
|
+
LOG_LEVEL_NOTICE
|
|
224
|
+
);
|
|
225
|
+
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
226
|
+
}
|
|
227
|
+
}
|
|
212
228
|
let safeDeletionSnapshot;
|
|
213
229
|
if (!force && !settings.writeDocumentsIfConflicted) {
|
|
214
230
|
let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry, void 0);
|
|
@@ -259,11 +275,37 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
|
|
|
259
275
|
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
260
276
|
}
|
|
261
277
|
}
|
|
278
|
+
const observedPath = safeDeletionSnapshot?.file.path ?? existDoc.path;
|
|
279
|
+
if (observedPath !== path) {
|
|
280
|
+
if (safeDeletionSnapshot) {
|
|
281
|
+
if (!sameProvenance(await readProvenanceSnapshot(ctx, observedPath), safeDeletionSnapshot.revision)) {
|
|
282
|
+
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
283
|
+
}
|
|
284
|
+
const resolvedForRead = await ctx.host.storage().getStub(path);
|
|
285
|
+
if (!resolvedForRead || isFolderInfo(resolvedForRead) || resolvedForRead.path !== observedPath) {
|
|
286
|
+
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
287
|
+
}
|
|
288
|
+
const readResolved = await ctx.host.readFileFromStub(resolvedForRead);
|
|
289
|
+
if (readResolved.path !== observedPath || readResolved.stat.mtime !== safeDeletionSnapshot.file.stat.mtime || readResolved.stat.size !== safeDeletionSnapshot.file.stat.size || !await isDocContentSame(readResolved.body, safeDeletionSnapshot.file.body)) {
|
|
290
|
+
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const resolvedTarget = await ctx.host.storage().getStub(path);
|
|
294
|
+
if (!resolvedTarget || isFolderInfo(resolvedTarget) || resolvedTarget.path !== observedPath || safeDeletionSnapshot && (resolvedTarget.stat.mtime !== safeDeletionSnapshot.file.stat.mtime || resolvedTarget.stat.size !== safeDeletionSnapshot.file.stat.size)) {
|
|
295
|
+
throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
|
|
296
|
+
}
|
|
297
|
+
}
|
|
262
298
|
if (operation?.checkpoint?.() === false) {
|
|
263
299
|
return FILE_REFLECTION_CANCELLED;
|
|
264
300
|
}
|
|
265
301
|
await ctx.host.storage().deleteVaultItem(path);
|
|
266
|
-
|
|
302
|
+
const clearedKeys = /* @__PURE__ */ new Set();
|
|
303
|
+
for (const candidate of [observedPath, existDoc.path, path]) {
|
|
304
|
+
const key = getProvenancePath(ctx, candidate);
|
|
305
|
+
if (clearedKeys.has(key)) continue;
|
|
306
|
+
clearedKeys.add(key);
|
|
307
|
+
await deleteProvenance(ctx, candidate);
|
|
308
|
+
}
|
|
267
309
|
return FILE_REFLECTION_COMPLETED;
|
|
268
310
|
}
|
|
269
311
|
async function reconcileStoragePath(ctx, existDoc, path, settings) {
|
|
@@ -291,12 +333,26 @@ async function reconcileStoragePath(ctx, existDoc, path, settings) {
|
|
|
291
333
|
);
|
|
292
334
|
return false;
|
|
293
335
|
}
|
|
336
|
+
const oldPath = existDoc.path;
|
|
337
|
+
const renameProvenance = await captureRenameProvenance(ctx, oldPath, path);
|
|
338
|
+
if (renameProvenance === false) {
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
294
341
|
const renamedFile = await ctx.host.storage().renameFile(existDoc, path);
|
|
295
342
|
if (!renamedFile) {
|
|
296
|
-
ctx.host.log(`Could not apply the stored filename case: ${
|
|
343
|
+
ctx.host.log(`Could not apply the stored filename case: ${oldPath} -> ${path}`, LOG_LEVEL_NOTICE);
|
|
344
|
+
return false;
|
|
345
|
+
}
|
|
346
|
+
if (getProvenancePath(ctx, renamedFile.path) !== getProvenancePath(ctx, path)) {
|
|
347
|
+
ctx.host.log(
|
|
348
|
+
`Could not align renamed filename identity: ${oldPath} -> ${renamedFile.path} (expected ${path})`,
|
|
349
|
+
LOG_LEVEL_NOTICE
|
|
350
|
+
);
|
|
351
|
+
return false;
|
|
352
|
+
}
|
|
353
|
+
if (renameProvenance && !await commitRenamedProvenance(ctx, renameProvenance, renamedFile.path)) {
|
|
297
354
|
return false;
|
|
298
355
|
}
|
|
299
|
-
await deleteProvenance(ctx, existDoc.path);
|
|
300
356
|
existDoc = renamedFile;
|
|
301
357
|
}
|
|
302
358
|
return existDoc;
|
|
@@ -7,12 +7,12 @@ import type { ReplicatorInstance } from "../../replication/ReplicatorInstance.js
|
|
|
7
7
|
import type { SimpleStore } from "octagonal-wheels/databases/SimpleStoreBase";
|
|
8
8
|
import type { Confirm } from "../../interfaces/Confirm.js";
|
|
9
9
|
import type { ReactiveSource } from "octagonal-wheels/dataobject/reactive";
|
|
10
|
-
import type {
|
|
10
|
+
import type { ReplicationStaticsSource } from "./ReplicationStaticsOwner.js";
|
|
11
11
|
import type { ReplicatorService } from "./ReplicatorService.js";
|
|
12
12
|
import type { DatabaseEventService } from "./DatabaseEventService.js";
|
|
13
13
|
import type { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../../common/models/shared.const.symbols.js";
|
|
14
14
|
import type { AsyncActivityOptions } from "../../interfaces/AsyncActivityRunner.js";
|
|
15
|
-
import type { OwnedCouchDBConnection, RemoteConnectionOpenOptions } from "./RemoteConnection.js";
|
|
15
|
+
import type { CouchDBConnectionOpenResult, OwnedCouchDBConnection, RemoteConnectionOpenOptions } from "./RemoteConnection.js";
|
|
16
16
|
import type { ActiveReplicatorContext, ContinuousReplicationRequest, ReplicationAttemptFailure, ReplicationFailureRequest, ReplicatorProviderDefinitionMap, ReplicationOutcome, ReplicationReadinessRequirements, UnattendedOneShotRequest, UserInitiatedOneShotRequest } from "../../replication/ReplicatorProvider.js";
|
|
17
17
|
import type { RemoteResourceKind, RemoteResourceMap } from "../../replication/RemoteResource.js";
|
|
18
18
|
import type { CentralRemoteAdministrationRequest, CentralRemoteAdministrationResult } from "../../replication/CentralRemoteAdministration.js";
|
|
@@ -188,7 +188,7 @@ export interface IReplicatorService {
|
|
|
188
188
|
* `ActiveReplicatorContext` before using a Replicator.
|
|
189
189
|
*/
|
|
190
190
|
hasActiveReplicator(): boolean;
|
|
191
|
-
replicationStatics:
|
|
191
|
+
readonly replicationStatics: ReplicationStaticsSource;
|
|
192
192
|
/** Number of finite remote operations currently in progress. */
|
|
193
193
|
boundedRemoteActivityCount: ReactiveSource<number>;
|
|
194
194
|
/** Number of finite replication operations which can still deliver database documents. */
|
|
@@ -283,6 +283,8 @@ export interface IRemoteService {
|
|
|
283
283
|
* before a connection result can be produced.
|
|
284
284
|
*/
|
|
285
285
|
connect(uri: string, auth: CouchDBCredentials, disableRequestURI: boolean, passphrase: string | false, useDynamicIterationCount: boolean, performSetup: boolean, skipInfo: boolean, compression: boolean, customHeaders: Record<string, string>, useRequestAPI: boolean, getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>, options?: RemoteConnectionOpenOptions): Promise<string | OwnedCouchDBConnection<EntryDoc>>;
|
|
286
|
+
/** Open a remote connection with its original failure available to the caller. */
|
|
287
|
+
openCouchDBConnection?(...args: Parameters<IRemoteService["connect"]>): Promise<CouchDBConnectionOpenResult<EntryDoc>>;
|
|
286
288
|
/**
|
|
287
289
|
* State if the last POST request failed due to payload size.
|
|
288
290
|
*/
|
|
@@ -376,10 +378,11 @@ export interface IVaultService {
|
|
|
376
378
|
getVaultName(): string;
|
|
377
379
|
scanVault(showingNotice?: boolean, ignoreSuspending?: boolean, continueOnFileFailure?: boolean, scanOptions?: VaultScanOptions): Promise<VaultScanResult>;
|
|
378
380
|
isIgnoredByIgnoreFile(file: string | UXFileInfoStub): Promise<boolean>;
|
|
379
|
-
isTargetFile(file: string | UXFileInfoStub,
|
|
380
|
-
|
|
381
|
-
options?: {
|
|
381
|
+
isTargetFile(file: string | UXFileInfoStub, options?: {
|
|
382
|
+
/** Inspect selection policy without treating a filename collision as an exclusion. */
|
|
382
383
|
skipCaseCollisionCheck?: boolean;
|
|
384
|
+
/** Host-admitted internal file event. Preserve vetoes while omitting ordinary-file eligibility. */
|
|
385
|
+
internalFileEvent?: boolean;
|
|
383
386
|
}): Promise<boolean>;
|
|
384
387
|
isTargetFileInExtra(file: string | UXFileInfoStub): Promise<boolean>;
|
|
385
388
|
isFileSizeTooLarge(size: number): boolean;
|
|
@@ -4,8 +4,8 @@ import { ServiceBase, type ServiceContext } from "./ServiceBase.js";
|
|
|
4
4
|
import type { KeyValueDatabase, KeyValueDatabaseFactory } from "../../interfaces/KeyValueDatabase.js";
|
|
5
5
|
import type { InjectableDatabaseEventService } from "../implements/injectable/InjectableDatabaseEventService.js";
|
|
6
6
|
import type { AppLifecycleServiceBase } from "../implements/injectable/InjectableAppLifecycleService.js";
|
|
7
|
-
export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContext> {
|
|
8
|
-
openKeyValueDatabase: KeyValueDatabaseFactory
|
|
7
|
+
export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContext, TDatabase extends KeyValueDatabase = KeyValueDatabase> {
|
|
8
|
+
openKeyValueDatabase: KeyValueDatabaseFactory<TDatabase>;
|
|
9
9
|
databaseEvents: InjectableDatabaseEventService<T>;
|
|
10
10
|
vault: IVaultService;
|
|
11
11
|
appLifecycle: AppLifecycleServiceBase<T>;
|
|
@@ -15,13 +15,13 @@ export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContex
|
|
|
15
15
|
* The KeyValueDBService provides methods for managing the local key-value database.
|
|
16
16
|
* Please note that each event of database lifecycle is handled in DatabaseEventService.
|
|
17
17
|
*/
|
|
18
|
-
export declare abstract class KeyValueDBService<T extends ServiceContext = ServiceContext> extends ServiceBase<T> implements IKeyValueDBService {
|
|
18
|
+
export declare abstract class KeyValueDBService<T extends ServiceContext = ServiceContext, TDatabase extends KeyValueDatabase = KeyValueDatabase> extends ServiceBase<T> implements IKeyValueDBService {
|
|
19
19
|
private _kvDB;
|
|
20
20
|
private databaseKey;
|
|
21
21
|
private readonly lifecycleLock;
|
|
22
22
|
private _simpleStore;
|
|
23
23
|
get simpleStore(): SimpleStore<unknown, any>;
|
|
24
|
-
get kvDB():
|
|
24
|
+
get kvDB(): TDatabase;
|
|
25
25
|
private databaseEvents;
|
|
26
26
|
private vault;
|
|
27
27
|
private appLifecycle;
|
|
@@ -33,7 +33,7 @@ export declare abstract class KeyValueDBService<T extends ServiceContext = Servi
|
|
|
33
33
|
private openSelectedDatabase;
|
|
34
34
|
private openKeyValueDB;
|
|
35
35
|
private _everyOnloadAfterLoadSettings;
|
|
36
|
-
constructor(context: T, dependencies: KeyValueDBDependencies<T>);
|
|
36
|
+
constructor(context: T, dependencies: KeyValueDBDependencies<T, TDatabase>);
|
|
37
37
|
/**
|
|
38
38
|
* Create an inert namespaced handle over the service's current database.
|
|
39
39
|
* @param kind - Namespace identifier; stored keys receive this identifier and a trailing hyphen.
|
|
@@ -48,6 +48,6 @@ export declare abstract class KeyValueDBService<T extends ServiceContext = Servi
|
|
|
48
48
|
set: (key: string, value: unknown) => Promise<void>;
|
|
49
49
|
delete: (key: string) => Promise<void>;
|
|
50
50
|
keys: (from: string | undefined, to: string | undefined, count?: number) => Promise<string[]>;
|
|
51
|
-
readonly db: Promise<
|
|
51
|
+
readonly db: Promise<Awaited<TDatabase>>;
|
|
52
52
|
};
|
|
53
53
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** One ordered condition in a readiness evaluation. */
|
|
2
|
-
export interface ReadinessCondition<TContext> {
|
|
2
|
+
export interface ReadinessCondition<TContext, TRejection extends object = never> {
|
|
3
3
|
/** Stable diagnostic name for the condition; it is not user-facing text. */
|
|
4
4
|
readonly name: string;
|
|
5
5
|
/**
|
|
@@ -10,25 +10,26 @@ export interface ReadinessCondition<TContext> {
|
|
|
10
10
|
*/
|
|
11
11
|
readonly appliesTo?: (context: TContext) => boolean;
|
|
12
12
|
/** Return whether the condition admits the requested operation. */
|
|
13
|
-
readonly evaluate: (context: TContext) => boolean | Promise<boolean>;
|
|
13
|
+
readonly evaluate: (context: TContext) => boolean | TRejection | Promise<boolean | TRejection>;
|
|
14
14
|
/** Perform condition-specific reporting after a false result. */
|
|
15
15
|
readonly onRejected?: (context: TContext) => void | Promise<void>;
|
|
16
16
|
}
|
|
17
17
|
/** A purpose and its ordered readiness conditions. */
|
|
18
|
-
export interface ReadinessEvaluationRequest<TContext> {
|
|
18
|
+
export interface ReadinessEvaluationRequest<TContext, TRejection extends object = never> {
|
|
19
19
|
/** Stable diagnostic purpose; it is not user-facing text. */
|
|
20
20
|
readonly purpose: string;
|
|
21
21
|
readonly context: TContext;
|
|
22
|
-
readonly conditions: readonly ReadinessCondition<TContext>[];
|
|
22
|
+
readonly conditions: readonly ReadinessCondition<TContext, TRejection>[];
|
|
23
23
|
}
|
|
24
24
|
/** Structured result from an ordered readiness evaluation. */
|
|
25
|
-
export type ReadinessEvaluationResult = {
|
|
25
|
+
export type ReadinessEvaluationResult<TRejection extends object = never> = {
|
|
26
26
|
readonly ready: true;
|
|
27
27
|
readonly purpose: string;
|
|
28
28
|
} | {
|
|
29
29
|
readonly ready: false;
|
|
30
30
|
readonly purpose: string;
|
|
31
31
|
readonly rejectedCondition: string;
|
|
32
|
+
readonly rejection?: TRejection;
|
|
32
33
|
};
|
|
33
34
|
/**
|
|
34
35
|
* Evaluate applicable conditions in declaration order until one rejects.
|
|
@@ -37,4 +38,4 @@ export type ReadinessEvaluationResult = {
|
|
|
37
38
|
* from applicability, evaluation, or reporting callbacks propagate unchanged;
|
|
38
39
|
* the evaluator does not reinterpret operational failures as policy results.
|
|
39
40
|
*/
|
|
40
|
-
export declare function evaluateReadiness<TContext>(request: ReadinessEvaluationRequest<TContext>): Promise<ReadinessEvaluationResult
|
|
41
|
+
export declare function evaluateReadiness<TContext, TRejection extends object = never>(request: ReadinessEvaluationRequest<TContext, TRejection>): Promise<ReadinessEvaluationResult<TRejection>>;
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
async function evaluateReadiness(request) {
|
|
2
2
|
for (const condition of request.conditions) {
|
|
3
3
|
if (condition.appliesTo && !condition.appliesTo(request.context)) continue;
|
|
4
|
-
|
|
4
|
+
const decision = await condition.evaluate(request.context);
|
|
5
|
+
if (decision === true) continue;
|
|
5
6
|
await condition.onRejected?.(request.context);
|
|
6
7
|
return {
|
|
7
8
|
ready: false,
|
|
8
9
|
purpose: request.purpose,
|
|
9
|
-
rejectedCondition: condition.name
|
|
10
|
+
rejectedCondition: condition.name,
|
|
11
|
+
...decision !== false && { rejection: decision }
|
|
10
12
|
};
|
|
11
13
|
}
|
|
12
14
|
return { ready: true, purpose: request.purpose };
|
|
@@ -51,3 +51,7 @@ export interface OwnedCouchDBConnection<T extends object> {
|
|
|
51
51
|
/** Cancels scoped requests and closes the PouchDB handle exactly once. */
|
|
52
52
|
close(): Promise<void>;
|
|
53
53
|
}
|
|
54
|
+
/** The connection attempt preserves its refusal or opening error until the caller handles it. */
|
|
55
|
+
export type CouchDBConnectionOpenResult<T extends object> = OwnedCouchDBConnection<T> | {
|
|
56
|
+
readonly error: Error;
|
|
57
|
+
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type EntryDoc } from "../../common/types.js";
|
|
2
2
|
import type { IRemoteService } from "./IService.js";
|
|
3
3
|
import { ServiceBase, type ServiceContext } from "./ServiceBase.js";
|
|
4
4
|
import { type LOG_LEVEL } from "../../common/types.js";
|
|
@@ -9,7 +9,7 @@ import type { SettingService } from "./SettingService.js";
|
|
|
9
9
|
import { UnresolvedErrorManager } from "./UnresolvedErrorManager.js";
|
|
10
10
|
import { type LogFunction } from "../lib/logUtils.js";
|
|
11
11
|
import type { PouchDBConstructor } from "../../pouchdb/PouchDBConstructor.js";
|
|
12
|
-
import type {
|
|
12
|
+
import type { CouchDBConnectionOpenResult, OwnedCouchDBConnection } from "./RemoteConnection.js";
|
|
13
13
|
export interface RemoteServiceDependencies {
|
|
14
14
|
/** PouchDB with the HTTP adapter required by the host runtime already registered. */
|
|
15
15
|
pouchDB: PouchDBConstructor;
|
|
@@ -60,6 +60,8 @@ export declare abstract class RemoteService<T extends ServiceContext = ServiceCo
|
|
|
60
60
|
* @returns An error description, or the owned connection. The caller must
|
|
61
61
|
* transfer ownership or call `close()`.
|
|
62
62
|
*/
|
|
63
|
-
connect(
|
|
63
|
+
connect(...args: Parameters<IRemoteService["connect"]>): Promise<string | OwnedCouchDBConnection<EntryDoc>>;
|
|
64
|
+
openCouchDBConnection(...args: Parameters<IRemoteService["connect"]>): Promise<CouchDBConnectionOpenResult<EntryDoc>>;
|
|
65
|
+
private openConnection;
|
|
64
66
|
}
|
|
65
67
|
export {};
|