@vrtmrz/livesync-commonlib 0.5.0 → 0.6.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 (73) hide show
  1. package/dist/common/LSError.d.ts +13 -0
  2. package/dist/common/LSError.js +19 -1
  3. package/dist/diagnostics/local.d.ts +7 -2
  4. package/dist/interfaces/DatabaseFileAccess.d.ts +20 -4
  5. package/dist/interfaces/FileHandler.d.ts +67 -1
  6. package/dist/interfaces/FileHandler.js +16 -0
  7. package/dist/interfaces/StorageEventManager.d.ts +7 -0
  8. package/dist/managers/ChunkFetcher.d.ts +16 -0
  9. package/dist/managers/ChunkFetcher.js +190 -112
  10. package/dist/managers/EntryManager/EntryManager.d.ts +7 -0
  11. package/dist/managers/EntryManager/EntryManager.js +6 -0
  12. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +9 -5
  13. package/dist/managers/EntryManager/EntryManagerImpls.js +103 -76
  14. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.d.ts +7 -3
  15. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.js +83 -16
  16. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.d.ts +3 -2
  17. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.js +38 -36
  18. package/dist/managers/LayeredChunkManager/types.d.ts +15 -1
  19. package/dist/managers/LayeredChunkManager.d.ts +4 -0
  20. package/dist/managers/LayeredChunkManager.js +19 -6
  21. package/dist/managers/LiveSyncManagers.d.ts +2 -0
  22. package/dist/managers/LiveSyncManagers.js +6 -0
  23. package/dist/managers/StorageEventManager.d.ts +22 -0
  24. package/dist/managers/StorageEventManager.js +48 -1
  25. package/dist/pouchdb/LiveSyncLocalDB.d.ts +32 -0
  26. package/dist/pouchdb/LiveSyncLocalDB.js +72 -18
  27. package/dist/pouchdb/LocalDatabaseReadScope.d.ts +24 -0
  28. package/dist/pouchdb/LocalDatabaseReadScope.js +62 -0
  29. package/dist/pouchdb/pathIdentityCompatibility.d.ts +6 -2
  30. package/dist/pouchdb/pathIdentityCompatibility.js +15 -10
  31. package/dist/replication/contentRead.d.ts +3 -0
  32. package/dist/replication/contentRead.js +4 -0
  33. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +8 -1
  34. package/dist/replication/couchdb/LiveSyncReplicator.js +187 -119
  35. package/dist/replication/index.d.ts +5 -1
  36. package/dist/replication/index.js +18 -1
  37. package/dist/serviceFeatures/offlineScanner/files.d.ts +1 -1
  38. package/dist/serviceFeatures/offlineScanner/files.js +27 -7
  39. package/dist/serviceFeatures/offlineScanner/scan.d.ts +5 -1
  40. package/dist/serviceFeatures/offlineScanner/scan.js +2 -1
  41. package/dist/serviceFeatures/offlineScanner.d.ts +1 -1
  42. package/dist/serviceFeatures/offlineScanner.js +10 -2
  43. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +13 -0
  44. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +190 -123
  45. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +17 -7
  46. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +3 -2
  47. package/dist/serviceModules/ServiceFileHandlerBase/events.js +9 -9
  48. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -9
  49. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +10 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +28 -4
  51. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +11 -5
  52. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +144 -58
  53. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +16 -2
  54. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +1 -0
  55. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +7 -2
  56. package/dist/serviceModules/ServiceFileHandlerBase.js +13 -4
  57. package/dist/services/base/ControlService.js +1 -5
  58. package/dist/services/base/DatabaseEventService.d.ts +3 -0
  59. package/dist/services/base/DatabaseEventService.js +3 -0
  60. package/dist/services/base/DatabaseService.d.ts +15 -0
  61. package/dist/services/base/DatabaseService.js +85 -4
  62. package/dist/services/base/IService.d.ts +18 -1
  63. package/dist/services/base/KeyValueDBService.d.ts +5 -4
  64. package/dist/services/base/KeyValueDBService.js +46 -48
  65. package/dist/services/base/ReplicationService.d.ts +3 -1
  66. package/dist/services/base/ReplicationService.js +3 -1
  67. package/dist/services/base/VaultScanResult.d.ts +5 -0
  68. package/dist/services/lib/HandlerUtils.d.ts +40 -5
  69. package/dist/services/lib/HandlerUtils.js +52 -4
  70. package/docs/development.md +8 -0
  71. package/docs/offline-scanner.md +46 -0
  72. package/docs/releasing.md +42 -0
  73. package/package.json +1 -1
@@ -27,13 +27,13 @@ import {
27
27
  arrayToChunkedArray,
28
28
  parseHeaderValues
29
29
  } from "../../common/utils.js";
30
- import { Logger } from "../../common/logger.js";
31
30
  import { checkRemoteVersion, countCompromisedChunks, declareRemoteFeatures } from "../../pouchdb/negotiation.js";
32
31
  import { requiredRemoteFeatures, usesEncryptedInternalMetadata } from "../../pouchdb/remoteFeatureCompatibility.js";
33
32
  import { assessRemoteDocumentIds } from "../../pouchdb/remoteIdCompatibility.js";
34
33
  import { isErrorOfMissingDoc } from "../../pouchdb/utils_couchdb.js";
35
34
  import { preprocessOutgoing } from "../../pouchdb/encryption.js";
36
35
  import { prepareInitialFetchFastForward } from "./fastForward.js";
36
+ import { ContentReadError, LiveSyncError, RemoteRequestError } from "../../common/LSError.js";
37
37
  import { ensureDatabaseIsCompatible, getEffectiveTweakValues } from "../../pouchdb/LiveSyncDBFunctions.js";
38
38
  import {
39
39
  LiveSyncAbstractReplicator
@@ -80,12 +80,12 @@ class OneShotConnectivityPreflightTimeoutError extends Error {
80
80
  this.name = "OneShotConnectivityPreflightTimeoutError";
81
81
  }
82
82
  }
