@vrtmrz/livesync-commonlib 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +29 -19
  2. package/dist/common/models/shared.definition.d.ts +10 -1
  3. package/dist/common/models/shared.definition.js +4 -3
  4. package/dist/events/coreEvents.d.ts +3 -0
  5. package/dist/events/coreEvents.js +2 -0
  6. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  7. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  8. package/dist/managers/EntryManager/EntryManager.d.ts +1 -1
  9. package/dist/managers/EntryManager/EntryManager.js +2 -2
  10. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +1 -1
  11. package/dist/managers/EntryManager/EntryManagerImpls.js +80 -8
  12. package/dist/managers/StorageEventManager/admission.d.ts +16 -3
  13. package/dist/managers/StorageEventManager/admission.js +18 -4
  14. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  15. package/dist/managers/StorageEventManager/processing.js +3 -3
  16. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  17. package/dist/managers/StorageEventManager/queue.js +70 -30
  18. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  19. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  20. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  21. package/dist/managers/StorageEventManager/state.js +9 -7
  22. package/dist/managers/StorageEventManager.d.ts +8 -0
  23. package/dist/managers/StorageEventManager.js +136 -18
  24. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  25. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  26. package/dist/managers/adapters/index.d.ts +1 -1
  27. package/dist/pouchdb/LiveSyncLocalDB.d.ts +1 -1
  28. package/dist/pouchdb/LiveSyncLocalDB.js +2 -2
  29. package/dist/replication/LiveSyncAbstractReplicator.d.ts +7 -0
  30. package/dist/replication/LiveSyncAbstractReplicator.js +5 -2
  31. package/dist/replication/ReplicatorInstance.d.ts +3 -0
  32. package/dist/replication/ReplicatorProvider.d.ts +23 -2
  33. package/dist/replication/ReplicatorProvider.js +10 -0
  34. package/dist/replication/SyncParamsHandler.js +26 -25
  35. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +14 -2
  36. package/dist/replication/couchdb/LiveSyncReplicator.js +247 -122
  37. package/dist/replication/index.d.ts +4 -2
  38. package/dist/replication/index.js +6 -0
  39. package/dist/replication/remoteTransportFailure.d.ts +24 -0
  40. package/dist/replication/remoteTransportFailure.js +80 -0
  41. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +1 -1
  42. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +2 -2
  43. package/dist/replication/trystero/TrysteroRpcRoom.d.ts +14 -0
  44. package/dist/replication/trystero/TrysteroRpcRoom.js +168 -0
  45. package/dist/replication/trystero/rpcCompat.d.ts +1 -0
  46. package/dist/replication/trystero/rpcCompat.js +15 -0
  47. package/dist/rpc/RpcRoom.d.ts +1 -0
  48. package/dist/rpc/RpcRoom.js +21 -9
  49. package/dist/rpc/RpcSession.d.ts +8 -13
  50. package/dist/rpc/RpcSession.js +14 -35
  51. package/dist/rpc/commonlibRpcRoom.d.ts +1 -0
  52. package/dist/rpc/commonlibRpcRoom.js +4 -0
  53. package/dist/rpc/errors.d.ts +9 -3
  54. package/dist/rpc/errors.js +13 -16
  55. package/dist/rpc/index.d.ts +10 -1
  56. package/dist/rpc/index.js +2 -1
  57. package/dist/rpc/pouchdb/RpcPouchDBProxy.d.ts +1 -1
  58. package/dist/rpc/pouchdb/RpcPouchDBServer.d.ts +1 -1
  59. package/dist/serviceFeatures/targetFilter.d.ts +3 -1
  60. package/dist/serviceFeatures/targetFilter.js +2 -2
  61. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +5 -2
  62. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -4
  63. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +28 -0
  64. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +53 -0
  65. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +59 -3
  66. package/dist/services/base/IService.d.ts +9 -6
  67. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  68. package/dist/services/base/ReadinessEvaluator.d.ts +7 -6
  69. package/dist/services/base/ReadinessEvaluator.js +4 -2
  70. package/dist/services/base/RemoteConnection.d.ts +4 -0
  71. package/dist/services/base/RemoteService.d.ts +5 -3
  72. package/dist/services/base/RemoteService.js +85 -33
  73. package/dist/services/base/ReplicationService.d.ts +10 -2
  74. package/dist/services/base/ReplicationService.js +13 -7
  75. package/dist/services/base/ReplicationService.readiness.d.ts +14 -4
  76. package/dist/services/base/ReplicationService.readiness.js +29 -2
  77. package/dist/services/base/ReplicationService.typedReplication.d.ts +5 -2
  78. package/dist/services/base/ReplicationService.typedReplication.js +67 -6
  79. package/dist/services/base/ReplicationStaticsOwner.d.ts +18 -0
  80. package/dist/services/base/ReplicationStaticsOwner.js +33 -0
  81. package/dist/services/base/ReplicatorService.d.ts +2 -10
  82. package/dist/services/base/ReplicatorService.js +6 -3
  83. package/dist/services/base/VaultService.d.ts +1 -0
  84. package/dist/string_and_binary/chunks.d.ts +1 -1
  85. package/dist/string_and_binary/chunks.js +63 -50
  86. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  87. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  88. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  89. package/dist/worker/WorkerPushStreamReader.js +179 -0
  90. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  91. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  92. package/dist/worker/bg.worker.js +2 -14
  93. package/dist/worker/bg.worker.splitting.d.ts +3 -6
  94. package/dist/worker/bg.worker.splitting.js +65 -30
  95. package/dist/worker/bgWorker.d.ts +9 -11
  96. package/dist/worker/bgWorker.direct.d.ts +5 -28
  97. package/dist/worker/bgWorker.direct.js +32 -2
  98. package/dist/worker/bgWorker.errors.d.ts +1 -0
  99. package/dist/worker/bgWorker.errors.js +12 -0
  100. package/dist/worker/bgWorker.js +718 -268
  101. package/dist/worker/bgWorker.splitting.d.ts +12 -27
  102. package/dist/worker/bgWorker.splitting.js +114 -110
  103. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  104. package/dist/worker/outOfBandCancelIterator.js +8 -0
  105. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  106. package/dist/worker/serveBackgroundWorker.js +35 -0
  107. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  108. package/dist/worker/splitConnectionTracker.js +73 -0
  109. package/dist/worker/splitGate.d.ts +19 -0
  110. package/dist/worker/splitGate.js +71 -0
  111. package/dist/worker/universalTypes.d.ts +1 -19
  112. package/dist/worker/universalTypes.js +0 -4
  113. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  114. package/dist/worker/workerPushStreamProtocol.js +143 -0
  115. package/docs/development.md +75 -32
  116. package/docs/p2p-transport-lifecycle.md +2 -3
  117. package/docs/storage-events-and-reflection.md +40 -5
  118. package/package.json +3 -2
  119. package/dist/worker/bg.common.d.ts +0 -2
  120. package/dist/worker/bg.common.js +0 -6
  121. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  122. package/dist/worker/bg.worker.encryption.js +0 -30
  123. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  124. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -8,7 +8,14 @@ import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
