@vrtmrz/livesync-commonlib 0.2.0 → 0.2.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.
Files changed (49) hide show
  1. package/README.md +43 -0
  2. package/dist/API/processSetting.d.ts +2 -0
  3. package/dist/common/models/setting.const.defaults.js +2 -0
  4. package/dist/common/models/setting.const.qr.js +3 -0
  5. package/dist/common/models/setting.policy.d.ts +8 -0
  6. package/dist/common/models/setting.policy.js +2 -0
  7. package/dist/common/models/setting.type.d.ts +6 -0
  8. package/dist/common/models/shared.definition.d.ts +20 -0
  9. package/dist/common/models/tweak.definition.d.ts +2 -0
  10. package/dist/common/settingConstants.d.ts +2 -0
  11. package/dist/common/settingConstants.js +10 -2
  12. package/dist/interfaces/FileHandler.d.ts +7 -1
  13. package/dist/interfaces/StorageAccess.d.ts +2 -0
  14. package/dist/interfaces/StorageEventManager.d.ts +7 -0
  15. package/dist/interfaces/StorageEventManager.js +11 -0
  16. package/dist/managers/StorageEventManager.d.ts +20 -10
  17. package/dist/managers/StorageEventManager.js +268 -189
  18. package/dist/replication/LiveSyncAbstractReplicator.d.ts +2 -0
  19. package/dist/replication/LiveSyncAbstractReplicator.js +5 -2
  20. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +6 -0
  21. package/dist/replication/couchdb/LiveSyncReplicator.js +39 -2
  22. package/dist/replication/couchdb/replicationProgress.d.ts +6 -0
  23. package/dist/replication/couchdb/replicationProgress.js +105 -0
  24. package/dist/replication/index.d.ts +1 -0
  25. package/dist/replication/trystero/TrysteroReplicator.d.ts +4 -0
  26. package/dist/serviceFeatures/offlineScanner.d.ts +4 -4
  27. package/dist/serviceFeatures/offlineScanner.js +30 -13
  28. package/dist/serviceFeatures/prepareDatabaseForUse.d.ts +3 -2
  29. package/dist/serviceFeatures/prepareDatabaseForUse.js +5 -4
  30. package/dist/serviceModules/ServiceFileAccessBase.d.ts +1 -0
  31. package/dist/serviceModules/ServiceFileAccessBase.js +8 -0
  32. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +9 -5
  33. package/dist/serviceModules/ServiceFileHandlerBase.js +96 -38
  34. package/dist/services/base/AppLifecycleService.js +1 -1
  35. package/dist/services/base/ControlService.js +6 -2
  36. package/dist/services/base/DatabaseEventService.d.ts +1 -1
  37. package/dist/services/base/FileProcessingService.d.ts +7 -1
  38. package/dist/services/base/FileProcessingService.js +9 -1
  39. package/dist/services/base/IService.d.ts +12 -4
  40. package/dist/services/base/ReplicatorService.d.ts +1 -0
  41. package/dist/services/base/VaultScanResult.d.ts +5 -0
  42. package/dist/services/base/VaultService.d.ts +1 -1
  43. package/dist/services/lib/HandlerUtils.d.ts +60 -0
  44. package/dist/services/lib/HandlerUtils.js +46 -0
  45. package/dist/worker/bgWorker.js +1 -1
  46. package/docs/offline-scanner.md +23 -13
  47. package/docs/settings-lifecycle.md +2 -0
  48. package/docs/storage-events-and-reflection.md +113 -10
  49. package/package.json +2 -2
package/README.md CHANGED
@@ -108,6 +108,49 @@ The `/replication` entry includes the `joined-devices` finite resource contract.
108
108
 
109
109
  `forget(id)` removes one other device from all participation maps and the accepted list, while retaining the lock state, preferred tweaks, and unknown fields. The CouchDB implementation rereads the existing milestone before editing and verifies removal after saving. CouchDB local documents do not reject stale revisions, so concurrent changes to other device records can be overwritten. A failed verification is reported to the caller for manual refresh and retry. Object Storage checks ETags with conditional writes and retries conflicts a bounded number of times. Missing records, unsupported conditional writes, and exhausted conflicts have distinct results. Forgetting is not credential revocation: an unlocked remote permits a returning device to register again.
110
110
 