83
- async function* genReplication(s, signal) {
83
+ async function* genReplication(s, signal, log) {
84
84
  const inbox = new StreamInbox({ capacity: 1e4 });
85
85
  const push = function(e) {
86
86
  if (signal.aborted || inbox.isClosed) return;
87
87
  if (inbox.post(e)) return;
88
- Logger(`Replication event queue is full: ${e[0]}`, LOG_LEVEL_VERBOSE);
88
+ log(`Replication event queue is full: ${e[0]}`, LOG_LEVEL_VERBOSE);
89
89
  if (e[0] === "error" || e[0] === "denied") {
90
90
  inbox.error(e[1]);
91
91
  } else if (e[0] === "complete" || e[0] === "finally") {
@@ -118,7 +118,7 @@ async function* genReplication(s, signal) {
118
118
  }
119
119
  } catch (ex) {
120
120
  if (ex instanceof Error && ex.name == "AbortError") {
121
- Logger(`Replication aborted`, LOG_LEVEL_VERBOSE);
121
+ log(`Replication aborted`, LOG_LEVEL_VERBOSE);
122
122
  } else {
123
123
  throw ex;
124
124
  }
@@ -162,6 +162,9 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
162
162
  super(env);
163
163
  this.env = env;
164
164
  }
165
+ log(message, level = LOG_LEVEL_INFO, key = "") {
166
+ this.env.services.API.addLog(message, level, key);
167
+ }
165
168
  /** Own the checkpoint handoff for one fresh, suspended Fast Fetch only. */
166
169
  createInitialFetchFastForwardResource(setting) {
167
170
  const snapshot = { ...setting };
@@ -236,7 +239,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
236
239
  }
237
240
  return downloadedSyncParams;
238
241
  } catch (ex) {
239
- Logger(`Could not retrieve remote sync parameters`, LOG_LEVEL_INFO);
242
+ this.log(`Could not retrieve remote sync parameters`, LOG_LEVEL_INFO);
240
243
  throw SyncParamsFetchError.fromError(ex);
241
244
  }
242
245
  }
@@ -249,7 +252,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
249
252
  throw new SyncParamsUpdateError(`Could not store remote sync parameters: ${JSON.stringify(ret)}`);
250
253
  }
251
254
  } catch (ex) {
252
- Logger(`Could not store remote sync parameters`, LOG_LEVEL_INFO);
255
+ this.log(`Could not store remote sync parameters`, LOG_LEVEL_INFO);
253
256
  throw SyncParamsUpdateError.fromError(ex);
254
257
  }
255
258
  }
@@ -263,7 +266,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
263
266
  return await manager.getPBKDF2Salt(refresh);
264
267
  }
265
268
  async migrate(from, to) {
266
- Logger(`Database updated from ${from} to ${to}`, LOG_LEVEL_NOTICE);
269
+ this.log(`Database updated from ${from} to ${to}`, LOG_LEVEL_NOTICE);
267
270
  return Promise.resolve(true);
268
271
  }
269
272
  /** Abort only the active controller; internal transitions must not await their own task. */
