@vrtmrz/livesync-commonlib 0.4.3 → 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 (130) hide show
  1. package/README.md +2 -2
  2. package/dist/common/LSError.d.ts +13 -0
  3. package/dist/common/LSError.js +19 -1
  4. package/dist/diagnostics/local.d.ts +7 -2
  5. package/dist/interfaces/DatabaseFileAccess.d.ts +20 -4
  6. package/dist/interfaces/FileHandler.d.ts +67 -1
  7. package/dist/interfaces/FileHandler.js +16 -0
  8. package/dist/interfaces/StorageAccess.d.ts +8 -2
  9. package/dist/interfaces/StorageEventManager.d.ts +7 -0
  10. package/dist/managers/ChunkFetcher.d.ts +16 -0
  11. package/dist/managers/ChunkFetcher.js +190 -112
  12. package/dist/managers/EntryManager/EntryManager.d.ts +7 -0
  13. package/dist/managers/EntryManager/EntryManager.js +6 -0
  14. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +9 -5
  15. package/dist/managers/EntryManager/EntryManagerImpls.js +103 -76
  16. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.d.ts +7 -3
  17. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.js +83 -16
  18. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.d.ts +3 -2
  19. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.js +38 -36
  20. package/dist/managers/LayeredChunkManager/types.d.ts +15 -1
  21. package/dist/managers/LayeredChunkManager.d.ts +4 -0
  22. package/dist/managers/LayeredChunkManager.js +19 -6
  23. package/dist/managers/LiveSyncManagers.d.ts +2 -0
  24. package/dist/managers/LiveSyncManagers.js +6 -0
  25. package/dist/managers/StorageEventManager.d.ts +22 -0
  26. package/dist/managers/StorageEventManager.js +48 -1
  27. package/dist/platform/FilePathIndex.d.ts +110 -0
  28. package/dist/platform/FilePathIndex.js +146 -0
  29. package/dist/pouchdb/LiveSyncLocalDB.d.ts +32 -0
  30. package/dist/pouchdb/LiveSyncLocalDB.js +72 -18
  31. package/dist/pouchdb/LocalDatabaseReadScope.d.ts +24 -0
  32. package/dist/pouchdb/LocalDatabaseReadScope.js +62 -0
  33. package/dist/pouchdb/pathIdentityCompatibility.d.ts +6 -2
  34. package/dist/pouchdb/pathIdentityCompatibility.js +15 -10
  35. package/dist/replication/contentRead.d.ts +3 -0
  36. package/dist/replication/contentRead.js +4 -0
  37. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +8 -1
  38. package/dist/replication/couchdb/LiveSyncReplicator.js +187 -119
  39. package/dist/replication/index.d.ts +5 -1
  40. package/dist/replication/index.js +18 -1
  41. package/dist/replication/trystero/LiveSyncTrysteroReplicator.d.ts +3 -3
  42. package/dist/replication/trystero/P2PAutomationCoordinator.d.ts +1 -1
  43. package/dist/replication/trystero/P2PReplicationWire.d.ts +1 -1
  44. package/dist/replication/trystero/TrysteroReplicator/changeRelay.d.ts +133 -0
  45. package/dist/replication/trystero/TrysteroReplicator/changeRelay.js +176 -0
  46. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.d.ts +55 -0
  47. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.js +99 -0
  48. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.d.ts +83 -0
  49. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.js +121 -0
  50. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.d.ts +75 -0
  51. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.js +131 -0
  52. package/dist/replication/trystero/TrysteroReplicator/progress.d.ts +57 -0
  53. package/dist/replication/trystero/TrysteroReplicator/progress.js +84 -0
  54. package/dist/replication/trystero/TrysteroReplicator/relayControl.d.ts +20 -0
  55. package/dist/replication/trystero/TrysteroReplicator/relayControl.js +25 -0
  56. package/dist/replication/trystero/TrysteroReplicator/transfers.d.ts +125 -0
  57. package/dist/replication/trystero/TrysteroReplicator/transfers.js +278 -0
  58. package/dist/replication/trystero/TrysteroReplicator.d.ts +65 -483
  59. package/dist/replication/trystero/TrysteroReplicator.js +240 -673
  60. package/dist/replication/trystero/TrysteroReplicatorP2PClient.d.ts +19 -6
  61. package/dist/replication/trystero/TrysteroReplicatorP2PClient.js +29 -25
  62. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.d.ts +66 -0
  63. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.js +142 -0
  64. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +19 -16
  65. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +33 -93
  66. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +1 -1
  67. package/dist/replication/trystero/p2pReplicationProgress.d.ts +2 -11
  68. package/dist/replication/trystero/replicationTypes.d.ts +88 -0
  69. package/dist/replication/trystero/replicationTypes.js +0 -0
  70. package/dist/replication/trystero/rpcSessionProvider.d.ts +13 -0
  71. package/dist/replication/trystero/rpcSessionProvider.js +0 -0
  72. package/dist/rpc/RpcRoom/pendingInvocations.d.ts +141 -0
  73. package/dist/rpc/RpcRoom/pendingInvocations.js +225 -0
  74. package/dist/rpc/RpcRoom.d.ts +9 -4
  75. package/dist/rpc/RpcRoom.js +73 -118
  76. package/dist/rpc/RpcSession.d.ts +6 -0
  77. package/dist/rpc/RpcSession.js +11 -0
  78. package/dist/rpc/types.d.ts +2 -0
  79. package/dist/serviceFeatures/offlineScanner/files.d.ts +1 -1
  80. package/dist/serviceFeatures/offlineScanner/files.js +27 -7
  81. package/dist/serviceFeatures/offlineScanner/scan.d.ts +5 -1
  82. package/dist/serviceFeatures/offlineScanner/scan.js +2 -1
  83. package/dist/serviceFeatures/offlineScanner.d.ts +1 -1
  84. package/dist/serviceFeatures/offlineScanner.js +10 -2
  85. package/dist/serviceFeatures/targetFilter.d.ts +1 -1
  86. package/dist/serviceFeatures/targetFilter.js +8 -38
  87. package/dist/serviceModules/FileAccessBase.d.ts +4 -0
  88. package/dist/serviceModules/FileAccessBase.js +10 -0
  89. package/dist/serviceModules/Rebuilder.js +1 -1
  90. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +13 -0
  91. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +190 -123
  92. package/dist/serviceModules/ServiceFileAccessBase/fileNames.d.ts +54 -0
  93. package/dist/serviceModules/ServiceFileAccessBase/fileNames.js +57 -0
  94. package/dist/serviceModules/ServiceFileAccessBase.d.ts +5 -1
  95. package/dist/serviceModules/ServiceFileAccessBase.js +18 -3
  96. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +17 -7
  97. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +3 -2
  98. package/dist/serviceModules/ServiceFileHandlerBase/events.js +9 -9
  99. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -9
  100. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +10 -0
  101. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +28 -4
  102. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +11 -5
  103. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +144 -58
  104. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +16 -2
  105. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +1 -0
  106. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +7 -2
  107. package/dist/serviceModules/ServiceFileHandlerBase.js +13 -4
  108. package/dist/serviceModules/adapters/IFileSystemAdapter.d.ts +3 -0
  109. package/dist/services/base/ControlService.js +1 -5
  110. package/dist/services/base/DatabaseEventService.d.ts +3 -0
  111. package/dist/services/base/DatabaseEventService.js +3 -0
  112. package/dist/services/base/DatabaseService.d.ts +15 -0
  113. package/dist/services/base/DatabaseService.js +85 -4
  114. package/dist/services/base/IService.d.ts +18 -1
  115. package/dist/services/base/KeyValueDBService.d.ts +5 -4
  116. package/dist/services/base/KeyValueDBService.js +46 -48
  117. package/dist/services/base/ReplicationService.d.ts +3 -1
  118. package/dist/services/base/ReplicationService.js +3 -1
  119. package/dist/services/base/VaultScanResult.d.ts +5 -0
  120. package/dist/services/lib/HandlerUtils.d.ts +40 -5
  121. package/dist/services/lib/HandlerUtils.js +52 -4
  122. package/dist/storage.d.ts +2 -0
  123. package/dist/storage.js +2 -0
  124. package/docs/development.md +111 -0
  125. package/docs/offline-scanner.md +46 -0
  126. package/docs/p2p-transport-lifecycle.md +24 -0
  127. package/docs/platform-storage.md +22 -0
  128. package/docs/releasing.md +48 -0
  129. package/docs/settings-lifecycle.md +4 -2
  130. package/package.json +1 -1
