@vrtmrz/livesync-commonlib 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -2
- package/dist/common/models/fileaccess.definition.d.ts +35 -0
- package/dist/common/models/fileaccess.definition.js +11 -0
- package/dist/common/typeUtils.d.ts +27 -4
- package/dist/interfaces/FileHandler.d.ts +60 -1
- package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
- package/dist/interfaces/FileReflectionProvenance.js +11 -1
- package/dist/managers/StorageEventManager/admission.d.ts +50 -0
- package/dist/managers/StorageEventManager/admission.js +129 -0
- package/dist/managers/StorageEventManager/batching.d.ts +93 -0
- package/dist/managers/StorageEventManager/batching.js +97 -0
- package/dist/managers/StorageEventManager/operations.d.ts +142 -0
- package/dist/managers/StorageEventManager/operations.js +69 -0
- package/dist/managers/StorageEventManager/processing.d.ts +63 -0
- package/dist/managers/StorageEventManager/processing.js +94 -0
- package/dist/managers/StorageEventManager/queue.d.ts +73 -0
- package/dist/managers/StorageEventManager/queue.js +113 -0
- package/dist/managers/StorageEventManager/retry.d.ts +33 -0
- package/dist/managers/StorageEventManager/retry.js +31 -0
- package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
- package/dist/managers/StorageEventManager/snapshot.js +53 -0
- package/dist/managers/StorageEventManager/state.d.ts +155 -0
- package/dist/managers/StorageEventManager/state.js +105 -0
- package/dist/managers/StorageEventManager/watching.d.ts +93 -0
- package/dist/managers/StorageEventManager/watching.js +36 -0
- package/dist/managers/StorageEventManager.d.ts +303 -83
- package/dist/managers/StorageEventManager.js +457 -547
- package/dist/serviceFeatures/offlineScanner/fileStatus.d.ts +61 -0
- package/dist/serviceFeatures/offlineScanner/fileStatus.js +85 -0
- package/dist/serviceFeatures/offlineScanner/files.d.ts +47 -0
- package/dist/serviceFeatures/offlineScanner/files.js +218 -0
- package/dist/serviceFeatures/offlineScanner/metadata.d.ts +56 -0
- package/dist/serviceFeatures/offlineScanner/metadata.js +320 -0
- package/dist/serviceFeatures/offlineScanner/paths.d.ts +20 -0
- package/dist/serviceFeatures/offlineScanner/paths.js +16 -0
- package/dist/serviceFeatures/offlineScanner/scan.d.ts +35 -0
- package/dist/serviceFeatures/offlineScanner/scan.js +358 -0
- package/dist/serviceFeatures/offlineScanner/types.d.ts +134 -0
- package/dist/serviceFeatures/offlineScanner/types.js +66 -0
- package/dist/serviceFeatures/offlineScanner.d.ts +25 -251
- package/dist/serviceFeatures/offlineScanner.js +36 -860
- package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
- package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
- package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
- package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.d.ts +13 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
- package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
- package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
- package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
- package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
- package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
- package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
- package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
- package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
- package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
- package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
- package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
- package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
- package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
- package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
- package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
- package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
- package/dist/serviceModules/ServiceFileHandlerBase.d.ts +141 -183
- package/dist/serviceModules/ServiceFileHandlerBase.js +206 -1397
- package/dist/services/base/KeyValueDBService.d.ts +9 -0
- package/dist/services/base/KeyValueDBService.js +11 -1
- package/docs/conflict-resolution.md +3 -1
- package/docs/development.md +40 -0
- package/docs/offline-scanner.md +26 -1
- package/docs/p2p-transport-lifecycle.md +8 -1
- package/docs/storage-events-and-reflection.md +212 -22
- package/package.json +1 -1
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.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Transient handler requests which reuse reconciliation without changing the persisted event schema. */
|
|
2
|
+
import type { FileEventItem } from "./fileaccess.type.js";
|
|
3
|
+
/** Keep the runtime brand private so callers construct requests through the factory. */
|
|
4
|
+
declare const RECONCILE_FILE_EVENT: unique symbol;
|
|
5
|
+
/**
|
|
6
|
+
* A transient request to re-evaluate an event against current storage and database state.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* This is a handler invocation, not a new durable operation. The manager retains
|
|
10
|
+
* the original event for snapshots; the private symbol is absent from JSON persistence.
|
|
11
|
+
*/
|
|
12
|
+
export type ReconcileFileEvent = FileEventItem & {
|
|
13
|
+
[RECONCILE_FILE_EVENT]: true;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Create a marked handler invocation without changing the retained operation's event.
|
|
17
|
+
*
|
|
18
|
+
* @param event - The original accepted file event whose current effect must be reconsidered.
|
|
19
|
+
* @returns A shallow event copy branded as a reconciliation request; its arguments are shared with the original.
|
|
20
|
+
* @remarks
|
|
21
|
+
* Continue persisting the original event. The returned request only selects the
|
|
22
|
+
* current-state reconciliation route for this attempt and does not alter earlier results.
|
|
23
|
+
*/
|
|
24
|
+
export declare function createReconcileEvent(event: FileEventItem): ReconcileFileEvent;
|
|
25
|
+
/**
|
|
26
|
+
* Narrow a valid file event to a transient reconciliation request.
|
|
27
|
+
*
|
|
28
|
+
* @param event - An already typed file event passed to a handler.
|
|
29
|
+
* @returns Whether the private reconciliation marker is present and true.
|
|
30
|
+
* @remarks
|
|
31
|
+
* This checks the invocation marker, not the full shape of an unknown payload.
|
|
32
|
+
* Persisted restart events use restoredFromPreviousRuntime and are checked separately.
|
|
33
|
+
*/
|
|
34
|
+
export declare function isReconcileEvent(event: FileEventItem): event is ReconcileFileEvent;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const RECONCILE_FILE_EVENT = /* @__PURE__ */ Symbol("reconcileFileEvent");
|
|
2
|
+
function createReconcileEvent(event) {
|
|
3
|
+
return { ...event, [RECONCILE_FILE_EVENT]: true };
|
|
4
|
+
}
|
|
5
|
+
function isReconcileEvent(event) {
|
|
6
|
+
return RECONCILE_FILE_EVENT in event && event[RECONCILE_FILE_EVENT] === true;
|
|
7
|
+
}
|
|
8
|
+
export {
|
|
9
|
+
createReconcileEvent,
|
|
10
|
+
isReconcileEvent
|
|
11
|
+
};
|
|
@@ -1,17 +1,40 @@
|
|
|
1
1
|
import type { DocumentID, FilePath, FilePathWithPrefix } from "./models/db.type.js";
|
|
2
2
|
import type { UXFileInfoStub } from "./types.js";
|
|
3
|
+
/** Path conversion requires identity only; internal files need no storage statistics. */
|
|
4
|
+
type FilePathInput = string | Pick<UXFileInfoStub, "path" | "isInternal">;
|
|
3
5
|
/**
|
|
4
6
|
* returns is internal chunk of file
|
|
5
7
|
* @param id ID
|
|
6
8
|
* @returns
|
|
7
9
|
*/
|
|
8
10
|
export declare function isInternalMetadata(id: FilePath | FilePathWithPrefix | DocumentID): boolean;
|
|
9
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Identify the internal namespace from a path or file identity.
|
|
13
|
+
* @param file - A path or identity whose optional internal flag is retained.
|
|
14
|
+
* @returns Whether the path namespace or explicit flag denotes an internal file.
|
|
15
|
+
*/
|
|
16
|
+
export declare function isInternalFile(file: FilePathInput): boolean;
|
|
10
17
|
export declare function stripInternalMetadataPrefix<T extends FilePath | FilePathWithPrefix | DocumentID>(id: T): T;
|
|
11
18
|
export declare function id2InternalMetadataId(id: DocumentID): DocumentID;
|
|
12
19
|
export declare function isChunk(str: string): boolean;
|
|
13
20
|
export declare function isPluginMetadata(str: string): boolean;
|
|
14
21
|
export declare function isCustomisationSyncMetadata(str: string): boolean;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Read the supplied path without changing its namespace or spelling.
|
|
24
|
+
* @param file - A path or file identity; storage statistics are not required.
|
|
25
|
+
* @returns The original path, including any namespace prefix.
|
|
26
|
+
*/
|
|
27
|
+
export declare function getPathFromUXFileInfo(file: FilePathInput): FilePathWithPrefix;
|
|
28
|
+
/**
|
|
29
|
+
* Resolve a physical storage path from a path or file identity.
|
|
30
|
+
* @param file - A path or file identity; internal observations may omit statistics.
|
|
31
|
+
* @returns The path with recognised database namespace prefixes removed.
|
|
32
|
+
*/
|
|
33
|
+
export declare function getStoragePathFromUXFileInfo(file: FilePathInput): FilePath;
|
|
34
|
+
/**
|
|
35
|
+
* Resolve the database namespace from a path or file identity.
|
|
36
|
+
* @param file - A path or identity carrying its optional internal flag.
|
|
37
|
+
* @returns The existing customisation path or the path with its internal namespace applied.
|
|
38
|
+
*/
|
|
39
|
+
export declare function getDatabasePathFromUXFileInfo(file: FilePathInput): FilePathWithPrefix;
|
|
40
|
+
export {};
|
|
@@ -4,16 +4,74 @@ 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
|
/**
|
|
10
49
|
* Record an untracked, unchanged file during an equal-time scan.
|
|
11
50
|
* Return true only when the exact current revision was recorded. This
|
|
12
|
-
* operation never stores a
|
|
51
|
+
* operation never stores a Metadata revision or writes to storage.
|
|
13
52
|
*/
|
|
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,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Select host storage callbacks and admit valid events into the manager's operation queue.
|
|
3
|
+
*/
|
|
4
|
+
import { type FileEventItem, type ObsidianLiveSyncSettings } from "../../common/types.js";
|
|
5
|
+
import type { FileEvent } from "../../interfaces/StorageEventManager.js";
|
|
6
|
+
import type { IStorageAccessManager } from "../../interfaces/StorageAccess.js";
|
|
7
|
+
import type { LogFunction } from "../../services/lib/logUtils.js";
|
|
8
|
+
import type { StorageEventState } from "./state.js";
|
|
9
|
+
import type { PendingFileEvent } from "./operations.js";
|
|
10
|
+
/**
|
|
11
|
+
* Inject host settings, path and file checks, queue actions, and diagnostics into admission.
|
|
12
|
+
* @remarks
|
|
13
|
+
* Admission owns event selection; the facade supplies platform services and asynchronous target checks.
|
|
14
|
+
* Settings are read once for each appended batch, while enqueueing and reporting remain host effects.
|
|
15
|
+
*/
|
|
16
|
+
export interface StorageEventAdmissionEffects {
|
|
17
|
+
settings(): ObsidianLiveSyncSettings;
|
|
18
|
+
isFolder(file: FileEvent["file"]): boolean;
|
|
19
|
+
isFile(file: FileEvent["file"]): boolean;
|
|
20
|
+
isTarget(path: string): Promise<boolean>;
|
|
21
|
+
isTooLarge(size: number): boolean;
|
|
22
|
+
recentlyTouched: IStorageAccessManager["recentlyTouched"];
|
|
23
|
+
onStorageFileEvent(): void;
|
|
24
|
+
enqueue(event: FileEventItem): void;
|
|
25
|
+
release(operations: readonly PendingFileEvent[]): void;
|
|
26
|
+
reportFailure(error: unknown): void;
|
|
27
|
+
log: LogFunction;
|
|
28
|
+
}
|
|
29
|
+
/** Normalised event intent before cache data and host context are attached. */
|
|
30
|
+
type SelectedFileEvent = Pick<FileEventItem, "type" | "args">;
|
|
31
|
+
/**
|
|
32
|
+
* Convert old and new path selection into the operation which preserves the selected side.
|
|
33
|
+
* @param param - The host rename event.
|
|
34
|
+
* @param oldSelected - Whether the source path is a sync target.
|
|
35
|
+
* @param newSelected - Whether the destination path is a sync target and within the size limit.
|
|
36
|
+
* @returns `null` when neither path is selected; otherwise a CREATE, RENAME, or source-path DELETE intent.
|
|
37
|
+
* @remarks The source-only case asserts that `oldPath` and file `stat` are present; `selectRename` establishes those preconditions.
|
|
38
|
+
*/
|
|
39
|
+
export declare function selectRenameFileEvent(param: FileEvent, oldSelected: boolean, newSelected: boolean): SelectedFileEvent | null;
|
|
40
|
+
/**
|
|
41
|
+
* Start and track a batch of host events through filtering and queue admission.
|
|
42
|
+
* @param state - Mutable state which owns admission and operation boundaries.
|
|
43
|
+
* @param params - Host watcher events to select.
|
|
44
|
+
* @param ctx - Optional host context forwarded to admitted items.
|
|
45
|
+
* @param effects - Host services used during selection and enqueueing.
|
|
46
|
+
* @returns A promise for admission completion, not handler completion; rejected admission is reported and remains rejected.
|
|
47
|
+
* @remarks When the manager no longer accepts events, this returns an already-fulfilled promise without admitting them.
|
|
48
|
+
*/
|
|
49
|
+
export declare function admitStorageEvents(state: StorageEventState, params: readonly FileEvent[], ctx: unknown, effects: StorageEventAdmissionEffects): Promise<void>;
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import {
|
|
2
|
+
LOG_LEVEL_NOTICE,
|
|
3
|
+
LOG_LEVEL_VERBOSE
|
|
4
|
+
} from "../../common/types.js";
|
|
5
|
+
import { shouldBeIgnored } from "../../string_and_binary/path.js";
|
|
6
|
+
import { delay, isRemediationModeActive } from "../../common/utils.js";
|
|
7
|
+
async function isSelectedPath(path, settings, effects) {
|
|
8
|
+
if (shouldBeIgnored(path)) return false;
|
|
9
|
+
if (!settings.syncInternalFiles && path.startsWith(".")) return false;
|
|
10
|
+
return await effects.isTarget(path);
|
|
11
|
+
}
|
|
12
|
+
function logOversizedEvent(path, effects) {
|
|
13
|
+
effects.log(`The storage file has been changed but exceeds the maximum size. Skipping: ${path}`, LOG_LEVEL_NOTICE);
|
|
14
|
+
}
|
|
15
|
+
function selectRenameFileEvent(param, oldSelected, newSelected) {
|
|
16
|
+
if (!oldSelected && !newSelected) return null;
|
|
17
|
+
if (oldSelected && !newSelected) {
|
|
18
|
+
const oldPath = param.oldPath;
|
|
19
|
+
return {
|
|
20
|
+
type: "DELETE",
|
|
21
|
+
args: {
|
|
22
|
+
file: {
|
|
23
|
+
path: oldPath,
|
|
24
|
+
name: oldPath.split("/").pop() ?? param.file.name,
|
|
25
|
+
stat: param.file.stat,
|
|
26
|
+
deleted: true
|
|
27
|
+
},
|
|
28
|
+
oldPath: void 0,
|
|
29
|
+
renameTarget: param.file.path
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
type: oldSelected ? "RENAME" : "CREATE",
|
|
35
|
+
args: {
|
|
36
|
+
file: param.file,
|
|
37
|
+
oldPath: oldSelected ? param.oldPath : void 0
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
async function selectRename(param, settings, effects) {
|
|
42
|
+
const file = param.file;
|
|
43
|
+
if (!param.oldPath || !effects.isFile(file) || !file.stat) {
|
|
44
|
+
effects.log(`Invalid rename event skipped: ${file.path}`, LOG_LEVEL_VERBOSE);
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
const oldSelected = await isSelectedPath(param.oldPath, settings, effects);
|
|
48
|
+
let newSelected = await isSelectedPath(file.path, settings, effects);
|
|
49
|
+
if (newSelected && effects.isTooLarge(file.stat.size)) {
|
|
50
|
+
logOversizedEvent(param.file.path, effects);
|
|
51
|
+
newSelected = false;
|
|
52
|
+
}
|
|
53
|
+
return selectRenameFileEvent(param, oldSelected, newSelected);
|
|
54
|
+
}
|
|
55
|
+
async function selectOrdinaryEvent(param, settings, effects) {
|
|
56
|
+
if (!await isSelectedPath(param.file.path, settings, effects)) return null;
|
|
57
|
+
if (param.type !== "INTERNAL") {
|
|
58
|
+
const size = param.file.stat.size;
|
|
59
|
+
if (effects.isTooLarge(size) && (param.type === "CREATE" || param.type === "CHANGED")) {
|
|
60
|
+
logOversizedEvent(param.file.path, effects);
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return { type: param.type, args: { file: param.file, oldPath: void 0 } };
|
|
65
|
+
}
|
|
66
|
+
async function wasRecentlyTouched(event, effects) {
|
|
67
|
+
if (!effects.isFile(event.args.file)) return false;
|
|
68
|
+
if (event.type !== "CREATE" && event.type !== "CHANGED" && event.type !== "RENAME") return false;
|
|
69
|
+
await delay(10);
|
|
70
|
+
const file = event.args.file;
|
|
71
|
+
return effects.recentlyTouched({ path: file.path, stat: file.stat ?? { ctime: 0, mtime: 0, size: 0 } });
|
|
72
|
+
}
|
|
73
|
+
async function prepareEvent(param, settings, ctx, effects) {
|
|
74
|
+
const key = [0, 0, 0, 0, 0, 0].map(() => `${Math.floor(Math.random() * 1e5)}`).join("-");
|
|
75
|
+
if (effects.isFolder(param.file)) {
|
|
76
|
+
effects.log(`Folder event skipped: ${param.file.path}`, LOG_LEVEL_VERBOSE);
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
const selected = param.type === "RENAME" ? await selectRename(param, settings, effects) : await selectOrdinaryEvent(param, settings, effects);
|
|
80
|
+
if (!selected || await wasRecentlyTouched(selected, effects)) return null;
|
|
81
|
+
return {
|
|
82
|
+
...selected,
|
|
83
|
+
args: { ...selected.args, cache: param.cachedData || void 0, ctx },
|
|
84
|
+
skipBatchWait: param.skipBatchWait,
|
|
85
|
+
key
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function registerAdmission(state, admission, item, effects) {
|
|
89
|
+
effects.enqueue(item);
|
|
90
|
+
const operation = state.operations.get(item);
|
|
91
|
+
if (!operation) return;
|
|
92
|
+
operation.acceptedAt = admission.acceptedAt;
|
|
93
|
+
operation.failureBoundary = admission.failureBoundary;
|
|
94
|
+
if (admission.flushRequested) effects.release([operation]);
|
|
95
|
+
admission.operations.set(operation, operation.attempt);
|
|
96
|
+
}
|
|
97
|
+
async function appendStorageEvents(state, params, ctx, admission, effects) {
|
|
98
|
+
const settings = effects.settings();
|
|
99
|
+
if (!settings.isConfigured || settings.suspendFileWatching || isRemediationModeActive(settings)) return;
|
|
100
|
+
effects.onStorageFileEvent();
|
|
101
|
+
for (const param of params) {
|
|
102
|
+
const item = await prepareEvent(param, settings, ctx, effects);
|
|
103
|
+
if (item) registerAdmission(state, admission, item, effects);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function admitStorageEvents(state, params, ctx, effects) {
|
|
107
|
+
if (!state.acceptingEvents) return Promise.resolve();
|
|
108
|
+
const admission = {
|
|
109
|
+
acceptedAt: Date.now(),
|
|
110
|
+
completion: Promise.resolve(),
|
|
111
|
+
operations: /* @__PURE__ */ new Map(),
|
|
112
|
+
failureBoundary: state.nextFailureSequence,
|
|
113
|
+
flushRequested: false
|
|
114
|
+
};
|
|
115
|
+
state.admissions.add(admission);
|
|
116
|
+
admission.completion = appendStorageEvents(state, params, ctx, admission, effects);
|
|
117
|
+
void admission.completion.then(
|
|
118
|
+
() => state.admissions.delete(admission),
|
|
119
|
+
(error) => {
|
|
120
|
+
state.admissions.delete(admission);
|
|
121
|
+
effects.reportFailure(error);
|
|
122
|
+
}
|
|
123
|
+
);
|
|
124
|
+
return admission.completion;
|
|
125
|
+
}
|
|
126
|
+
export {
|
|
127
|
+
admitStorageEvents,
|
|
128
|
+
selectRenameFileEvent
|
|
129
|
+
};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manage batch gates, deadlines, and predecessor coalescing for storage-event operations.
|
|
3
|
+
*/
|
|
4
|
+
import type { FileEventItem, FileEventType } from "../../common/types.js";
|
|
5
|
+
import type { LogFunction } from "../../services/lib/logUtils.js";
|
|
6
|
+
import { type DeferredAction } from "octagonal-wheels/concurrency/deferredAction";
|
|
7
|
+
import { type PromiseWithResolvers } from "octagonal-wheels/promises";
|
|
8
|
+
import { type PendingFileEvent } from "./operations.js";
|
|
9
|
+
/** One path's pending batch gate, its deadline, and the event which owns the gate. */
|
|
10
|
+
export type WaitInfo = {
|
|
11
|
+
since: number;
|
|
12
|
+
type: FileEventType;
|
|
13
|
+
canProceed: PromiseWithResolvers<boolean>;
|
|
14
|
+
deadline: DeferredAction;
|
|
15
|
+
event: FileEventItem;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Inject waiting state, live delay settings, logging, snapshots, and gate control into batching.
|
|
19
|
+
* @remarks The facade provides dynamic setting accessors so each new gate observes current host settings.
|
|
20
|
+
*/
|
|
21
|
+
export interface StorageEventBatching {
|
|
22
|
+
waiting(): Map<string, WaitInfo>;
|
|
23
|
+
operation(event: FileEventItem): PendingFileEvent | undefined;
|
|
24
|
+
minimumDelay(): number;
|
|
25
|
+
maximumDelay(): number;
|
|
26
|
+
enabled(): boolean;
|
|
27
|
+
log: LogFunction;
|
|
28
|
+
requestSnapshot(): void;
|
|
29
|
+
proceed(path: string): void;
|
|
30
|
+
cancel(path: string): void;
|
|
31
|
+
add(path: string, event: FileEventItem, since?: number): WaitInfo;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Resolve and remove a path's current gate, dispose its timer, and request a snapshot.
|
|
35
|
+
* @param batching - Host effects for waiting state and snapshot requests.
|
|
36
|
+
* @param path - The path whose gate should be completed.
|
|
37
|
+
* @param proceed - Whether the waiting event may proceed or has been cancelled.
|
|
38
|
+
* @returns Nothing; snapshotting is requested even when the path has no current gate, and processing is not awaited.
|
|
39
|
+
*/
|
|
40
|
+
export declare function finishBatchWaiting(batching: StorageEventBatching, path: string, proceed: boolean): void;
|
|
41
|
+
/**
|
|
42
|
+
* Calculate a gate delay which honours both minimum and maximum batch windows.
|
|
43
|
+
* @param now - The current time in milliseconds.
|
|
44
|
+
* @param acceptedAt - When the operation entered admission, used for the minimum delay.
|
|
45
|
+
* @param since - The inherited start of the maximum-delay window.
|
|
46
|
+
* @param minimum - The minimum delay in milliseconds.
|
|
47
|
+
* @param maximum - The maximum delay in milliseconds.
|
|
48
|
+
* @returns Whether the maximum window has expired and the non-negative delay to schedule.
|
|
49
|
+
* @remarks The original timing sketch follows; each row shows an event arriving within the same maximum window.
|
|
50
|
+
* ```text
|
|
51
|
+
* x*<------- maxDelay --------->*
|
|
52
|
+
* x*<-- minDelay -->*
|
|
53
|
+
* x* x<-- nextDelay -->*
|
|
54
|
+
* x* x<-- Capped-->*
|
|
55
|
+
* x* x.......*
|
|
56
|
+
* x: event
|
|
57
|
+
* *: batch gate becomes eligible for processing
|
|
58
|
+
* ```
|
|
59
|
+
* The quiet delay is measured from the latest accepted event. Coalescing inherits the first uncommitted event's
|
|
60
|
+
* maximum window, so repeated events cannot postpone eligibility indefinitely. Filtering time already spent since
|
|
61
|
+
* acceptance counts towards both delays. The maximum caps intentional batching, not semaphore, I/O, or snapshot
|
|
62
|
+
* completion time; it does not guarantee a minimum interval between completed saves.
|
|
63
|
+
*/
|
|
64
|
+
export declare function planBatchDeadline(now: number, acceptedAt: number, since: number, minimum: number, maximum: number): {
|
|
65
|
+
expired: boolean;
|
|
66
|
+
delay: number;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Create and schedule a timed gate for one path, then request a snapshot.
|
|
70
|
+
* @param batching - Host effects for state, settings, logging, and gate control.
|
|
71
|
+
* @param path - The key which must not already own a gate.
|
|
72
|
+
* @param event - The event which will wait at this gate.
|
|
73
|
+
* @param waitedSince - Optional inherited start for the maximum-delay window.
|
|
74
|
+
* @returns The gate and its `canProceed` promise; its boolean result is not handler completion.
|
|
75
|
+
* @throws An error when a gate already exists for `path`.
|
|
76
|
+
*/
|
|
77
|
+
export declare function addBatchWaiting(batching: StorageEventBatching, path: string, event: FileEventItem, waitedSince?: number): WaitInfo;
|
|
78
|
+
/**
|
|
79
|
+
* Mark operations for flushing, signal active optional handlers, and release matching gates.
|
|
80
|
+
* @param batching - Host effects for waiting state and gate control.
|
|
81
|
+
* @param operations - The operations whose flush requests should be applied.
|
|
82
|
+
* @returns Nothing; this opens gates but does not wait for handlers or operation completion.
|
|
83
|
+
*/
|
|
84
|
+
export declare function releaseFileEventBatches(batching: StorageEventBatching, operations: readonly PendingFileEvent[]): void;
|
|
85
|
+
/**
|
|
86
|
+
* Initialise predecessor relationships and obtain this operation's batch-gate result.
|
|
87
|
+
* @param batching - Host effects for operation lookup, current settings, deadlines, and gate control.
|
|
88
|
+
* @param operation - The operation whose predecessor plan and gate are being prepared.
|
|
89
|
+
* @returns A promise resolving to the gate's boolean proceed result, not file-handler completion.
|
|
90
|
+
* @remarks A coalesced predecessor's eventual completion follows its successor attempt.
|
|
91
|
+
* @throws An error if the path already has a batch gate when this operation needs one.
|
|
92
|
+
*/
|
|
93
|
+
export declare function initialiseFileEventBatch(batching: StorageEventBatching, operation: PendingFileEvent): Promise<boolean>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { LOG_LEVEL_DEBUG } from "../../common/types.js";
|
|
2
|
+
import { compatGlobal } from "../../common/coreEnvFunctions.js";
|
|
3
|
+
import {
|
|
4
|
+
createDeferredAction
|
|
5
|
+
} from "octagonal-wheels/concurrency/deferredAction";
|
|
6
|
+
import { promiseWithResolvers } from "octagonal-wheels/promises";
|
|
7
|
+
import { planFileEventPredecessors } from "./operations.js";
|
|
8
|
+
const scheduleStorageTimeout = (callback, delayMs) => {
|
|
9
|
+
const handle = compatGlobal.setTimeout(callback, delayMs);
|
|
10
|
+
return () => compatGlobal.clearTimeout(handle);
|
|
11
|
+
};
|
|
12
|
+
function finishBatchWaiting(batching, path, proceed) {
|
|
13
|
+
const waiting = batching.waiting();
|
|
14
|
+
const waitInfo = waiting.get(path);
|
|
15
|
+
if (waitInfo) {
|
|
16
|
+
waitInfo.canProceed.resolve(proceed);
|
|
17
|
+
waitInfo.deadline.dispose();
|
|
18
|
+
waiting.delete(path);
|
|
19
|
+
}
|
|
20
|
+
batching.requestSnapshot();
|
|
21
|
+
}
|
|
22
|
+
function planBatchDeadline(now, acceptedAt, since, minimum, maximum) {
|
|
23
|
+
const elapsed = now - since;
|
|
24
|
+
return {
|
|
25
|
+
expired: elapsed >= maximum,
|
|
26
|
+
delay: Math.min(Math.max(0, maximum - elapsed), Math.max(0, minimum - (now - acceptedAt)))
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function addBatchWaiting(batching, path, event, waitedSince) {
|
|
30
|
+
const waiting = batching.waiting();
|
|
31
|
+
if (waiting.has(path)) throw new Error(`Already waiting for key: ${path}`);
|
|
32
|
+
const now = Date.now();
|
|
33
|
+
const acceptedAt = batching.operation(event)?.acceptedAt ?? now;
|
|
34
|
+
const since = waitedSince ?? acceptedAt;
|
|
35
|
+
const maximum = batching.maximumDelay() * 1e3;
|
|
36
|
+
const minimum = batching.minimumDelay() * 1e3;
|
|
37
|
+
const plan = planBatchDeadline(now, acceptedAt, since, minimum, maximum);
|
|
38
|
+
batching.log(
|
|
39
|
+
plan.expired ? `Processing ${path}: Batch save maximum delay already exceeded: ${event.type}` : `Processing ${path}: Adding waiting for batch save: ${event.type} (${plan.delay}ms)`,
|
|
40
|
+
LOG_LEVEL_DEBUG
|
|
41
|
+
);
|
|
42
|
+
const deadline = createDeferredAction(() => {
|
|
43
|
+
batching.log(`Processing ${path}: Batch save timeout reached: ${event.type}`, LOG_LEVEL_DEBUG);
|
|
44
|
+
batching.proceed(path);
|
|
45
|
+
}, scheduleStorageTimeout);
|
|
46
|
+
const waitInfo = {
|
|
47
|
+
since,
|
|
48
|
+
type: event.type,
|
|
49
|
+
event,
|
|
50
|
+
canProceed: promiseWithResolvers(),
|
|
51
|
+
deadline
|
|
52
|
+
};
|
|
53
|
+
deadline.schedule(plan.delay);
|
|
54
|
+
waiting.set(path, waitInfo);
|
|
55
|
+
batching.requestSnapshot();
|
|
56
|
+
return waitInfo;
|
|
57
|
+
}
|
|
58
|
+
function releaseFileEventBatches(batching, operations) {
|
|
59
|
+
for (const operation of operations) {
|
|
60
|
+
operation.flushRequested = true;
|
|
61
|
+
operation.flushSignal?.resolve();
|
|
62
|
+
const path = operation.event.args.file.path;
|
|
63
|
+
if (batching.waiting().get(path)?.event === operation.event) batching.proceed(path);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function applyPredecessorPlan(batching, operation, plan) {
|
|
67
|
+
for (const action of plan.actions) {
|
|
68
|
+
const { previous, path } = action;
|
|
69
|
+
if (action.kind === "coalesce") {
|
|
70
|
+
previous.attempt.successor = operation.attempt;
|
|
71
|
+
for (const dependency of previous.prerequisites) operation.prerequisites.add(dependency);
|
|
72
|
+
batching.cancel(path);
|
|
73
|
+
} else {
|
|
74
|
+
operation.prerequisites.add(previous);
|
|
75
|
+
if (batching.waiting().get(path)?.event === previous.event) batching.proceed(path);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function initialiseFileEventBatch(batching, operation) {
|
|
80
|
+
operation.initialised = true;
|
|
81
|
+
const event = operation.event;
|
|
82
|
+
const path = event.args.file.path;
|
|
83
|
+
const waiting = batching.waiting().get(path);
|
|
84
|
+
const plan = planFileEventPredecessors(operation, waiting);
|
|
85
|
+
applyPredecessorPlan(batching, operation, plan);
|
|
86
|
+
if (batching.waiting().get(path) === waiting && waiting) batching.proceed(path);
|
|
87
|
+
if (operation.flushRequested) releaseFileEventBatches(batching, [...operation.prerequisites]);
|
|
88
|
+
const shouldWait = batching.enabled() && !event.skipBatchWait && !operation.flushRequested && (event.type === "CREATE" || event.type === "CHANGED");
|
|
89
|
+
return shouldWait ? batching.add(path, event, plan.since).canProceed.promise : Promise.resolve(true);
|
|
90
|
+
}
|
|
91
|
+
export {
|
|
92
|
+
addBatchWaiting,
|
|
93
|
+
finishBatchWaiting,
|
|
94
|
+
initialiseFileEventBatch,
|
|
95
|
+
planBatchDeadline,
|
|
96
|
+
releaseFileEventBatches
|
|
97
|
+
};
|