@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
@@ -10,6 +10,8 @@ import { replicationFilter } from "../../pouchdb/compress.js";
10
10
  import { disableEncryption, enableEncryption } from "../../pouchdb/encryption.js";
11
11
  import { isCloudantURI, isValidRemoteCouchDBURI } from "../../pouchdb/utils_couchdb.js";
12
12
  import { AuthorizationHeaderGenerator } from "../../replication/httplib.js";
13
+ import { observedOfflineReplicationFailure } from "../../replication/ReplicatorProvider.js";
14
+ import { captureRemoteTransportFailure, ReplicationNetworkError } from "../../replication/remoteTransportFailure.js";
13
15
  import { UnresolvedErrorManager } from "./UnresolvedErrorManager.js";
14
16
  import { createInstanceLogFunction, MARK_LOG_NETWORK_ERROR } from "../lib/logUtils.js";
15
17
  import { runWithTrackedPhysicalRequest } from "../lib/remoteActivity.js";
@@ -88,6 +90,41 @@ function createCouchDBConnection(db, info, scope) {
88
90
  }
89
91
  };
90
92
  }
93
+ const responseBodyReaders = /* @__PURE__ */ new Set([
94
+ "arrayBuffer",
95
+ "blob",
96
+ "buffer",
97
+ "bytes",
98
+ "formData",
99
+ "json",
100
+ "text"
101
+ ]);
102
+ function observeResponseBody(response, captureFailure) {
103
+ if (!response.ok) {
104
+ return response;
105
+ }
106
+ return new Proxy(response, {
107
+ get(target, property) {
108
+ if (property === "clone") {
109
+ return () => observeResponseBody(target.clone(), captureFailure);
110
+ }
111
+ const member = Reflect.get(target, property);
112
+ if (typeof member !== "function" || property === "constructor") {
113
+ return member;
114
+ }
115
+ if (!responseBodyReaders.has(property)) {
116
+ return member.bind(target);
117
+ }
118
+ return async () => {
119
+ try {
120
+ return await Reflect.apply(member, target, []);
121
+ } catch (error) {
122
+ throw captureFailure(error);
123
+ }
124
+ };
125
+ }
126
+ });
127
+ }
91
128
  const FetchMethod = {
92
129
  webCompat: 0,
93
130
  native: 1
@@ -182,12 +219,27 @@ class RemoteService extends ServiceBase {
182
219
  * @returns An error description, or the owned connection. The caller must
183
220
  * transfer ownership or call `close()`.
184
221
  */
185
- async connect(uri, auth, disableRequestURI, passphrase, useDynamicIterationCount, performSetup, skipInfo, compression, customHeaders, useRequestAPI, getPBKDF2Salt, connectionOptions = {}) {
186
- if (!isValidRemoteCouchDBURI(uri)) return "Remote URI is not valid";
187
- if (uri.toLowerCase() != uri) return "Remote URI and database name could not contain capital letters.";
188
- if (uri.indexOf(" ") !== -1) return "Remote URI and database name could not contain spaces.";
222
+ async connect(...args) {
223
+ const opened = await this.openCouchDBConnection(...args);
224
+ return "error" in opened ? opened.error.message : opened;
225
+ }
226
+ async openCouchDBConnection(...args) {
227
+ return await this.openConnection(...args);
228
+ }
229
+ async openConnection(uri, auth, disableRequestURI, passphrase, useDynamicIterationCount, performSetup, skipInfo, compression, customHeaders, useRequestAPI, getPBKDF2Salt, connectionOptions = {}) {
230
+ if (!isValidRemoteCouchDBURI(uri)) {
231
+ return { error: new Error("Remote URI is not valid") };
232
+ }
233
+ if (uri.toLowerCase() !== uri) {
234
+ return { error: new Error("Remote URI and database name could not contain capital letters.") };
235
+ }
236
+ if (uri.includes(" ")) {
237
+ return { error: new Error("Remote URI and database name could not contain spaces.") };
238
+ }
189
239
  if (!this._APIService.isOnline) {
190
- return "Network is offline";
240
+ return {
241
+ error: new ReplicationNetworkError("Network is offline", observedOfflineReplicationFailure())
242
+ };
191
243
  }
192
244
  const connectionScope = createRemoteConnectionScope(connectionOptions.signal);
193
245
  const encryptionAlgorithm = connectionOptions.encryptionAlgorithm ?? this._settingService.currentSettings().E2EEAlgorithm;
@@ -231,44 +283,45 @@ class RemoteService extends ServiceBase {
231
283
  headers.append("authorization", authHeader);
232
284
  }
233
285
  const cachedRequest = await prepareCachedRequest(requestSrc, opts);
286
+ const signal = connectionScope.combine(opts?.signal);
287
+ const captureFailure = (error) => captureRemoteTransportFailure(error, signal, () => this._APIService.isOnline);
234
288
  try {
235
- const signal = connectionScope.combine(opts?.signal);
236
289
  const response = await this.performFetch(
237
290
  cachedRequest.request,
238
291
  { ...opts, headers, signal, cache: cachedRequest.cache },
239
292
  useRequestAPI ? FetchMethod.native : FetchMethod.webCompat
240
293
  );
241
- return response;
242
- } catch (ex) {
243
- if (ex instanceof TypeError) {
244
- if (connectionScope.signal.aborted || connectionOptions.allowNativeFallback === false) {
245
- throw ex;
246
- }
247
- if (useRequestAPI) {
294
+ return observeResponseBody(response, captureFailure);
295
+ } catch (error) {
296
+ if (!(error instanceof TypeError) || connectionScope.signal.aborted || connectionOptions.allowNativeFallback === false || useRequestAPI) {
297
+ if (useRequestAPI && error instanceof TypeError && !connectionScope.signal.aborted) {
248
298
  this._log("Failed to request by API.");
249
- throw ex;
250
299
  }
251
- this._log(
252
- "Failed to fetch by native fetch API. Trying to fetch by API to get more information."
253
- );
254
- const resp2 = await this.performFetch(
300
+ throw captureFailure(error);
301
+ }
302
+ this._log(
303
+ "Failed to fetch by native fetch API. Trying to fetch by API to get more information."
304
+ );
305
+ let response;
306
+ try {
307
+ response = await this.performFetch(
255
308
  cachedRequest.request,
256
309
  { ...opts, headers, cache: cachedRequest.cache },
257
310
  FetchMethod.native
258
311
  );
259
- if (resp2.status / 100 == 2) {
260
- this.showError(
261
- "The request was successful by API. But the native fetch API failed! Please check CORS settings on the remote database!. While this condition, you cannot enable LiveSync",
262
- LOG_LEVEL_NOTICE
263
- );
264
- return resp2;
265
- }
266
- const r2 = resp2.clone();
267
- const msg = await r2.text();
268
- this.showError(`Failed to fetch by API. ${resp2.status}: ${msg}`, LOG_LEVEL_NOTICE);
269
- return resp2;
312
+ } catch (fallbackError) {
313
+ throw captureFailure(fallbackError);
314
+ }
315
+ if (response.status / 100 == 2) {
316
+ this.showError(
317
+ "The request was successful by API. But the native fetch API failed! Please check CORS settings on the remote database!. While this condition, you cannot enable LiveSync",
318
+ LOG_LEVEL_NOTICE
319
+ );
320
+ } else {
321
+ const msg = await response.clone().text();
322
+ this.showError(`Failed to fetch by API. ${response.status}: ${msg}`, LOG_LEVEL_NOTICE);
270
323
  }
271
- throw ex;
324
+ return observeResponseBody(response, captureFailure);
272
325
  }
273
326
  } catch (ex) {
274
327
  this._log(`HTTP:${method}${size} to:${localURL} -> failed`, LOG_LEVEL_VERBOSE);
@@ -331,11 +384,10 @@ class RemoteService extends ServiceBase {
331
384
  const info = await db.info();
332
385
  return { ...connection, info };
333
386
  } catch (ex) {
334
- const exMsg = ex instanceof Error ? ex : LiveSyncError.fromError(ex);
335
- const msg = `${exMsg.name}:${exMsg.message}`;
387
+ const error = ex instanceof Error ? ex : LiveSyncError.fromError(ex);
336
388
  this._log(ex, LOG_LEVEL_VERBOSE);
337
389
  await closeAfterConnectionFailure();
338
- return msg;
390
+ return { error: new Error(`${error.name}:${error.message}`, { cause: ex }) };
339
391
  }
340
392
  }
341
393
  }
@@ -51,14 +51,22 @@ export declare abstract class ReplicationService<T extends ServiceContext = Serv
51
51
  * Process a virtual document (e.g., for customisation sync).
52
52
  */
53
53
  readonly processVirtualDocument: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(docs: PouchDB.Core.ExistingDocument<import("../../common/types.js").EntryDoc>) => Promise<boolean>>;
54
+ private readonly _beforeReplicate;
54
55
  /**
55
56
  * An event triggered before starting replication.
56
57
  */
57
- readonly onBeforeReplicate: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(showMessage: boolean) => Promise<boolean>>;
58
+ readonly onBeforeReplicate: ((showMessage: boolean) => Promise<boolean>) & {
59
+ addHandler: (callback: (showMessage: boolean) => import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult | Promise<import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult>, priority?: number, allowSwap?: boolean) => import("../lib/HandlerUtils.js").UnregisterFunction;
60
+ removeHandler: (callback: (showMessage: boolean) => import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult | Promise<import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult>) => void;
61
+ };
58
62
  readonly onFiniteReplicationCompleted: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
59
63
  readonly onFileReflectionFailed: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(target: import("../../interfaces/FileHandler.js").ReflectionTarget, error: unknown) => Promise<boolean>>;
64
+ private readonly _prepareCentralRemote;
60
65
  /** Provider preparation which applies only to the central remote. */
61
- readonly onPrepareCentralRemoteReplication: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(showMessage: boolean) => Promise<boolean>>;
66
+ readonly onPrepareCentralRemoteReplication: ((showMessage: boolean) => Promise<boolean>) & {
67
+ addHandler: (callback: (showMessage: boolean) => import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult | Promise<import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult>, priority?: number, allowSwap?: boolean) => import("../lib/HandlerUtils.js").UnregisterFunction;
68
+ removeHandler: (callback: (showMessage: boolean) => import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult | Promise<import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult>) => void;
69
+ };
62
70
  /**
63
71
  * Lightweight, repeatable policy checks shared by every replication entry point.
64
72
  * Handlers must remain idempotent because a high-level replication may cross
@@ -20,9 +20,11 @@ import {
20
20
  replicationFailed,
21
21
  outcomeFromFiniteOpenReplication
22
22
  } from "../../replication/ReplicatorProvider.js";
23
+ import { EVENT_REPLICATION_ABORT_REQUESTED } from "../../events/coreEvents.js";
23
24
  import { UnresolvedErrorManager } from "./UnresolvedErrorManager.js";
24
25
  import { isLockAcquired, shareRunningResult } from "octagonal-wheels/concurrency/lock";
25
26
  import {
27
+ createReplicationPreparation,
26
28
  createReplicationReadinessEvaluator
27
29
  } from "./ReplicationService.readiness.js";
28
30
  import { TypedReplicationCoordinator } from "./ReplicationService.typedReplication.js";
@@ -129,8 +131,8 @@ class ReplicationService extends ServiceBase {
129
131
  },
130
132
  preparation: {
131
133
  commitPendingFileEvents: () => this.fileProcessing.commitPendingFileEvents(),
132
- prepareCentralRemote: (showMessage) => this.onPrepareCentralRemoteReplication(showMessage),
133
- runBeforeReplicate: (showMessage) => this.onBeforeReplicate(showMessage)
134
+ prepareCentralRemote: (showMessage) => this.onPrepareCentralRemoteReplication === this._prepareCentralRemote.invoke ? this._prepareCentralRemote.evaluate(showMessage) : this.onPrepareCentralRemoteReplication(showMessage),
135
+ runBeforeReplicate: (showMessage) => this.onBeforeReplicate === this._beforeReplicate.invoke ? this._beforeReplicate.evaluate(showMessage) : this.onBeforeReplicate(showMessage)
134
136
  },
135
137
  diagnostics: {
136
138
  getUnresolvedMessages: () => this.appLifecycleService.getUnresolvedMessages(),
@@ -143,7 +145,10 @@ class ReplicationService extends ServiceBase {
143
145
  this._typedReplication = new TypedReplicationCoordinator({
144
146
  replicatorService: this.replicatorService,
145
147
  currentSettings: () => this.settingService.currentSettings(),
146
- checkReadiness: (showMessage, readiness) => this.isReplicationReady(showMessage, readiness),
148
+ checkReadiness: async (showMessage, requirements) => {
149
+ const decision = await this._evaluateReadiness({ showMessage, requirements });
150
+ return decision.ready === true ? true : decision.rejection ?? false;
151
+ },
147
152
  handleFailure: (request) => this.onReplicationFailed(request),
148
153
  recordFiniteAttempt: () => {
149
154
  this.previousReplicated = Date.now();
@@ -169,16 +174,16 @@ class ReplicationService extends ServiceBase {
169
174
  * Process a virtual document (e.g., for customisation sync).
170
175
  */
171
176
  processVirtualDocument = handlers().anySuccess("processVirtualDocument");
177
+ _beforeReplicate = createReplicationPreparation("onBeforeReplicate");
172
178
  /**
173
179
  * An event triggered before starting replication.
174
180
  */
175
- onBeforeReplicate = handlers().bailFirstFailure("onBeforeReplicate");
181
+ onBeforeReplicate = this._beforeReplicate.invoke;
176
182
  onFiniteReplicationCompleted = handlers().allSettled("onFiniteReplicationCompleted");
177
183
  onFileReflectionFailed = handlers().allOrThrow("onFileReflectionFailed");
184
+ _prepareCentralRemote = createReplicationPreparation("onPrepareCentralRemoteReplication");
178
185
  /** Provider preparation which applies only to the central remote. */
179
- onPrepareCentralRemoteReplication = handlers().bailFirstFailure(
180
- "onPrepareCentralRemoteReplication"
181
- );
186
+ onPrepareCentralRemoteReplication = this._prepareCentralRemote.invoke;
182
187
  /**
183
188
  * Lightweight, repeatable policy checks shared by every replication entry point.
184
189
  * Handlers must remain idempotent because a high-level replication may cross
@@ -240,6 +245,7 @@ class ReplicationService extends ServiceBase {
240
245
  * replication, so it does not invoke failure-recovery handlers.
241
246
  */
242
247
  async stopActiveTransfer() {
248
+ this.context.events.emitEvent(EVENT_REPLICATION_ABORT_REQUESTED);
243
249
  return await this._typedReplication.stopActiveTransfer();
244
250
  }
245
251
  async performReplicationRequest(showMessage) {
@@ -1,8 +1,17 @@
1
1
  import { type LOG_LEVEL, type ObsidianLiveSyncSettings } from "../../common/types.js";
2
- import { type ReplicationReadinessRequirements } from "../../replication/ReplicatorProvider.js";
2
+ import { type ContinuousReplicationNetworkFailure, type ReplicationReadinessRequirements, type ReplicationPreparationResult } from "../../replication/ReplicatorProvider.js";
3
3
  import { type LogFunction } from "../lib/logUtils.js";
4
4
  import type { MessageTranslator } from "./MessageTranslator.js";
5
5
  import { type ReadinessEvaluationResult } from "./ReadinessEvaluator.js";
6
+ type PreparationHandler = (showMessage: boolean) => ReplicationPreparationResult | Promise<ReplicationPreparationResult>;
7
+ /** Direct legacy callers receive a boolean. Readiness also receives the rejecting handler's observation. */
8
+ export declare function createReplicationPreparation(name: string): {
9
+ invoke: ((showMessage: boolean) => Promise<boolean>) & {
10
+ addHandler: (callback: PreparationHandler, priority?: number, allowSwap?: boolean) => import("../lib/HandlerUtils.js").UnregisterFunction;
11
+ removeHandler: (callback: PreparationHandler) => void;
12
+ };
13
+ evaluate: (showMessage: boolean) => Promise<ReplicationPreparationResult>;
14
+ };
6
15
  /** State and policy gates consulted without beginning remote preparation. */
7
16
  export interface ReplicationReadinessGates {
8
17
  readonly isApplicationReady: () => boolean;
@@ -14,8 +23,8 @@ export interface ReplicationReadinessGates {
14
23
  /** Ordered operational gates which may release or prepare replication work. */
15
24
  export interface ReplicationReadinessPreparation {
16
25
  readonly commitPendingFileEvents: () => Promise<boolean>;
17
- readonly prepareCentralRemote: (showMessage: boolean) => Promise<boolean>;
18
- readonly runBeforeReplicate: (showMessage: boolean) => Promise<boolean>;
26
+ readonly prepareCentralRemote: PreparationHandler;
27
+ readonly runBeforeReplicate: PreparationHandler;
19
28
  }
20
29
  /** Diagnostic state, presentation, and unresolved-error output for readiness. */
21
30
  export interface ReplicationReadinessDiagnostics {
@@ -40,7 +49,7 @@ export interface ReplicationReadinessRequest {
40
49
  readonly showMessage?: boolean;
41
50
  readonly requirements?: ReplicationReadinessRequirements;
42
51
  }
43
- export type ReplicationReadinessEvaluator = (context?: ReplicationReadinessRequest) => Promise<ReadinessEvaluationResult>;
52
+ export type ReplicationReadinessEvaluator = (context?: ReplicationReadinessRequest) => Promise<ReadinessEvaluationResult<ContinuousReplicationNetworkFailure>>;
44
53
  /**
45
54
  * Compose the ordered readiness conditions shared by replication entry points.
46
55
  *
@@ -50,3 +59,4 @@ export type ReplicationReadinessEvaluator = (context?: ReplicationReadinessReque
50
59
  * requirements while the common conditions retain their declaration order.
51
60
  */
52
61
  export declare function createReplicationReadinessEvaluator(dependencies: ReplicationReadinessDependencies): ReplicationReadinessEvaluator;
62
+ export {};
@@ -1,9 +1,35 @@
1
1
  import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE } from "../../common/types.js";
2
2
  import {
3
- CENTRAL_REMOTE_REPLICATION_READINESS
3
+ CENTRAL_REMOTE_REPLICATION_READINESS,
4
+ observedOfflineReplicationFailure
4
5
  } from "../../replication/ReplicatorProvider.js";
6
+ import { MultiBinder } from "../lib/HandlerUtils.js";
7
+ import { Logger, LOG_LEVEL_VERBOSE } from "../../common/logger.js";
5
8
  import { MARK_LOG_NETWORK_ERROR } from "../lib/logUtils.js";
6
9
  import { evaluateReadiness } from "./ReadinessEvaluator.js";
10
+ class ReplicationPreparationHandlers extends MultiBinder {
11
+ async evaluate(showMessage) {
12
+ for (const handler of [...this._callbacks]) {
13
+ try {
14
+ const decision = await handler(showMessage);
15
+ if (decision !== true) return decision;
16
+ } catch (error) {
17
+ Logger(error, LOG_LEVEL_VERBOSE);
18
+ return false;
19
+ }
20
+ }
21
+ return true;
22
+ }
23
+ }
24
+ function createReplicationPreparation(name) {
25
+ const handlers = new ReplicationPreparationHandlers(name);
26
+ const evaluate = handlers.evaluate.bind(handlers);
27
+ const invoke = Object.assign(async (showMessage) => await evaluate(showMessage) === true, {
28
+ addHandler: handlers.addHandler.bind(handlers),
29
+ removeHandler: handlers.removeHandler.bind(handlers)
30
+ });
31
+ return { invoke, evaluate };
32
+ }
7
33
  function createReplicationReadinessEvaluator(dependencies) {
8
34
  const { diagnostics, gates, preparation } = dependencies;
9
35
  const reportPreparationFailure = async () => {
@@ -52,7 +78,7 @@ function createReplicationReadinessEvaluator(dependencies) {
52
78
  },
53
79
  {
54
80
  name: "network-online",
55
- evaluate: () => gates.isOnline(),
81
+ evaluate: () => gates.isOnline() || observedOfflineReplicationFailure(),
56
82
  onRejected: ({ showMessage }) => {
57
83
  diagnostics.showError("Network is offline", showMessage ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
58
84
  }
@@ -83,5 +109,6 @@ function createReplicationReadinessEvaluator(dependencies) {
83
109
  };
84
110
  }
85
111
  export {
112
+ createReplicationPreparation,
86
113
  createReplicationReadinessEvaluator
87
114
  };
@@ -1,11 +1,11 @@
1
1
  import type { ObsidianLiveSyncSettings } from "../../common/types.js";
2
- import { type ContinuousReplicationRequest, type ReplicationFailureRequest, type ReplicationOutcome, type ReplicationReadinessRequirements, type UnattendedOneShotRequest, type UserInitiatedOneShotRequest } from "../../replication/ReplicatorProvider.js";
2
+ import { type ContinuousReplicationRequest, type ReplicationFailureRequest, type ReplicationPreparationResult, type ReplicationOutcome, type ReplicationReadinessRequirements, type UnattendedOneShotRequest, type UserInitiatedOneShotRequest } from "../../replication/ReplicatorProvider.js";
3
3
  import type { IReplicatorService } from "./IService.js";
4
4
  /** ReplicationService collaborators required to execute typed provider roles. */
5
5
  export interface TypedReplicationCoordinatorDependencies {
6
6
  readonly replicatorService: Pick<IReplicatorService, "acquireActiveReplicatorContext" | "hasActiveReplicator" | "runWithActiveReplicatorContext" | "runFiniteReplicationActivity">;
7
7
  readonly currentSettings: () => ObsidianLiveSyncSettings;
8
- readonly checkReadiness: (showMessage: boolean, readiness: ReplicationReadinessRequirements) => Promise<boolean>;
8
+ readonly checkReadiness: (showMessage: boolean, readiness: ReplicationReadinessRequirements) => Promise<ReplicationPreparationResult>;
9
9
  readonly handleFailure: (request: ReplicationFailureRequest) => Promise<boolean>;
10
10
  /**
11
11
  * Advance the host's finite-attempt clock after readiness admits dispatch.
@@ -30,6 +30,8 @@ export interface TypedReplicationCoordinatorDependencies {
30
30
  export declare class TypedReplicationCoordinator {
31
31
  private readonly dependencies;
32
32
  private oneShotInProgress;
33
+ private continuousStopGeneration;
34
+ private readonly cancelReadinessWaits;
33
35
  constructor(dependencies: TypedReplicationCoordinatorDependencies);
34
36
  /**
35
37
  * Execute a user-initiated finite role with the request's interaction authority.
@@ -60,6 +62,7 @@ export declare class TypedReplicationCoordinator {
60
62
  * recovery handler.
61
63
  */
62
64
  startContinuous(request: ContinuousReplicationRequest): Promise<ReplicationOutcome>;
65
+ private admitContinuous;
63
66
  /**
64
67
  * Request transfer cancellation on one atomically acquired active context.
65
68
  *
@@ -1,6 +1,9 @@
1
+ import { promiseWithResolvers } from "octagonal-wheels/promises";
2
+ import { LOG_LEVEL_VERBOSE, Logger } from "../../common/logger.js";
1
3
  import {
2
4
  CAPABILITY_SUPPORT_KINDS,
3
5
  NO_INTERACTION,
6
+ REPLICATION_CANCELLED,
4
7
  REPLICATION_PROGRESS_PRESENTATIONS,
5
8
  isActiveReplicatorContextBoundToSetting,
6
9
  replicationBlocked,
@@ -13,6 +16,8 @@ class TypedReplicationCoordinator {
13
16
  }
14
17
  dependencies;
15
18
  oneShotInProgress = false;
19
+ continuousStopGeneration = 0;
20
+ cancelReadinessWaits = /* @__PURE__ */ new Set();
16
21
  /**
17
22
  * Execute a user-initiated finite role with the request's interaction authority.
18
23
  *
@@ -84,21 +89,72 @@ class TypedReplicationCoordinator {
84
89
  * recovery handler.
85
90
  */
86
91
  async startContinuous(request) {
92
+ const generation = this.continuousStopGeneration;
93
+ const isCancelled = () => generation !== this.continuousStopGeneration;
94
+ const observer = request.onStartSettled;
95
+ if (!observer) return await this.admitContinuous(request, isCancelled);
96
+ const settlement = promiseWithResolvers();
97
+ void settlement.promise.then(observer).catch((error) => Logger(error, LOG_LEVEL_VERBOSE));
98
+ try {
99
+ const admitted = await this.admitContinuous(
100
+ { ...request, onStartSettled: settlement.resolve },
101
+ isCancelled
102
+ );
103
+ if (admitted.status !== "completed") {
104
+ settlement.resolve({ status: admitted.status === "cancelled" ? "cancelled" : "failed" });
105
+ }
106
+ return admitted;
107
+ } catch (error) {
108
+ settlement.resolve({ status: "failed" });
109
+ throw error;
110
+ }
111
+ }
112
+ async admitContinuous(request, isCancelled) {
87
113
  if (request.interaction.kind !== NO_INTERACTION.kind) {
88
114
  return replicationBlocked("interaction-required");
89
115
  }
90
116
  const context = await this.acquireContext();
117
+ if (isCancelled()) {
118
+ return REPLICATION_CANCELLED;
119
+ }
91
120
  if ("status" in context) return context;
92
121
  const capability = context.provider.continuous;
93
122
  if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {
94
123
  return replicationBlocked(capability.reason);
95
124
  }
96
- const ready = await this.acquireReadyContext(false, context);
97
- if ("status" in ready) return ready;
125
+ const cancellation = promiseWithResolvers();
126
+ const cancel = () => cancellation.resolve(false);
127
+ this.cancelReadinessWaits.add(cancel);
128
+ let readiness;
129
+ try {
130
+ readiness = await Promise.race([
131
+ this.dependencies.checkReadiness(false, context.provider.readiness),
132
+ cancellation.promise
133
+ ]);
134
+ } catch (error) {
135
+ if (isCancelled()) {
136
+ return REPLICATION_CANCELLED;
137
+ }
138
+ throw error;
139
+ } finally {
140
+ this.cancelReadinessWaits.delete(cancel);
141
+ }
142
+ if (isCancelled()) {
143
+ return REPLICATION_CANCELLED;
144
+ }
145
+ if (readiness !== true) {
146
+ request.onStartSettled?.(
147
+ readiness === false ? { status: "failed" } : { status: "failed", networkFailure: readiness }
148
+ );
149
+ return replicationBlocked("not-ready");
150
+ }
98
151
  const setting = Object.freeze(asCopy(this.dependencies.currentSettings()));
99
152
  const admitted = await this.dependencies.replicatorService.runWithActiveReplicatorContext(
100
153
  async (activeContext) => {
101
- if (activeContext !== ready || !isActiveReplicatorContextBoundToSetting(activeContext, setting)) {
154
+ if (isCancelled()) {
155
+ return REPLICATION_CANCELLED;
156
+ }
157
+ if (activeContext !== context || !isActiveReplicatorContextBoundToSetting(activeContext, setting)) {
102
158
  return replicationBlocked("not-ready");
103
159
  }
104
160
  try {
@@ -118,6 +174,11 @@ class TypedReplicationCoordinator {
118
174
  * not a request to begin new remote work.
119
175
  */
120
176
  async stopActiveTransfer() {
177
+ this.continuousStopGeneration++;
178
+ for (const cancel of this.cancelReadinessWaits) {
179
+ cancel();
180
+ }
181
+ this.cancelReadinessWaits.clear();
121
182
  const context = await this.acquireContext();
122
183
  if ("status" in context) return context;
123
184
  const capability = context.provider.stopActiveTransfer;
@@ -162,10 +223,10 @@ class TypedReplicationCoordinator {
162
223
  if (context) return context;
163
224
  return this.dependencies.replicatorService.hasActiveReplicator() ? replicationBlocked("provider-not-composed") : replicationBlocked("no-active-replicator");
164
225
  }
165
- async acquireReadyContext(showMessage, contextOverride) {
166
- const context = contextOverride ?? await this.acquireContext();
226
+ async acquireReadyContext(showMessage) {
227
+ const context = await this.acquireContext();
167
228
  if ("status" in context) return context;
168
- if (!await this.dependencies.checkReadiness(showMessage, context.provider.readiness)) {
229
+ if (await this.dependencies.checkReadiness(showMessage, context.provider.readiness) !== true) {
169
230
  return replicationBlocked("not-ready");
170
231
  }
171
232
  return context;
@@ -0,0 +1,18 @@
1
+ import { type ReactiveValue } from "octagonal-wheels/dataobject/reactive";
2
+ import { type PublishedReplicationStatics, type ReplicationStatics } from "../../common/models/shared.definition.js";
3
+ /** A reactive source which accepts raw statistics and returns published values. */
4
+ export interface ReplicationStaticsSource {
5
+ get value(): PublishedReplicationStatics;
6
+ set value(value: ReplicationStatics);
7
+ onChanged: ReactiveValue<PublishedReplicationStatics>["onChanged"];
8
+ offChanged: ReactiveValue<PublishedReplicationStatics>["offChanged"];
9
+ }
10
+ /** Own the publication timestamp and initial state for replication statistics. */
11
+ export declare class ReplicationStaticsOwner {
12
+ private readonly state;
13
+ private readonly view;
14
+ readonly source: ReplicationStaticsSource;
15
+ constructor();
16
+ reset(): void;
17
+ private publish;
18
+ }
@@ -0,0 +1,33 @@
1
+ import { reactive, reactiveSource } from "octagonal-wheels/dataobject/reactive";
2
+ import {
3
+ DEFAULT_REPLICATION_STATICS
4
+ } from "../../common/models/shared.definition.js";
5
+ class ReplicationStaticsOwner {
6
+ state = reactiveSource(
7
+ Object.freeze({ ...DEFAULT_REPLICATION_STATICS })
8
+ );
9
+ view = reactive(() => this.state.value);
10
+ source;
11
+ constructor() {
12
+ const owner = this;
13
+ this.source = {
14
+ get value() {
15
+ return owner.state.value;
16
+ },
17
+ set value(value) {
18
+ owner.publish(value);
19
+ },
20
+ onChanged: (handler) => owner.view.onChanged(handler),
21
+ offChanged: (handler) => owner.view.offChanged(handler)
22
+ };
23
+ }
24
+ reset() {
25
+ this.state.value = Object.freeze({ ...DEFAULT_REPLICATION_STATICS });
26
+ }
27
+ publish(value) {
28
+ this.state.value = Object.freeze({ ...value, statsUpdatedAt: Date.now() });
29
+ }
30
+ }
31
+ export {
32
+ ReplicationStaticsOwner
33
+ };
@@ -28,9 +28,11 @@ export interface ReplicatorServiceDependencies {
28
28
  * readiness and replication dispatch.
29
29
  */
30
30
  export declare abstract class ReplicatorService<T extends ServiceContext = ServiceContext> extends ServiceBase<T> implements IReplicatorService {
31
+ #private;
31
32
  protected dependencies: ReplicatorServiceDependencies;
32
33
  readonly boundedRemoteActivityCount: import("octagonal-wheels/dataobject/reactive_v2").ReactiveSource<number>;
33
34
  readonly finiteReplicationActivityCount: import("octagonal-wheels/dataobject/reactive_v2").ReactiveSource<number>;
35
+ get replicationStatics(): import("./ReplicationStaticsOwner.js").ReplicationStaticsSource;
34
36
  _log: (msg: unknown, level?: import("octagonal-wheels/common/logger").LOG_LEVEL, key?: string) => void;
35
37
  private settingService;
36
38
  private databaseEventService;
@@ -117,14 +119,4 @@ export declare abstract class ReplicatorService<T extends ServiceContext = Servi
117
119
  * `ActiveReplicatorContext` before using a Replicator.
118
120
  */
119
121
  hasActiveReplicator(): boolean;
120
- replicationStatics: import("octagonal-wheels/dataobject/reactive_v2").ReactiveSource<{
121
- sent: number;
122
- arrived: number;
123
- maxPullSeq: number;
124
- maxPushSeq: number;
125
- lastSyncPullSeq: number;
126
- lastSyncPushSeq: number;
127
- syncStatus: import("../../common/types.js").DatabaseConnectingStatus;
128
- couchDB?: import("../../common/models/shared.definition.js").CouchDBReplicationProgress;
129
- }>;
130
122
  }
@@ -4,7 +4,7 @@ import { createInstanceLogFunction } from "../lib/logUtils.js";
4
4
  import { UnresolvedErrorManager } from "./UnresolvedErrorManager.js";
5
5
  import { yieldMicrotask } from "octagonal-wheels/promises";
6
6
  import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "../../common/logger.js";
7
- import { DEFAULT_REPLICATION_STATICS } from "../../common/models/shared.definition.js";
7
+ import { ReplicationStaticsOwner } from "./ReplicationStaticsOwner.js";
8
8
  import { reactiveSource } from "octagonal-wheels/dataobject/reactive";
9
9
  import {
10
10
  runWithOptionalActivity
@@ -39,6 +39,10 @@ class ReplicatorService extends ServiceBase {
39
39
  dependencies;
40
40
  boundedRemoteActivityCount = reactiveSource(0);
41
41
  finiteReplicationActivityCount = reactiveSource(0);
42
+ #replicationStaticsOwner = new ReplicationStaticsOwner();
43
+ get replicationStatics() {
44
+ return this.#replicationStaticsOwner.source;
45
+ }
42
46
  _log = createInstanceLogFunction("ReplicatorService");
43
47
  settingService;
44
48
  databaseEventService;
@@ -217,7 +221,7 @@ class ReplicatorService extends ServiceBase {
217
221
  this._unresolvedErrorManager.showError(message, LOG_LEVEL_NOTICE);
218
222
  return false;
219
223
  }
220
- this.replicationStatics.value = { ...DEFAULT_REPLICATION_STATICS };
224
+ this.#replicationStaticsOwner.reset();
221
225
  await yieldMicrotask();
222
226
  try {
223
227
  if (!await newReplicator.initializeDatabaseForReplication()) {
@@ -364,7 +368,6 @@ class ReplicatorService extends ServiceBase {
364
368
  hasActiveReplicator() {
365
369
  return this._activeReplicatorState.current !== void 0;
366
370
  }
367
- replicationStatics = reactiveSource({ ...DEFAULT_REPLICATION_STATICS });
368
371
  }
369
372
  export {
370
373
  ReplicatorService
@@ -39,6 +39,7 @@ export declare abstract class VaultService<T extends ServiceContext = ServiceCon
39
39
  */
40
40
  readonly isTargetFile: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(file: string | import("../../common/types.js").UXFileInfoStub, options?: {
41
41
  skipCaseCollisionCheck?: boolean;
42
+ internalFileEvent?: boolean;
42
43
  }) => Promise<boolean>>;
43
44
  /**
44
45
  * Check if a file is a target file for some extra feature
@@ -6,5 +6,5 @@ export declare function collectGenAll(strGen: AsyncGenerator<string, unknown, un
6
6
  export declare function concatGeneratedAll(strGen: AsyncGenerator<string, unknown, unknown> | Generator<string>): Promise<string>;
7
7
  export declare function splitPieces2V2(dataSrc: Blob, pieceSize: number, plainSplit: boolean, minimumChunkSize: number, filename?: string, useSegmenter?: boolean): Promise<(() => Generator<string>) | (() => AsyncGenerator<string>)>;
8
8
  export declare function splitPieces2(dataSrc: Blob, pieceSize: number, plainSplit: boolean, minimumChunkSize: number, filename?: string, useSegmenter?: boolean): Promise<(() => Generator<string>) | (() => AsyncGenerator<string>)>;
9
- export declare function splitPiecesRabinKarp(dataSrc: Blob, absoluteMaxPieceSize: number, doPlainSplit: boolean, minimumChunkSize: number, _filename?: string, _useSegmenter?: boolean): Promise<() => AsyncGenerator<string, void, unknown>>;
9
+ export declare function splitPiecesRabinKarp(dataSrc: Blob, absoluteMaxPieceSize: number, doPlainSplit: boolean, minimumChunkSize: number, _filename?: string, _useSegmenter?: boolean, signal?: AbortSignal): Promise<() => AsyncGenerator<string, void, unknown>>;
10
10
  export declare function splitPiecesRabinKarpOld(dataSrc: Blob, absoluteMaxPieceSize: number, doPlainSplit: boolean, minimumChunkSize: number, _filename?: string, _useSegmenter?: boolean): Promise<() => AsyncGenerator<string, void, unknown>>;