@@ -1,3 +1,5 @@
1
+ import { isReflectionCancelled } from "../../interfaces/FileHandler.js";
2
+ import { ContentReadError } from "../../common/LSError.js";
1
3
  import { isFolderInfo, infoToStub } from "./storage.js";
2
4
  import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
3
5
  import {
@@ -146,8 +148,20 @@ async function saveClassifiedStorage(ctx, save, preferredBasePath, retryIfStorag
146
148
  );
147
149
  return false;
148
150
  }
149
- const details = await observeClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges);
150
151
  const recovery = { preferredBasePath, retryIfStorageChanges, snapshotRetry };
152
+ let details;
153
+ try {
154
+ details = await observeClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges);
155
+ } catch (error) {
156
+ if (retryIfStorageChanges || !(error instanceof ContentReadError)) {
157
+ throw error;
158
+ }
159
+ const preserved = await storeClassifiedStorageEdit(ctx, save, { kind: "unknown" }, recovery);
160
+ if (!preserved) {
161
+ throw error;
162
+ }
163
+ return true;
164
+ }
151
165
  const classification = details.classification;
152
166
  if (classification.kind === "unchanged")
153
167
  return await finishUnchangedStorageSave(ctx, save, classification.revision, details, recovery);
@@ -265,7 +279,7 @@ async function finishUnchangedStorageSave(ctx, save, revision, details, recovery
265
279
  await queueConflictCheckFor(ctx, file.path);
266
280
  } else if (!currentEntry || currentEntry.deleted || currentEntry._deleted || revision !== currentEntry._rev) {
267
281
  if (!currentEntry) return false;
268
- return await dbToStorageCore(ctx, file.path, file);
282
+ return !isReflectionCancelled(await dbToStorageCore(ctx, file.path, file));
269
283
  } else {
270
284
  if (upgradeCurrentRecord && snapshotMatches) {
271
285
  await setProvenance(ctx, file.path, revision, readFile.stat.mtime, readFile.body, evidence);
@@ -2,6 +2,7 @@ import { withFileEventPaths } from "./locking.js";
2
2
  import {
3
3
  getProvenancePath,
4
4
  sameProvenance,
5
+ readProvenanceSnapshot,
5
6
  contentEvidence,
6
7
  currentStorageSnapshotMatches,
7
8
  hasContentHash
@@ -1,3 +1,4 @@
1
+ import type { FileReflectionResult, ReflectionOperationContext } from "../interfaces/FileHandler.js";
1
2
  import type { AnyEntry, FilePath, FilePathWithPrefix, MetaEntry, UXFileInfo, UXFileInfoStub, UXInternalFileInfoStub } from "../common/types.js";
2
3
  import type { DeletionRecoveryResult, IFileHandler, StoreFileOptions } from "../interfaces/FileHandler.js";
3
4
  import type { DatabaseFileAccess } from "../interfaces/DatabaseFileAccess.js";
@@ -60,6 +61,8 @@ export declare abstract class ServiceFileHandlerBase extends ServiceModuleBase<S
60
61
  * @returns Whether the scan may skip this unchanged metadata observation.
61
62
  * @remarks Acquire the document lock while checking a metadata-only hint. No revision or file content is written; inspection failures are logged and return false.
62
63
  */
64
+ /** Confirm current bytes against existing provenance without retrieving Chunks. */
65
+ inspectCurrentFileProvenance(path: FilePathWithPrefix, revision: string): Promise<boolean>;
63
66
  canSkipUnchangedFile(info: UXFileInfoStub, expected: MetaEntry): Promise<boolean>;
64
67
  /**
65
68
  * Check the host's explicit deletion-recovery capability without store access.
@@ -161,10 +164,12 @@ export declare abstract class ServiceFileHandlerBase extends ServiceModuleBase<S
161
164
  /**
162
165
  * Select and reflect a replicated document while retaining host override dispatch.
163
166
  * @param entry - The database metadata being processed.
164
- * @returns Whether replication reflection completed; excluded or unsafe documents retain a false result.
167
+ * @returns Completion or a policy hand-off; unsuccessful reads and effects reject to the target owner.
165
168
  * @remarks Acquire the related document lock before selection and reflection. Constructor registration captures the current subclass override with bind; internal public seams remain live at use time.
166
169
  */
167
- _anyProcessReplicatedDoc(entry: MetaEntry): Promise<boolean>;
170
+ _anyProcessReplicatedDoc(entry: MetaEntry, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
171
+ /** Reflect an owner's selected target without converting terminal failures to false. */
172
+ reflectDatabaseEntry(entry: MetaEntry, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
168
173
  /**
169
174
  * Repair missing chunks with at most ten acquired file operations at a time.
170
175
  * @param showingNotice - Whether progress uses notice-level messages instead of informational messages.
@@ -1,4 +1,5 @@
1
1
  import { createFileHandlerContext } from "./ServiceFileHandlerBase/context.js";
2
+ import { inspectCurrentFileProvenance } from "./ServiceFileHandlerBase/provenance.js";
2
3
  import { processFileEvent, processReplicatedDocument } from "./ServiceFileHandlerBase/events.js";
3
4
  import { getFileEntryPath, getFileStoragePath, readStorageFile } from "./ServiceFileHandlerBase/storage.js";
4
5
  import { canSkipUnchangedFile, tryRecordUntrackedFileRevision } from "./ServiceFileHandlerBase/scanning.js";
@@ -9,7 +10,7 @@ import {
9
10
  resolveConflictedByDeletingRevision
10
11
  } from "./ServiceFileHandlerBase/deletion.js";
11
12
  import { renameFileInDB } from "./ServiceFileHandlerBase/renaming.js";
12
- import { dbToStorageWithSpecificRev, dbToStorage } from "./ServiceFileHandlerBase/reflection.js";
13
+ import { dbToStorageWithSpecificRev, dbToStorage, reflectDatabaseEntry } from "./ServiceFileHandlerBase/reflection.js";
13
14
  import { recoverDatabaseDeletion } from "./ServiceFileHandlerBase/deletionRecovery.js";
14
15
  import { createAllChunks } from "./ServiceFileHandlerBase/chunks.js";
15
16
  import { ServiceModuleBase } from "./ServiceModuleBase.js";
@@ -133,6 +134,10 @@ class ServiceFileHandlerBase extends ServiceModuleBase {
133
134
  * @returns Whether the scan may skip this unchanged metadata observation.
134
135
  * @remarks Acquire the document lock while checking a metadata-only hint. No revision or file content is written; inspection failures are logged and return false.
135
136
  */
137
+ /** Confirm current bytes against existing provenance without retrieving Chunks. */
138
+ async inspectCurrentFileProvenance(path, revision) {
139
+ return await inspectCurrentFileProvenance(this.context, path, revision);
140
+ }
136
141
  async canSkipUnchangedFile(info, expected) {
137
142
  return await canSkipUnchangedFile(this.context, info, expected);
138
143
  }
@@ -261,11 +266,15 @@ class ServiceFileHandlerBase extends ServiceModuleBase {
261
266
  /**
262
267
  * Select and reflect a replicated document while retaining host override dispatch.
263
268
  * @param entry - The database metadata being processed.
264
- * @returns Whether replication reflection completed; excluded or unsafe documents retain a false result.
269
+ * @returns Completion or a policy hand-off; unsuccessful reads and effects reject to the target owner.
265
270
  * @remarks Acquire the related document lock before selection and reflection. Constructor registration captures the current subclass override with bind; internal public seams remain live at use time.
266
271
  */
267
- async _anyProcessReplicatedDoc(entry) {
268
- return await processReplicatedDocument(this.context, entry);
272
+ async _anyProcessReplicatedDoc(entry, operation) {
273
+ return await processReplicatedDocument(this.context, entry, operation);
274
+ }
275
+ /** Reflect an owner's selected target without converting terminal failures to false. */
276
+ async reflectDatabaseEntry(entry, info, force, operation) {
277
+ return await reflectDatabaseEntry(this.context, entry, info, force, operation);
269
278
  }
270
279
  /**
271
280
  * Repair missing chunks with at most ten acquired file operations at a time.
@@ -4,6 +4,7 @@ import type { ITypeGuardAdapter } from "./ITypeGuardAdapter.js";
4
4
  import type { IConversionAdapter } from "./IConversionAdapter.js";
5
5
  import type { IStorageAdapter } from "./IStorageAdapter.js";
6
6
  import type { IVaultAdapter } from "./IVaultAdapter.js";
7
+ import type { FileNameLookup } from "../../platform/FilePathIndex.js";
7
8
  /**
8
9
  * Main file system adapter interface
9
10
  * Composes all other adapters and provides platform-specific operations
@@ -17,6 +18,8 @@ export interface IFileSystemAdapter<TNativeAbstractFile = any, TNativeFile = any
17
18
  readonly conversion: IConversionAdapter<TNativeFile, TNativeFolder>;
18
19
  /** Storage operations */
19
20
  readonly storage: IStorageAdapter<TStat>;
21
+ /** Optional maintained file-name inventory and candidate lookup. */
22
+ readonly fileNameLookup?: FileNameLookup;
20
23
  /** Vault operations */
21
24
  readonly vault: IVaultAdapter<TNativeFile>;
22
25
  /**
@@ -59,11 +59,7 @@ class ControlService extends ServiceBase {
59
59
  stopAllRunningProcessors();
60
60
  await this.services.appLifecycleService.onUnload();
61
61
  this._unloaded = true;
62
- const localDatabase = this.services.databaseService.localDatabaseDirect;
63
- if (localDatabase != null) {
64
- localDatabase.onunload();
65
- await localDatabase.close();
66
- }
62
+ await this.services.databaseService.closeDatabase();
67
63
  this.context.events.emitEvent(EVENT_PLATFORM_UNLOADED);
68
64
  this.context.events.offAll();
69
65
  this._log(this.context.translate("moduleLiveSyncMain.logUnloadingPlugin"));
@@ -4,6 +4,9 @@ import { ServiceBase, type ServiceContext } from "./ServiceBase.js";
4
4
  * The DatabaseEventService provides methods for handling database lifecycle events.
5
5
  */
6
6
  export declare abstract class DatabaseEventService<T extends ServiceContext = ServiceContext> extends ServiceBase<T> implements IDatabaseEventService {
7
+ readonly onBeforeDatabaseResume: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
8
+ readonly onBeforeDatabaseRecovery: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
9
+ readonly onAfterDatabaseRecovery: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
7
10
  /**
8
11
  * Event triggered when the database is about to be unloaded.
9
12
  */
@@ -1,6 +1,9 @@
1
1
  import { handlers } from "../lib/HandlerUtils.js";
2
2
  import { ServiceBase } from "./ServiceBase.js";
3
3
  class DatabaseEventService extends ServiceBase {
4
+ onBeforeDatabaseResume = handlers().bailFirstFailure("onBeforeDatabaseResume");
5
+ onBeforeDatabaseRecovery = handlers().bailFirstFailure("onBeforeDatabaseRecovery");
6
+ onAfterDatabaseRecovery = handlers().bailFirstFailure("onAfterDatabaseRecovery");
4
7
  /**
5
8
  * Event triggered when the database is about to be unloaded.
6
9
  */
@@ -21,6 +21,11 @@ export declare abstract class DatabaseService<T extends ServiceContext = Service
21
21
  _log: (msg: unknown, level?: import("octagonal-wheels/common/logger").LOG_LEVEL, key?: string) => void;
22
22
  constructor(context: T, dependencies: DatabaseServiceDependencies);
23
23
  protected _localDatabase: LiveSyncLocalDB | null;
24
+ private readonly databaseLock;
25
+ private closingRequested;
26
+ private databaseSelection;
27
+ /** Observes a failed local operation; handlers must not retry that operation. */
28
+ readonly onLocalDatabaseError: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(database: LiveSyncLocalDB, error: unknown) => Promise<boolean>>;
24
29
  protected services: DatabaseServiceDependencies;
25
30
  onOpenDatabase: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(vaultName: string) => Promise<boolean>>;
26
31
  /** Called after the active database has been reset and successfully reinitialised. */
@@ -32,10 +37,20 @@ export declare abstract class DatabaseService<T extends ServiceContext = Service
32
37
  options: PouchDB.Configuration.DatabaseConfiguration;
33
38
  };
34
39
  createPouchDBInstance<T extends object>(name?: string, options?: PouchDB.Configuration.DatabaseConfiguration): PouchDB.Database<T>;
40
+ private selectDatabase;
41
+ private isSelectedDatabase;
35
42
  openDatabase(params: openDatabaseParameters): Promise<boolean>;
43
+ /** Replace only the failed lifetime; a queued duplicate cannot close its replacement. */
44
+ reopenDatabase(database: LiveSyncLocalDB, params: openDatabaseParameters): Promise<boolean>;
45
+ /** Check only an initialised, currently owned Pouch. This does not construct a Pouch instance. */
46
+ canReadCurrentDatabaseInfo(): Promise<boolean>;
47
+ /** Closing participates in the same owner lock as opening and recovery. */
48
+ closeDatabase(): Promise<void>;
49
+ private openDatabaseUnlocked;
36
50
  isDatabaseReady(): boolean;
37
51
  private discardFailedActiveDatabase;
38
52
  resetDatabase(): Promise<boolean>;
53
+ private resetDatabaseUnlocked;
39
54
  /**
40
55
  * Reset the database selected by the current settings.
41
56
  *
@@ -1,8 +1,9 @@
1
+ import { withLock } from "octagonal-wheels/concurrency/lock";
1
2
  import { ServiceBase } from "./ServiceBase.js";
2
3
  import { LiveSyncLocalDB } from "../../pouchdb/LiveSyncLocalDB.js";
3
4
  import { handlers } from "../lib/HandlerUtils.js";
4
5
  import { createInstanceLogFunction } from "../lib/logUtils.js";
5
- import { ExtraSuffixIndexedDB } from "../../common/models/shared.const.js";
6
+ import { ExtraSuffixIndexedDB, SuffixDatabaseName } from "../../common/models/shared.const.js";
6
7
  import { LOG_LEVEL_VERBOSE } from "../../common/logger.js";
7
8
  class DatabaseService extends ServiceBase {
8
9
  _log = createInstanceLogFunction("InjectableDatabaseService");
@@ -11,6 +12,11 @@ class DatabaseService extends ServiceBase {
11
12
  this.services = dependencies;
12
13
  }
13
14
  _localDatabase = null;
15
+ databaseLock = /* @__PURE__ */ Symbol("local-database-lifecycle");
16
+ closingRequested = false;
17
+ databaseSelection;
18
+ /** Observes a failed local operation; handlers must not retry that operation. */
19
+ onLocalDatabaseError = handlers().allSettled("onLocalDatabaseError");
14
20
  services;
15
21
  // Additional process when opening database, such as initialising managers or local database instance.
16
22
  onOpenDatabase = handlers().bailFirstFailure("onOpenDatabase");
@@ -45,11 +51,74 @@ class DatabaseService extends ServiceBase {
45
51
  const optionPass = this.modifyDatabaseOptions(settings, name ?? "", options ?? {});
46
52
  return new this.services.pouchDB(optionPass.name, optionPass.options);
47
53
  }
54
+ selectDatabase() {
55
+ const vaultName = this.services.vault.getVaultName();
56
+ const resolved = this.modifyDatabaseOptions(
57
+ this.services.setting.currentSettings(),
58
+ vaultName + SuffixDatabaseName,
59
+ {}
60
+ );
61
+ return { vaultName, ...resolved };
62
+ }
63
+ isSelectedDatabase(selection) {
64
+ const current = this.selectDatabase();
65
+ return current.name === selection.name && current.options.adapter === selection.options.adapter;
66
+ }
48
67
  async openDatabase(params) {
68
+ return await withLock(this.databaseLock, async () => {
69
+ this.closingRequested = false;
70
+ return await this.openDatabaseUnlocked(params);
71
+ });
72
+ }
73
+ /** Replace only the failed lifetime; a queued duplicate cannot close its replacement. */
74
+ async reopenDatabase(database, params) {
75
+ return await withLock(this.databaseLock, async () => {
76
+ if (this.closingRequested || this._localDatabase !== database) {
77
+ return false;
78
+ }
79
+ const selection = this.databaseSelection;
80
+ if (!selection || !this.isSelectedDatabase(selection)) {
81
+ return false;
82
+ }
83
+ database.isReady = false;
84
+ database.stopReads();
85
+ if (params.databaseEvents?.onBeforeDatabaseRecovery && !await params.databaseEvents.onBeforeDatabaseRecovery()) {
86
+ return false;
87
+ }
88
+ if (this.closingRequested || this._localDatabase !== database || !this.isSelectedDatabase(selection)) {
89
+ return false;
90
+ }
91
+ return await this.openDatabaseUnlocked(params, selection);
92
+ });
93
+ }
94
+ /** Check only an initialised, currently owned Pouch. This does not construct a Pouch instance. */
95
+ async canReadCurrentDatabaseInfo() {
96
+ const database = this._localDatabase;
97
+ if (this.closingRequested || !database?.isReady || !database.localDatabase) {
98
+ return false;
99
+ }
100
+ await database.readFromDatabase((pouch) => pouch.info());
101
+ return !this.closingRequested && this._localDatabase === database && database.isReady;
102
+ }
103
+ /** Closing participates in the same owner lock as opening and recovery. */
104
+ async closeDatabase() {
105
+ this.closingRequested = true;
106
+ await withLock(this.databaseLock, async () => {
107
+ const database = this._localDatabase;
108
+ if (database) {
109
+ database.onunload();
110
+ await database.close();
111
+ if (this._localDatabase === database) {
112
+ this._localDatabase = null;
113
+ }
114
+ }
115
+ });
116
+ }
117
+ async openDatabaseUnlocked(params, selection = this.selectDatabase()) {
49
118
  if (this._localDatabase != null) {
50
119
  await this._localDatabase.close();
51
120
  }
52
- const vaultName = this.services.vault.getVaultName();
121
+ const { vaultName } = selection;
53
122
  this._log(this.context.translate("moduleLocalDatabase.logWaitingForReady"));
54
123
  const env = {
55
124
  services: {
@@ -59,7 +128,10 @@ class DatabaseService extends ServiceBase {
59
128
  database: this
60
129
  }
61
130
  };
62
- const selectedDatabase = new LiveSyncLocalDB(vaultName, env);
131
+ const selectedDatabase = new LiveSyncLocalDB(vaultName, env, {
132
+ createPouchDBInstance: (_name, options) => new this.services.pouchDB(selection.name, { ...options, ...selection.options })
133
+ });
134
+ this.databaseSelection = selection;
63
135
  this._localDatabase = selectedDatabase;
64
136
  try {
65
137
  await this.onOpenDatabase(vaultName);
@@ -76,7 +148,7 @@ class DatabaseService extends ServiceBase {
76
148
  }
77
149
  }
78
150
  isDatabaseReady() {
79
- return this._localDatabase != null && this._localDatabase.isReady;
151
+ return !this.closingRequested && this._localDatabase != null && this._localDatabase.isReady;
80
152
  }
81
153
  async discardFailedActiveDatabase(database) {
82
154
  if (this._localDatabase === database) {
@@ -90,6 +162,15 @@ class DatabaseService extends ServiceBase {
90
162
  }
91
163
  }
92
164
  async resetDatabase() {
165
+ const selected = this._localDatabase;
166
+ return await withLock(this.databaseLock, () => {
167
+ if (this._localDatabase !== selected) {
168
+ return false;
169
+ }
170
+ return this.resetDatabaseUnlocked();
171
+ });
172
+ }
173
+ async resetDatabaseUnlocked() {
93
174
  if (!this._localDatabase) {
94
175
  return Promise.resolve(true);
95
176
  }
@@ -17,6 +17,7 @@ import type { ActiveReplicatorContext, ContinuousReplicationRequest, Replication
17
17
  import type { RemoteResourceKind, RemoteResourceMap } from "../../replication/RemoteResource.js";
18
18
  import type { CentralRemoteAdministrationRequest, CentralRemoteAdministrationResult } from "../../replication/CentralRemoteAdministration.js";
19
19
  import type { HandlerOutcome, MultipleHandlerFunction } from "../lib/HandlerUtils.js";
20
+ import type { FileReflectionResult, ReflectionOperationContext, ReflectionTarget } from "../../interfaces/FileHandler.js";
20
21
  import type { VaultScanResult, VaultScanOptions } from "./VaultScanResult.js";
21
22
  import type { UICommandRegistry } from "../../uiCommands.js";
22
23
  declare global {
@@ -78,8 +79,14 @@ export interface openDatabaseParameters {
78
79
  }
79
80
  export interface IDatabaseService {
80
81
  localDatabase: LiveSyncLocalDB;
82
+ /** Current physical owner, without constructing a database or throwing before open. */
83
+ readonly localDatabaseDirect: LiveSyncLocalDB | null;
81
84
  createPouchDBInstance<T extends object>(name?: string, options?: PouchDB.Configuration.DatabaseConfiguration): PouchDB.Database<T>;
82
85
  openDatabase(params: openDatabaseParameters): Promise<boolean>;
86
+ reopenDatabase(database: LiveSyncLocalDB, params: openDatabaseParameters): Promise<boolean>;
87
+ canReadCurrentDatabaseInfo(): Promise<boolean>;
88
+ closeDatabase(): Promise<void>;
89
+ onLocalDatabaseError?(database: LiveSyncLocalDB, error: unknown): Promise<boolean>;
83
90
  resetDatabase(): Promise<boolean>;
84
91
  resetDatabaseForCurrentSettings(params: openDatabaseParameters): Promise<boolean>;
85
92
  onDatabaseReset: () => Promise<boolean>;
@@ -87,6 +94,12 @@ export interface IDatabaseService {
87
94
  isDatabaseReady(): boolean;
88
95
  }
89
96
  export interface IDatabaseEventService {
97
+ /** Host foreground gate, before pending file work and replication resume. */
98
+ onBeforeDatabaseResume(): Promise<boolean>;
99
+ /** Stop dispatch and settle accepted host work before a connection is replaced. */
100
+ onBeforeDatabaseRecovery(): Promise<boolean>;
101
+ /** Continue held host work after the connection and pending local edits are ready. */
102
+ onAfterDatabaseRecovery(): Promise<boolean>;
90
103
  onUnloadDatabase(db: LiveSyncLocalDB): Promise<boolean>;
91
104
  onCloseDatabase(db: LiveSyncLocalDB): Promise<boolean>;
92
105
  onDatabaseInitialisation(db: LiveSyncLocalDB): Promise<boolean>;
@@ -188,10 +201,14 @@ export interface IReplicatorService {
188
201
  export type ReplicatorFactoryCallback = (settingOverride?: Partial<ObsidianLiveSyncSettings>) => Promise<ReplicatorInstance | undefined | false>;
189
202
  export type ReplicatorFactoryHandler = MultipleHandlerFunction<ReplicatorFactoryCallback>;
190
203
  export interface IReplicationService {
191
- processSynchroniseResult(doc: MetaEntry): Promise<boolean>;
204
+ processSynchroniseResult(doc: MetaEntry, operation?: ReflectionOperationContext): Promise<FileReflectionResult | undefined>;
192
205
  processOptionalSynchroniseResult(doc: LoadedEntry): Promise<boolean>;
193
206
  processVirtualDocument(docs: PouchDB.Core.ExistingDocument<EntryDoc>): Promise<boolean>;
194
207
  onBeforeReplicate(showMessage: boolean): Promise<boolean>;
208
+ /** Notify hosts after a successful finite pull or sync, including zero-change completions. */
209
+ onFiniteReplicationCompleted(): Promise<boolean>;
210
+ /** Notify the owning startup scan that a file's content could not be read. */
211
+ onFileReflectionFailed(target: ReflectionTarget, error: unknown): Promise<boolean>;
195
212
  /** Prepare provider state which exists only for the central remote. */
196
213
  onPrepareCentralRemoteReplication(showMessage: boolean): Promise<boolean>;
197
214
  checkConnectionFailure(failure: ReplicationAttemptFailure): Promise<boolean | "CHECKAGAIN" | undefined>;
@@ -17,6 +17,8 @@ export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContex
17
17
  */
18
18
  export declare abstract class KeyValueDBService<T extends ServiceContext = ServiceContext> extends ServiceBase<T> implements IKeyValueDBService {
19
19
  private _kvDB;
20
+ private databaseKey;
21
+ private readonly lifecycleLock;
20
22
  private _simpleStore;
21
23
  get simpleStore(): SimpleStore<unknown, any>;
22
24
  get kvDB(): KeyValueDatabase;
@@ -25,12 +27,11 @@ export declare abstract class KeyValueDBService<T extends ServiceContext = Servi
25
27
  private appLifecycle;
26
28
  private openKeyValueDatabase;
27
29
  private _log;
30
+ private selectedDatabaseKey;
28
31
  private _everyOnResetDatabase;
29
- private tryCloseKvDB;
32
+ private closeKeyValueDB;
33
+ private openSelectedDatabase;
30
34
  private openKeyValueDB;
31
- private _onOtherDatabaseUnload;
32
- private _onOtherDatabaseClose;
33
- private _everyOnInitializeDatabase;
34
35
  private _everyOnloadAfterLoadSettings;
35
36
  constructor(context: T, dependencies: KeyValueDBDependencies<T>);
36
37
  /**
@@ -1,9 +1,11 @@
1
1
  import { ServiceBase } from "./ServiceBase.js";
2
- import { delay, yieldMicrotask } from "octagonal-wheels/promises";
2
+ import { withLock } from "octagonal-wheels/concurrency/lock";
3
3
  import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "../../common/logger.js";
4
4
  import { createInstanceLogFunction } from "../lib/logUtils.js";
5
5
  class KeyValueDBService extends ServiceBase {
6
6
  _kvDB;
7
+ databaseKey;
8
+ lifecycleLock = /* @__PURE__ */ Symbol("key-value-database-lifecycle");
7
9
  _simpleStore;
8
10
  get simpleStore() {
9
11
  if (!this._simpleStore) {
@@ -22,63 +24,57 @@ class KeyValueDBService extends ServiceBase {
22
24
  appLifecycle;
23
25
  openKeyValueDatabase;
24
26
  _log = createInstanceLogFunction("KeyValueDBService");
25
- async _everyOnResetDatabase(any) {
26
- try {
27
- const kvDBKey = "queued-files";
28
- await this._kvDB?.del(kvDBKey);
29
- await this._kvDB?.destroy();
30
- await yieldMicrotask();
31
- this._kvDB = await this.openKeyValueDatabase(this.vault.getVaultName() + "-livesync-kv");
32
- await delay(100);
33
- } catch (e) {
27
+ selectedDatabaseKey() {
28
+ return this.vault.getVaultName() + "-livesync-kv";
29
+ }
30
+ async _everyOnResetDatabase() {
31
+ return await withLock(this.lifecycleLock, async () => {
32
+ const previous = this._kvDB;
34
33
  this._kvDB = void 0;
35
- this._log("Failed to reset KeyValueDB", LOG_LEVEL_NOTICE);
36
- this._log(e, LOG_LEVEL_VERBOSE);
37
- return false;
38
- }
39
- return true;
34
+ this.databaseKey = void 0;
35
+ try {
36
+ await previous?.destroy();
37
+ return await this.openSelectedDatabase();
38
+ } catch (error) {
39
+ this._log("Failed to reset KeyValueDB", LOG_LEVEL_NOTICE);
40
+ this._log(error, LOG_LEVEL_VERBOSE);
41
+ return false;
42
+ }
43
+ });
40
44
  }
41
- async tryCloseKvDB() {
45
+ async closeKeyValueDB() {
46
+ const previous = this._kvDB;
47
+ this._kvDB = void 0;
48
+ this.databaseKey = void 0;
42
49
  try {
43
- await this._kvDB?.close();
50
+ await previous?.close();
44
51
  return true;
45
- } catch (e) {
52
+ } catch (error) {
46
53
  this._log("Failed to close KeyValueDB", LOG_LEVEL_VERBOSE);
47
- this._log(e);
54
+ this._log(error, LOG_LEVEL_VERBOSE);
48
55
  return false;
49
56
  }
50
57
  }
51
- async openKeyValueDB() {
52
- await delay(10);
58
+ async openSelectedDatabase() {
59
+ const selectedKey = this.selectedDatabaseKey();
60
+ if (this._kvDB && this.databaseKey === selectedKey) {
61
+ return true;
62
+ }
63
+ if (!await this.closeKeyValueDB()) {
64
+ return false;
65
+ }
53
66
  try {
54
- await this.tryCloseKvDB();
55
- await delay(10);
56
- await yieldMicrotask();
57
- this._kvDB = await this.openKeyValueDatabase(this.vault.getVaultName() + "-livesync-kv");
58
- await yieldMicrotask();
59
- await delay(100);
60
- } catch (e) {
61
- this._kvDB = void 0;
67
+ this._kvDB = await this.openKeyValueDatabase(selectedKey);
68
+ this.databaseKey = selectedKey;
69
+ return true;
70
+ } catch (error) {
62
71
  this._log("Failed to open KeyValueDB", LOG_LEVEL_NOTICE);
63
- this._log(e, LOG_LEVEL_VERBOSE);
72
+ this._log(error, LOG_LEVEL_VERBOSE);
64
73
  return false;
65
74
  }
66
- return true;
67
- }
68
- // Called when another database; LiveSyncLocalDB, is being unloaded.
69
- // We need to close our KeyValueDB to avoid IndexedDB locking issues.
70
- async _onOtherDatabaseUnload() {
71
- if (this._kvDB) await this.tryCloseKvDB();
72
- return Promise.resolve(true);
73
- }
74
- // Also, Called when another database; LiveSyncLocalDB, is being closed.
75
- // We need to close our KeyValueDB to avoid IndexedDB locking issues.
76
- async _onOtherDatabaseClose() {
77
- if (this._kvDB) await this.tryCloseKvDB();
78
- return Promise.resolve(true);
79
75
  }
80
- _everyOnInitializeDatabase(any) {
81
- return this.openKeyValueDB();
76
+ openKeyValueDB() {
77
+ return withLock(this.lifecycleLock, () => this.openSelectedDatabase());
82
78
  }
83
79
  async _everyOnloadAfterLoadSettings() {
84
80
  if (!await this.openKeyValueDB()) {
@@ -96,9 +92,11 @@ class KeyValueDBService extends ServiceBase {
96
92
  if (dependencies.registerLifecycleHandlers ?? true) {
97
93
  this.databaseEvents.onResetDatabase.addHandler(this._everyOnResetDatabase.bind(this));
98
94
  this.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));
99
- this.databaseEvents.onDatabaseInitialisation.addHandler(this._everyOnInitializeDatabase.bind(this));
100
- this.databaseEvents.onUnloadDatabase.addHandler(this._onOtherDatabaseUnload.bind(this));
101
- this.databaseEvents.onCloseDatabase.addHandler(this._onOtherDatabaseClose.bind(this));
95
+ this.databaseEvents.onDatabaseInitialisation.addHandler(() => this.openKeyValueDB());
96
+ this.appLifecycle.onUnload.addHandler(
97
+ () => withLock(this.lifecycleLock, () => this.closeKeyValueDB()),
98
+ 100
99
+ );
102
100
  }
103
101
  }
104
102
  /**
@@ -37,7 +37,7 @@ export declare abstract class ReplicationService<T extends ServiceContext = Serv
37
37
  /**
38
38
  * Process a synchronisation result document.
39
39
  */
40
- readonly processSynchroniseResult: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(doc: import("../../common/types.js").MetaEntry) => Promise<boolean>>;
40
+ readonly processSynchroniseResult: import("../lib/HandlerUtils.js").FirstApplicableFunction<(doc: import("../../common/types.js").MetaEntry, operation?: import("../../interfaces/FileHandler.js").ReflectionOperationContext) => Promise<import("../../interfaces/FileHandler.js").FileReflectionResult | undefined>>;
41
41
  /**
42
42
  * Process a synchronisation result document for optional entries i.e., hidden files.
43
43
  */
@@ -55,6 +55,8 @@ export declare abstract class ReplicationService<T extends ServiceContext = Serv
55
55
  * An event triggered before starting replication.
56
56
  */
57
57
  readonly onBeforeReplicate: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(showMessage: boolean) => Promise<boolean>>;
58
+ readonly onFiniteReplicationCompleted: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
59
+ readonly onFileReflectionFailed: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(target: import("../../interfaces/FileHandler.js").ReflectionTarget, error: unknown) => Promise<boolean>>;
58
60
  /** Provider preparation which applies only to the central remote. */
59
61
  readonly onPrepareCentralRemoteReplication: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(showMessage: boolean) => Promise<boolean>>;
60
62
  /**
@@ -152,7 +152,7 @@ class ReplicationService extends ServiceBase {
152
152
  /**
153
153
  * Process a synchronisation result document.
154
154
  */
155
- processSynchroniseResult = handlers().anySuccess("processSynchroniseResult");
155
+ processSynchroniseResult = handlers().firstApplicable("processSynchroniseResult");
156
156
  /**
157
157
  * Process a synchronisation result document for optional entries i.e., hidden files.
158
158
  */
@@ -172,6 +172,8 @@ class ReplicationService extends ServiceBase {
172
172
  * An event triggered before starting replication.
173
173
  */
174
174
  onBeforeReplicate = handlers().bailFirstFailure("onBeforeReplicate");
175
+ onFiniteReplicationCompleted = handlers().allSettled("onFiniteReplicationCompleted");
176
+ onFileReflectionFailed = handlers().allOrThrow("onFileReflectionFailed");
175
177
  /** Provider preparation which applies only to the central remote. */
176
178
  onPrepareCentralRemoteReplication = handlers().bailFirstFailure(
177
179
  "onPrepareCentralRemoteReplication"
@@ -1,3 +1,4 @@
1
+ import type { ReflectionOperationContext, ReflectionTarget } from "../../interfaces/FileHandler.js";
1
2
  /**
2
3
  * Outcome of scanning the Vault against the local database.
3
4
  *
@@ -14,5 +15,9 @@ export declare const VaultScanResults: {
14
15
  export interface VaultScanOptions {
15
16
  /** False permits unchanged tracked files to be skipped using storage and revision metadata. */
16
17
  strictContentCheck?: boolean;
18
+ /** Existing target scope borrowed by a retained scan retry, including its write checkpoint. */
19
+ reflectionOperation?: ReflectionOperationContext;
20
+ /** Await the owning host's response to an unsuccessful database-to-Vault content read. */
21
+ onReflectionFailed?: (target: ReflectionTarget, error: unknown) => void | Promise<void>;
17
22
  }
18
23
  export type VaultScanResult = (typeof VaultScanResults)[keyof typeof VaultScanResults];