@vrtmrz/livesync-commonlib 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +43 -0
  2. package/dist/API/processSetting.d.ts +1 -0
  3. package/dist/common/models/setting.const.defaults.js +1 -0
  4. package/dist/common/models/setting.const.qr.js +1 -0
  5. package/dist/common/models/setting.policy.d.ts +4 -0
  6. package/dist/common/models/setting.policy.js +1 -0
  7. package/dist/common/models/setting.type.d.ts +2 -0
  8. package/dist/common/models/shared.definition.d.ts +20 -0
  9. package/dist/common/models/tweak.definition.d.ts +1 -0
  10. package/dist/common/settingConstants.d.ts +1 -0
  11. package/dist/common/settingConstants.js +6 -2
  12. package/dist/interfaces/FileHandler.d.ts +5 -1
  13. package/dist/interfaces/StorageEventManager.d.ts +5 -0
  14. package/dist/interfaces/StorageEventManager.js +7 -0
  15. package/dist/managers/StorageEventManager.d.ts +19 -10
  16. package/dist/managers/StorageEventManager.js +259 -189
  17. package/dist/replication/LiveSyncAbstractReplicator.d.ts +2 -0
  18. package/dist/replication/LiveSyncAbstractReplicator.js +5 -2
  19. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +6 -0
  20. package/dist/replication/couchdb/LiveSyncReplicator.js +39 -2
  21. package/dist/replication/couchdb/replicationProgress.d.ts +6 -0
  22. package/dist/replication/couchdb/replicationProgress.js +105 -0
  23. package/dist/replication/index.d.ts +1 -0
  24. package/dist/replication/trystero/TrysteroReplicator.d.ts +2 -0
  25. package/dist/serviceFeatures/offlineScanner.js +19 -7
  26. package/dist/serviceModules/ServiceFileAccessBase.js +5 -0
  27. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +8 -5
  28. package/dist/serviceModules/ServiceFileHandlerBase.js +75 -38
  29. package/dist/services/base/AppLifecycleService.js +1 -1
  30. package/dist/services/base/ControlService.js +6 -2
  31. package/dist/services/base/FileProcessingService.d.ts +7 -1
  32. package/dist/services/base/FileProcessingService.js +9 -1
  33. package/dist/services/base/IService.d.ts +9 -1
  34. package/dist/services/base/ReplicatorService.d.ts +1 -0
  35. package/dist/services/lib/HandlerUtils.d.ts +60 -0
  36. package/dist/services/lib/HandlerUtils.js +46 -0
  37. package/dist/worker/bgWorker.js +1 -1
  38. package/docs/offline-scanner.md +15 -13
  39. package/docs/settings-lifecycle.md +2 -0
  40. package/docs/storage-events-and-reflection.md +109 -10
  41. 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,6 +59,7 @@ 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;
64
65
  syncOnFileOpen: boolean;
@@ -40,6 +40,7 @@ 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,
45
46
  savingDelay: 200,
@@ -181,6 +181,7 @@ const KeyIndexOfSettings = {
181
181
  idDerivationVersion: 166,
182
182
  idDerivationKey: 167,
183
183
  pathNormalizationVersion: 168,
184
+ batchSaveInLiveSync: 169,
184
185
  encryptedIdDerivationKey: -1
185
186
  };
186
187
  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";
@@ -14,6 +14,7 @@ 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,
19
20
  syncOnFileOpen: 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.
@@ -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,6 +142,7 @@ 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;
147
148
  syncOnFileOpen?: boolean;
@@ -30,6 +30,7 @@ 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;
35
36
  syncOnFileOpen: boolean;
@@ -144,6 +144,10 @@ const SettingInformation = {
144
144
  name: "Batch database update",
145
145
  desc: "Reducing the frequency with which on-disk changes are reflected into the DB"
146
146
  },
147
+ batchSaveInLiveSync: {
148
+ name: "Batch database updates in LiveSync mode",
149
+ 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."
150
+ },
147
151
  readChunksOnline: {
148
152
  name: "Fetch chunks on demand",
149
153
  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 +317,11 @@ const SettingInformation = {
313
317
  },
314
318
  batchSaveMinimumDelay: {
315
319
  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."
320
+ desc: "Seconds. The quiet period after the latest pending update before local database processing becomes due."
317
321
  },
318
322
  batchSaveMaximumDelay: {
319
323
  name: "Maximum delay for batch database updating",
320
- desc: "Saving will be performed forcefully after this number of seconds."
324
+ 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
325
  },
322
326
  notifyThresholdOfRemoteStorageSize: {
323
327
  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,7 @@ 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
+ storeFileToDB(info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean, options?: StoreFileOptions): Promise<boolean>;
12
16
  /**
13
17
  * Store the current storage content as a child of an exact live database revision.
14
18
  *
@@ -13,4 +13,9 @@ export declare abstract class StorageEventManager {
13
13
  abstract isWaiting(filename: FilePath): boolean;
14
14
  abstract waitForIdle(): Promise<void>;
15
15
  abstract restoreState(): Promise<void>;
16
+ /**
17
+ * Complete accepted work before its storage closes. Custom hosts must stop
18
+ * their watcher admission before invoking this default implementation.
19
+ */
20
+ stopWatching?(): Promise<void>;
16
21
  }
@@ -1,4 +1,11 @@
1
1
  class StorageEventManager {
2
+ /**
3
+ * Complete accepted work before its storage closes. Custom hosts must stop
4
+ * their watcher admission before invoking this default implementation.
5
+ */
6
+ stopWatching() {
7
+ return this.waitForIdle();
8
+ }
2
9
  }
3
10
  export {
4
11
  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
  */