8
8
  import { promiseWithResolvers } from "octagonal-wheels/promises";
9
9
  import { StorageEventManager } from "../interfaces/StorageEventManager.js";
10
10
  import { createInstanceLogFunction } from "../services/lib/logUtils.js";
11
- import { admitStorageEvents } from "./StorageEventManager/admission.js";
11
+ import {
12
+ assertSuccessfulFileEvents
13
+ } from "./StorageEventManager/operations.js";
14
+ import {
15
+ admitStorageEvents,
16
+ registerAdmission,
17
+ trackStorageEventAdmission
18
+ } from "./StorageEventManager/admission.js";
12
19
  import {
13
20
  forwardVaultEvent,
14
21
  hasEditorChangePath,
@@ -23,6 +30,8 @@ import {
23
30
  import {
24
31
  enqueueStorageEvent,
25
32
  flushStorageEvents,
33
+ publishCommittedStorageEvents,
34
+ restoreOrderedStorageEvents,
26
35
  restoreStorageEvents,
27
36
  runBufferedStorageEvents
28
37
  } from "./StorageEventManager/queue.js";
@@ -30,7 +39,12 @@ import {
30
39
  captureFileEventAttempts,
31
40
  waitForFileEventAttempts
32
41
  } from "./StorageEventManager/retry.js";
33
- import { persistFileEventSnapshot } from "./StorageEventManager/snapshot.js";
42
+ import {
43
+ acknowledgeEmptyOrderedBuffer,
44
+ acknowledgeOrderedEntry,
45
+ appendPendingEventBuffer,
46
+ persistFileEventSnapshot
47
+ } from "./StorageEventManager/snapshot.js";
34
48
  import {
35
49
  handleStorageFileEvent,
36
50
  processStorageEventAttempt
@@ -52,7 +66,9 @@ class StorageEventManagerBase extends StorageEventManager {
52
66
  concurrentProcessing = Semaphore(5);
53
67
  _waitingMap = /* @__PURE__ */ new Map();
54
68
  processingCount = 0;
55
- eventState = createStorageEventState();
69
+ eventState;
70
+ orderedStoreLoaded = false;
71
+ orderedStoreLoad;
56
72
  dispatchPaused = false;
57
73
  dispatchResumeSignal;
58
74
  activeDispatches = /* @__PURE__ */ new Set();
@@ -64,7 +80,14 @@ class StorageEventManagerBase extends StorageEventManager {
64
80
  append: (event) => {
65
81
  this.bufferedQueuedItems.push(event);
66
82
  },
67
- shift: () => this.bufferedQueuedItems.shift()
83
+ peek: () => this.bufferedQueuedItems[0],
84
+ takeHead: (expected) => {
85
+ if (this.bufferedQueuedItems[0] !== expected) {
86
+ return false;
87
+ }
88
+ this.bufferedQueuedItems.shift();
89
+ return true;
90
+ }
68
91
  };
69
92
  notifications = {
70
93
  updateStatus: () => this.updateStatus(),
@@ -107,6 +130,17 @@ class StorageEventManagerBase extends StorageEventManager {
107
130
  wait: (attempts) => this.waitForAttempts(attempts),
108
131
  fail: (operation, error, attempt) => this.failOperation(operation, error, attempt)
109
132
  };
133
+ orderedAppend = {
134
+ publish: (events) => publishCommittedStorageEvents(this.eventState, events, this.queue),
135
+ reportAppendFailure: (error) => {
136
+ this._log(
137
+ "Some local file changes could not be queued for sync. Once file activity settles, rescan the Vault to check the current files.",
138
+ LOG_LEVEL_NOTICE
139
+ );
140
+ this._log(error, LOG_LEVEL_VERBOSE);
141
+ this.updateStatus();
142
+ }
143
+ };
110
144
  admission = {
111
145
  settings: () => this.settings,
112
146
  isFolder: (file) => this.isFolder(file),
@@ -155,8 +189,14 @@ class StorageEventManagerBase extends StorageEventManager {
155
189
  constructor(adapter, dependencies) {
156
190
  super();
157
191
  this.adapter = adapter;
192
+ this.eventState = createStorageEventState(adapter.pendingEventStore);
193
+ const ordered = this.eventState.ordered;
194
+ if (ordered) {
195
+ this.queue.acknowledgeSentinel = (entry) => acknowledgeOrderedEntry(this.eventState, ordered, entry, this.notifications.updateStatus);
196
+ }
158
197
  this.setting = dependencies.setting;
159
198
  this.vaultService = dependencies.vaultService;
199
+ this.admission.isTargetInternal = dependencies.isTargetInternalFile?.bind(dependencies);
160
200
  this.fileProcessing = dependencies.fileProcessing;
161
201
  this.storageAccess = dependencies.storageAccessManager;
162
202
  this._log = createInstanceLogFunction("StorageEventManager", dependencies.APIService);
@@ -237,9 +277,7 @@ class StorageEventManagerBase extends StorageEventManager {
237
277
  this.adapter.status.updateStatus({
238
278
  batched: this._waitingMap.size,
239
279
  processing: this.processingCount,
240
- totalQueued: [...this.eventState.pendingSnapshot.values()].filter(
241
- (entry) => entry.operation && !entry.completed
242
- ).length
280
+ totalQueued: this.eventState.ordered?.pendingOperations ?? [...this.eventState.pendingSnapshot.values()].filter((entry) => entry.operation && !entry.completed).length
243
281
  });
244
282
  }
245
283
  /** Completes restored operations before the host starts watching. */
@@ -249,8 +287,16 @@ class StorageEventManagerBase extends StorageEventManager {
249
287
  * @returns A promise fulfilled after restoration and replay attempts settle; snapshot or dispatch errors reject it, while failed operation results are reported and retained.
250
288
  */
251
289
  restoreState() {
252
- this.snapShotRestored = this._restoreFromSnapshot();
253
- return this.snapShotRestored;
290
+ if (this.eventState.ordered && this.snapShotRestored) return this.snapShotRestored;
291
+ const restore = this._restoreFromSnapshot();
292
+ this.snapShotRestored = restore;
293
+ if (this.eventState.ordered) {
294
+ const clear = () => {
295
+ this.snapShotRestored = null;
296
+ };
297
+ void restore.then(clear, clear);
298
+ }
299
+ return restore;
254
300
  }
255
301
  /**
256
302
  * Filter and admit host watcher events into the operation queue.
@@ -260,14 +306,18 @@ class StorageEventManagerBase extends StorageEventManager {
260
306
  * @remarks The promise may resolve while admitted handlers are still pending. Use `waitForIdle` for the captured processing boundary.
261
307
  */
262
308
  appendQueue(params, ctx) {
263
- return admitStorageEvents(this.eventState, params, ctx, this.admission);
309
+ return admitStorageEvents(this.eventState, params, ctx, this.admission, () => this.loadOrderedEvents());
264
310
  }
265
311
  /**
266
312
  * Add an already selected event to the buffer and start background snapshotting and dispatch.
267
313
  * @param event - The event which has already passed host admission checks.
268
314
  * @returns Nothing; processing and persistence failures are reported through manager effects.
315
+ * @remarks Ordered stores must have completed their initial load. Append watcher events through `appendQueue`.
269
316
  */
270
317
  enqueue(event) {
318
+ if (this.eventState.ordered && !this.orderedStoreLoaded) {
319
+ throw new Error("Load the pending storage events before enqueueing an event");
320
+ }
271
321
  enqueueStorageEvent(this.eventState, event, this.queue);
272
322
  }
273
323
  /**
@@ -276,7 +326,7 @@ class StorageEventManagerBase extends StorageEventManager {
276
326
  * @remarks Later admissions are outside this flush boundary. Batch gates in the captured work are released before waiting.
277
327
  */
278
328
  async waitForIdle() {
279
- await flushStorageEvents(this.eventState, this.queue);
329
+ await flushStorageEvents(this.eventState, this.queue, this.orderedStoreLoad);
280
330
  }
281
331
  /**
282
332
  * Pause new file-handler dispatch and wait for dispatches already in progress.
@@ -310,8 +360,13 @@ class StorageEventManagerBase extends StorageEventManager {
310
360
  try {
311
361
  await this.waitForIdle();
312
362
  } catch (error) {
313
- this.reportOperationFailure(error);
363
+ if (!this.eventState.ordered) {
364
+ this.reportOperationFailure(error);
365
+ } else {
366
+ this._log(error, LOG_LEVEL_VERBOSE);
367
+ }
314
368
  }
369
+ if (this.eventState.ordered) await this.runQueuedEvents().catch(this.notifications.reportFailure);
315
370
  await this._takeSnapshot();
316
371
  }
317
372
  /**
@@ -455,8 +510,22 @@ class StorageEventManagerBase extends StorageEventManager {
455
510
  * @returns A promise fulfilled when the attempt completes; a failed attempt rejects it.
456
511
  */
457
512
  async processFileEvent(event) {
458
- const operation = this.retainEvent(event).operation;
459
- await this.processOperation(operation, operation.attempt);
513
+ if (!this.eventState.ordered) {
514
+ const operation = this.retainEvent(event).operation;
515
+ await this.processOperation(operation, operation.attempt);
516
+ return;
517
+ }
518
+ const existing = this.operations.get(event);
519
+ if (existing) {
520
+ await this.processOperation(existing, existing.attempt);
521
+ return;
522
+ }
523
+ let attempt;
524
+ await trackStorageEventAdmission(this.eventState, this.admission, async (admission) => {
525
+ await this.loadOrderedEvents();
526
+ attempt = this.operations.get(event)?.attempt ?? registerAdmission(this.eventState, admission, event, this.admission);
527
+ });
528
+ if (attempt) assertSuccessfulFileEvents([await attempt.completion.promise]);
460
529
  }
461
530
  /**
462
531
  * Persist the manager snapshot and optionally acknowledge one attempt in that snapshot.
@@ -464,7 +533,16 @@ class StorageEventManagerBase extends StorageEventManager {
464
533
  * @returns A promise for the serialised save; snapshot I/O failures reject it.
465
534
  */
466
535
  persistSnapshot(completion) {
467
- return persistFileEventSnapshot(this.eventState, this.buffer, this.snapshotIO, completion);
536
+ const ordered = this.eventState.ordered;
537
+ if (!ordered) return persistFileEventSnapshot(this.eventState, this.buffer, this.snapshotIO, completion);
538
+ if (!completion) return appendPendingEventBuffer(this.eventState, ordered, this.orderedAppend);
539
+ return acknowledgeOrderedEntry(
540
+ this.eventState,
541
+ ordered,
542
+ completion.entry,
543
+ this.notifications.updateStatus,
544
+ completion
545
+ );
468
546
  }
469
547
  /**
470
548
  * Wait for the next serialised snapshot write.
@@ -478,7 +556,41 @@ class StorageEventManagerBase extends StorageEventManager {
478
556
  * @returns A promise for restoration; storage or dispatch errors reject it, while failed attempt results are reported and retained.
479
557
  */
480
558
  async _restoreFromSnapshot() {
481
- await restoreStorageEvents(this.queue);
559
+ if (!this.eventState.ordered) {
560
+ await restoreStorageEvents(this.queue);
561
+ return;
562
+ }
563
+ if (!this.eventState.acceptingEvents) return;
564
+ await this.loadOrderedEvents();
565
+ await this.runQueuedEvents({ waitForProcessing: true });
566
+ }
567
+ /** Join the initial load without waiting for restored handlers. */
568
+ loadOrderedEvents() {
569
+ const ordered = this.eventState.ordered;
570
+ if (!ordered || this.orderedStoreLoaded) return;
571
+ if (this.orderedStoreLoad) return this.orderedStoreLoad;
572
+ const load = Promise.resolve().then(async () => {
573
+ const buffers = await ordered.store.load();
574
+ for (const { key, events } of buffers) {
575
+ if (events.length === 0) {
576
+ await acknowledgeEmptyOrderedBuffer(this.eventState, ordered, key).catch(
577
+ this.notifications.reportFailure
578
+ );
579
+ }
580
+ }
581
+ const operations = restoreOrderedStorageEvents(this.eventState, this.queue, buffers);
582
+ this.orderedStoreLoaded = true;
583
+ if (this.eventState.acceptingEvents) {
584
+ fireAndForget(this.runQueuedEvents().catch(this.notifications.reportFailure));
585
+ }
586
+ return operations;
587
+ });
588
+ this.orderedStoreLoad = load;
589
+ const clear = () => {
590
+ this.orderedStoreLoad = void 0;
591
+ };
592
+ void load.then(clear, clear);
593
+ return load;
482
594
  }
483
595
  /**
484
596
  * Dispatch events in the buffer and optionally wait for captured processing attempts.
@@ -493,7 +605,8 @@ class StorageEventManagerBase extends StorageEventManager {
493
605
  * @returns Nothing; the write is deliberately not awaited by the caller.
494
606
  */
495
607
  _triggerTakeSnapshot() {
496
- fireAndForget(() => this._takeSnapshot().catch((error) => this.reportOperationFailure(error)));
608
+ const snapshot = this._takeSnapshot();
609
+ fireAndForget(this.eventState.ordered ? snapshot : snapshot.catch(this.notifications.reportFailure));
497
610
  }
498
611
  /**
499
612
  * Throttled callback for requesting a background snapshot write.
@@ -537,7 +650,12 @@ class StorageEventManagerBase extends StorageEventManager {
537
650
  * @returns A promise fulfilled when watcher registration finishes; a restoration failure prevents registration and rejects it.
538
651
  */
539
652
  async beginWatch() {
540
- await this.snapShotRestored;
653
+ if (this.eventState.ordered) {
654
+ await this.restoreState();
655
+ } else {
656
+ await this.snapShotRestored;
657
+ }
658
+ if (this.eventState.ordered && !this.eventState.acceptingEvents) return;
541
659
  await this.adapter.watch.beginWatch({
542
660
  onCreate: (file, ctx) => this.watchVaultCreate(file, ctx),
543
661
  onChange: (file, ctx) => this.watchVaultChange(file, ctx),
@@ -1,5 +1,5 @@
1
1
  import type { IStorageEventTypeGuardAdapter } from "./IStorageEventTypeGuardAdapter.js";
2
- import type { IStorageEventPersistenceAdapter } from "./IStorageEventPersistenceAdapter.js";
2
+ import type { IStorageEventPersistenceAdapter, PendingStorageEventStore } from "./IStorageEventPersistenceAdapter.js";
3
3
  import type { IStorageEventWatchAdapter } from "./IStorageEventWatchAdapter.js";
4
4
  import type { IStorageEventStatusAdapter } from "./IStorageEventStatusAdapter.js";
5
5
  import type { IStorageEventConverterAdapter } from "./IStorageEventConverterAdapter.js";
@@ -12,6 +12,8 @@ import type { IStorageEventConverterAdapter } from "./IStorageEventConverterAdap
12
12
  export interface IStorageEventManagerAdapter<TFile, TFolder> {
13
13
  readonly typeGuard: IStorageEventTypeGuardAdapter<TFile, TFolder>;
14
14
  readonly persistence: IStorageEventPersistenceAdapter;
15
+ /** Select the ordered store when the host can persist separate event buffers. */
16
+ readonly pendingEventStore?: PendingStorageEventStore;
15
17
  readonly watch: IStorageEventWatchAdapter<TFile, unknown>;
16
18
  readonly status: IStorageEventStatusAdapter;
17
19
  readonly converter: IStorageEventConverterAdapter<TFile>;
@@ -1,5 +1,21 @@
1
1
  import type { FileEventItem } from "../../common/types.js";
2
2
  import type { FileEventItemSentinel } from "../StorageEventManager.js";
3
+ export interface PendingStorageEventBuffer {
4
+ readonly key: string;
5
+ readonly events: readonly (FileEventItem | FileEventItemSentinel)[];
6
+ }
7
+ /** Store immutable buffers of pending event intents. */
8
+ export interface PendingStorageEventStore {
9
+ /** Load buffers in replay order, with any legacy snapshot first. */
10
+ load(): Promise<readonly PendingStorageEventBuffer[]>;
11
+ /**
12
+ * Save the whole buffer atomically and return its unique key after the write commits.
13
+ * A rejected append leaves the store unchanged.
14
+ */
15
+ append(events: PendingStorageEventBuffer["events"]): Promise<string>;
16
+ /** Remove the buffer under the supplied key after all of its entries have completed. */
17
+ remove(key: string): Promise<void>;
18
+ }
3
19
  /**
4
20
  * Adapter interface for snapshot persistence operations
5
21
  */
@@ -1,5 +1,5 @@
1
1
  export type { IStorageEventTypeGuardAdapter } from "./IStorageEventTypeGuardAdapter.js";
2
- export type { IStorageEventPersistenceAdapter } from "./IStorageEventPersistenceAdapter.js";
2
+ export type { IStorageEventPersistenceAdapter, PendingStorageEventBuffer, PendingStorageEventStore, } from "./IStorageEventPersistenceAdapter.js";
3
3
  export type { IStorageEventWatchAdapter, IStorageEventWatchHandlers } from "./IStorageEventWatchAdapter.js";
4
4
  export type { IStorageEventStatusAdapter } from "./IStorageEventStatusAdapter.js";
5
5
  export type { IStorageEventConverterAdapter } from "./IStorageEventConverterAdapter.js";
@@ -230,7 +230,7 @@ export declare class LiveSyncLocalDB {
230
230
  /** Read a raw document listing with caller-wait retirement owned by this database. */
231
231
  allDocsRaw<T extends EntryDoc | DatabaseEntry>(options?: PouchDB.Core.AllDocsWithKeyOptions | PouchDB.Core.AllDocsWithKeysOptions | PouchDB.Core.AllDocsWithinRangeOptions | PouchDB.Core.AllDocsOptions): Promise<PouchDB.Core.AllDocsResponse<T>>;
232
232
  bulkDocsRaw<T extends EntryDoc>(docs: Array<PouchDB.Core.PutDocument<T>>, options?: PouchDB.Core.BulkDocsOptions): Promise<Array<PouchDB.Core.Response | PouchDB.Core.Error>>;
233
- isTargetFile(filenameSrc: string): boolean;
233
+ isTargetFile(filenameSrc: string, internalFileEvent?: boolean): boolean;
234
234
  getDBEntryMeta(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
235
235
  getDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, dump?: boolean, waitForReady?: boolean, includeDeleted?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
236
236
  readDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, dump?: boolean, waitForReady?: boolean, includeDeleted?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
@@ -493,8 +493,8 @@ class LiveSyncLocalDB {
493
493
  return this.localDatabase.bulkDocs(docs, options || {});
494
494
  }
495
495
  // For compatibility
496
- isTargetFile(filenameSrc) {
497
- return this.managers.entryManager.isTargetFile(filenameSrc);
496
+ isTargetFile(filenameSrc, internalFileEvent = false) {
497
+ return this.managers.entryManager.isTargetFile(filenameSrc, internalFileEvent);
498
498
  }
499
499
  async getDBEntryMeta(path, opt, includeDeleted = false) {
500
500
  return await this.managers.entryManager.getDBEntryMeta(path, opt, includeDeleted);
@@ -5,6 +5,12 @@ import type { TranslationParameters } from "../services/base/MessageTranslator.j
5
5
  import type { CommonlibMessageKey } from "../services/base/CommonlibMessages.js";
6
6
  import type { ReplicatorInstance } from "./ReplicatorInstance.js";
7
7
  export type ReplicationCallback = (e: PouchDB.Core.ExistingDocument<EntryDoc>[]) => Promise<boolean> | boolean;
8
+ export type SecuritySeedPreparationResult = {
9
+ ready: true;
10
+ } | {
11
+ ready: false;
12
+ error: unknown;
13
+ };
8
14
  export type ReplicationStat = {
9
15
  sent: number;
10
16
  arrived: number;
@@ -58,6 +64,7 @@ export declare abstract class LiveSyncAbstractReplicator implements ReplicatorIn
58
64
  sendChunks(setting: RemoteDBSettings, remoteDB: PouchDB.Database<EntryDoc> | undefined, showResult: boolean, fromSeq?: number | string): Promise<boolean>;
59
65
  abstract getReplicationPBKDF2Salt(setting: RemoteDBSettings, refresh?: boolean): Promise<Uint8Array<ArrayBuffer>>;
60
66
  ensurePBKDF2Salt(setting: RemoteDBSettings, showMessage?: boolean, useCache?: boolean): Promise<boolean>;
67
+ protected prepareSecuritySeed(setting: RemoteDBSettings, showMessage: boolean, useCache: boolean): Promise<SecuritySeedPreparationResult>;
61
68
  env: LiveSyncReplicatorEnv;
62
69
  initializeDatabaseForReplication(): Promise<boolean>;
63
70
  constructor(env: LiveSyncReplicatorEnv);
@@ -37,18 +37,21 @@ class LiveSyncAbstractReplicator {
37
37
  return Promise.resolve(true);
38
38
  }
39
39
  async ensurePBKDF2Salt(setting, showMessage = false, useCache = true) {
40
+ return (await this.prepareSecuritySeed(setting, showMessage, useCache)).ready;
41
+ }
42
+ async prepareSecuritySeed(setting, showMessage, useCache) {
40
43
  try {
41
44
  const hash = await this.getReplicationPBKDF2Salt(setting, !useCache);
42
45
  if (hash.length == 0) {
43
46
  throw new Error("PBKDF2 salt (Security Seed) is empty");
44
47
  }
45
48
  Logger(`PBKDF2 salt (Security Seed): ${await arrayBufferToBase64Single(hash)}`, LOG_LEVEL_VERBOSE);
46
- return true;
49
+ return { ready: true };
47
50
  } catch (ex) {
48
51
  const level = showMessage ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
49
52
  Logger(`Failed to obtain PBKDF2 salt (Security Seed) for replication`, level);
50
53
  Logger(ex, LOG_LEVEL_VERBOSE);
51
- return false;
54
+ return { ready: false, error: ex };
52
55
  }
53
56
  }
54
57
  env;
@@ -1,4 +1,5 @@
1
1
  import type { RemoteDBSettings } from "../common/types.js";
2
+ import type { ContinuousReplicationStartResult } from "./ReplicatorProvider.js";
2
3
  /**
3
4
  * Minimal lifecycle contract shared by active Replicator instances.
4
5
  *
@@ -16,6 +17,8 @@ export interface ReplicatorInstance {
16
17
  * compatibility result to a typed outcome before exposing it to callers.
17
18
  */
18
19
  openReplication(setting: RemoteDBSettings, keepAlive: boolean, showResult: boolean, ignoreCleanLock: boolean): Promise<void | boolean>;
20
+ /** Admit a continuous task and report when its initial handoff settles. */
21
+ startContinuousReplication?(setting: RemoteDBSettings, onStartSettled: (result: ContinuousReplicationStartResult) => void): Promise<void | boolean>;
19
22
  /** Stop active transfer work; providers may settle this synchronously. */
20
23
  terminateSync(): void | Promise<void>;
21
24
  /** Close the instance; providers may settle this synchronously. */
@@ -15,7 +15,7 @@ export type { CapabilitySupport, NotApplicableCapability, NotImplementedCapabili
15
15
  */
16
16
  export type UnattendedReplicationTrigger = "resume" | "periodic" | "database-event" | "editor-save" | "file-open" | "merge" | "daemon";
17
17
  /** Automatic trigger which may start or resume a long-lived connection. */
18
- export type ContinuousReplicationTrigger = "resume" | "daemon";
18
+ export type ContinuousReplicationTrigger = "resume" | "daemon" | "online";
19
19
  /** No user interaction may be requested by an unattended replication path. */
20
20
  export declare const NO_INTERACTION: Readonly<{
21
21
  readonly kind: "forbidden";
@@ -91,10 +91,30 @@ export interface UnattendedOneShotRequest {
91
91
  readonly trigger: UnattendedReplicationTrigger;
92
92
  readonly interaction: NoInteraction;
93
93
  }
94
+ export interface ContinuousReplicationNetworkFailure {
95
+ readonly reason: "offline" | "remote-transport";
96
+ readonly hostOnlineAtFailure: boolean;
97
+ readonly failedAt: number;
98
+ }
99
+ /** A preparation gate can return the observation which caused it to refuse this operation. */
100
+ export type ReplicationPreparationResult = boolean | ContinuousReplicationNetworkFailure;
101
+ /** Capture the host observation at the gate which refused this operation. */
102
+ export declare function observedOfflineReplicationFailure(): ContinuousReplicationNetworkFailure;
103
+ /** Result of preparation and initial handoff to a continuous transfer. */
104
+ export type ContinuousReplicationStartResult = {
105
+ readonly status: "started";
106
+ } | {
107
+ readonly status: "cancelled";
108
+ } | {
109
+ readonly status: "failed";
110
+ readonly networkFailure?: ContinuousReplicationNetworkFailure;
111
+ };
94
112
  /** A request which starts a provider's long-lived/continuous operation. */
95
113
  export interface ContinuousReplicationRequest {
96
114
  readonly trigger: ContinuousReplicationTrigger;
97
115
  readonly interaction: NoInteraction;
116
+ /** Receive the result once, independently of short startup admission. */
117
+ readonly onStartSettled?: (result: ContinuousReplicationStartResult) => void;
98
118
  }
99
119
  /** Stable reasons for which a provider role cannot be run. */
100
120
  export type ReplicationBlockReason = "no-active-replicator" | "no-targets" | "not-ready" | "provider-not-composed" | "provider-not-configured" | "capability-not-implemented" | "capability-not-applicable" | "interaction-required" | "replication-in-progress" | "rate-limited";
@@ -156,7 +176,8 @@ export type UnattendedOneShotRunner = (replicator: ReplicatorInstance, setting:
156
176
  *
157
177
  * The runner must return after task ownership and pre-controller cancellation
158
178
  * have been registered. It must not retain the caller's active-publication
159
- * admission for the lifetime of the long-lived transfer.
179
+ * admission for the lifetime of the long-lived transfer. After successful
180
+ * admission the runner owns delivery of the request's eventual start result.
160
181
  */
161
182
  export type ContinuousRunner = (replicator: ReplicatorInstance, setting: RemoteDBSettings, request: ContinuousReplicationRequest) => Promise<ReplicationOutcome>;
162
183
  /**
@@ -20,6 +20,9 @@ const REPLICATION_PROGRESS_PRESENTATIONS = Object.freeze({
20
20
  QUIET: "quiet",
21
21
  NOTICE: "notice"
22
22
  });
23
+ function observedOfflineReplicationFailure() {
24
+ return { reason: "offline", hostOnlineAtFailure: false, failedAt: Date.now() };
25
+ }
23
26
  const REPLICATION_COMPLETED = Object.freeze({ status: "completed" });
24
27
  const REPLICATION_CANCELLED = Object.freeze({ status: "cancelled" });
25
28
  const CENTRAL_REMOTE_REPLICATION_READINESS = Object.freeze({
@@ -109,7 +112,13 @@ function supportedOpenReplicationContinuous() {
109
112
  return replicationBlocked("interaction-required");
110
113
  }
111
114
  try {
115
+ const observe = request.onStartSettled;
116
+ if (observe && replicator.startContinuousReplication) {
117
+ const result2 = await replicator.startContinuousReplication(setting, observe);
118
+ return outcomeFromContinuousOpenReplication(result2);
119
+ }
112
120
  const result = await replicator.openReplication(setting, true, false, false);
121
+ if (result !== false) observe?.({ status: "started" });
113
122
  return outcomeFromContinuousOpenReplication(result);
114
123
  } catch (error) {
115
124
  return replicationFailed(error);
@@ -142,6 +151,7 @@ export {
142
151
  defineReplicatorProviderDefinitions,
143
152
  isActiveReplicatorContextBoundToSetting,
144
153
  isReplicationCompleted,
154
+ observedOfflineReplicationFailure,
145
155
  outcomeFromContinuousOpenReplication,
146
156
  outcomeFromFiniteOpenReplication,
147
157
  replicationBlocked,
@@ -26,9 +26,9 @@ function isSyncParamsError(error) {
26
26
  return error instanceof SyncParamsFetchError || error instanceof SyncParamsNotFoundError || error instanceof SyncParamsUpdateError;
27
27
  }
28
28
  function createSyncParamsHandler({ put, get, create }) {
29
- let taskFetchParameters = void 0;
30
- const _fetchSyncParameters = async () => {
31
- let syncParams = void 0;
29
+ let taskFetchParameters;
30
+ const readSyncParameters = async () => {
31
+ let syncParams;
32
32
  try {
33
33
  let shouldRetry = false;
34
34
  do {
@@ -77,37 +77,38 @@ function createSyncParamsHandler({ put, get, create }) {
77
77
  throw new Error(`Failed to prepare synchronisation key in synchronisation parameters`);
78
78
  }
79
79
  Logger(`Synchronisation parameters fetched successfully`, LOG_LEVEL_INFO);
80
- if (!syncParams.pbkdf2saltDecoded) {
81
- const decodedSalt = new Uint8Array(base64ToArrayBufferInternalBrowser(syncParams.pbkdf2salt));
82
- if (!decodedSalt) {
83
- throw new SyncParamsFetchError(`Failed to decode PBKDF2 salt`);
84
- }
85
- syncParams.pbkdf2saltDecoded = decodedSalt;
86
- }
87
- return syncParams;
88
- } catch (ex) {
80
+ const parameters = {
81
+ ...syncParams,
82
+ pbkdf2saltDecoded: new Uint8Array(base64ToArrayBufferInternalBrowser(syncParams.pbkdf2salt))
83
+ };
84
+ return { status: "success", parameters };
85
+ } catch (cause) {
89
86
  Logger(`Failed to fetch synchronisation parameters`, LOG_LEVEL_INFO);
90
- Logger(ex, LOG_LEVEL_VERBOSE);
91
- taskFetchParameters = void 0;
92
- return false;
87
+ Logger(cause, LOG_LEVEL_VERBOSE);
88
+ return { status: "failure", cause };
93
89
  }
94
90
  };
95
91
  const fetchSyncParameters = (refresh = false) => {
96
- if (taskFetchParameters && !refresh) {
97
- return taskFetchParameters;
98
- }
99
- taskFetchParameters = _fetchSyncParameters();
100
- return taskFetchParameters;
92
+ if (taskFetchParameters && !refresh) return taskFetchParameters;
93
+ const task = readSyncParameters();
94
+ taskFetchParameters = task;
95
+ void task.then((result) => {
96
+ if (result.status === "failure" && taskFetchParameters === task) taskFetchParameters = void 0;
97
+ });
98
+ return task;
101
99
  };
102
100
  return {
103
- fetch: fetchSyncParameters,
101
+ fetch: async (refresh) => {
102
+ const result = await fetchSyncParameters(refresh);
103
+ return result.status === "success" ? result.parameters : false;
104
+ },
104
105
  getPBKDF2Salt: async (refresh = false) => {
105
- const syncParams = await fetchSyncParameters(refresh);
106
- if (!syncParams) {
106
+ const result = await fetchSyncParameters(refresh);
107
+ if (result.status === "failure") {
107
108
  Logger(`Failed to fetch synchronisation parameters`, LOG_LEVEL_INFO);
108
- throw new SyncParamsFetchError(`Failed to fetch synchronisation parameters`);
109
+ throw new SyncParamsFetchError(`Failed to fetch synchronisation parameters`, { cause: result.cause });
109
110
  }
110
- return syncParams.pbkdf2saltDecoded;
111
+ return result.parameters.pbkdf2saltDecoded;
111
112
  }
112
113
  };
113
114
  }
@@ -7,10 +7,11 @@ import { LiveSyncAbstractReplicator, type LiveSyncReplicatorEnv, type RemoteDBSt
7
7
  import type { OwnedCouchDBConnection, RemoteConnectionOpenOptions } from "../../services/base/RemoteConnection.js";
8
8
  import type { IPathService } from "../../services/base/IService.js";
9
9
  import { type CentralCompatibilityDecisionRecorder } from "../CentralCompatibility.js";
10
- import { type ReplicationOutcome } from "../ReplicatorProvider.js";
10
+ import { type ContinuousReplicationStartResult, type ReplicationOutcome } from "../ReplicatorProvider.js";
11
11
  import { type ForgetJoinedDeviceResult, type JoinedDevicesSnapshot } from "../joinedDevices.js";
12
12
  export type { OwnedCouchDBConnection, RemoteConnectionOpenOptions } from "../../services/base/RemoteConnection.js";
13
13
  type SyncProcessingResult = "DONE" | "NEED_RETRY" | "NEED_RESURRECT" | "FAILED" | "CANCELLED" | UnsupportedEncryptedDocumentFormatError;
14
+ type SettleContinuousStart = (result: ContinuousReplicationStartResult) => void;
14
15
  /**
15
16
  * Compatibility constructor environment for the CouchDB Replicator facade.
16
17
  *
@@ -47,6 +48,7 @@ export declare class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicato
47
48
  * controller, so a stop request cannot be lost during catch-up.
48
49
  */
49
50
  private continuousTask;
51
+ private continuousStart;
50
52
  private continuousStopWaiter;
51
53
  private continuousStopRequested;
52
54
  private continuousPhase?;
@@ -72,6 +74,7 @@ export declare class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicato
72
74
  */
73
75
  terminateSync(): Promise<void>;
74
76
  openReplication(setting: RemoteDBSettings, keepAlive: boolean, showResult: boolean, ignoreCleanLock: boolean): Promise<boolean>;
77
+ startContinuousReplication(setting: RemoteDBSettings, onStartSettled: SettleContinuousStart): Promise<boolean>;
75
78
  /**
76
79
  * Run one finite CouchDB attempt and retain only its own compatibility result.
77
80
  *
@@ -92,6 +95,8 @@ export declare class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicato
92
95
  replicationErrored(e: unknown, database?: LiveSyncLocalDB | null): void;
93
96
  replicationPaused(): void;
94
97
  processSync(syncHandler: PouchDB.Replication.Sync<EntryDoc> | PouchDB.Replication.Replication<EntryDoc>, showResult: boolean, docSentOnStart: number, docArrivedOnStart: number, syncMode: "sync" | "pullOnly" | "pushOnly", retrying: boolean, reportCancelledAsDone?: boolean): Promise<SyncProcessingResult>;
98
+ private processSyncWithOutcome;
99
+ private runSyncTransfer;
95
100
  getEmptyMaxEntry(remoteID: number): {
96
101
  _id: string;
97
102
  maxSeq: number | string;
@@ -117,6 +122,7 @@ export declare class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicato
117
122
  * controller. The admitted owner retains the established transfer behaviour.
118
123
  */
119
124
  private runOneShotReplication;
125
+ private prepareOneShotSecuritySeed;
120
126
  private checkOneShotReplicationConnectivity;
121
127
  private closeRemoteConnection;
122
128
  private notifyFiniteReplicationCompleted;
@@ -127,8 +133,12 @@ export declare class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicato
127
133
  replicateAllFromServerWithOutcome(setting: RemoteDBSettings, showingNotice?: boolean): Promise<ReplicationOutcome>;
128
134
  private reportConnectivityPreflightTimeout;
129
135
  checkReplicationConnectivity(setting: RemoteDBSettings, keepAlive: boolean, skipCheck: boolean, showResult: boolean, ignoreCleanLock?: boolean, connectionOptions?: RemoteConnectionOpenOptions, recordCompatibilityDecision?: CentralCompatibilityDecisionRecorder): Promise<false | CouchDBReplicationConnection>;
130
- openContinuousReplication(setting: RemoteDBSettings, showResult: boolean, retrying: boolean): Promise<boolean>;
136
+ private checkReplicationConnectivityWithOutcome;
137
+ private openReplicationConnection;
138
+ openContinuousReplication(setting: RemoteDBSettings, showResult: boolean, retrying: boolean, onStartSettled?: SettleContinuousStart): Promise<boolean>;
139
+ private observeContinuousStart;
131
140
  private clearContinuousTask;
141
+ private runContinuousCatchUp;
132
142
  private runContinuousReplication;
133
143
  closeReplication(): Promise<void>;
134
144
  tryResetRemoteDatabase(setting: RemoteDBSettings): Promise<void>;
@@ -136,6 +146,8 @@ export declare class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicato
136
146
  markRemoteLocked(setting: RemoteDBSettings, locked: boolean, lockByClean: boolean): Promise<void>;
137
147
  markRemoteResolved(setting: RemoteDBSettings): Promise<void>;
138
148
  connectRemoteCouchDBWithSetting(settings: RemoteDBSettings, isMobile: boolean, performSetup?: boolean, skipInfo?: boolean, connectionOptions?: RemoteConnectionOpenOptions): Promise<string | OwnedCouchDBConnection<EntryDoc>>;
149
+ private connectRemoteCouchDBWithOutcome;
150
+ private openRemoteCouchDBWithSetting;
139
151
  private openOwnedConnection;
140
152
  /**
141
153
  * Opens a raw PouchDB handle for compatibility with earlier Commonlib