@vrtmrz/livesync-commonlib 0.4.1 → 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/interfaces/FileHandler.d.ts +59 -0
- package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
- package/dist/interfaces/FileReflectionProvenance.js +11 -1
- 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/deletionRecovery.d.ts +13 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
- package/dist/serviceModules/ServiceFileHandlerBase.d.ts +22 -1
- package/dist/serviceModules/ServiceFileHandlerBase.js +29 -0
- package/dist/services/base/KeyValueDBService.d.ts +9 -0
- package/dist/services/base/KeyValueDBService.js +11 -1
- package/docs/development.md +4 -0
- package/docs/offline-scanner.md +21 -0
- package/docs/storage-events-and-reflection.md +16 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,8 +14,11 @@ This package is primarily for maintainers of those clients and for integrations
|
|
|
14
14
|
|
|
15
15
|
## Status and versioning
|
|
16
16
|
|
|
17
|
-
Commonlib [0.
|
|
18
|
-
is published on npm
|
|
17
|
+
Commonlib [0.4.1](https://www.npmjs.com/package/@vrtmrz/livesync-commonlib/v/0.4.1)
|
|
18
|
+
is published on npm through `latest` and `next`
|
|
19
|
+
([release notes](https://github.com/vrtmrz/livesync-commonlib/releases/tag/0.4.1)).
|
|
20
|
+
|
|
21
|
+
Self-hosted LiveSync
|
|
19
22
|
[1.0.44](https://github.com/vrtmrz/obsidian-livesync/releases/tag/1.0.44)
|
|
20
23
|
uses Commonlib 0.2.3. The [0.2.3 release notes](updates.md#023) record its
|
|
21
24
|
handler-setter source compatibility change and positive-infinity formatting
|
|
@@ -269,6 +272,15 @@ standardIo.writeStdout("ready\n");
|
|
|
269
272
|
|
|
270
273
|
See [the standard-I/O contract](docs/platform-standard-io.md) for host composition and test-double examples.
|
|
271
274
|
|
|
275
|
+
## Ordinary deletion recovery (unreleased)
|
|
276
|
+
|
|
277
|
+
Hosts using the ordinary file handler can opt in to recovery of retained logical
|
|
278
|
+
deletions by supplying provenance key enumeration. Recovery preserves edited or
|
|
279
|
+
unproven files, uses existing Chunk delivery policy, and reports physical removal
|
|
280
|
+
and interrupted bookkeeping separately. Hosts which do not opt in retain their
|
|
281
|
+
existing scanner policy. See [the recovery contract](docs/deletion-recovery.md)
|
|
282
|
+
for capability composition, concurrency, runtime costs, and verification limits.
|
|
283
|
+
|
|
272
284
|
## Settings lifecycle
|
|
273
285
|
|
|
274
286
|
New-Vault recommendations are deliberately separate from the conservative values used to complete older stored settings. The focused settings entry also reports migrations and safety-review requirements without changing a user's synchronisation choices or persisting a device-local acknowledgement.
|
|
@@ -4,6 +4,45 @@ export interface StoreFileOptions {
|
|
|
4
4
|
/** Recheck storage and provenance, with bounded retries for recovery scans. */
|
|
5
5
|
revalidateStorage?: boolean;
|
|
6
6
|
}
|
|
7
|
+
/** Diagnostic context shared by each observed deletion-recovery outcome. */
|
|
8
|
+
interface DeletionRecoveryDiagnostics {
|
|
9
|
+
reason: string;
|
|
10
|
+
phase?: string;
|
|
11
|
+
warning?: string;
|
|
12
|
+
error?: unknown;
|
|
13
|
+
}
|
|
14
|
+
/** No provenance was cleared; edits and unknown content remain protected. */
|
|
15
|
+
export interface DeletionRecoveryUnchangedResult extends DeletionRecoveryDiagnostics {
|
|
16
|
+
status: "deferred" | "failed";
|
|
17
|
+
file: "present" | "absent" | "unknown";
|
|
18
|
+
provenance: "unchanged";
|
|
19
|
+
}
|
|
20
|
+
/** Absence was observed, but remaining bookkeeping must be rediscovered on a later scan. */
|
|
21
|
+
export interface DeletionRecoveryCleanupPendingResult extends DeletionRecoveryDiagnostics {
|
|
22
|
+
status: "deferred" | "failed";
|
|
23
|
+
file: "absent";
|
|
24
|
+
provenance: "pending";
|
|
25
|
+
}
|
|
26
|
+
/** Removal was attempted, but its effect could not be read; retain evidence until the next observation. */
|
|
27
|
+
export interface DeletionRecoveryRemovalUnconfirmedResult extends DeletionRecoveryDiagnostics {
|
|
28
|
+
status: "failed";
|
|
29
|
+
file: "unknown";
|
|
30
|
+
provenance: "pending";
|
|
31
|
+
}
|
|
32
|
+
/** Both effects were confirmed; a subsequent lock or permit failure can still fail the operation. */
|
|
33
|
+
export interface DeletionRecoveryClearedResult extends DeletionRecoveryDiagnostics {
|
|
34
|
+
status: "applied" | "failed";
|
|
35
|
+
file: "absent";
|
|
36
|
+
provenance: "cleared";
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Coherent observed effects of one guarded deletion-recovery attempt.
|
|
40
|
+
* @remarks The `applied` status requires observed absence and cleared provenance.
|
|
41
|
+
* Unchanged refers to provenance operations, not proof that a file still exists.
|
|
42
|
+
* Pending and unconfirmed effects retain retry evidence. A deferred protected
|
|
43
|
+
* file may require user reconciliation; automatic convergence is not guaranteed.
|
|
44
|
+
*/
|
|
45
|
+
export type DeletionRecoveryResult = DeletionRecoveryUnchangedResult | DeletionRecoveryCleanupPendingResult | DeletionRecoveryRemovalUnconfirmedResult | DeletionRecoveryClearedResult;
|
|
7
46
|
export interface IFileHandler {
|
|
8
47
|
readFileFromStub(file: UXFileInfoStub | UXFileInfo): Promise<UXFileInfo>;
|
|
9
48
|
/**
|
|
@@ -14,6 +53,25 @@ export interface IFileHandler {
|
|
|
14
53
|
tryRecordUntrackedFileRevision(info: UXFileInfoStub | UXFileInfo, expectedRevision: string): Promise<boolean>;
|
|
15
54
|
/** Metadata-only scan hint; never certifies content equality or changes provenance. */
|
|
16
55
|
canSkipUnchangedFile?(info: UXFileInfoStub, expected: MetaEntry): Promise<boolean>;
|
|
56
|
+
/**
|
|
57
|
+
* Report whether complete provenance-key discovery is configured.
|
|
58
|
+
* @returns A composition capability, rather than a store-readiness or health check.
|
|
59
|
+
*/
|
|
60
|
+
supportsDeletionRecovery?(): boolean;
|
|
61
|
+
/**
|
|
62
|
+
* Enumerate existing provenance paths without loading record values or bodies.
|
|
63
|
+
* @returns Complete namespaced keys; unsupported or unavailable stores may reject.
|
|
64
|
+
*/
|
|
65
|
+
listDeletionRecoveryPaths?(): Promise<FilePathWithPrefix[]>;
|
|
66
|
+
/**
|
|
67
|
+
* Recover one exact retained deletion without adding revision history.
|
|
68
|
+
* @param expected - The selected logical deletion whose identity and revision must remain current.
|
|
69
|
+
* @param cleanupOnly - Permit bookkeeping for an absent file only; never remove a present file.
|
|
70
|
+
* @returns Observed effects and completion status, including conservative deferral or failure.
|
|
71
|
+
* @remarks A failed result can retain confirmed absence or completed cleanup.
|
|
72
|
+
* Callers must use those effects when preserving retry evidence.
|
|
73
|
+
*/
|
|
74
|
+
recoverDatabaseDeletion?(expected: MetaEntry, cleanupOnly?: boolean): Promise<DeletionRecoveryResult>;
|
|
17
75
|
storeFileToDB(info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean, options?: StoreFileOptions): Promise<boolean>;
|
|
18
76
|
/**
|
|
19
77
|
* Store the current storage content as a child of an exact live database revision.
|
|
@@ -39,3 +97,4 @@ export interface IFileHandler {
|
|
|
39
97
|
dbToStorage(entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean): Promise<boolean>;
|
|
40
98
|
createAllChunks(showingNotice?: boolean): Promise<void>;
|
|
41
99
|
}
|
|
100
|
+
export {};
|
|
@@ -15,6 +15,12 @@ export interface FileReflectionProvenance {
|
|
|
15
15
|
set(path: FilePathWithPrefix, record: FileReflectionProvenanceRecord): Promise<void>;
|
|
16
16
|
delete(path: FilePathWithPrefix): Promise<void>;
|
|
17
17
|
move(from: FilePathWithPrefix, to: FilePathWithPrefix): Promise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* Enumerate the complete provenance namespace without reading record values.
|
|
20
|
+
* @returns Existing paths; backing-store failures reject the promise.
|
|
21
|
+
* @remarks Absence of this optional method means that enumeration is unsupported.
|
|
22
|
+
*/
|
|
23
|
+
listPaths?: () => Promise<FilePathWithPrefix[]>;
|
|
18
24
|
}
|
|
19
25
|
/**
|
|
20
26
|
* Device-local provenance backed by an existing host-owned key-value store.
|
|
@@ -28,7 +34,15 @@ export interface FileReflectionProvenance {
|
|
|
28
34
|
*/
|
|
29
35
|
export declare class StoredFileReflectionProvenance implements FileReflectionProvenance {
|
|
30
36
|
private readonly store;
|
|
31
|
-
|
|
37
|
+
listPaths?: () => Promise<FilePathWithPrefix[]>;
|
|
38
|
+
/**
|
|
39
|
+
* Create a provenance view without opening or reading its backing store.
|
|
40
|
+
* @param store - The host-owned, namespaced store used by later operations.
|
|
41
|
+
* @param enableEnumeration - Advertise keys-only enumeration when true; defaults to false.
|
|
42
|
+
* @remarks Registering the optional capability performs no I/O. The host must
|
|
43
|
+
* complete its normal store lifecycle before invoking any provenance operation.
|
|
44
|
+
*/
|
|
45
|
+
constructor(store: SimpleStore<FileReflectionProvenanceRecord>, enableEnumeration?: boolean);
|
|
32
46
|
get(path: FilePathWithPrefix): Promise<FileReflectionProvenanceRecord | undefined>;
|
|
33
47
|
set(path: FilePathWithPrefix, record: FileReflectionProvenanceRecord): Promise<void>;
|
|
34
48
|
delete(path: FilePathWithPrefix): Promise<void>;
|
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
class StoredFileReflectionProvenance {
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Create a provenance view without opening or reading its backing store.
|
|
4
|
+
* @param store - The host-owned, namespaced store used by later operations.
|
|
5
|
+
* @param enableEnumeration - Advertise keys-only enumeration when true; defaults to false.
|
|
6
|
+
* @remarks Registering the optional capability performs no I/O. The host must
|
|
7
|
+
* complete its normal store lifecycle before invoking any provenance operation.
|
|
8
|
+
*/
|
|
9
|
+
constructor(store, enableEnumeration = false) {
|
|
3
10
|
this.store = store;
|
|
11
|
+
if (enableEnumeration) {
|
|
12
|
+
this.listPaths = async () => (await this.store.keys(void 0, void 0)).map((path) => path);
|
|
13
|
+
}
|
|
4
14
|
}
|
|
5
15
|
store;
|
|
6
16
|
async get(path) {
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { FilePathWithPrefix } from "../../common/types.js";
|
|
2
|
+
import type { NecessaryServices } from "../../interfaces/ServiceModule.js";
|
|
3
|
+
type FileStatusState = {
|
|
4
|
+
map: Map<string, number>;
|
|
5
|
+
timeout: number | null;
|
|
6
|
+
loaded: boolean;
|
|
7
|
+
scanLock: symbol;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Borrow the in-memory observations and scan lock for one backing store.
|
|
11
|
+
* @param host - Owner of the active key-value database.
|
|
12
|
+
* @returns Shared process-local state; no database operation is performed.
|
|
13
|
+
*/
|
|
14
|
+
export declare function fileStatus(host: NecessaryServices<"keyValueDB", never>): FileStatusState;
|
|
15
|
+
/**
|
|
16
|
+
* Drain an earlier scheduled write before reloading durable observations.
|
|
17
|
+
* @param host - Owner of the active key-value database.
|
|
18
|
+
* @returns After the map has been loaded under the persistence lock.
|
|
19
|
+
* @throws If a required backing-store read or preceding write fails.
|
|
20
|
+
*/
|
|
21
|
+
export declare function loadFileStatus(host: NecessaryServices<"keyValueDB", never>): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Cancel the scheduled callback and await an ordered last-seen write.
|
|
24
|
+
* @param host - Owner of the map and backing store.
|
|
25
|
+
* @returns After the store write settles successfully.
|
|
26
|
+
* @throws If persistence fails; physical file effects are not rolled back.
|
|
27
|
+
*/
|
|
28
|
+
export declare function flushFileStatus(host: NecessaryServices<"keyValueDB", never>): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Remove a stale presence record before Metadata identity repair publishes its target.
|
|
31
|
+
* @param host - Borrowed settings and key-value storage capabilities.
|
|
32
|
+
* @param path - Logical path whose comparison key must be forgotten.
|
|
33
|
+
* @returns After loading any missing map state and persisting the removal.
|
|
34
|
+
* @remarks Retaining this record could turn the repaired database-only target
|
|
35
|
+
* into an apparent later local deletion. No Vault file or Metadata is modified.
|
|
36
|
+
* @throws If loading or persisting the last-seen map fails.
|
|
37
|
+
*/
|
|
38
|
+
export declare function clearOfflineScannerLastSeen(host: NecessaryServices<"setting" | "keyValueDB", never>, path: FilePathWithPrefix): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Schedule one coalesced map write without awaiting persistence.
|
|
41
|
+
* @param host - Owner of the observations to save.
|
|
42
|
+
* @param immediate - Replace pending work with a zero-delay callback when true.
|
|
43
|
+
* @remarks Ordinary updates keep the first pending deadline; this is not a
|
|
44
|
+
* debounce. Use flushFileStatus when completion depends on the ordered write.
|
|
45
|
+
*/
|
|
46
|
+
export declare function saveFileStatus(host: NecessaryServices<"keyValueDB", never>, immediate?: boolean): void;
|
|
47
|
+
/**
|
|
48
|
+
* Remember a raw observed mtime and request a coalesced save.
|
|
49
|
+
* @param host - Owner of the last-seen state.
|
|
50
|
+
* @param key - Already-normalised comparison key.
|
|
51
|
+
* @param mtime - Observed storage timestamp, which does not prove unchanged bytes.
|
|
52
|
+
*/
|
|
53
|
+
export declare function updateFileMTimeInMap(host: NecessaryServices<"keyValueDB", never>, key: string, mtime: number): void;
|
|
54
|
+
/**
|
|
55
|
+
* Read the current in-memory last-seen observation without storage access.
|
|
56
|
+
* @param host - Owner of the loaded map.
|
|
57
|
+
* @param key - Already-normalised comparison key.
|
|
58
|
+
* @returns The remembered timestamp, or undefined when no observation exists.
|
|
59
|
+
*/
|
|
60
|
+
export declare function getFileMTimeFromMap(host: NecessaryServices<"keyValueDB", never>, key: string): number | undefined;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { withLock } from "octagonal-wheels/concurrency/lock.scoped";
|
|
2
|
+
import { compatGlobal } from "../../common/coreEnvFunctions.js";
|
|
3
|
+
import { convertCase } from "./paths.js";
|
|
4
|
+
const fileStatuses = /* @__PURE__ */ new WeakMap();
|
|
5
|
+
const FILE_STATUS_MAP_KEY = "fileStatusMap";
|
|
6
|
+
const FILE_STATUS_MAP_LOCK = "offlineScanner-fileStatusMap";
|
|
7
|
+
function fileStatus(host) {
|
|
8
|
+
const owner = host.services.keyValueDB.kvDB ?? host.services.keyValueDB;
|
|
9
|
+
let state = fileStatuses.get(owner);
|
|
10
|
+
if (!state) {
|
|
11
|
+
state = { map: /* @__PURE__ */ new Map(), timeout: null, loaded: false, scanLock: /* @__PURE__ */ Symbol("offlineScanner-scan") };
|
|
12
|
+
fileStatuses.set(owner, state);
|
|
13
|
+
}
|
|
14
|
+
return state;
|
|
15
|
+
}
|
|
16
|
+
async function loadFileStatus(host) {
|
|
17
|
+
if (fileStatus(host).timeout !== null) await flushFileStatus(host);
|
|
18
|
+
await withLock(FILE_STATUS_MAP_LOCK, async () => {
|
|
19
|
+
const state = fileStatus(host);
|
|
20
|
+
const kvDB = host.services.keyValueDB.kvDB;
|
|
21
|
+
const items = kvDB?.get ? await kvDB.get(FILE_STATUS_MAP_KEY) : void 0;
|
|
22
|
+
state.map = new Map(Object.entries(items ?? {}));
|
|
23
|
+
state.loaded = true;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
async function _saveFileStatus(host) {
|
|
27
|
+
await withLock(FILE_STATUS_MAP_LOCK, async () => {
|
|
28
|
+
const kvDB = host.services.keyValueDB.kvDB;
|
|
29
|
+
if (kvDB?.set) await kvDB.set(FILE_STATUS_MAP_KEY, Object.fromEntries(fileStatus(host).map));
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
async function flushFileStatus(host) {
|
|
33
|
+
const state = fileStatus(host);
|
|
34
|
+
if (state.timeout !== null) compatGlobal.clearTimeout(state.timeout);
|
|
35
|
+
state.timeout = null;
|
|
36
|
+
await _saveFileStatus(host);
|
|
37
|
+
}
|
|
38
|
+
async function clearOfflineScannerLastSeen(host, path) {
|
|
39
|
+
const key = convertCase(host.services.setting.currentSettings(), path);
|
|
40
|
+
const state = fileStatus(host);
|
|
41
|
+
if (state.timeout !== null) compatGlobal.clearTimeout(state.timeout);
|
|
42
|
+
state.timeout = null;
|
|
43
|
+
await withLock(FILE_STATUS_MAP_LOCK, async () => {
|
|
44
|
+
const kvDB = host.services.keyValueDB.kvDB;
|
|
45
|
+
if (!state.loaded) {
|
|
46
|
+
const persisted = kvDB?.get ? await kvDB.get(FILE_STATUS_MAP_KEY) : void 0;
|
|
47
|
+
state.map = new Map(Object.entries(persisted ?? {}));
|
|
48
|
+
state.loaded = true;
|
|
49
|
+
}
|
|
50
|
+
state.map.delete(key);
|
|
51
|
+
if (kvDB?.set) await kvDB.set(FILE_STATUS_MAP_KEY, Object.fromEntries(state.map));
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function saveFileStatus(host, immediate = false) {
|
|
55
|
+
const state = fileStatus(host);
|
|
56
|
+
if (immediate && state.timeout !== null) {
|
|
57
|
+
compatGlobal.clearTimeout(state.timeout);
|
|
58
|
+
state.timeout = null;
|
|
59
|
+
}
|
|
60
|
+
if (state.timeout === null) {
|
|
61
|
+
state.timeout = compatGlobal.setTimeout(
|
|
62
|
+
() => {
|
|
63
|
+
state.timeout = null;
|
|
64
|
+
void _saveFileStatus(host);
|
|
65
|
+
},
|
|
66
|
+
immediate ? 0 : 1e3
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function updateFileMTimeInMap(host, key, mtime) {
|
|
71
|
+
fileStatus(host).map.set(key, mtime);
|
|
72
|
+
saveFileStatus(host);
|
|
73
|
+
}
|
|
74
|
+
function getFileMTimeFromMap(host, key) {
|
|
75
|
+
return fileStatus(host).map.get(key);
|
|
76
|
+
}
|
|
77
|
+
export {
|
|
78
|
+
clearOfflineScannerLastSeen,
|
|
79
|
+
fileStatus,
|
|
80
|
+
flushFileStatus,
|
|
81
|
+
getFileMTimeFromMap,
|
|
82
|
+
loadFileStatus,
|
|
83
|
+
saveFileStatus,
|
|
84
|
+
updateFileMTimeInMap
|
|
85
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type MetaEntry, type UXFileInfoStub, type ObsidianLiveSyncSettings, type FilePathWithPrefix, type FilePathWithPrefixLC, type LOG_LEVEL } from "../../common/types.js";
|
|
2
|
+
import type { NecessaryServices } from "../../interfaces/ServiceModule.js";
|
|
3
|
+
import type { LogFunction } from "../../services/lib/logUtils.js";
|
|
4
|
+
import type { VaultScanOptions } from "../../services/base/VaultScanResult.js";
|
|
5
|
+
import { type FilePairProcessResult } from "./types.js";
|
|
6
|
+
/**
|
|
7
|
+
* Synchronise a single file between database and storage based on freshness comparison.
|
|
8
|
+
* @param host Services container
|
|
9
|
+
* @param log Logging function
|
|
10
|
+
* @param file Storage file information
|
|
11
|
+
* @param doc Database entry
|
|
12
|
+
*/
|
|
13
|
+
export declare function syncFileBetweenDBandStorage(host: NecessaryServices<"setting" | "vault" | "path", "storageAccess" | "fileHandler">, log: LogFunction, file: UXFileInfoStub, doc: MetaEntry, scanOptions?: VaultScanOptions): Promise<FilePairProcessResult>;
|
|
14
|
+
/**
|
|
15
|
+
* Collect selected storage stubs for later policy and content checks.
|
|
16
|
+
* @param host - Borrowed Vault-selection and storage-listing capabilities.
|
|
17
|
+
* @param settings - Comparison-key normalisation settings.
|
|
18
|
+
* @param log - Collection diagnostics.
|
|
19
|
+
* @returns Path and comparison-key lookups of selected storage observations.
|
|
20
|
+
* @remarks Content acquisition remains with the later file-handler operations.
|
|
21
|
+
*/
|
|
22
|
+
export declare function collectFilesOnStorage(host: NecessaryServices<"vault", "storageAccess">, settings: ObsidianLiveSyncSettings, log: LogFunction): Promise<{
|
|
23
|
+
storageFileNameMap: {
|
|
24
|
+
[k: string]: UXFileInfoStub;
|
|
25
|
+
};
|
|
26
|
+
storageFileNames: FilePathWithPrefix[];
|
|
27
|
+
storageFileNameCI2CS: Record<FilePathWithPrefixLC, FilePathWithPrefix>;
|
|
28
|
+
}>;
|
|
29
|
+
/**
|
|
30
|
+
* Collect selected Metadata while quarantining unresolved document identities.
|
|
31
|
+
* @param host - Borrowed database, Vault-selection, and path capabilities.
|
|
32
|
+
* @param settings - Comparison-key normalisation settings.
|
|
33
|
+
* @param log - Collection diagnostics.
|
|
34
|
+
* @param showingNotice - Whether progress is reported as a visible notice.
|
|
35
|
+
* @returns Metadata lookups and comparison keys which ordinary scans must quarantine.
|
|
36
|
+
* @remarks Conflicts are retained for later policy checks. This collection does
|
|
37
|
+
* not repair identities, write revisions, or fetch file bodies.
|
|
38
|
+
*/
|
|
39
|
+
export declare function collectDatabaseFiles(host: NecessaryServices<"database" | "vault" | "path", never>, settings: ObsidianLiveSyncSettings, log: LogFunction, showingNotice: boolean): Promise<{
|
|
40
|
+
databaseFileNameMap: Record<FilePathWithPrefix, MetaEntry>;
|
|
41
|
+
databaseFileNames: FilePathWithPrefix[];
|
|
42
|
+
databaseFileNameCI2CS: Record<FilePathWithPrefixLC, FilePathWithPrefix>;
|
|
43
|
+
quarantinedFileNamesLC: Set<FilePathWithPrefixLC>;
|
|
44
|
+
}>;
|
|
45
|
+
export declare function updateToDatabase(host: NecessaryServices<"vault", "fileHandler">, log: LogFunction, logLevel: LOG_LEVEL, file: UXFileInfoStub): Promise<FilePairProcessResult>;
|
|
46
|
+
export declare function updateToStorage(host: NecessaryServices<"vault" | "path", "fileHandler">, log: LogFunction, logLevel: LOG_LEVEL, w: MetaEntry): Promise<FilePairProcessResult>;
|
|
47
|
+
export declare function syncStorageAndDatabase(host: NecessaryServices<"setting" | "vault" | "path", "storageAccess" | "fileHandler">, log: LogFunction, file: UXFileInfoStub, logLevel: LOG_LEVEL, doc: MetaEntry, scanOptions?: VaultScanOptions): Promise<FilePairProcessResult>;
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import {
|
|
2
|
+
LOG_LEVEL_DEBUG,
|
|
3
|
+
LOG_LEVEL_INFO,
|
|
4
|
+
LOG_LEVEL_NOTICE,
|
|
5
|
+
LOG_LEVEL_VERBOSE,
|
|
6
|
+
isMetaEntry
|
|
7
|
+
} from "../../common/types.js";
|
|
8
|
+
import { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../../common/models/shared.const.symbols.js";
|
|
9
|
+
import { shouldBeIgnored, stripAllPrefixes } from "../../string_and_binary/path.js";
|
|
10
|
+
import { inspectMetadataDocumentIdentity } from "./metadata.js";
|
|
11
|
+
import { getPathFromEntry, convertCase } from "./paths.js";
|
|
12
|
+
import { FilePairProcessResults, MetadataDocumentIdentityStatuses } from "./types.js";
|
|
13
|
+
async function syncFileBetweenDBandStorage(host, log, file, doc, scanOptions) {
|
|
14
|
+
const docPath = getPathFromEntry(host, doc);
|
|
15
|
+
if (!doc) {
|
|
16
|
+
throw new Error(`Missing doc:${docPath}`);
|
|
17
|
+
}
|
|
18
|
+
const compareResult = host.services.path.compareFileFreshness(file, doc);
|
|
19
|
+
switch (compareResult) {
|
|
20
|
+
case BASE_IS_NEW:
|
|
21
|
+
if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
|
|
22
|
+
log("STORAGE -> DB :" + file.path);
|
|
23
|
+
return await host.serviceModules.fileHandler.storeFileToDB(file) ? FilePairProcessResults.COMPLETED : FilePairProcessResults.FAILED;
|
|
24
|
+
} else {
|
|
25
|
+
log(
|
|
26
|
+
`STORAGE -> DB : ${file.path} has been skipped due to file size exceeding the limit`,
|
|
27
|
+
LOG_LEVEL_NOTICE
|
|
28
|
+
);
|
|
29
|
+
return FilePairProcessResults.SKIPPED;
|
|
30
|
+
}
|
|
31
|
+
case TARGET_IS_NEW:
|
|
32
|
+
if (!host.services.vault.isFileSizeTooLarge(doc.size)) {
|
|
33
|
+
log("STORAGE <- DB :" + docPath);
|
|
34
|
+
if (await host.serviceModules.fileHandler.dbToStorage(doc, stripAllPrefixes(docPath), false)) {
|
|
35
|
+
host.services.context.events.emitEvent("event-file-changed", {
|
|
36
|
+
file: file.path,
|
|
37
|
+
automated: true
|
|
38
|
+
});
|
|
39
|
+
return FilePairProcessResults.COMPLETED;
|
|
40
|
+
} else {
|
|
41
|
+
log(`STORAGE <- DB : Cloud not read ${file.path}, possibly deleted`, LOG_LEVEL_NOTICE);
|
|
42
|
+
return FilePairProcessResults.FAILED;
|
|
43
|
+
}
|
|
44
|
+
} else {
|
|
45
|
+
log(
|
|
46
|
+
`STORAGE <- DB : ${file.path} has been skipped due to file size exceeding the limit`,
|
|
47
|
+
LOG_LEVEL_NOTICE
|
|
48
|
+
);
|
|
49
|
+
return FilePairProcessResults.SKIPPED;
|
|
50
|
+
}
|
|
51
|
+
case EVEN:
|
|
52
|
+
if (host.services.vault.isFileSizeTooLarge(file.stat.size) || host.services.vault.isFileSizeTooLarge(doc.size)) {
|
|
53
|
+
log(
|
|
54
|
+
`STORAGE ? DB : ${file.path} has been skipped due to file size exceeding the limit`,
|
|
55
|
+
LOG_LEVEL_NOTICE
|
|
56
|
+
);
|
|
57
|
+
return FilePairProcessResults.SKIPPED;
|
|
58
|
+
}
|
|
59
|
+
if (scanOptions?.strictContentCheck === false && await host.serviceModules.fileHandler.canSkipUnchangedFile?.(file, doc)) {
|
|
60
|
+
log(
|
|
61
|
+
`STORAGE ? DB : ${file.path} skipped using unchanged storage and revision metadata`,
|
|
62
|
+
LOG_LEVEL_DEBUG
|
|
63
|
+
);
|
|
64
|
+
return FilePairProcessResults.SKIPPED;
|
|
65
|
+
}
|
|
66
|
+
if (doc._rev && await host.serviceModules.fileHandler.tryRecordUntrackedFileRevision(file, doc._rev)) {
|
|
67
|
+
log("STORAGE == DB :" + file.path, LOG_LEVEL_DEBUG);
|
|
68
|
+
return FilePairProcessResults.COMPLETED;
|
|
69
|
+
}
|
|
70
|
+
log("STORAGE ? DB :" + file.path + " Checking content", LOG_LEVEL_DEBUG);
|
|
71
|
+
try {
|
|
72
|
+
return await host.serviceModules.fileHandler.storeFileToDB(file, false, false, {
|
|
73
|
+
revalidateStorage: true
|
|
74
|
+
}) ? FilePairProcessResults.COMPLETED : FilePairProcessResults.FAILED;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
log(`STORAGE ? DB : Could not reconcile ${file.path}`, LOG_LEVEL_NOTICE);
|
|
77
|
+
log(error, LOG_LEVEL_VERBOSE);
|
|
78
|
+
return FilePairProcessResults.FAILED;
|
|
79
|
+
}
|
|
80
|
+
default:
|
|
81
|
+
log("STORAGE ?? DB :" + file.path + " Something got weird");
|
|
82
|
+
return FilePairProcessResults.FAILED;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function createComparisonPathLookup(settings, paths) {
|
|
86
|
+
return Object.fromEntries(paths.map((path) => [convertCase(settings, path), path]));
|
|
87
|
+
}
|
|
88
|
+
async function collectFilesOnStorage(host, settings, log) {
|
|
89
|
+
log("Collecting local files on the storage", LOG_LEVEL_VERBOSE);
|
|
90
|
+
const filesStorageSrc = await host.serviceModules.storageAccess.getFiles();
|
|
91
|
+
const _filesStorage = [];
|
|
92
|
+
for (const f of filesStorageSrc) {
|
|
93
|
+
if (shouldBeIgnored(f.path)) continue;
|
|
94
|
+
if (await host.services.vault.isTargetFile(f.path)) {
|
|
95
|
+
_filesStorage.push(f);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const storageFileNameMap = Object.fromEntries(_filesStorage.map((e) => [e.path, e]));
|
|
99
|
+
const storageFileNames = Object.keys(storageFileNameMap);
|
|
100
|
+
const storageFileNameCI2CS = createComparisonPathLookup(settings, storageFileNames);
|
|
101
|
+
return { storageFileNameMap, storageFileNames, storageFileNameCI2CS };
|
|
102
|
+
}
|
|
103
|
+
async function collectDatabaseFiles(host, settings, log, showingNotice) {
|
|
104
|
+
log("Collecting local files on the DB", LOG_LEVEL_VERBOSE);
|
|
105
|
+
const _DBEntries = [];
|
|
106
|
+
const unresolvedFileNamesLC = /* @__PURE__ */ new Set();
|
|
107
|
+
const resolvableFileNamesLC = /* @__PURE__ */ new Set();
|
|
108
|
+
let count = 0;
|
|
109
|
+
for await (const doc of host.services.database.localDatabase.findAllNormalDocs({ conflicts: true }) || []) {
|
|
110
|
+
count++;
|
|
111
|
+
if (count % 25 === 0)
|
|
112
|
+
log(
|
|
113
|
+
`Collecting local files on the DB: ${count}`,
|
|
114
|
+
showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
|
|
115
|
+
"syncAll"
|
|
116
|
+
);
|
|
117
|
+
if (!isMetaEntry(doc)) {
|
|
118
|
+
const documentId = doc._id ?? "unknown";
|
|
119
|
+
log(`Invalid Metadata entry: ${documentId}`, LOG_LEVEL_INFO);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const identity = await inspectMetadataDocumentIdentity(host, doc);
|
|
123
|
+
if (identity.status === MetadataDocumentIdentityStatuses.EXCLUDED) {
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
|
|
127
|
+
const { diagnostic } = identity;
|
|
128
|
+
const unresolvedKey = convertCase(settings, stripAllPrefixes(diagnostic.declaredPath));
|
|
129
|
+
unresolvedFileNamesLC.add(unresolvedKey);
|
|
130
|
+
log(
|
|
131
|
+
`Metadata identity is unresolved and will be left unchanged: ${diagnostic.declaredPath} (${diagnostic.reason})`,
|
|
132
|
+
LOG_LEVEL_INFO
|
|
133
|
+
);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const path = identity.declaredPath;
|
|
137
|
+
if (host.services.vault.isValidPath(path) && !shouldBeIgnored(path) && await host.services.vault.isTargetFile(path)) {
|
|
138
|
+
_DBEntries.push(doc);
|
|
139
|
+
resolvableFileNamesLC.add(convertCase(settings, stripAllPrefixes(path)));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const databaseFileNameMap = Object.fromEntries(_DBEntries.map((e) => [getPathFromEntry(host, e), e]));
|
|
143
|
+
const databaseFileNames = Object.keys(databaseFileNameMap);
|
|
144
|
+
const databaseFileNameCI2CS = createComparisonPathLookup(settings, databaseFileNames);
|
|
145
|
+
const quarantinedFileNamesLC = new Set(
|
|
146
|
+
[...unresolvedFileNamesLC].filter((path) => !resolvableFileNamesLC.has(path))
|
|
147
|
+
);
|
|
148
|
+
return {
|
|
149
|
+
databaseFileNameMap,
|
|
150
|
+
databaseFileNames,
|
|
151
|
+
databaseFileNameCI2CS,
|
|
152
|
+
quarantinedFileNamesLC
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
async function updateToDatabase(host, log, logLevel, file) {
|
|
156
|
+
if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
|
|
157
|
+
const path = file.path;
|
|
158
|
+
if (!await host.serviceModules.fileHandler.storeFileToDB(file)) {
|
|
159
|
+
return FilePairProcessResults.FAILED;
|
|
160
|
+
}
|
|
161
|
+
host.services.context.events.emitEvent("event-file-changed", { file: path, automated: true });
|
|
162
|
+
return FilePairProcessResults.COMPLETED;
|
|
163
|
+
} else {
|
|
164
|
+
log(`UPDATE DATABASE: ${file.path} has been skipped due to file size exceeding the limit`, logLevel);
|
|
165
|
+
return FilePairProcessResults.SKIPPED;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async function updateToStorage(host, log, logLevel, w) {
|
|
169
|
+
const path = getPathFromEntry(host, w);
|
|
170
|
+
if (w && !(w.deleted || w._deleted)) {
|
|
171
|
+
if (!host.services.vault.isFileSizeTooLarge(w.size)) {
|
|
172
|
+
if ((w._conflicts?.length ?? 0) > 0) {
|
|
173
|
+
log(`UPDATE STORAGE: ${path} has conflicts. skipped (x)`, LOG_LEVEL_INFO);
|
|
174
|
+
return FilePairProcessResults.SKIPPED;
|
|
175
|
+
}
|
|
176
|
+
const reflected = await host.serviceModules.fileHandler.dbToStorage(path, null, true);
|
|
177
|
+
if (!reflected) return FilePairProcessResults.FAILED;
|
|
178
|
+
host.services.context.events.emitEvent("event-file-changed", {
|
|
179
|
+
file: path,
|
|
180
|
+
automated: true
|
|
181
|
+
});
|
|
182
|
+
log(`Check or pull from db:${path} OK`);
|
|
183
|
+
return FilePairProcessResults.COMPLETED;
|
|
184
|
+
} else {
|
|
185
|
+
log(`UPDATE STORAGE: ${path} has been skipped due to file size exceeding the limit`, logLevel);
|
|
186
|
+
return FilePairProcessResults.SKIPPED;
|
|
187
|
+
}
|
|
188
|
+
} else if (w) {
|
|
189
|
+
log(`Deletion history skipped: ${path}`, LOG_LEVEL_VERBOSE);
|
|
190
|
+
return FilePairProcessResults.SKIPPED;
|
|
191
|
+
} else {
|
|
192
|
+
log(`entry not found: ${path}`);
|
|
193
|
+
return FilePairProcessResults.FAILED;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async function syncStorageAndDatabase(host, log, file, logLevel, doc, scanOptions) {
|
|
197
|
+
if ((doc._conflicts?.length ?? 0) > 0) {
|
|
198
|
+
log(`SYNC DATABASE AND STORAGE: ${file.path} has conflicts. skipped`, LOG_LEVEL_INFO);
|
|
199
|
+
return FilePairProcessResults.SKIPPED;
|
|
200
|
+
}
|
|
201
|
+
if (!host.services.vault.isFileSizeTooLarge(file.stat.size) && !host.services.vault.isFileSizeTooLarge(doc.size)) {
|
|
202
|
+
return await syncFileBetweenDBandStorage(host, log, file, doc, scanOptions);
|
|
203
|
+
} else {
|
|
204
|
+
log(
|
|
205
|
+
`SYNC DATABASE AND STORAGE: ${getPathFromEntry(host, doc)} has been skipped due to file size exceeding the limit`,
|
|
206
|
+
logLevel
|
|
207
|
+
);
|
|
208
|
+
return FilePairProcessResults.SKIPPED;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
export {
|
|
212
|
+
collectDatabaseFiles,
|
|
213
|
+
collectFilesOnStorage,
|
|
214
|
+
syncFileBetweenDBandStorage,
|
|
215
|
+
syncStorageAndDatabase,
|
|
216
|
+
updateToDatabase,
|
|
217
|
+
updateToStorage
|
|
218
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type MetaEntry } from "../../common/types.js";
|
|
2
|
+
import type { NecessaryServices } from "../../interfaces/ServiceModule.js";
|
|
3
|
+
import type { IPathService } from "../../services/base/IService.js";
|
|
4
|
+
import type { LogFunction } from "../../services/lib/logUtils.js";
|
|
5
|
+
import { type MetadataDocumentNamespace, type MetadataDocumentIdentityInspection, type MetadataDocumentIdentityIssue, type MetadataDocumentRepairRequest, type MetadataDocumentRepairResult } from "./types.js";
|
|
6
|
+
/**
|
|
7
|
+
* Classify the logical Metadata namespace before platform path filtering.
|
|
8
|
+
*
|
|
9
|
+
* Internal, customisation, and plug-in storage entries are owned by their
|
|
10
|
+
* dedicated synchronisation paths. The ordinary file scanner handles only the
|
|
11
|
+
* normal namespace.
|
|
12
|
+
*/
|
|
13
|
+
export declare function getMetadataDocumentNamespace(value: string): MetadataDocumentNamespace;
|
|
14
|
+
/**
|
|
15
|
+
* Inspect whether a Metadata document identifier still represents its
|
|
16
|
+
* declared path under the active path settings.
|
|
17
|
+
*
|
|
18
|
+
* This check deliberately runs before any scanner action. A mismatch can be
|
|
19
|
+
* caused by an old path-obfuscation key, a case-sensitivity change, or a
|
|
20
|
+
* historical rename. Selecting a repair without additional evidence would be
|
|
21
|
+
* destructive, so callers must leave an unresolved document unchanged. A
|
|
22
|
+
* separate consistent document for the same logical path may still proceed
|
|
23
|
+
* through ordinary path-based handling.
|
|
24
|
+
*/
|
|
25
|
+
export declare function inspectMetadataDocumentIdentity(host: {
|
|
26
|
+
services: {
|
|
27
|
+
path: Pick<IPathService, "getPath" | "path2id">;
|
|
28
|
+
};
|
|
29
|
+
}, doc: MetaEntry): Promise<MetadataDocumentIdentityInspection>;
|
|
30
|
+
/**
|
|
31
|
+
* Enumerate Metadata from its actual local document IDs and report only the
|
|
32
|
+
* entries which ordinary path-based inspection cannot address.
|
|
33
|
+
*
|
|
34
|
+
* Path-addressed file inspection cannot discover a document whose stored path
|
|
35
|
+
* derives a different ID. The report therefore provides the evidence needed
|
|
36
|
+
* by an existing host-owned repair inspector without adding a batch-repair
|
|
37
|
+
* policy to the scanner.
|
|
38
|
+
*/
|
|
39
|
+
export declare function inspectMetadataDocumentIdentities(host: NecessaryServices<"path" | "database" | "setting" | "vault", never>): Promise<MetadataDocumentIdentityIssue[]>;
|
|
40
|
+
/**
|
|
41
|
+
* Repair one previously inspected normal-file Metadata identity.
|
|
42
|
+
*
|
|
43
|
+
* The request identifies the exact source revision which the operator
|
|
44
|
+
* approved. Every precondition is inspected again under the same ordered
|
|
45
|
+
* document locks as file-event handling. The target is created and verified
|
|
46
|
+
* before the source receives a hard tombstone. If interruption leaves that
|
|
47
|
+
* exact target in place, the same single-entry action can safely be repeated.
|
|
48
|
+
*/
|
|
49
|
+
export declare function repairMetadataDocumentIdentity(host: NecessaryServices<"path" | "database" | "setting" | "vault" | "keyValueDB", never>, request: MetadataDocumentRepairRequest): Promise<MetadataDocumentRepairResult>;
|
|
50
|
+
/**
|
|
51
|
+
* Collect deleted files that have expired according to retention policy.
|
|
52
|
+
* @param host Services container
|
|
53
|
+
* @param log Logging function
|
|
54
|
+
* @returns Array of expired deletion history
|
|
55
|
+
*/
|
|
56
|
+
export declare function collectDeletedFiles(host: NecessaryServices<"setting" | "database" | "path", never>, log: LogFunction): Promise<void>;
|