111
+ ## Replication statistics
112
+
113
+ Hosts can read the latest `services.replicator.replicationStatics.value` and
114
+ subscribe to that reactive source. The focused `/replication` entry exports
115
+ `ReplicationStatics`, `CouchDBReplicationProgress`, and
116
+ `ReplicationCheckpointProgress`. Existing transfer counters and `syncStatus`
117
+ retain their meanings.
118
+
119
+ The optional `couchDB` snapshot describes the ordinary CouchDB replication
120
+ attempt. Other providers omit it. Its `phase` distinguishes `one-shot`,
121
+ `catch-up` (the pull preceding each continuous start or reconnect),
122
+ `continuous`, and `idle`. Preparation can expose a phase before directional
123
+ progress is available. This is independent of activity, pause, or failure in
124
+ `syncStatus`; entering `continuous` does not establish that Vault reflection
125
+ has finished or that editing is safe.
126
+
127
+ Optional `pull` and `push` observations each contain:
128
+
129
+ - `checkedChanges`: changes-feed entries presented for revision comparison,
130
+ including both existing and missing revisions. One entry with several
131
+ revisions counts once; repeated entries during retries can count again.
132
+ This is neither a Vault file count nor an exact count of skipped transfers.
133
+ - `completedBatches`: batches which reached PouchDB's checkpoint notification,
134
+ including batches which transferred no documents.
135
+ - `lastSeq`: the last processed checkpoint position, preserved as a number or
136
+ an opaque string. It is not a remaining-work estimate, percentage, or proof
137
+ that a checkpoint was durably written.
138
+ - `checking`: observed revision comparison in the current batch, cleared by
139
+ a transfer notification, pause, or termination. It does not establish that
140
+ network transfer has not begun.
141
+
142
+ Counts and positions reset for each underlying PouchDB handler, including the
143
+ transition from catch-up to continuous replication and a replacement attempt.
144
+ Completion, failure, and cancellation retain final values with `phase: 'idle'`
145
+ and `checking: false`. Replacing the provider clears its previous snapshot.
146
+
147
+ Checkpoint events are accumulated internally and published periodically
148
+ (currently about 200 ms). Transfer, pause, and terminal boundaries flush
149
+ pending observations promptly. The interval is an implementation detail.
150
+ The observer releases its timer and listeners on termination; late callbacks
151
+ cannot publish into the next attempt. These observations do not modify the
152
+ replication options, received documents, or native checkpoints.
153
+
111
154
  ## Rooted storage
112
155
 
113
156
  Both platform storage factories receive an existing root from the host. They never select a directory, request browser permission, infer a process directory, or persist a handle.
