@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,22 +1,14 @@
1
- import { Logger, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
2
- import { LiveSyncError } from "../../common/LSError.js";
1
+ import { ContentReadError } from "../../common/LSError.js";
3
2
  class DatabaseReadLayer {
4
- constructor(database) {
3
+ constructor(database, readScope) {
5
4
  this.database = database;
5
+ this.readScope = readScope;
6
6
  }
7
7
  database;
8
+ readScope;
8
9
  isChunkDoc(doc) {
9
10
  return doc && typeof doc._id === "string" && doc.type === "leaf";
10
11
  }
11
- getError(error) {
12
- if (error instanceof Error) {
13
- return error;
14
- }
15
- if (typeof error === "object" && error !== null && "error" in error && error.error instanceof Error) {
16
- return error.error;
17
- }
18
- return void 0;
19
- }
20
12
  isMissingError(error) {
21
13
  if (typeof error !== "object" || error === null) {
22
14
  return false;
@@ -27,9 +19,6 @@ class DatabaseReadLayer {
27
19
  if ("error" in error && error.error === "not_found") {
28
20
  return true;
29
21
  }
30
- if ("error" in error) {
31
- return this.isMissingError(error.error);
32
- }
33
22
  return false;
34
23
  }
35
24
  async read(ids, options, next) {
@@ -38,31 +27,44 @@ class DatabaseReadLayer {
38
27
  }
39
28
  const resultMap = /* @__PURE__ */ new Map();
40
29
  const remainingIds = [];
30
+ let results;
41
31
  try {
42
- const results = await this.database.allDocs({ keys: ids, include_docs: true });
43
- for (const row of results.rows) {
44
- if ("doc" in row && row.doc && this.isChunkDoc(row.doc)) {
45
- const chunk = row.doc;
46
- resultMap.set(chunk._id, chunk);
47
- } else if (!this.isMissingError(row)) {
48
- throw new LiveSyncError(`Failed to read chunk ${row.key}`, {
49
- status: 404,
50
- cause: this.getError(row)
51
- });
52
- } else {
53
- const idFromRow = typeof row.key === "string" ? row.key : void 0;
54
- if (idFromRow) {
55
- remainingIds.push(idFromRow);
56
- }
32
+ const read = () => this.database.allDocs({ keys: ids, include_docs: true });
33
+ results = await (this.readScope ? this.readScope.run(read) : read());
34
+ } catch (error) {
35
+ const localFailure = new ContentReadError({
36
+ documentId: ids[0],
37
+ resources: ["local-database"],
38
+ cause: error
39
+ });
40
+ if (this.readScope?.isClosed) throw localFailure;
41
+ try {
42
+ const fallback = await next(ids);
43
+ if (fallback.every(Boolean)) {
44
+ return fallback;
57
45
  }
46
+ } catch (fallbackError) {
47
+ const resources = fallbackError instanceof ContentReadError ? fallbackError.failure.resources : [];
48
+ throw new ContentReadError({
49
+ documentId: ids[0],
50
+ resources: resources.length === 0 ? [] : [.../* @__PURE__ */ new Set(["local-database", ...resources])],
51
+ cause: new AggregateError([error, fallbackError], "Local and fallback Chunk reads failed")
52
+ });
58
53
  }
59
- } catch (error) {
60
- if (error instanceof LiveSyncError) {
61
- throw error;
54
+ throw localFailure;
55
+ }
56
+ for (const row of results.rows) {
57
+ if ("doc" in row && row.doc && this.isChunkDoc(row.doc)) {
58
+ const chunk = row.doc;
59
+ resultMap.set(chunk._id, chunk);
60
+ } else if (!this.isMissingError(row)) {
61
+ throw new ContentReadError({ documentId: row.key, resources: [], cause: row });
62
+ } else {
63
+ const idFromRow = typeof row.key === "string" ? row.key : void 0;
64
+ if (idFromRow) {
65
+ remainingIds.push(idFromRow);
66
+ }
62
67
  }
63
- Logger(`Database read error!`, LOG_LEVEL_VERBOSE);
64
- Logger(error, LOG_LEVEL_VERBOSE);
65
- return ids.map(() => false);
66
68
  }
67
69
  if (remainingIds.length === 0) {
68
70
  return ids.map((id) => resultMap.get(id) ?? false);
@@ -1,11 +1,21 @@
1
+ import type { LocalDatabaseReadScope } from "../../pouchdb/LocalDatabaseReadScope.js";
1
2
  import type { EntryDoc } from "../../common/models/db.definition.js";
2
3
  import type { DocumentID, EntryLeaf } from "../../common/models/db.type.js";
3
4
  import type { ISettingService } from "../../services/base/IService.js";
4
5
  import type { ChangeManager } from "../ChangeManager.js";
5
- import type { EVENT_CHUNK_FETCHED, EVENT_MISSING_CHUNK_REMOTE, EVENT_MISSING_CHUNKS } from "../ChunkFetcher.js";
6
+ import type { EVENT_CHUNK_FAILED, EVENT_CHUNK_FETCHED, EVENT_MISSING_CHUNK_REMOTE, EVENT_MISSING_CHUNKS } from "../ChunkFetcher.js";
6
7
  import type { ActivityCountSource } from "../ChunkDeliveryCoordinator.js";
8
+ import type { ContentReadResource } from "../../interfaces/DatabaseFileAccess.js";
9
+ import type { LogFunction } from "../../services/lib/logUtils.js";
10
+ export type ChunkDeliveryFailure = {
11
+ resources: readonly ContentReadResource[];
12
+ cause: unknown;
13
+ };
7
14
  export type ChunkManagerOptions = {
15
+ /** Host-owned logger; standalone instances default to the global logger. */
16
+ log?: LogFunction;
8
17
  database: PouchDB.Database<EntryDoc>;
18
+ readScope?: LocalDatabaseReadScope;
9
19
  changeManager: ChangeManager<EntryDoc>;
10
20
  settingService: ISettingService;
11
21
  /** Finite replication which may still deliver a requested chunk. */
@@ -36,4 +46,8 @@ export type ChunkManagerEventMap = {
36
46
  [EVENT_MISSING_CHUNK_REMOTE]: DocumentID;
37
47
  [EVENT_MISSING_CHUNKS]: DocumentID[];
38
48
  [EVENT_CHUNK_FETCHED]: EntryLeaf;
49
+ [EVENT_CHUNK_FAILED]: {
50
+ id: DocumentID;
51
+ failure: ChunkDeliveryFailure;
52
+ };
39
53
  };
@@ -1,5 +1,6 @@
1
1
  import type { DocumentID, EntryDoc, EntryLeaf } from "../common/types.js";
2
2
  import type { ChangeManager } from "./ChangeManager.js";
3
+ import { EVENT_CHUNK_FAILED } from "./ChunkFetcher.js";
3
4
  import type { ChunkManagerEventMap, ChunkManagerOptions, ChunkReadOptions, ChunkWriteOptions, WriteResult } from "./LayeredChunkManager/types.js";
4
5
  import { ChunkDeliveryCoordinator } from "./ChunkDeliveryCoordinator.js";
5
6
  /**
@@ -8,6 +9,7 @@ import { ChunkDeliveryCoordinator } from "./ChunkDeliveryCoordinator.js";
8
9
  */
9
10
  export declare class LayeredChunkManager {
10
11
  protected options: ChunkManagerOptions;
12
+ private readonly log;
11
13
  protected eventTarget: EventTarget;
12
14
  private cacheLayer;
13
15
  private databaseReadLayer;
@@ -45,6 +47,8 @@ export declare class LayeredChunkManager {
45
47
  protected onChangeHandler: (change: PouchDB.Core.ChangesResponseChange<EntryDoc>) => void;
46
48
  onMissingChunkRemote(id: DocumentID): void;
47
49
  protected onMissingChunkRemoteHandler: (id: DocumentID) => void;
50
+ private onChunkFailed;
51
+ protected onChunkFailedHandler: ({ id, failure }: ChunkManagerEventMap[typeof EVENT_CHUNK_FAILED]) => void;
48
52
  protected concurrentTransactions: number;
49
53
  protected stabilised: Promise<void>;
50
54
  transaction<T>(callback: () => Promise<T>): Promise<T>;
@@ -1,6 +1,11 @@
1
1
  import { LOG_LEVEL_VERBOSE, Logger } from "../common/logger.js";
2
2
  import { promiseWithResolvers } from "octagonal-wheels/promises";
3
- import { EVENT_MISSING_CHUNK_REMOTE, EVENT_MISSING_CHUNKS, EVENT_CHUNK_FETCHED } from "./ChunkFetcher.js";
3
+ import {
4
+ EVENT_MISSING_CHUNK_REMOTE,
5
+ EVENT_MISSING_CHUNKS,
6
+ EVENT_CHUNK_FETCHED,
7
+ EVENT_CHUNK_FAILED
8
+ } from "./ChunkFetcher.js";
4
9
  import { DatabaseReadLayer } from "./LayeredChunkManager/DatabaseReadLayer.js";
5
10
  import { CacheLayer } from "./LayeredChunkManager/CacheLayer.js";
6
11
  import { ArrivalWaitLayer } from "./LayeredChunkManager/ArrivalWaitLayer.js";
@@ -9,6 +14,7 @@ import { unique } from "octagonal-wheels/collection";
9
14
  import { ChunkDeliveryCoordinator } from "./ChunkDeliveryCoordinator.js";
10
15
  class LayeredChunkManager {
11
16
  options;
17
+ log;
12
18
  eventTarget = new EventTarget();
13
19
  // Middleware layers
14
20
  cacheLayer;
@@ -46,15 +52,16 @@ class LayeredChunkManager {
46
52
  // initialisation promise to ensure the manager is ready before processing transactions
47
53
  initialised = Promise.resolve();
48
54
  async _initialise() {
49
- Logger("ChunkManager initialised", LOG_LEVEL_VERBOSE);
55
+ this.log("ChunkManager initialised", LOG_LEVEL_VERBOSE);
50
56
  return await Promise.resolve();
51
57
  }
52
58
  constructor(options) {
53
59
  this.options = options;
60
+ this.log = options.log ?? Logger;
54
61
  const settings = options.settingService.currentSettings();
55
62
  const maxCacheSize = settings.hashCacheMaxCount * 10;
56
63
  this.cacheLayer = new CacheLayer(maxCacheSize);
57
- this.databaseReadLayer = new DatabaseReadLayer(this.database);
64
+ this.databaseReadLayer = new DatabaseReadLayer(this.database, options.readScope);
58
65
  this.deliveryCoordinator = new ChunkDeliveryCoordinator(options.finiteReplicationActivity);
59
66
  this.arrivalWaitLayer = new ArrivalWaitLayer(
60
67
  (eventName, data) => {
@@ -67,7 +74,8 @@ class LayeredChunkManager {
67
74
  [...ids],
68
75
  { preventRemoteRequest: true, skipCache: true, waitForDelivery: false },
69
76
  (remaining) => Promise.resolve(remaining.map(() => false))
70
- )
77
+ ),
78
+ this.log
71
79
  );
72
80
  this.readLayers = [this.cacheLayer, this.databaseReadLayer, this.arrivalWaitLayer];
73
81
  this.writeLayers = [
@@ -78,6 +86,7 @@ class LayeredChunkManager {
78
86
  this.offChangeHandler = this.changeManager.addCallback(this.onChangeHandler);
79
87
  this.addListener(EVENT_CHUNK_FETCHED, this.onChunkArrivedHandler, { signal: this.abort.signal });
80
88
  this.addListener(EVENT_MISSING_CHUNK_REMOTE, this.onMissingChunkRemoteHandler, { signal: this.abort.signal });
89
+ this.addListener(EVENT_CHUNK_FAILED, this.onChunkFailedHandler, { signal: this.abort.signal });
81
90
  this.initialised = this._initialise();
82
91
  }
83
92
  destroy() {
@@ -202,6 +211,10 @@ class LayeredChunkManager {
202
211
  this.arrivalWaitLayer.onMissingChunk(id);
203
212
  }
204
213
  onMissingChunkRemoteHandler = this.onMissingChunkRemote.bind(this);
214
+ onChunkFailed({ id, failure }) {
215
+ this.arrivalWaitLayer.onChunkFailed(id, failure);
216
+ }
217
+ onChunkFailedHandler = this.onChunkFailed.bind(this);
205
218
  // Transaction management
206
219
  concurrentTransactions = 0;
207
220
  stabilised = Promise.resolve();
@@ -215,10 +228,10 @@ class LayeredChunkManager {
215
228
  } finally {
216
229
  this.concurrentTransactions--;
217
230
  if (this.concurrentTransactions === 0) {
218
- Logger(`All transactions completed. Performing stabilisation.`, LOG_LEVEL_VERBOSE);
231
+ this.log(`All transactions completed. Performing stabilisation.`, LOG_LEVEL_VERBOSE);
219
232
  await this._stabilise();
220
233
  } else {
221
- Logger(`Transaction completed. Remaining: ${this.concurrentTransactions}`, LOG_LEVEL_VERBOSE);
234
+ this.log(`Transaction completed. Remaining: ${this.concurrentTransactions}`, LOG_LEVEL_VERBOSE);
222
235
  }
223
236
  }
224
237
  }
@@ -1,3 +1,4 @@
1
+ import type { LocalDatabaseReadScope } from "../pouchdb/LocalDatabaseReadScope.js";
1
2
  import { type EntryDoc } from "../common/types.js";
2
3
  import { ContentSplitter } from "../ContentSplitter/ContentSplitters.js";
3
4
  import { ChangeManager } from "./ChangeManager.js";
@@ -11,6 +12,7 @@ import type { IAPIService, IDatabaseService, IPathService, IReplicatorService, I
11
12
  import { type LogFunction } from "../services/lib/logUtils.js";
12
13
  export interface LiveSyncManagersOptions<TSettingService extends ISettingService = ISettingService> {
13
14
  database: PouchDB.Database<EntryDoc>;
15
+ readScope?: LocalDatabaseReadScope;
14
16
  databaseService: IDatabaseService;
15
17
  settingService: TSettingService;
16
18
  pathService: IPathService;
@@ -59,6 +59,7 @@ class LiveSyncManagers {
59
59
  getManagerMembers() {
60
60
  this.log("Creating LiveSync Managers...");
61
61
  const database = this.options.database;
62
+ const readScope = this.options.readScope;
62
63
  const changeManager = new ChangeManager({
63
64
  database
64
65
  });
@@ -69,19 +70,24 @@ class LiveSyncManagers {
69
70
  settingService: this.options.settingService
70
71
  });
71
72
  const chunkManager = new ChunkManager({
73
+ log: createInstanceLogFunction("ChunkManager", this._APIService),
72
74
  changeManager,
73
75
  database,
76
+ readScope,
74
77
  settingService: this.options.settingService,
75
78
  finiteReplicationActivity: this.options.replicatorService.finiteReplicationActivityCount
76
79
  });
77
80
  const chunkFetcher = new ChunkFetcher({
81
+ log: createInstanceLogFunction("ChunkFetcher", this._APIService),
78
82
  chunkManager,
79
83
  source: this.options.chunkFetchSource,
80
84
  replicatorService: this.options.replicatorService,
81
85
  settingService: this.options.settingService
82
86
  });
83
87
  const entryManager = new EntryManager({
88
+ log: createInstanceLogFunction("EntryManager", this._APIService),
84
89
  database,
90
+ readScope,
85
91
  hashManager,
86
92
  chunkManager,
87
93
  splitter,
@@ -57,6 +57,9 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
57
57
  protected _waitingMap: Map<string, WaitInfo>;
58
58
  protected processingCount: number;
59
59
  private readonly eventState;
60
+ private dispatchPaused;
61
+ private dispatchResumeSignal;
62
+ private readonly activeDispatches;
60
63
  private readonly buffer;
61
64
  private readonly notifications;
62
65
  private readonly log;
@@ -156,6 +159,18 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
156
159
  * @remarks Later admissions are outside this flush boundary. Batch gates in the captured work are released before waiting.
157
160
  */
158
161
  waitForIdle(): Promise<void>;
162
+ /**
163
+ * Pause new file-handler dispatch and wait for dispatches already in progress.
164
+ * @returns A promise fulfilled after processing that had started at the call settles; queued and not-yet-started work is not awaited.
165
+ * @remarks Event admission, buffering, and snapshotting continue while paused. Repeated calls are safe.
166
+ */
167
+ pauseDispatch(): Promise<void>;
168
+ /**
169
+ * Resume file-handler dispatch after a temporary pause.
170
+ * @returns Nothing; waiting dispatches are released and the existing queue scheduler is asked to continue.
171
+ * @remarks Repeated calls are safe.
172
+ */
173
+ resumeDispatch(): void;
159
174
  /**
160
175
  * Stop accepting events, flush current work, and persist the remaining snapshot.
161
176
  * @returns A promise fulfilled after the final snapshot write; a flush failure is logged, while a final snapshot failure rejects it.
@@ -247,6 +262,13 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
247
262
  * @returns A promise fulfilled on successful completion; attempt failures are recorded and rethrown.
248
263
  */
249
264
  private processOperation;
265
+ /**
266
+ * Hold a file-handler request while dispatch is paused and track requests which have started.
267
+ * @param event - The event passed to the host processing hook after the pause is released.
268
+ * @returns A promise fulfilled when the host processing hook completes.
269
+ * @remarks The pause check and active registration happen synchronously together, preventing a request from starting after a pause.
270
+ */
271
+ private dispatchFileEvent;
250
272
  /**
251
273
  * Retain an event and await its current processing attempt.
252
274
  * @param event - The already selected event to process.
@@ -5,6 +5,7 @@ import {
5
5
  } from "../common/types.js";
6
6
  import { fireAndForget, throttle } from "../common/utils.js";
7
7
  import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
8
+ import { promiseWithResolvers } from "octagonal-wheels/promises";
8
9
  import { StorageEventManager } from "../interfaces/StorageEventManager.js";
9
10
  import { createInstanceLogFunction } from "../services/lib/logUtils.js";
10
11
  import { admitStorageEvents } from "./StorageEventManager/admission.js";
@@ -52,6 +53,9 @@ class StorageEventManagerBase extends StorageEventManager {
52
53
  _waitingMap = /* @__PURE__ */ new Map();
53
54
  processingCount = 0;
54
55
  eventState = createStorageEventState();
56
+ dispatchPaused = false;
57
+ dispatchResumeSignal;
58
+ activeDispatches = /* @__PURE__ */ new Set();
55
59
  buffer = {
56
60
  read: () => this.bufferedQueuedItems,
57
61
  replace: (events) => {
@@ -125,7 +129,7 @@ class StorageEventManagerBase extends StorageEventManager {
125
129
  takeSnapshot: this.queue.takeSnapshot,
126
130
  completeSnapshot: (completion) => this.persistSnapshot(completion),
127
131
  semaphore: () => this.concurrentProcessing,
128
- requestProcessQueue: (event) => this.requestProcessQueue(event),
132
+ requestProcessQueue: (event) => this.dispatchFileEvent(event),
129
133
  cancelWaiting: (event) => {
130
134
  const path = event.args.file.path;
131
135
  if (this._waitingMap.get(path)?.event === event) this._cancelWaiting(path);
@@ -274,6 +278,29 @@ class StorageEventManagerBase extends StorageEventManager {
274
278
  async waitForIdle() {
275
279
  await flushStorageEvents(this.eventState, this.queue);
276
280
  }
281
+ /**
282
+ * Pause new file-handler dispatch and wait for dispatches already in progress.
283
+ * @returns A promise fulfilled after processing that had started at the call settles; queued and not-yet-started work is not awaited.
284
+ * @remarks Event admission, buffering, and snapshotting continue while paused. Repeated calls are safe.
285
+ */
286
+ async pauseDispatch() {
287
+ this.dispatchPaused = true;
288
+ await Promise.all([...this.activeDispatches]);
289
+ }
290
+ /**
291
+ * Resume file-handler dispatch after a temporary pause.
292
+ * @returns Nothing; waiting dispatches are released and the existing queue scheduler is asked to continue.
293
+ * @remarks Repeated calls are safe.
294
+ */
295
+ resumeDispatch() {
296
+ if (!this.dispatchPaused) {
297
+ return;
298
+ }
299
+ this.dispatchPaused = false;
300
+ this.dispatchResumeSignal?.resolve();
301
+ this.dispatchResumeSignal = void 0;
302
+ fireAndForget(() => this.runQueuedEvents().catch((error) => this.reportOperationFailure(error)));
303
+ }
277
304
  /**
278
305
  * Stop accepting events, flush current work, and persist the remaining snapshot.
279
306
  * @returns A promise fulfilled after the final snapshot write; a flush failure is logged, while a final snapshot failure rejects it.
@@ -402,6 +429,26 @@ class StorageEventManagerBase extends StorageEventManager {
402
429
  async processOperation(operation, attempt) {
403
430
  await processStorageEventAttempt(this.eventState, operation, attempt, this.attempts);
404
431
  }
432
+ /**
433
+ * Hold a file-handler request while dispatch is paused and track requests which have started.
434
+ * @param event - The event passed to the host processing hook after the pause is released.
435
+ * @returns A promise fulfilled when the host processing hook completes.
436
+ * @remarks The pause check and active registration happen synchronously together, preventing a request from starting after a pause.
437
+ */
438
+ async dispatchFileEvent(event) {
439
+ while (this.dispatchPaused) {
440
+ this.dispatchResumeSignal ??= promiseWithResolvers();
441
+ await this.dispatchResumeSignal.promise;
442
+ }
443
+ const activeDispatch = promiseWithResolvers();
444
+ this.activeDispatches.add(activeDispatch.promise);
445
+ try {
446
+ await this.requestProcessQueue(event);
447
+ } finally {
448
+ this.activeDispatches.delete(activeDispatch.promise);
449
+ activeDispatch.resolve();
450
+ }
451
+ }
405
452
  /**
406
453
  * Retain an event and await its current processing attempt.
407
454
  * @param event - The already selected event to process.
@@ -0,0 +1,110 @@
1
+ import type { FilePath, PathComparisonSettings } from "./pathTypes.js";
2
+ /**
3
+ * Original file paths removed and added by one synchronous membership change.
4
+ *
5
+ * @remarks
6
+ * Repeated additions and absent removals are harmless. A path present in both
7
+ * lists remains present, including when it was absent before the change.
8
+ * Hosts expand folder renames into file-path deltas before applying them.
9
+ */
10
+ export interface FilePathDelta {
11
+ readonly removed: readonly FilePath[];
12
+ readonly added: readonly FilePath[];
13
+ }
14
+ /** Controls whether a name read can reuse the host's maintained inventory. */
15
+ export interface FileNameReadOptions {
16
+ /**
17
+ * Ask the host's listing authority again instead of reusing the name index.
18
+ *
19
+ * @remarks
20
+ * Freshness follows that host's existing listing contract. For example,
21
+ * Obsidian supplies its Vault listing rather than an independent disk walk.
22
+ */
23
+ readonly fresh?: boolean;
24
+ }
25
+ /** Host-owned name reads and candidate selection for one storage root. */
26
+ export interface FileNameLookup {
27
+ /**
28
+ * Read the host's supported original file paths.
29
+ *
30
+ * @param options - Whether to ask the listing authority for a fresh view.
31
+ * @returns A copy of the complete supported inventory, preserving spelling.
32
+ * @throws Rejects unavailable or failed inventory reads rather than reporting
33
+ * a successful empty inventory. Host-specific listing exclusions still apply.
34
+ */
35
+ getFileNames(options?: FileNameReadOptions): Promise<FilePath[]>;
36
+ /**
37
+ * Find original paths which match the requested path-identity comparison key.
38
+ *
39
+ * @param path - Original file path to compare within this storage root.
40
+ * @param policy - Explicit Unicode normalisation and case comparison rules.
41
+ * @returns Every matching original path in diagnostic order, including the
42
+ * requested spelling when present. An empty result means no supported match.
43
+ * @throws Rejects unavailable coverage and host validation or read failures.
44
+ * @remarks
45
+ * The host establishes read readiness and physical-path safety. The caller
46
+ * decides whether multiple candidates constitute a collision; this operation
47
+ * neither chooses a preferred spelling nor compares file contents.
48
+ */
49
+ findPathIdentityCandidates(path: FilePath, policy: PathComparisonSettings): Promise<readonly FilePath[]>;
50
+ }
51
+ /**
52
+ * Maintains original file-path membership and lazily materialised identity buckets.
53
+ *
54
+ * @remarks
55
+ * The host owns supported-path validation, observation, and query readiness.
56
+ * This class stores original spellings and performs no I/O. Membership changes
57
+ * update every materialised policy map; at most four policy maps are retained.
58
+ * Queries return copies and leave file contents and physical names untouched.
59
+ *
60
+ * A first query for a policy derives its buckets in one pass over the retained
61
+ * paths. Subsequent queries select and sort only the matching candidates.
62
+ */
63
+ export declare class FilePathIndex {
64
+ private paths;
65
+ private indexes;
66
+ /**
67
+ * Replace the complete inventory and all materialised policy maps together.
68
+ *
69
+ * @param paths - Host-enumerated original file paths. Duplicate paths collapse
70
+ * into one membership without normalising their spelling.
71
+ * @throws Propagates invalid runtime members or iterable failures before
72
+ * replacing the current inventory or any existing policy map.
73
+ * @remarks
74
+ * Validation checks string members; filesystem admission remains the host's
75
+ * responsibility. Callers use this after a successful initial or fresh read.
76
+ */
77
+ replaceAll(paths: Iterable<FilePath>): void;
78
+ /**
79
+ * Apply one membership delta to the inventory and every cached policy map.
80
+ *
81
+ * @param delta - Original paths removed and added by the same change.
82
+ * @throws Propagates invalid runtime members before changing retained state.
83
+ * @remarks
84
+ * Inputs and comparison keys are prepared before mutation. The synchronous
85
+ * update publishes no intermediate rename state. Repeated notifications do
86
+ * not create duplicate memberships, and content-only edits need no delta.
87
+ */
88
+ apply(delta: FilePathDelta): void;
89
+ /**
90
+ * Copy the current in-memory membership without refreshing the host listing.
91
+ *
92
+ * @returns Original spellings in an independent array. Full-list ordering is
93
+ * unspecified; changing the returned array cannot change this index.
94
+ */
95
+ getFileNames(): FilePath[];
96
+ /**
97
+ * Select every indexed path with the requested storage comparison key.
98
+ *
99
+ * @param path - Path whose identity selects a candidate bucket.
100
+ * @param policy - Explicit Unicode normalisation and case comparison rules.
101
+ * @returns A sorted copy of all matching original paths, or an empty array
102
+ * when no indexed path matches. Multiple paths remain separate candidates.
103
+ * @throws Rejects a non-string path or unsupported comparison settings.
104
+ * @remarks
105
+ * The first query for each policy materialises its buckets. Later membership
106
+ * deltas maintain those buckets incrementally. Host readiness, existence,
107
+ * physical alias checks, and the final collision decision are external.
108
+ */
109
+ findPathIdentityCandidates(path: FilePath, policy: PathComparisonSettings): readonly FilePath[];
110
+ }
@@ -0,0 +1,146 @@
1
+ import { getStoragePathComparisonKey } from "./pathComparison.js";
2
+ function validatePath(path) {
3
+ if (typeof path !== "string") {
4
+ throw new TypeError("File paths must be strings");
5
+ }
6
+ return path;
7
+ }
8
+ function snapshotPolicy(policy) {
9
+ const { pathNormalizationVersion, handleFilenameCaseSensitive } = policy;
10
+ if (pathNormalizationVersion !== 0 && pathNormalizationVersion !== 1) {
11
+ throw new Error(`Unsupported path normalisation version: ${pathNormalizationVersion}`);
12
+ }
13
+ if (typeof handleFilenameCaseSensitive !== "boolean") {
14
+ throw new TypeError("Filename case handling must be explicit");
15
+ }
16
+ return { pathNormalizationVersion, handleFilenameCaseSensitive };
17
+ }
18
+ function getPolicyKey(policy) {
19
+ return `${policy.pathNormalizationVersion}:${policy.handleFilenameCaseSensitive ? "sensitive" : "insensitive"}`;
20
+ }
21
+ function createIdentityBuckets(paths, policy) {
22
+ const buckets = /* @__PURE__ */ new Map();
23
+ for (const path of paths) {
24
+ const key = getStoragePathComparisonKey(path, policy);
25
+ const bucket = buckets.get(key) ?? /* @__PURE__ */ new Set();
26
+ bucket.add(path);
27
+ buckets.set(key, bucket);
28
+ }
29
+ return buckets;
30
+ }
31
+ class FilePathIndex {
32
+ paths = /* @__PURE__ */ new Set();
33
+ indexes = /* @__PURE__ */ new Map();
34
+ /**
35
+ * Replace the complete inventory and all materialised policy maps together.
36
+ *
37
+ * @param paths - Host-enumerated original file paths. Duplicate paths collapse
38
+ * into one membership without normalising their spelling.
39
+ * @throws Propagates invalid runtime members or iterable failures before
40
+ * replacing the current inventory or any existing policy map.
41
+ * @remarks
42
+ * Validation checks string members; filesystem admission remains the host's
43
+ * responsibility. Callers use this after a successful initial or fresh read.
44
+ */
45
+ replaceAll(paths) {
46
+ const nextPaths = /* @__PURE__ */ new Set();
47
+ for (const path of paths) {
48
+ nextPaths.add(validatePath(path));
49
+ }
50
+ const nextIndexes = /* @__PURE__ */ new Map();
51
+ for (const [key, { policy }] of this.indexes) {
52
+ nextIndexes.set(key, { policy, buckets: createIdentityBuckets(nextPaths, policy) });
53
+ }
54
+ this.paths = nextPaths;
55
+ this.indexes = nextIndexes;
56
+ }
57
+ /**
58
+ * Apply one membership delta to the inventory and every cached policy map.
59
+ *
60
+ * @param delta - Original paths removed and added by the same change.
61
+ * @throws Propagates invalid runtime members before changing retained state.
62
+ * @remarks
63
+ * Inputs and comparison keys are prepared before mutation. The synchronous
64
+ * update publishes no intermediate rename state. Repeated notifications do
65
+ * not create duplicate memberships, and content-only edits need no delta.
66
+ */
67
+ apply(delta) {
68
+ const removed = new Set(delta.removed.map(validatePath));
69
+ const added = new Set(delta.added.map(validatePath));
70
+ for (const path of added) {
71
+ if (removed.has(path)) {
72
+ removed.delete(path);
73
+ if (this.paths.has(path)) {
74
+ added.delete(path);
75
+ }
76
+ }
77
+ }
78
+ const actualRemoved = [...removed].filter((path) => this.paths.has(path));
79
+ const actualAdded = [...added].filter((path) => !this.paths.has(path));
80
+ if (actualRemoved.length === 0 && actualAdded.length === 0) {
81
+ return;
82
+ }
83
+ const indexUpdates = [...this.indexes.values()].map(({ buckets, policy }) => ({
84
+ buckets,
85
+ removed: actualRemoved.map((path) => [getStoragePathComparisonKey(path, policy), path]),
86
+ added: actualAdded.map((path) => [getStoragePathComparisonKey(path, policy), path])
87
+ }));
88
+ for (const path of actualRemoved) {
89
+ this.paths.delete(path);
90
+ }
91
+ for (const path of actualAdded) {
92
+ this.paths.add(path);
93
+ }
94
+ for (const { buckets, removed: removedKeys, added: addedKeys } of indexUpdates) {
95
+ for (const [key, path] of removedKeys) {
96
+ const bucket = buckets.get(key);
97
+ bucket?.delete(path);
98
+ if (bucket?.size === 0) {
99
+ buckets.delete(key);
100
+ }
101
+ }
102
+ for (const [key, path] of addedKeys) {
103
+ const bucket = buckets.get(key) ?? /* @__PURE__ */ new Set();
104
+ bucket.add(path);
105
+ buckets.set(key, bucket);
106
+ }
107
+ }
108
+ }
109
+ /**
110
+ * Copy the current in-memory membership without refreshing the host listing.
111
+ *
112
+ * @returns Original spellings in an independent array. Full-list ordering is
113
+ * unspecified; changing the returned array cannot change this index.
114
+ */
115
+ getFileNames() {
116
+ return [...this.paths];
117
+ }
118
+ /**
119
+ * Select every indexed path with the requested storage comparison key.
120
+ *
121
+ * @param path - Path whose identity selects a candidate bucket.
122
+ * @param policy - Explicit Unicode normalisation and case comparison rules.
123
+ * @returns A sorted copy of all matching original paths, or an empty array
124
+ * when no indexed path matches. Multiple paths remain separate candidates.
125
+ * @throws Rejects a non-string path or unsupported comparison settings.
126
+ * @remarks
127
+ * The first query for each policy materialises its buckets. Later membership
128
+ * deltas maintain those buckets incrementally. Host readiness, existence,
129
+ * physical alias checks, and the final collision decision are external.
130
+ */
131
+ findPathIdentityCandidates(path, policy) {
132
+ const validatedPath = validatePath(path);
133
+ const policySnapshot = snapshotPolicy(policy);
134
+ const policyKey = getPolicyKey(policySnapshot);
135
+ let index = this.indexes.get(policyKey);
136
+ if (!index) {
137
+ index = { policy: policySnapshot, buckets: createIdentityBuckets(this.paths, policySnapshot) };
138
+ this.indexes.set(policyKey, index);
139
+ }
140
+ const key = getStoragePathComparisonKey(validatedPath, policySnapshot);
141
+ return [...index.buckets.get(key) ?? []].sort();
142
+ }
143
+ }
144
+ export {
145
+ FilePathIndex
146
+ };