@@ -333,7 +336,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
333
336
  replicationActivated(showResult) {
334
337
  this.syncStatus = "CONNECTED";
335
338
  this.updateInfo();
336
- Logger("Replication activated", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
339
+ this.log("Replication activated", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
337
340
  }
338
341
  async replicationChangeDetected(e, showResult, docSentOnStart, docArrivedOnStart) {
339
342
  try {
@@ -350,7 +353,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
350
353
  const lastSyncPushSeq = this.lastSyncPushSeq;
351
354
  const pushLast = lastSyncPushSeq == 0 ? "" : lastSyncPushSeq >= maxPushSeq ? " (LIVE)" : ` (${maxPushSeq - lastSyncPushSeq})`;
352
355
  const pullLast = lastSyncPullSeq == 0 ? "" : lastSyncPullSeq >= maxPullSeq ? " (LIVE)" : ` (${maxPullSeq - lastSyncPullSeq})`;
353
- Logger(
356
+ this.log(
354
357
  `\u2191${this.docSent - docSentOnStart}${pushLast} \u2193${this.docArrived - docArrivedOnStart}${pullLast}`,
355
358
  LOG_LEVEL_NOTICE,
356
359
  "sync"
@@ -358,47 +361,76 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
358
361
  }
359
362
  this.updateInfo();
360
363
  } catch (ex) {
361
- Logger("Replication callback error", LOG_LEVEL_NOTICE, "sync");
362
- Logger(ex, LOG_LEVEL_VERBOSE);
364
+ this.log("Replication callback error", LOG_LEVEL_NOTICE, "sync");
365
+ this.log(ex, LOG_LEVEL_VERBOSE);
363
366
  }
364
367
  }
365
368
  replicationCompleted(showResult) {
366
369
  this.syncStatus = "COMPLETED";
367
370
  this.updateInfo();
368
- Logger("Replication completed", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, showResult ? "sync" : "");
371
+ this.log("Replication completed", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, showResult ? "sync" : "");
369
372
  this.abortController();
370
373
  }
371
374
  replicationDenied(e) {
372
375
  this.syncStatus = "ERRORED";
373
376
  this.updateInfo();
374
377
  this.abortController();
375
- Logger("Replication denied", LOG_LEVEL_NOTICE, "sync");
376
- Logger(e, LOG_LEVEL_VERBOSE);
378
+ this.log("Replication denied", LOG_LEVEL_NOTICE, "sync");
379
+ this.log(e, LOG_LEVEL_VERBOSE);
380
+ }
381
+ /** Ask the current owner to inspect ambiguous managed-operation failures without joining its drain. */
382
+ requestCurrentDatabaseInspection(error, database) {
383
+ if (error instanceof RemoteRequestError || error instanceof ContentReadError && !error.failure.resources.includes("local-database")) {
384
+ return;
385
+ }
386
+ const service = this.env.services.database;
387
+ if (!database || service?.localDatabaseDirect !== database || !service.onLocalDatabaseError) {
388
+ return;
389
+ }
390
+ void Promise.resolve().then(() => {
391
+ if (service.localDatabaseDirect === database) {
392
+ return service.onLocalDatabaseError(database, error);
393
+ }
394
+ }).catch((failure) => {
395
+ this.log("Could not request current database inspection after replication failed.", LOG_LEVEL_VERBOSE);
396
+ this.log(failure, LOG_LEVEL_VERBOSE);
397
+ });
377
398
  }
378
- replicationErrored(e) {
399
+ /** Report only the captured local read; recovery must not join the operation it drains. */
400
+ async readLocalDatabase(database, operation) {
401
+ try {
402
+ return await database.readFromDatabase(operation);
403
+ } catch (error) {
404
+ if (!isErrorOfMissingDoc(error)) this.requestCurrentDatabaseInspection(error, database);
405
+ throw error;
406
+ }
407
+ }
408
+ replicationErrored(e, database) {
379
409
  this.syncStatus = "ERRORED";
380
410
  this.abortController();
381
411
  this.updateInfo();
382
412
  if (isUnencryptedContentRejectedError(e)) {
383
- Logger(getUnencryptedContentRejectionMessage("replication"), LOG_LEVEL_NOTICE, "sync");
413
+ this.log(getUnencryptedContentRejectionMessage("replication"), LOG_LEVEL_NOTICE, "sync");
384
414
  const rejection = getUnencryptedContentRejection(e);
385
415
  if (rejection) {
386
- Logger(
416
+ this.log(
387
417
  `CouchDB replication rejected ${rejection.contentKind}: ${rejection.documentId}`,
388
418
  LOG_LEVEL_VERBOSE
389
419
  );
390
420
  }
391
421
  return;
392
422
  }
393
- Logger("Replication error", LOG_LEVEL_NOTICE, "sync");
394
- Logger(e, LOG_LEVEL_VERBOSE);
423
+ this.requestCurrentDatabaseInspection(e, database);
424
+ this.log("Replication error", LOG_LEVEL_NOTICE, "sync");
425
+ this.log(e, LOG_LEVEL_VERBOSE);
395
426
  }
396
427
  replicationPaused() {
397
428
  this.syncStatus = "PAUSED";
398
429
  this.updateInfo();
399
- Logger("Replication paused", LOG_LEVEL_VERBOSE, "sync");
430
+ this.log("Replication paused", LOG_LEVEL_VERBOSE, "sync");
400
431
  }
401
432
  async processSync(syncHandler, showResult, docSentOnStart, docArrivedOnStart, syncMode, retrying, reportCancelledAsDone = true) {
433
+ const databaseOwner = this.env.services.database?.localDatabaseDirect;
402
434
  const controller = new AbortController();
403
435
  if (this.controller) {
404
436
  this.controller.abort();
@@ -415,12 +447,12 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
415
447
  this.updateInfo();
416
448
  }
417
449
  );
418
- const gen = genReplication(syncHandler, controller.signal);
450
+ const gen = genReplication(syncHandler, controller.signal, this.log.bind(this));
419
451
  try {
420
452
  for await (const [type, e] of gen) {
421
453
  const releaser = await globalConcurrencyController.tryAcquire(1, REPLICATION_BUSY_TIMEOUT);
422
454
  if (releaser === false) {
423
- Logger("Replication stopped for busy.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
455
+ this.log("Replication stopped for busy.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
424
456
  return "FAILED";
425
457
  }
426
458
  releaser();
@@ -470,12 +502,12 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
470
502
  this.replicationDenied(e);
471
503
  return "FAILED";
472
504
  case "error":
473
- this.replicationErrored(e);
505
+ this.replicationErrored(e, databaseOwner);
474
506
  if (isUnencryptedContentRejectedError(e)) return "FAILED";
475
- Logger("Replication stopped.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
507
+ this.log("Replication stopped.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
476
508
  if (this.env.services.remote.hadLastPostFailedBySize) {
477
509
  if (e && e.status == 413) {
478
- Logger(
510
+ this.log(
479
511
  `Something went wrong during synchronisation. Please check the log!`,
480
512
  LOG_LEVEL_NOTICE
481
513
  );
@@ -483,8 +515,8 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
483
515
  }
484
516
  return "NEED_RETRY";
485
517
  } else {
486
- Logger("Replication error", LOG_LEVEL_NOTICE, "sync");
487
- Logger(e, LOG_LEVEL_VERBOSE);
518
+ this.log("Replication error", LOG_LEVEL_NOTICE, "sync");
519
+ this.log(e, LOG_LEVEL_VERBOSE);
488
520
  }
489
521
  return "FAILED";
490
522
  case "paused":
@@ -493,7 +525,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
493
525
  case "finally":
494
526
  break;
495
527
  default:
496
- Logger(`Unexpected synchronization status:${JSON.stringify(e)}`);
528
+ this.log(`Unexpected synchronization status:${JSON.stringify(e)}`);
497
529
  }
498
530
  }
499
531
  if (reportCancelledAsDone) {
@@ -502,11 +534,12 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
502
534
  return "CANCELLED";
503
535
  } catch (ex) {
504
536
  if (isUnencryptedContentRejectedError(ex)) {
505
- this.replicationErrored(ex);
537
+ this.replicationErrored(ex, databaseOwner);
506
538
  return "FAILED";
507
539
  }
508
- Logger(`Unexpected synchronization exception`);
509
- Logger(ex, LOG_LEVEL_VERBOSE);
540
+ this.requestCurrentDatabaseInspection(ex, databaseOwner);
541
+ this.log(`Unexpected synchronization exception`);
542
+ this.log(ex, LOG_LEVEL_VERBOSE);
510
543
  return "FAILED";
511
544
  } finally {
512
545
  progress.dispose();
@@ -553,7 +586,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
553
586
  }
554
587
  maxSeq = seq;
555
588
  }
556
- Logger(`Updating max seq on chunk to ${maxSeq}`, LOG_LEVEL_VERBOSE);
589
+ this.log(`Updating max seq on chunk to ${maxSeq}`, LOG_LEVEL_VERBOSE);
557
590
  newMax.maxSeq = maxSeq;
558
591
  const previous_max_seq_on_chunk = await wrapException(() => localDB.get(newMax._id));
559
592
  if (previous_max_seq_on_chunk instanceof Error) {
@@ -575,7 +608,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
575
608
  if (!remoteDB) {
576
609
  const d = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
577
610
  if (typeof d === "string") {
578
- Logger(
611
+ this.log(
579
612
  this.translate("liveSyncReplicator.couldNotConnectToRemoteDb", { d }),
580
613
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
581
614
  "fetch"
@@ -587,12 +620,13 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
587
620
  const connectivity = await this.checkReplicationConnectivity(setting, false, false, false, false);
588
621
  if (connectivity === false) return false;
589
622
  await this.closeRemoteConnection(connectivity);
590
- Logger(`Bulk sending chunks to remote database...`, showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "fetch");
623
+ this.log(`Bulk sending chunks to remote database...`, showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "fetch");
591
624
  const remoteMilestone = await remoteDB.get(MILESTONE_DOCID);
592
625
  const remoteID = remoteMilestone?.created ?? 0;
593
- const localDB = this.rawDatabase;
626
+ const localOwner = this.env.services.database.localDatabase;
627
+ const localDB = localOwner.localDatabase;
594
628
  const te = new TextEncoder();
595
- Logger(
629
+ this.log(
596
630
  this.translate("liveSyncReplicator.checkingLastSyncPoint"),
597
631
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
598
632
  "fetch"
@@ -644,13 +678,13 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
644
678
  let sendingDocs = 0;
645
679
  let sentDocsCount = 0;
646
680
  const sendChunks = async (bulkDocs, bulkDocsSize, seq2) => {
647
- Logger(
681
+ this.log(
648
682
  `Sending ${bulkDocs.length} (${bulkDocsSize} => ${sizeToHumanReadable(bulkDocsSize)} in plain) chunks to remote database...`,
649
683
  LOG_LEVEL_VERBOSE
650
684
  );
651
685
  const releaser = await semaphore.acquire(1);
652
686
  sendingDocs += bulkDocs.length;
653
- Logger(
687
+ this.log(
654
688
  `\u2191 Uploading chunks
655
689
  ${sendingDocs}/(${sentDocsCount} done)`,
656
690
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
@@ -663,15 +697,15 @@ ${sendingDocs}/(${sentDocsCount} done)`,
663
697
  uploadBulkDocs.forEach((e) => sentMap[idSeqMap[e._id]] = true);
664
698
  await this.updateMaxTransferredSeqOnChunks(localDB, remoteID, sentMap);
665
699
  sentDocsCount += bulkDocs.length;
666
- Logger(
700
+ this.log(
667
701
  `\u2191 Uploading chunks
668
702
  ${sendingDocs}/(${sentDocsCount} done)`,
669
703
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
670
704
  "send"
671
705
  );
672
706
  } catch (ex) {
673
- Logger("Bulk sending failed.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "send");
674
- Logger(ex, LOG_LEVEL_VERBOSE);
707
+ this.log("Bulk sending failed.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "send");
708
+ this.log(ex, LOG_LEVEL_VERBOSE);
675
709
  return false;
676
710
  } finally {
677
711
  releaser();
@@ -709,8 +743,8 @@ ${sendingDocs}/(${sentDocsCount} done)`,
709
743
  try {
710
744
  return await e;
711
745
  } catch (ex) {
712
- Logger("Bulk sending failed.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "send");
713
- Logger(ex, LOG_LEVEL_VERBOSE);
746
+ this.log("Bulk sending failed.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "send");
747
+ this.log(ex, LOG_LEVEL_VERBOSE);
714
748
  return false;
715
749
  }
716
750
  })
@@ -762,15 +796,16 @@ ${sendingDocs}/(${sentDocsCount} done)`,
762
796
  return false;
763
797
  }
764
798
  if (this.controller) {
765
- Logger(
799
+ this.log(
766
800
  this.translate("liveSyncReplicator.replicationInProgress"),
767
801
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
768
802
  "sync"
769
803
  );
770
804
  return false;
771
805
  }
772
- const localDB = this.rawDatabase;
773
- Logger(this.translate("liveSyncReplicator.oneShotSyncBegin", { syncMode }));
806
+ const localOwner = this.env.services.database.localDatabase;
807
+ const localDB = localOwner.localDatabase;
808
+ this.log(this.translate("liveSyncReplicator.oneShotSyncBegin", { syncMode }));
774
809
  const ret = await this.checkOneShotReplicationConnectivity(
775
810
  setting,
776
811
  false,
@@ -780,7 +815,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
780
815
  );
781
816
  if (ret === false) {
782
817
  if (!cancellationRequested()) {
783
- Logger(
818
+ this.log(
784
819
  this.translate("liveSyncReplicator.couldNotConnectToServer"),
785
820
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
786
821
  "sync"
@@ -794,12 +829,16 @@ ${sendingDocs}/(${sentDocsCount} done)`,
794
829
  return false;
795
830
  }
796
831
  this.maxPullSeq = Number(`${ret.info.update_seq}`.split("-")[0]);
797
- this.maxPushSeq = Number(`${(await localDB.info()).update_seq}`.split("-")[0]);
832
+ this.maxPushSeq = Number(
833
+ `${(await this.readLocalDatabase(localOwner, (pouch) => pouch.info())).update_seq}`.split(
834
+ "-"
835
+ )[0]
836
+ );
798
837
  if (cancellationRequested()) {
799
838
  return false;
800
839
  }
801
840
  if (showResult) {
802
- Logger(this.translate("liveSyncReplicator.checkingLastSyncPoint"), LOG_LEVEL_NOTICE, "sync");
841
+ this.log(this.translate("liveSyncReplicator.checkingLastSyncPoint"), LOG_LEVEL_NOTICE, "sync");
803
842
  }
804
843
  this.syncStatus = "STARTED";
805
844
  this.updateInfo();
@@ -829,6 +868,9 @@ ${sendingDocs}/(${sentDocsCount} done)`,
829
868
  return false;
830
869
  }
831
870
  if (syncResult == "DONE") {
871
+ if (syncMode !== "pushOnly") {
872
+ await this.notifyFiniteReplicationCompleted();
873
+ }
832
874
  return true;
833
875
  }
834
876
  if (syncResult == "CANCELLED") {
@@ -854,13 +896,13 @@ ${sendingDocs}/(${sentDocsCount} done)`,
854
896
  tempSetting.batch_size = Math.ceil(tempSetting.batch_size / 2) + 2;
855
897
  tempSetting.batches_limit = Math.ceil(tempSetting.batches_limit / 2) + 2;
856
898
  if (tempSetting.batch_size <= 5 && tempSetting.batches_limit <= 5) {
857
- Logger(
899
+ this.log(
858
900
  this.translate("liveSyncReplicator.cantReplicateLowerValue"),
859
901
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
860
902
  );
861
903
  return false;
862
904
  } else {
863
- Logger(
905
+ this.log(
864
906
  this.translate("liveSyncReplicator.retryLowerBatchSize", {
865
907
  batch_size: tempSetting.batch_size.toString(),
866
908
  batches_limit: tempSetting.batches_limit.toString()
@@ -939,8 +981,20 @@ ${sendingDocs}/(${sentDocsCount} done)`,
939
981
  try {
940
982
  await connection.close();
941
983
  } catch (ex) {
942
- Logger("Failed to close remote database.", LOG_LEVEL_INFO, "sync");
943
- Logger(ex, LOG_LEVEL_VERBOSE, "sync");
984
+ this.log("Failed to close remote database.", LOG_LEVEL_INFO, "sync");
985
+ this.log(ex, LOG_LEVEL_VERBOSE, "sync");
986
+ }
987
+ }
988
+ async notifyFiniteReplicationCompleted() {
989
+ const handler = this.env.services.replication?.onFiniteReplicationCompleted;
990
+ if (typeof handler !== "function") {
991
+ return;
992
+ }
993
+ try {
994
+ await handler();
995
+ } catch (error) {
996
+ this.log("A finite-replication completion observer failed.", LOG_LEVEL_VERBOSE, "sync");
997
+ this.log(error, LOG_LEVEL_VERBOSE, "sync");
944
998
  }
945
999
  }
946
1000
  async withRemoteConnection(connection, task) {
@@ -966,21 +1020,21 @@ ${sendingDocs}/(${sentDocsCount} done)`,
966
1020
  if (!connectionOptions?.signal?.aborted || !(connectionOptions.signal.reason instanceof OneShotConnectivityPreflightTimeoutError)) {
967
1021
  return false;
968
1022
  }
969
- Logger("The remote connectivity check timed out.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
1023
+ this.log("The remote connectivity check timed out.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
970
1024
  if (error !== void 0) {
971
- Logger(error, LOG_LEVEL_VERBOSE, "sync");
1025
+ this.log(error, LOG_LEVEL_VERBOSE, "sync");
972
1026
  }
973
1027
  return true;
974
1028
  }
975
1029
  async checkReplicationConnectivity(setting, keepAlive, skipCheck, showResult, ignoreCleanLock = false, connectionOptions, recordCompatibilityDecision) {
976
1030
  recordCompatibilityDecision?.(CENTRAL_COMPATIBILITY_NOT_ASSESSED);
977
1031
  if (setting.versionUpFlash != "") {
978
- Logger(this.translate("Replicator.Message.VersionUpFlash"), LOG_LEVEL_NOTICE);
1032
+ this.log(this.translate("Replicator.Message.VersionUpFlash"), LOG_LEVEL_NOTICE);
979
1033
  return false;
980
1034
  }
981
1035
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
982
1036
  if (this.controller) {
983
- Logger("Another replication running.");
1037
+ this.log("Another replication running.");
984
1038
  return false;
985
1039
  }
986
1040
  let dbRet;
@@ -1002,7 +1056,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1002
1056
  if (this.reportConnectivityPreflightTimeout(connectionOptions, showResult)) {
1003
1057
  return false;
1004
1058
  }
1005
- Logger(
1059
+ this.log(
1006
1060
  this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }),
1007
1061
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
1008
1062
  );
@@ -1012,12 +1066,18 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1012
1066
  try {
1013
1067
  try {
1014
1068
  await assertDatabasePathIdentity(dbRet.db, setting);
1015
- await assertDatabasePathIdentity(this.env.services.database.localDatabase.localDatabase, setting);
1069
+ const localOwner = this.env.services.database.localDatabase;
1070
+ await assertDatabasePathIdentity(
1071
+ localOwner.localDatabase,
1072
+ setting,
1073
+ false,
1074
+ (operation) => this.readLocalDatabase(localOwner, () => operation())
1075
+ );
1016
1076
  } catch (error) {
1017
1077
  recordCompatibilityDecision?.(
1018
1078
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION)
1019
1079
  );
1020
- Logger(error, LOG_LEVEL_NOTICE);
1080
+ this.log(error, LOG_LEVEL_NOTICE);
1021
1081
  return false;
1022
1082
  }
1023
1083
  if (!skipCheck) {
@@ -1035,17 +1095,17 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1035
1095
  recordCompatibilityDecision?.(
1036
1096
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.ID_DERIVATION_MISMATCH)
1037
1097
  );
1038
- Logger("The remote document IDs do not match the configured ID key.", LOG_LEVEL_NOTICE);
1098
+ this.log("The remote document IDs do not match the configured ID key.", LOG_LEVEL_NOTICE);
1039
1099
  return false;
1040
1100
  }
1041
1101
  if (idCompatibility === "unverified" && setting.idDerivationVersion === 1 && setting.usePathObfuscation) {
1042
- Logger("No remote document was available to verify the configured ID key.", LOG_LEVEL_INFO);
1102
+ this.log("No remote document was available to verify the configured ID key.", LOG_LEVEL_INFO);
1043
1103
  }
1044
1104
  if (!await checkRemoteVersion(dbRet.db, this.migrate.bind(this), VER)) {
1045
1105
  recordCompatibilityDecision?.(
1046
1106
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION)
1047
1107
  );
1048
- Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1108
+ this.log(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1049
1109
  return false;
1050
1110
  }
1051
1111
  const progress = `${dbRet.info.update_seq}`;
@@ -1072,7 +1132,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1072
1132
  recordCompatibilityDecision?.(
1073
1133
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION)
1074
1134
  );
1075
- Logger(
1135
+ this.log(
1076
1136
  "The remote database has no compatibility with the running version. Please upgrade the plugin.",
1077
1137
  LOG_LEVEL_NOTICE
1078
1138
  );
@@ -1081,7 +1141,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1081
1141
  recordCompatibilityDecision?.(
1082
1142
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_LOCKED)
1083
1143
  );
1084
- Logger(
1144
+ this.log(
1085
1145
  "The remote database has been rebuilt or corrupted since we have synchronized last time. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",
1086
1146
  LOG_LEVEL_NOTICE
1087
1147
  );
@@ -1097,7 +1157,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1097
1157
  recordCompatibilityDecision?.(
1098
1158
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_CLEANED)
1099
1159
  );
1100
- Logger(
1160
+ this.log(
1101
1161
  "The remote database has been cleaned up. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",
1102
1162
  LOG_LEVEL_NOTICE
1103
1163
  );
@@ -1120,7 +1180,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1120
1180
  tweakAssessment
1121
1181
  )
1122
1182
  );
1123
- Logger(this.translate("liveSyncReplicator.mismatchedTweakDetected"), LOG_LEVEL_NOTICE);
1183
+ this.log(this.translate("liveSyncReplicator.mismatchedTweakDetected"), LOG_LEVEL_NOTICE);
1124
1184
  this.tweakSettingsMismatched = true;
1125
1185
  this.preferredTweakValue = ensure[1];
1126
1186
  return false;
@@ -1197,15 +1257,16 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1197
1257
  async runContinuousReplication(setting, showResult, retrying) {
1198
1258
  const next = await shareRunningResult("continuousReplication", async () => {
1199
1259
  if (this.continuousStopRequested || this.controller) {
1200
- Logger(
1260
+ this.log(
1201
1261
  this.translate("liveSyncReplicator.replicationInProgress"),
1202
1262
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
1203
1263
  );
1204
1264
  return false;
1205
1265
  }
1206
1266
  this.publishPreparationPhase("catch-up");
1207
- const localDB = this.rawDatabase;
1208
- Logger(this.translate("liveSyncReplicator.beforeLiveSync"));
1267
+ const localOwner = this.env.services.database.localDatabase;
1268
+ const localDB = localOwner.localDatabase;
1269
+ this.log(this.translate("liveSyncReplicator.beforeLiveSync"));
1209
1270
  const caughtUp = await this.env.services.replicator.runFiniteReplicationActivity(
1210
1271
  () => this.openOneShotReplication(
1211
1272
  setting,
@@ -1220,14 +1281,14 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1220
1281
  );
1221
1282
  if (caughtUp && !this.continuousStopRequested) {
1222
1283
  this.publishPreparationPhase("continuous");
1223
- Logger(this.translate("liveSyncReplicator.liveSyncBegin"));
1284
+ this.log(this.translate("liveSyncReplicator.liveSyncBegin"));
1224
1285
  const ret = await this.checkReplicationConnectivity(setting, true, false, showResult);
1225
1286
  if (ret === false || this.continuousStopRequested) {
1226
1287
  if (ret !== false) {
1227
1288
  await this.closeRemoteConnection(ret);
1228
1289
  }
1229
1290
  if (ret === false && !this.continuousStopRequested) {
1230
- Logger(
1291
+ this.log(
1231
1292
  this.translate("liveSyncReplicator.couldNotConnectToServer"),
1232
1293
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
1233
1294
  );
@@ -1235,7 +1296,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1235
1296
  return false;
1236
1297
  }
1237
1298
  if (showResult) {
1238
- Logger(this.translate("liveSyncReplicator.checkingLastSyncPoint"), LOG_LEVEL_NOTICE, "sync");
1299
+ this.log(this.translate("liveSyncReplicator.checkingLastSyncPoint"), LOG_LEVEL_NOTICE, "sync");
1239
1300
  }
1240
1301
  const { db, syncOption } = ret;
1241
1302
  try {
@@ -1244,7 +1305,11 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1244
1305
  }
1245
1306
  this.syncStatus = "STARTED";
1246
1307
  this.maxPullSeq = Number(`${ret.info.update_seq}`.split("-")[0]);
1247
- this.maxPushSeq = Number(`${(await localDB.info()).update_seq}`.split("-")[0]);
1308
+ this.maxPushSeq = Number(
1309
+ `${(await this.readLocalDatabase(localOwner, (pouch) => pouch.info())).update_seq}`.split(
1310
+ "-"
1311
+ )[0]
1312
+ );
1248
1313
  if (this.continuousStopRequested) {
1249
1314
  return false;
1250
1315
  }
@@ -1293,13 +1358,13 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1293
1358
  tempSetting.batch_size = Math.ceil(tempSetting.batch_size / 2) + 2;
1294
1359
  tempSetting.batches_limit = Math.ceil(tempSetting.batches_limit / 2) + 2;
1295
1360
  if (tempSetting.batch_size <= 5 && tempSetting.batches_limit <= 5) {
1296
- Logger(
1361
+ this.log(
1297
1362
  this.translate("liveSyncReplicator.cantReplicateLowerValue"),
1298
1363
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
1299
1364
  );
1300
1365
  return false;
1301
1366
  } else {
1302
- Logger(
1367
+ this.log(
1303
1368
  this.translate("liveSyncReplicator.retryLowerBatchSize", {
1304
1369
  batch_size: tempSetting.batch_size.toString(),
1305
1370
  batches_limit: tempSetting.batches_limit.toString()
@@ -1332,7 +1397,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1332
1397
  return stopped;
1333
1398
  }
1334
1399
  this.syncStatus = "CLOSED";
1335
- Logger(this.translate("liveSyncReplicator.replicationClosed"));
1400
+ this.log(this.translate("liveSyncReplicator.replicationClosed"));
1336
1401
  this.updateInfo();
1337
1402
  return stopped;
1338
1403
  }
@@ -1344,10 +1409,10 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1344
1409
  }
1345
1410
  try {
1346
1411
  await con.db.destroy();
1347
- Logger(this.translate("liveSyncReplicator.remoteDbDestroyed"), LOG_LEVEL_NOTICE);
1412
+ this.log(this.translate("liveSyncReplicator.remoteDbDestroyed"), LOG_LEVEL_NOTICE);
1348
1413
  } catch (ex) {
1349
- Logger(this.translate("liveSyncReplicator.remoteDbDestroyError"), LOG_LEVEL_NOTICE);
1350
- Logger(ex, LOG_LEVEL_NOTICE);
1414
+ this.log(this.translate("liveSyncReplicator.remoteDbDestroyError"), LOG_LEVEL_NOTICE);
1415
+ this.log(ex, LOG_LEVEL_NOTICE);
1351
1416
  throw ex;
1352
1417
  } finally {
1353
1418
  await this.closeRemoteConnection(con);
@@ -1365,18 +1430,18 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1365
1430
  if (!await this.ensurePBKDF2Salt(setting, true, false)) {
1366
1431
  throw new Error("Could not ensure PBKDF2 salt (Security Seed)");
1367
1432
  }
1368
- Logger(this.translate("liveSyncReplicator.remoteDbCreatedOrConnected"), LOG_LEVEL_NOTICE);
1433
+ this.log(this.translate("liveSyncReplicator.remoteDbCreatedOrConnected"), LOG_LEVEL_NOTICE);
1369
1434
  }
1370
1435
  async markRemoteLocked(setting, locked, lockByClean) {
1371
1436
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
1372
1437
  const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1373
1438
  if (typeof dbRet === "string") {
1374
- Logger(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1439
+ this.log(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1375
1440
  throw new Error(dbRet);
1376
1441
  }
1377
1442
  await this.withRemoteConnection(dbRet, async (db) => {
1378
1443
  if (!await checkRemoteVersion(db, this.migrate.bind(this), VER)) {
1379
- Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1444
+ this.log(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1380
1445
  throw new Error("The remote database version is not compatible");
1381
1446
  }
1382
1447
  const defInitPoint = {
@@ -1399,9 +1464,9 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1399
1464
  remoteMilestone.locked = locked;
1400
1465
  remoteMilestone.cleaned = remoteMilestone.cleaned || lockByClean;
1401
1466
  if (locked) {
1402
- Logger(this.translate("liveSyncReplicator.lockRemoteDb"), LOG_LEVEL_NOTICE);
1467
+ this.log(this.translate("liveSyncReplicator.lockRemoteDb"), LOG_LEVEL_NOTICE);
1403
1468
  } else {
1404
- Logger(this.translate("liveSyncReplicator.unlockRemoteDb"), LOG_LEVEL_NOTICE);
1469
+ this.log(this.translate("liveSyncReplicator.unlockRemoteDb"), LOG_LEVEL_NOTICE);
1405
1470
  }
1406
1471
  const result = await db.put(remoteMilestone);
1407
1472
  if (!result.ok) {
@@ -1413,12 +1478,12 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1413
1478
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
1414
1479
  const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1415
1480
  if (typeof dbRet === "string") {
1416
- Logger(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1481
+ this.log(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1417
1482
  throw new Error(dbRet);
1418
1483
  }
1419
1484
  await this.withRemoteConnection(dbRet, async (db) => {
1420
1485
  if (!await checkRemoteVersion(db, this.migrate.bind(this), VER)) {
1421
- Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1486
+ this.log(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1422
1487
  throw new Error("The remote database version is not compatible");
1423
1488
  }
1424
1489
  const defInitPoint = {
@@ -1437,12 +1502,12 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1437
1502
  };
1438
1503
  remoteMilestone.node_chunk_info = { ...defInitPoint.node_chunk_info, ...remoteMilestone.node_chunk_info };
1439
1504
  remoteMilestone.accepted_nodes = Array.from(/* @__PURE__ */ new Set([...remoteMilestone.accepted_nodes, this.nodeid]));
1440
- Logger(this.translate("liveSyncReplicator.markDeviceResolved"), LOG_LEVEL_NOTICE);
1505
+ this.log(this.translate("liveSyncReplicator.markDeviceResolved"), LOG_LEVEL_NOTICE);
1441
1506
  const result = await db.put(remoteMilestone);
1442
1507
  if (result.ok) {
1443
- Logger(this.translate("liveSyncReplicator.remoteDbMarkedResolved"), LOG_LEVEL_VERBOSE);
1508
+ this.log(this.translate("liveSyncReplicator.remoteDbMarkedResolved"), LOG_LEVEL_VERBOSE);
1444
1509
  } else {
1445
- Logger(this.translate("liveSyncReplicator.couldNotMarkResolveRemoteDb"), LOG_LEVEL_NOTICE);
1510
+ this.log(this.translate("liveSyncReplicator.couldNotMarkResolveRemoteDb"), LOG_LEVEL_NOTICE);
1446
1511
  throw new Error("Could not mark the remote database as resolved");
1447
1512
  }
1448
1513
  });
@@ -1548,25 +1613,28 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1548
1613
  async fetchRemoteChunks(missingChunks, showResult, setting = this.currentSettings) {
1549
1614
  const ret = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), false, true);
1550
1615
  if (typeof ret === "string") {
1551
- Logger(
1616
+ this.log(
1552
1617
  `${this.translate("liveSyncReplicator.couldNotConnectToServer")} ${ret} `,
1553
1618
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
1554
1619
  "fetch"
1555
1620
  );
1556
- return false;
1621
+ throw new RemoteRequestError(ret);
1557
1622
  }
1558
1623
  return await this.withRemoteConnection(ret, async (db) => {
1559
- if (!await checkRemoteVersion(db, this.migrate.bind(this), VER)) return false;
1624
+ const compatible = await checkRemoteVersion(db, this.migrate.bind(this), VER);
1625
+ if (!compatible) {
1626
+ throw new RemoteRequestError("Remote database version is incompatible");
1627
+ }
1560
1628
  const remoteChunks = await db.allDocs({ keys: missingChunks, include_docs: true });
1561
1629
  const errorRows = remoteChunks.rows.filter((e) => "error" in e);
1562
1630
  if (errorRows.length > 0) {
1563
- Logger(
1631
+ this.log(
1564
1632
  `Some requested chunks were not found in the remote database.`,
1565
1633
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
1566
1634
  "fetch"
1567
1635
  );
1568
- Logger(`Requested chunks: ${missingChunks.join(",")}`, LOG_LEVEL_VERBOSE);
1569
- Logger(
1636
+ this.log(`Requested chunks: ${missingChunks.join(",")}`, LOG_LEVEL_VERBOSE);
1637
+ this.log(
1570
1638
  `Error chunks: ${errorRows.map((e) => e.key).join(",")}`,
1571
1639
  LOG_LEVEL_VERBOSE
1572
1640
  );
@@ -1577,7 +1645,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1577
1645
  async tryConnectRemote(setting, showResult = true) {
1578
1646
  const db = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1579
1647
  if (typeof db === "string") {
1580
- Logger(
1648
+ this.log(
1581
1649
  this.translate("liveSyncReplicator.couldNotConnectTo", {
1582
1650
  uri: setting.couchDB_URI,
1583
1651
  name: setting.couchDB_DBNAME,
@@ -1588,7 +1656,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1588
1656
  return false;
1589
1657
  }
1590
1658
  return await this.withRemoteConnection(db, async () => {
1591
- Logger(`Connected to ${db.info.db_name} successfully`, LOG_LEVEL_NOTICE);
1659
+ this.log(`Connected to ${db.info.db_name} successfully`, LOG_LEVEL_NOTICE);
1592
1660
  return true;
1593
1661
  });
1594
1662
  }
@@ -1596,21 +1664,21 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1596
1664
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
1597
1665
  const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1598
1666
  if (typeof dbRet === "string") {
1599
- Logger(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1667
+ this.log(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1600
1668
  return;
1601
1669
  }
1602
1670
  await this.withRemoteConnection(dbRet, async (db) => {
1603
1671
  if (!await checkRemoteVersion(db, this.migrate.bind(this), VER)) {
1604
- Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1672
+ this.log(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1605
1673
  return;
1606
1674
  }
1607
1675
  try {
1608
1676
  const remoteMilestone = await db.get(MILESTONE_DOCID);
1609
1677
  remoteMilestone.tweak_values = {};
1610
1678
  await db.put(remoteMilestone);
1611
- Logger(`tweak values on the remote database have been cleared`, LOG_LEVEL_VERBOSE);
1679
+ this.log(`tweak values on the remote database have been cleared`, LOG_LEVEL_VERBOSE);
1612
1680
  } catch (ex) {
1613
- Logger(`Could not retrieve remote milestone`, LOG_LEVEL_NOTICE);
1681
+ this.log(`Could not retrieve remote milestone`, LOG_LEVEL_NOTICE);
1614
1682
  throw ex;
1615
1683
  }
1616
1684
  });
@@ -1619,21 +1687,21 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1619
1687
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
1620
1688
  const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1621
1689
  if (typeof dbRet === "string") {
1622
- Logger(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1690
+ this.log(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1623
1691
  throw new Error(dbRet);
1624
1692
  }
1625
1693
  await this.withRemoteConnection(dbRet, async (db) => {
1626
1694
  if (!await checkRemoteVersion(db, this.migrate.bind(this), VER)) {
1627
- Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1695
+ this.log(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1628
1696
  throw new Error("The remote database version is not compatible");
1629
1697
  }
1630
1698
  try {
1631
1699
  const remoteMilestone = await db.get(MILESTONE_DOCID);
1632
1700
  remoteMilestone.tweak_values[DEVICE_ID_PREFERRED] = getEffectiveTweakValues(setting);
1633
1701
  await db.put(remoteMilestone);
1634
- Logger(`Preferred tweak values has been registered`, LOG_LEVEL_VERBOSE);
1702
+ this.log(`Preferred tweak values has been registered`, LOG_LEVEL_VERBOSE);
1635
1703
  } catch (ex) {
1636
- Logger(`Could not retrieve remote milestone`, LOG_LEVEL_NOTICE);
1704
+ this.log(`Could not retrieve remote milestone`, LOG_LEVEL_NOTICE);
1637
1705
  throw ex;
1638
1706
  }
1639
1707
  });
@@ -1644,15 +1712,15 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1644
1712
  try {
1645
1713
  dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1646
1714
  } catch (ex) {
1647
- Logger(`Could not connect to the remote database`, LOG_LEVEL_NOTICE);
1648
- Logger(ex, LOG_LEVEL_VERBOSE);
1715
+ this.log(`Could not connect to the remote database`, LOG_LEVEL_NOTICE);
1716
+ this.log(ex, LOG_LEVEL_VERBOSE);
1649
1717
  return {
1650
1718
  status: RemotePreferredTweakStatuses.UNAVAILABLE,
1651
1719
  error: ex
1652
1720
  };
1653
1721
  }
1654
1722
  if (typeof dbRet === "string") {
1655
- Logger(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1723
+ this.log(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1656
1724
  return {
1657
1725
  status: RemotePreferredTweakStatuses.UNAVAILABLE,
1658
1726
  error: new Error(dbRet)
@@ -1662,15 +1730,15 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1662
1730
  try {
1663
1731
  if (!await checkRemoteVersion(db, this.migrate.bind(this), VER)) {
1664
1732
  const error = new Error("The remote database version is not compatible");
1665
- Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1733
+ this.log(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1666
1734
  return {
1667
1735
  status: RemotePreferredTweakStatuses.UNAVAILABLE,
1668
1736
  error
1669
1737
  };
1670
1738
  }
1671
1739
  } catch (ex) {
1672
- Logger(`Could not check the remote database version`, LOG_LEVEL_NOTICE);
1673
- Logger(ex, LOG_LEVEL_VERBOSE);
1740
+ this.log(`Could not check the remote database version`, LOG_LEVEL_NOTICE);
1741
+ this.log(ex, LOG_LEVEL_VERBOSE);
1674
1742
  return {
1675
1743
  status: RemotePreferredTweakStatuses.UNAVAILABLE,
1676
1744
  error: ex
@@ -1702,8 +1770,8 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1702
1770
  reason: RemotePreferredTweakNotConfiguredReasons.MILESTONE_MISSING
1703
1771
  };
1704
1772
  }
1705
- Logger(`Could not retrieve remote milestone`, LOG_LEVEL_NOTICE);
1706
- Logger(ex, LOG_LEVEL_VERBOSE);
1773
+ this.log(`Could not retrieve remote milestone`, LOG_LEVEL_NOTICE);
1774
+ this.log(ex, LOG_LEVEL_VERBOSE);
1707
1775
  return {
1708
1776
  status: RemotePreferredTweakStatuses.UNAVAILABLE,
1709
1777
  error: ex
@@ -1715,7 +1783,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1715
1783
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
1716
1784
  const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1717
1785
  if (typeof dbRet === "string") {
1718
- Logger(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1786
+ this.log(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1719
1787
  return false;
1720
1788
  }
1721
1789
  return await this.withRemoteConnection(dbRet, async (db) => (await db.compact({ interval: 1e3 })).ok);
@@ -1724,7 +1792,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1724
1792
  const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1725
1793
  if (typeof dbRet === "string") {
1726
1794
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
1727
- Logger(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1795
+ this.log(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1728
1796
  return false;
1729
1797
  }
1730
1798
  return await this.withRemoteConnection(dbRet, async (db) => {
@@ -1739,7 +1807,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1739
1807
  const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1740
1808
  if (typeof dbRet === "string") {
1741
1809
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
1742
- Logger(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1810
+ this.log(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1743
1811
  return false;
1744
1812
  }
1745
1813
  return await this.withRemoteConnection(dbRet, countCompromisedChunks);
@@ -1819,13 +1887,13 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1819
1887
  const dbRet = await this.connectRemoteCouchDBWithSetting(setting, this.isMobile(), true);
1820
1888
  if (typeof dbRet === "string") {
1821
1889
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
1822
- Logger(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1890
+ this.log(this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }), LOG_LEVEL_NOTICE);
1823
1891
  return false;
1824
1892
  }
1825
1893
  return await this.withRemoteConnection(dbRet, async (db) => {
1826
1894
  const milestoneDoc = await db.get(MILESTONE_DOCID);
1827
1895
  if (!milestoneDoc) {
1828
- Logger("Could not retrieve remote milestone", LOG_LEVEL_NOTICE);
1896
+ this.log("Could not retrieve remote milestone", LOG_LEVEL_NOTICE);
1829
1897
  return false;
1830
1898
  }
1831
1899
  const nodeInfo = milestoneDoc.node_info;