@@ -59,8 +59,10 @@ export declare function decodeSettingsFromSetupURI(uri: string, passphrase: stri
59
59
  idDerivationKey: string;
60
60
  pathNormalizationVersion: import("../settings.js").PathNormalizationVersion;
61
61
  liveSync: boolean;
62
+ batchSaveInLiveSync?: boolean;
62
63
  syncOnSave: boolean;
63
64
  syncOnStart: boolean;
65
+ strictContentCheckOnStartup?: boolean;
64
66
  syncOnFileOpen: boolean;
65
67
  syncOnEditorSave: boolean;
66
68
  keepReplicationActiveInBackground: boolean;
@@ -40,8 +40,10 @@ const SETTINGS_SCHEMA_DEFAULTS = {
40
40
  couchDB_PASSWORD: "",
41
41
  couchDB_DBNAME: "",
42
42
  liveSync: false,
43
+ batchSaveInLiveSync: false,
43
44
  syncOnSave: false,
44
45
  syncOnStart: false,
46
+ strictContentCheckOnStartup: false,
45
47
  savingDelay: 200,
46
48
  lessInformationInLog: false,
47
49
  gcDelay: 300,
@@ -51,6 +51,8 @@ const KeyIndexOfSettings = {
51
51
  liveSync: 49,
52
52
  syncOnSave: 50,
53
53
  syncOnStart: 51,
54
+ strictContentCheckOnStartup: -1,
55
+ // Installation-local preference; do not encode into the QR Code.
54
56
  syncOnFileOpen: 52,
55
57
  syncOnEditorSave: 53,
56
58
  keepReplicationActiveInBackground: -1,
@@ -181,6 +183,7 @@ const KeyIndexOfSettings = {
181
183
  idDerivationVersion: 166,
182
184
  idDerivationKey: 167,
183
185
  pathNormalizationVersion: 168,
186
+ batchSaveInLiveSync: 169,
184
187
  encryptedIdDerivationKey: -1
185
188
  };
186
189
  export {
@@ -53,6 +53,10 @@ export declare const SETTINGS_PROPERTY_POLICY: {
53
53
  readonly markdown: "include";
54
54
  readonly persistence: "include";
55
55
  };
56
+ readonly batchSaveInLiveSync: {
57
+ readonly markdown: "include";
58
+ readonly persistence: "include";
59
+ };
56
60
  readonly syncOnSave: {
57
61
  readonly markdown: "include";
58
62
  readonly persistence: "include";
@@ -61,6 +65,10 @@ export declare const SETTINGS_PROPERTY_POLICY: {
61
65
  readonly markdown: "include";
62
66
  readonly persistence: "include";
63
67
  };
68
+ readonly strictContentCheckOnStartup: {
69
+ readonly markdown: "omit";
70
+ readonly persistence: "include";
71
+ };
64
72
  readonly syncOnFileOpen: {
65
73
  readonly markdown: "include";
66
74
  readonly persistence: "include";
@@ -14,8 +14,10 @@ const SettingPolicies = {
14
14
  };
15
15
  const SETTINGS_PROPERTY_POLICY = {
16
16
  liveSync: SettingPolicies.Default,
17
+ batchSaveInLiveSync: SettingPolicies.Default,
17
18
  syncOnSave: SettingPolicies.Default,
18
19
  syncOnStart: SettingPolicies.Default,
20
+ strictContentCheckOnStartup: SettingPolicies.LocalOnly,
19
21
  syncOnFileOpen: SettingPolicies.Default,
20
22
  syncOnEditorSave: SettingPolicies.Default,
21
23
  keepReplicationActiveInBackground: SettingPolicies.Default,
@@ -80,6 +80,8 @@ interface SyncMethodSettings {
80
80
  * Synchronise in Live. This is an exclusive setting against other sync methods.
81
81
  */
82
82
  liveSync: boolean;
83
+ /** Explicitly enable batched local database updates in LiveSync mode; an absent value is false. */
84
+ batchSaveInLiveSync?: boolean;
83
85
  /**
84
86
  * automatically run sync on save.
85
87
  * File modification will trigger the sync, even if the file is not changed on the editor.
@@ -89,6 +91,10 @@ interface SyncMethodSettings {
89
91
  * automatically run sync on starting the plug-in.
90
92
  */
91
93
  syncOnStart: boolean;
94
+ /**
95
+ * Compare file contents during startup checks when modification time and size match.
96
+ */
97
+ strictContentCheckOnStartup?: boolean;
92
98
  /**
93
99
  * automatically run sync on opening a file.
94
100
  */
@@ -10,6 +10,24 @@ export declare const DatabaseConnectingStatuses: {
10
10
  readonly JOURNAL_RECEIVE: "JOURNAL_RECEIVE";
11
11
  };
12
12
  export type DatabaseConnectingStatus = (typeof DatabaseConnectingStatuses)[keyof typeof DatabaseConnectingStatuses];
13
+ /** The transfer stage; entering continuous replication does not imply Vault reflection is complete. */
14
+ export type CouchDBReplicationPhase = "idle" | "one-shot" | "catch-up" | "continuous";
15
+ export type ReplicationCheckpointProgress = {
16
+ /** Changes-feed entries presented for revision comparison, including repeated entries on retries. */
17
+ readonly checkedChanges: number;
18
+ /** Batches which reached PouchDB's checkpoint notification, including batches without transfers. */
19
+ readonly completedBatches: number;
20
+ /** Opaque processed position, not a remaining-document count or proof of durable checkpoint storage. */
21
+ readonly lastSeq?: string | number;
22
+ /** Revision comparison is progressing; this does not establish that network transfer has not begun. */
23
+ readonly checking: boolean;
24
+ };
25
+ /** Counters reset for each underlying PouchDB attempt, including the transition from catch-up to continuous. */
26
+ export type CouchDBReplicationProgress = {
27
+ readonly phase: CouchDBReplicationPhase;
28
+ readonly pull?: ReplicationCheckpointProgress;
29
+ readonly push?: ReplicationCheckpointProgress;
30
+ };
13
31
  export type ReplicationStatics = {
14
32
  sent: number;
15
33
  arrived: number;
@@ -18,5 +36,7 @@ export type ReplicationStatics = {
18
36
  lastSyncPullSeq: number;
19
37
  lastSyncPushSeq: number;
20
38
  syncStatus: DatabaseConnectingStatus;
39
+ /** Present only when the provider supplies CouchDB checkpoint observations. */
40
+ couchDB?: CouchDBReplicationProgress;
21
41
  };
22
42
  export declare const DEFAULT_REPLICATION_STATICS: ReplicationStatics;
@@ -142,8 +142,10 @@ export declare const TweakValuesTemplate: {
142
142
  enableCompression: boolean;
143
143
  handleFilenameCaseSensitive: boolean;
144
144
  liveSync?: boolean;
145
+ batchSaveInLiveSync?: boolean;
145
146
  syncOnSave?: boolean;
146
147
  syncOnStart?: boolean;
148
+ strictContentCheckOnStartup?: boolean;
147
149
  syncOnFileOpen?: boolean;
148
150
  syncOnEditorSave?: boolean;
149
151
  keepReplicationActiveInBackground?: boolean;
@@ -30,8 +30,10 @@ export declare const AllSettingDefault: {
30
30
  dummy: number;
31
31
  deviceAndVaultName: string;
32
32
  liveSync: boolean;
33
+ batchSaveInLiveSync?: boolean;
33
34
  syncOnSave: boolean;
34
35
  syncOnStart: boolean;
36
+ strictContentCheckOnStartup?: boolean;
35
37
  syncOnFileOpen: boolean;
36
38
  syncOnEditorSave: boolean;
37
39
  keepReplicationActiveInBackground: boolean;
@@ -104,6 +104,10 @@ const SettingInformation = {
104
104
  name: "Sync on Startup",
105
105
  desc: "Automatically Sync all files when opening Obsidian."
106
106
  },
107
+ strictContentCheckOnStartup: {
108
+ name: "Strict content check on startup",
109
+ desc: "Compare file contents even when modification time and size match. This can slow startup in large vaults."
110
+ },
107
111
  syncAfterMerge: {
108
112
  name: "Sync after merging file",
109
113
  desc: "Sync automatically after merging files"
@@ -144,6 +148,10 @@ const SettingInformation = {
144
148
  name: "Batch database update",
145
149
  desc: "Reducing the frequency with which on-disk changes are reflected into the DB"
146
150
  },
151
+ batchSaveInLiveSync: {
152
+ name: "Batch database updates in LiveSync mode",
153
+ desc: "Wait for a bounded local quiet period before processing file updates in LiveSync mode, reducing intermediate database updates while delaying their reflection to remote devices."
154
+ },
147
155
  readChunksOnline: {
148
156
  name: "Fetch chunks on demand",
149
157
  desc: "(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended."
@@ -313,11 +321,11 @@ const SettingInformation = {
313
321
  },
314
322
  batchSaveMinimumDelay: {
315
323
  name: "Minimum delay for batch database updating",
316
- desc: "Seconds. Saving to the local database will be delayed until this value after we stop typing or saving."
324
+ desc: "Seconds. The quiet period after the latest pending update before local database processing becomes due."
317
325
  },
318
326
  batchSaveMaximumDelay: {
319
327
  name: "Maximum delay for batch database updating",
320
- desc: "Saving will be performed forcefully after this number of seconds."
328
+ desc: "Seconds. The maximum intentional wait from the first pending update before local database processing becomes due. This does not guarantee when database processing, network delivery, or reflection to another device will complete."
321
329
  },
322
330
  notifyThresholdOfRemoteStorageSize: {
323
331
  name: "Notify when the estimated remote storage size exceeds on start up",
@@ -1,5 +1,9 @@
1
1
  import type { FilePath, FilePathWithPrefix, MetaEntry } from "../common/models/db.type.js";
2
2
  import type { UXFileInfo, UXFileInfoStub, UXInternalFileInfoStub } from "../common/models/fileaccess.type.js";
3
+ export interface StoreFileOptions {
4
+ /** Recheck storage and provenance, with bounded retries for recovery scans. */
5
+ revalidateStorage?: boolean;
6
+ }
3
7
  export interface IFileHandler {
4
8
  readFileFromStub(file: UXFileInfoStub | UXFileInfo): Promise<UXFileInfo>;
5
9
  /**
@@ -8,7 +12,9 @@ export interface IFileHandler {
8
12
  * operation never stores a document revision or writes to storage.
9
13
  */
10
14
  tryRecordUntrackedFileRevision(info: UXFileInfoStub | UXFileInfo, expectedRevision: string): Promise<boolean>;
11
- storeFileToDB(info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean): Promise<boolean>;
15
+ /** Metadata-only scan hint; never certifies content equality or changes provenance. */
16
+ canSkipUnchangedFile?(info: UXFileInfoStub, expected: MetaEntry): Promise<boolean>;
17
+ storeFileToDB(info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean, options?: StoreFileOptions): Promise<boolean>;
12
18
  /**
13
19
  * Store the current storage content as a child of an exact live database revision.
14
20
  *
@@ -12,6 +12,8 @@ export interface IStorageAccessManager {
12
12
  export interface StorageAccess {
13
13
  normalisePath(path: string): string;
14
14
  restoreState(): Promise<void>;
15
+ /** Includes queued, running, and failed work; absence requires a conservative content check. */
16
+ hasPendingFileEvent?(path: FilePath): boolean;
15
17
  deleteVaultItem(file: FilePathWithPrefix | UXFileInfoStub | UXFolderInfo): Promise<void>;
16
18
  renameFile(file: UXFileInfoStub | FilePathWithPrefix, newPath: FilePathWithPrefix): Promise<UXFileInfoStub | null>;
17
19
  writeFileAuto(path: string, data: string | ArrayBuffer, opt?: UXDataWriteOptions): Promise<boolean>;
@@ -11,6 +11,13 @@ export declare abstract class StorageEventManager {
11
11
  abstract beginWatch(): Promise<void>;
12
12
  abstract appendQueue(items: FileEvent[], ctx?: unknown): Promise<void>;
13
13
  abstract isWaiting(filename: FilePath): boolean;
14
+ /** Compatibility hosts without an ownership view must retain content checks. */
15
+ hasPendingFileEvent?(_filename: FilePath): boolean;
14
16
  abstract waitForIdle(): Promise<void>;
15
17
  abstract restoreState(): Promise<void>;
18
+ /**
19
+ * Complete accepted work before its storage closes. Custom hosts must stop
20
+ * their watcher admission before invoking this default implementation.
21
+ */
22
+ stopWatching?(): Promise<void>;
16
23
  }
@@ -1,4 +1,15 @@
1
1
  class StorageEventManager {
2
+ /** Compatibility hosts without an ownership view must retain content checks. */
3
+ hasPendingFileEvent(_filename) {
4
+ return true;
5
+ }
6
+ /**
7
+ * Complete accepted work before its storage closes. Custom hosts must stop
8
+ * their watcher admission before invoking this default implementation.
9
+ */
10
+ stopWatching() {
11
+ return this.waitForIdle();
12
+ }
2
13
  }
3
14
  export {
4
15
  StorageEventManager
@@ -71,26 +71,35 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
71
71
  * Restore and complete the previous storage-event snapshot when it exists.
72
72
  */
73
73
  restoreState(): Promise<void>;
74
+ private acceptingEvents;
75
+ private admissions;
74
76
  appendQueue(params: FileEvent[], ctx?: unknown): Promise<void>;
77
+ private appendQueueInternal;
75
78
  protected bufferedQueuedItems: (FileEventItem | FileEventItemSentinel)[];
79
+ private pendingSnapshot;
80
+ private operations;
81
+ private latestByPath;
82
+ private nextSequence;
83
+ private snapshotTail;
84
+ private dispatching;
85
+ private retainEvent;
86
+ private reportOperationFailure;
87
+ private failOperation;
76
88
  enqueue(newItem: FileEventItem): void;
77
- /**
78
- * Immediately take snapshot.
79
- */
80
89
  private _triggerTakeSnapshot;
81
- /**
82
- * Trigger taking snapshot after throttled period.
83
- */
84
90
  triggerTakeSnapshot: import("octagonal-wheels/function").ThrottledFunction<() => void>;
85
91
  protected concurrentProcessing: import("octagonal-wheels/concurrency/semaphore_v2").SemaphoreObject;
86
92
  protected _waitingMap: Map<string, WaitInfo>;
87
- private _waitForIdle;
93
+ private pendingOperations;
94
+ private releaseOperations;
95
+ private waitForOperations;
88
96
  /**
89
- * Wait until all queued events are processed.
90
- * Subsequent new events will not be waited, but new events will not be added.
91
- * @returns
97
+ * Complete the finite set of operations accepted before this call.
98
+ * Later edits cannot replace or extend that set while it is being flushed.
92
99
  */
93
100
  waitForIdle(): Promise<void>;
101
+ /** Stop watcher admission before draining or preserving accepted work. */
102
+ stopWatching(): Promise<void>;
94
103
  /**
95
104
  * Proceed waiting for the given key immediately.
96
105
  */
@@ -125,6 +134,7 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
125
134
  protected runQueuedEvents(options?: RunQueuedEventsOptions): Promise<void>;
126
135
  protected processingCount: number;
127
136
  protected requestProcessQueue(fei: FileEventItem): Promise<void>;
137
+ hasPendingFileEvent(filename: FilePath): boolean;
128
138
  isWaiting(filename: FilePath): boolean;
129
139
  protected handleFileEvent(queue: FileEventItem): Promise<void>;
130
140
  protected cancelRelativeEvent(item: FileEventItem): void;