@vrtmrz/livesync-commonlib 0.4.3 → 0.5.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 (60) hide show
  1. package/README.md +2 -2
  2. package/dist/interfaces/StorageAccess.d.ts +8 -2
  3. package/dist/platform/FilePathIndex.d.ts +110 -0
  4. package/dist/platform/FilePathIndex.js +146 -0
  5. package/dist/replication/trystero/LiveSyncTrysteroReplicator.d.ts +3 -3
  6. package/dist/replication/trystero/P2PAutomationCoordinator.d.ts +1 -1
  7. package/dist/replication/trystero/P2PReplicationWire.d.ts +1 -1
  8. package/dist/replication/trystero/TrysteroReplicator/changeRelay.d.ts +133 -0
  9. package/dist/replication/trystero/TrysteroReplicator/changeRelay.js +176 -0
  10. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.d.ts +55 -0
  11. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.js +99 -0
  12. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.d.ts +83 -0
  13. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.js +121 -0
  14. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.d.ts +75 -0
  15. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.js +131 -0
  16. package/dist/replication/trystero/TrysteroReplicator/progress.d.ts +57 -0
  17. package/dist/replication/trystero/TrysteroReplicator/progress.js +84 -0
  18. package/dist/replication/trystero/TrysteroReplicator/relayControl.d.ts +20 -0
  19. package/dist/replication/trystero/TrysteroReplicator/relayControl.js +25 -0
  20. package/dist/replication/trystero/TrysteroReplicator/transfers.d.ts +125 -0
  21. package/dist/replication/trystero/TrysteroReplicator/transfers.js +278 -0
  22. package/dist/replication/trystero/TrysteroReplicator.d.ts +65 -483
  23. package/dist/replication/trystero/TrysteroReplicator.js +240 -673
  24. package/dist/replication/trystero/TrysteroReplicatorP2PClient.d.ts +19 -6
  25. package/dist/replication/trystero/TrysteroReplicatorP2PClient.js +29 -25
  26. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.d.ts +66 -0
  27. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.js +142 -0
  28. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +19 -16
  29. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +33 -93
  30. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +1 -1
  31. package/dist/replication/trystero/p2pReplicationProgress.d.ts +2 -11
  32. package/dist/replication/trystero/replicationTypes.d.ts +88 -0
  33. package/dist/replication/trystero/replicationTypes.js +0 -0
  34. package/dist/replication/trystero/rpcSessionProvider.d.ts +13 -0
  35. package/dist/replication/trystero/rpcSessionProvider.js +0 -0
  36. package/dist/rpc/RpcRoom/pendingInvocations.d.ts +141 -0
  37. package/dist/rpc/RpcRoom/pendingInvocations.js +225 -0
  38. package/dist/rpc/RpcRoom.d.ts +9 -4
  39. package/dist/rpc/RpcRoom.js +73 -118
  40. package/dist/rpc/RpcSession.d.ts +6 -0
  41. package/dist/rpc/RpcSession.js +11 -0
  42. package/dist/rpc/types.d.ts +2 -0
  43. package/dist/serviceFeatures/targetFilter.d.ts +1 -1
  44. package/dist/serviceFeatures/targetFilter.js +8 -38
  45. package/dist/serviceModules/FileAccessBase.d.ts +4 -0
  46. package/dist/serviceModules/FileAccessBase.js +10 -0
  47. package/dist/serviceModules/Rebuilder.js +1 -1
  48. package/dist/serviceModules/ServiceFileAccessBase/fileNames.d.ts +54 -0
  49. package/dist/serviceModules/ServiceFileAccessBase/fileNames.js +57 -0
  50. package/dist/serviceModules/ServiceFileAccessBase.d.ts +5 -1
  51. package/dist/serviceModules/ServiceFileAccessBase.js +18 -3
  52. package/dist/serviceModules/adapters/IFileSystemAdapter.d.ts +3 -0
  53. package/dist/storage.d.ts +2 -0
  54. package/dist/storage.js +2 -0
  55. package/docs/development.md +103 -0
  56. package/docs/p2p-transport-lifecycle.md +24 -0
  57. package/docs/platform-storage.md +22 -0
  58. package/docs/releasing.md +6 -0
  59. package/docs/settings-lifecycle.md +4 -2
  60. package/package.json +1 -1
@@ -3,6 +3,7 @@ import {
3
3
  createDeferredAction
4
4
  } from "octagonal-wheels/concurrency/deferredAction";
5
5
  import { IncomingChunkBuffer, estimateBytes, splitIntoChunks } from "./chunking.js";
6
+ import { createPendingInvocations } from "./RpcRoom/pendingInvocations.js";
6
7
  import { asRpcErrorShape, RpcError } from "./errors.js";
7
8
  import { RpcSession } from "./RpcSession.js";
8
9
  import {
@@ -21,7 +22,7 @@ const scheduleRpcTimeout = (callback, delayMs) => {
21
22
  };
22
23
  class RpcRoom {
23
24
  options;
24
- pending = /* @__PURE__ */ new Map();
25
+ pendingInvocations;
25
26
  inboundCalls = /* @__PURE__ */ new Map();
26
27
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- This is a generic type for method handlers, so we can't be more specific about the types here.
27
28
  methods = /* @__PURE__ */ new Map();
@@ -38,6 +39,12 @@ class RpcRoom {
38
39
  chunkMissingRetryMs: options.chunkMissingRetryMs ?? 350,
39
40
  ...options
40
41
  };
42
+ this.pendingInvocations = createPendingInvocations({
43
+ sendEnvelope: (peerId, envelope) => this.sendEnvelope(peerId, envelope),
44
+ createRequestId: () => newId("req"),
45
+ scheduleTimeout: scheduleRpcTimeout,
46
+ onProtocolWarning: (message, peerId) => this.options.onProtocolWarning?.(message, peerId)
47
+ });
41
48
  this.disposers.push(
42
49
  this.options.transport.onMessage((msg, peerId) => {
43
50
  void this.onWireMessage(msg, peerId);
@@ -57,10 +64,7 @@ class RpcRoom {
57
64
  if (this.options.transport.onPeerLeave) {
58
65
  this.disposers.push(
59
66
  this.options.transport.onPeerLeave((peerId) => {
60
- this.pending.forEach((pending, requestId) => {
61
- if (pending.peerId !== peerId) return;
62
- this.rejectPending(requestId, new RpcError("NOT_CONNECTED", "Peer disconnected"));
63
- });
67
+ this.pendingInvocations.peerLeft(peerId);
64
68
  this.inboundCalls.forEach((context, requestId) => {
65
69
  if (context.peerId !== peerId) return;
66
70
  this.abortInboundCall(requestId, context);
@@ -79,9 +83,7 @@ class RpcRoom {
79
83
  if (this.closed) return;
80
84
  this.closed = true;
81
85
  this.disposers.splice(0).forEach((dispose) => dispose());
82
- this.pending.forEach((_pending, requestId) => {
83
- this.rejectPending(requestId, new RpcError("NOT_CONNECTED", "Room closed"), true);
84
- });
86
+ this.pendingInvocations.close();
85
87
  this.inboundCalls.forEach((context, requestId) => {
86
88
  this.abortInboundCall(requestId, context);
87
89
  });
@@ -124,98 +126,30 @@ class RpcRoom {
124
126
  if (this.closed) {
125
127
  throw new RpcError("NOT_CONNECTED", "Room is closed");
126
128
  }
127
- const options = typeof timeoutOrOptions === "number" ? { timeoutMs: timeoutOrOptions } : timeoutOrOptions ?? {};
128
- const timeoutMs = options.timeoutMs ?? 3e4;
129
- if (options.signal?.aborted) {
130
- throw new RpcError("CANCELLED", `RPC cancelled: ${method}`);
129
+ return await this.pendingInvocations.invoke(peerId, method, args, timeoutOrOptions);
130
+ }
131
+ /**
132
+ * Send a notification to a peer without creating an RPC response wait.
133
+ * Resolves when the local transport send completes; it does not report
134
+ * whether the peer accepted or completed the handler.
135
+ */
136
+ async notify(peerId, method, args) {
137
+ if (!validNamespacedMethod(method)) {
138
+ throw new RpcError("PROTOCOL_ERROR", `Method must be namespaced: ${method}`);
131
139
  }
132
- const requestId = newId("req");
133
- let pending;
134
- const p = new Promise((resolve, reject) => {
135
- const signal = options.signal;
136
- const onAbort = () => {
137
- const current = this.pending.get(requestId);
138
- if (!current) return;
139
- this.rejectPending(requestId, new RpcError("CANCELLED", `RPC cancelled: ${method}`), true);
140
- };
141
- const deadline = timeoutMs > 0 ? createDeferredAction(() => {
142
- this.rejectPending(requestId, new RpcError("TIMEOUT", `RPC timed out: ${method}`), true);
143
- }, scheduleRpcTimeout) : void 0;
144
- pending = {
145
- peerId,
146
- method,
147
- resolve,
148
- reject,
149
- releaseWait: () => {
150
- deadline?.dispose();
151
- signal?.removeEventListener("abort", onAbort);
152
- },
153
- requestSent: false,
154
- cancelRequested: false
155
- };
156
- deadline?.schedule(timeoutMs);
157
- this.pending.set(requestId, pending);
158
- if (signal) {
159
- signal.addEventListener("abort", onAbort, { once: true });
160
- if (signal.aborted) onAbort();
161
- }
162
- });
163
- const sendTask = this.sendEnvelope(peerId, {
140
+ if (this.closed) {
141
+ throw new RpcError("NOT_CONNECTED", "Room is closed");
142
+ }
143
+ await this.sendEnvelope(peerId, {
164
144
  kind: "request",
165
- requestId,
145
+ requestId: newId("req"),
166
146
  method,
167
- args
147
+ args,
148
+ expectsResponse: false
168
149
  });
169
- void sendTask.then(
170
- () => {
171
- const current = this.pending.get(requestId);
172
- pending.requestSent = true;
173
- if (!current && pending.cancelRequested) {
174
- this.notifyRemoteCancellation(peerId, requestId);
175
- }
176
- },
177
- (ex) => {
178
- const current = this.pending.get(requestId);
179
- if (!current) return;
180
- const failed = this.removePending(requestId);
181
- if (failed) failed.reject(ex);
182
- }
183
- );
184
- return await p;
185
150
  }
186
151
  async cancel(peerId, requestId) {
187
- const pending = this.pending.get(requestId);
188
- if (pending?.peerId === peerId) {
189
- const requestSent = pending.requestSent;
190
- pending.cancelRequested = true;
191
- this.rejectPending(requestId, new RpcError("CANCELLED", "Invocation cancelled"));
192
- if (!requestSent) return;
193
- }
194
- await this.sendEnvelope(peerId, {
195
- kind: "cancel",
196
- requestId
197
- });
198
- }
199
- removePending(requestId) {
200
- const pending = this.pending.get(requestId);
201
- if (!pending) return void 0;
202
- this.pending.delete(requestId);
203
- pending.releaseWait();
204
- return pending;
205
- }
206
- rejectPending(requestId, error, notifyRemote = false) {
207
- const pending = this.pending.get(requestId);
208
- if (!pending) return;
209
- if (notifyRemote) pending.cancelRequested = true;
210
- const removed = this.removePending(requestId);
211
- if (!removed) return;
212
- removed.reject(error);
213
- if (notifyRemote && removed.requestSent) this.notifyRemoteCancellation(removed.peerId, requestId);
214
- }
215
- notifyRemoteCancellation(peerId, requestId) {
216
- void this.sendEnvelope(peerId, { kind: "cancel", requestId }).catch((error) => {
217
- this.options.onProtocolWarning?.(`Failed to send RPC cancellation: ${String(error)}`, peerId);
218
- });
152
+ return await this.pendingInvocations.cancel(peerId, requestId);
219
153
  }
220
154
  abortInboundCall(requestId, context) {
221
155
  if (this.inboundCalls.get(requestId) !== context) return;
@@ -242,6 +176,19 @@ class RpcRoom {
242
176
  sendErrorResponse(peerId, requestId, error) {
243
177
  return this.sendEnvelope(peerId, { kind: "response", requestId, ok: false, error });
244
178
  }
179
+ async reportRequestFailure(envelope, peerId, error, notificationReason) {
180
+ if (envelope.expectsResponse === false) {
181
+ this.warnNotificationIssue(envelope, notificationReason, peerId);
182
+ return;
183
+ }
184
+ await this.sendErrorResponse(peerId, envelope.requestId, error);
185
+ }
186
+ warnNotificationIssue(envelope, reason, peerId) {
187
+ try {
188
+ this.options.onProtocolWarning?.(`RPC notification ${envelope.method}: ${reason}`, peerId);
189
+ } catch {
190
+ }
191
+ }
245
192
  scheduleMissingAck(streamId, peerId) {
246
193
  this.incomingChunkWaits.get(streamId)?.dispose();
247
194
  const wait = createDeferredAction(() => {
@@ -315,15 +262,7 @@ class RpcRoom {
315
262
  return;
316
263
  }
317
264
  if (envelope.kind === "response") {
318
- const pending = this.pending.get(envelope.requestId);
319
- if (!pending) return;
320
- const settled = this.removePending(envelope.requestId);
321
- if (!settled) return;
322
- if (envelope.ok === true) {
323
- settled.resolve(envelope.data);
324
- } else {
325
- settled.reject(new RpcError(envelope.error.code, envelope.error.message, envelope.error.details));
326
- }
265
+ this.pendingInvocations.receiveResponse(envelope);
327
266
  return;
328
267
  }
329
268
  return this.onRequest(envelope, peerId);
@@ -338,7 +277,7 @@ class RpcRoom {
338
277
  } catch (ex) {
339
278
  this.inboundCalls.delete(envelope.requestId);
340
279
  if (!ctx.signal.aborted && !this.closed) {
341
- await this.sendErrorResponse(peerId, envelope.requestId, asRpcErrorShape(ex));
280
+ await this.reportRequestFailure(envelope, peerId, asRpcErrorShape(ex), "admission check failed");
342
281
  }
343
282
  return;
344
283
  }
@@ -353,27 +292,41 @@ class RpcRoom {
353
292
  const version = this.peerVersion.get(peerId);
354
293
  if (version && version.major !== RPC_VERSION_MAJOR) {
355
294
  if (!ctx.signal.aborted && !this.closed) {
356
- await this.sendErrorResponse(peerId, envelope.requestId, {
357
- code: "REMOTE_ERROR",
358
- message: `RPC major mismatch: local=${RPC_VERSION_MAJOR}, remote=${version.major}`
359
- });
295
+ await this.reportRequestFailure(
296
+ envelope,
297
+ peerId,
298
+ {
299
+ code: "REMOTE_ERROR",
300
+ message: `RPC major mismatch: local=${RPC_VERSION_MAJOR}, remote=${version.major}`
301
+ },
302
+ "protocol major version mismatch"
303
+ );
360
304
  }
361
305
  this.inboundCalls.delete(envelope.requestId);
362
306
  return;
363
307
  }
364
308
  if (version && version.minor !== RPC_VERSION_MINOR) {
365
- this.options.onProtocolWarning?.(
366
- `RPC minor mismatch: local=${RPC_VERSION_MINOR}, remote=${version.minor}`,
367
- peerId
368
- );
309
+ if (envelope.expectsResponse === false) {
310
+ this.warnNotificationIssue(envelope, "protocol minor version mismatch", peerId);
311
+ } else {
312
+ this.options.onProtocolWarning?.(
313
+ `RPC minor mismatch: local=${RPC_VERSION_MINOR}, remote=${version.minor}`,
314
+ peerId
315
+ );
316
+ }
369
317
  }
370
318
  const method = this.methods.get(envelope.method);
371
319
  if (!method) {
372
320
  if (!ctx.signal.aborted && !this.closed) {
373
- await this.sendErrorResponse(peerId, envelope.requestId, {
374
- code: "REMOTE_ERROR",
375
- message: `Method not found: ${envelope.method}`
376
- });
321
+ await this.reportRequestFailure(
322
+ envelope,
323
+ peerId,
324
+ {
325
+ code: "REMOTE_ERROR",
326
+ message: `Method not found: ${envelope.method}`
327
+ },
328
+ "method not found"
329
+ );
377
330
  }
378
331
  this.inboundCalls.delete(envelope.requestId);
379
332
  return;
@@ -394,7 +347,9 @@ class RpcRoom {
394
347
  peerId,
395
348
  ...envelope.args
396
349
  ) : await method.handler(peerId, ...envelope.args);
397
- if (ctx.signal.aborted || this.closed) return;
350
+ if (ctx.signal.aborted || this.closed || envelope.expectsResponse === false) {
351
+ return;
352
+ }
398
353
  await this.sendEnvelope(peerId, {
399
354
  kind: "response",
400
355
  requestId: envelope.requestId,
@@ -403,7 +358,7 @@ class RpcRoom {
403
358
  });
404
359
  } catch (ex) {
405
360
  if (ctx.signal.aborted || this.closed) return;
406
- await this.sendErrorResponse(peerId, envelope.requestId, asRpcErrorShape(ex));
361
+ await this.reportRequestFailure(envelope, peerId, asRpcErrorShape(ex), "handler failed");
407
362
  } finally {
408
363
  if (this.inboundCalls.get(envelope.requestId) === ctx) {
409
364
  this.inboundCalls.delete(envelope.requestId);
@@ -7,5 +7,11 @@ export declare class RpcSession {
7
7
  call<T = JsonLike>(method: string, args?: JsonLike[], timeoutMs?: number): Promise<T>;
8
8
  call<T = JsonLike>(method: string, args?: JsonLike[], options?: RpcCallOptions): Promise<T>;
9
9
  call<T = JsonLike>(method: string, args: JsonLike[] | undefined, timeoutOrOptions?: number | RpcCallOptions): Promise<T>;
10
+ /**
11
+ * Send a notification to the bound peer without creating an RPC response
12
+ * wait. Resolves when the local transport send completes, not when remote
13
+ * processing finishes.
14
+ */
15
+ notify(method: string, args?: JsonLike[]): Promise<void>;
10
16
  createProxy<T extends object>(namespace: string): T;
11
17
  }
@@ -12,6 +12,17 @@ class RpcSession {
12
12
  }
13
13
  return await this.room.invoke(this.peerId, method, args, timeoutOrOptions);
14
14
  }
15
+ /**
16
+ * Send a notification to the bound peer without creating an RPC response
17
+ * wait. Resolves when the local transport send completes, not when remote
18
+ * processing finishes.
19
+ */
20
+ async notify(method, args = []) {
21
+ if (!this.peerId) {
22
+ throw new RpcError("NOT_CONNECTED", "Peer is not connected");
23
+ }
24
+ await this.room.notify(this.peerId, method, args);
25
+ }
15
26
  createProxy(namespace) {
16
27
  const session = this;
17
28
  return new Proxy(
@@ -37,6 +37,8 @@ export type RpcRequestEnvelope = {
37
37
  requestId: string;
38
38
  method: string;
39
39
  args: JsonLike[];
40
+ /** Omit for a response-bearing call; set false for a send-only notification. */
41
+ expectsResponse?: false;
40
42
  };
41
43
  export type RpcResponseEnvelope = {
42
44
  kind: "response";
@@ -9,7 +9,7 @@ export declare function isAcceptedAlwaysFactory(host: NecessaryServices<never, n
9
9
  /**
10
10
  * Check if a file is accepted based on filename duplication in the vault.
11
11
  */
12
- export declare function isAcceptedInFilenameDuplicationFactory(host: NecessaryServices<"vault" | "fileProcessing" | "setting", "storageAccess">, log: LogFunction): (file: string | UXFileInfoStub, options?: Parameters<IVaultService["isTargetFile"]>[1]) => Promise<boolean>;
12
+ export declare function isAcceptedInFilenameDuplicationFactory(host: NecessaryServices<"vault" | "setting", "storageAccess">, log: LogFunction): (file: string | UXFileInfoStub, options?: Parameters<IVaultService["isTargetFile"]>[1]) => Promise<boolean>;
13
13
  /**
14
14
  * Check if a file is accepted by the local database (e.g., not rejected by the local DB's target file check).
15
15
  * Local database responsible for non-internal files, syncOnlyRegEx, syncIgnoreRegEx
@@ -2,9 +2,8 @@ import { LOG_LEVEL_DEBUG, LOG_LEVEL_VERBOSE } from "../common/types.js";
2
2
  import { createInstanceLogFunction } from "../services/lib/logUtils.js";
3
3
  import { getStoragePathFromUXFileInfo } from "../common/typeUtils.js";
4
4
  import { isAcceptedAll } from "../string_and_binary/path.js";
5
- import { Computed } from "octagonal-wheels/dataobject/Computed";
6
5
  import { promiseWithResolvers } from "octagonal-wheels/promises";
7
- import { getPathNormalizationVersion, normalisePathForIdentity } from "../common/pathNormalization.js";
6
+ import { getPathNormalizationVersion } from "../common/pathNormalization.js";
8
7
  function isAcceptedAlwaysFactory(host, log) {
9
8
  return (file) => {
10
9
  log("File is target finally: " + getStoragePathFromUXFileInfo(file), LOG_LEVEL_DEBUG);
@@ -12,44 +11,16 @@ function isAcceptedAlwaysFactory(host, log) {
12
11
  };
13
12
  }
14
13
  function isAcceptedInFilenameDuplicationFactory(host, log) {
15
- const fileCountMapComputed = new Computed({
16
- evaluation: async (fileEventCount, version, caseInsensitive) => {
17
- const vaultFiles = (await host.serviceModules.storageAccess.getFileNames()).sort();
18
- const fileCountMap = /* @__PURE__ */ new Map();
19
- for (const file of vaultFiles) {
20
- const normalised = normalisePathForIdentity(file, version);
21
- const key = caseInsensitive ? normalised.toLowerCase() : normalised;
22
- const paths = fileCountMap.get(key) ?? [];
23
- paths.push(file);
24
- fileCountMap.set(key, paths);
25
- }
26
- return fileCountMap;
27
- },
28
- requiresUpdate: (args, previousArgs, previousResult) => {
29
- if (!previousResult) return true;
30
- if (previousResult instanceof Error) return true;
31
- if (!previousArgs) return true;
32
- if (args.every((value, index) => value === previousArgs[index])) {
33
- return false;
34
- }
35
- return true;
36
- }
37
- });
38
14
  return async function isAcceptedInFilenameDuplication(file, options) {
39
15
  if (options?.skipCaseCollisionCheck) return true;
40
- const version = getPathNormalizationVersion(host.services.setting.currentSettings());
41
- const caseInsensitive = host.services.vault.shouldCheckCaseInsensitively();
42
- const fileCountMap = (await fileCountMapComputed.update(
43
- host.services.fileProcessing.totalStorageFileEventCount,
44
- version,
45
- caseInsensitive
46
- )).value;
16
+ const policy = {
17
+ pathNormalizationVersion: getPathNormalizationVersion(host.services.setting.currentSettings()),
18
+ handleFilenameCaseSensitive: !host.services.vault.shouldCheckCaseInsensitively()
19
+ };
47
20
  const filepath = getStoragePathFromUXFileInfo(file);
48
- const normalised = normalisePathForIdentity(filepath, version);
49
- const key = caseInsensitive ? normalised.toLowerCase() : normalised;
50
- const duplicates = fileCountMap.get(key);
51
- if (duplicates && duplicates.length > 1) {
52
- log("File path identity collision: " + duplicates.map((path) => JSON.stringify(path)).join(", "));
21
+ const candidates = await host.serviceModules.storageAccess.findPathIdentityCandidates(filepath, policy);
22
+ if (candidates.length > 1) {
23
+ log("File path identity collision: " + candidates.map((path) => JSON.stringify(path)).join(", "));
53
24
  return false;
54
25
  }
55
26
  log("File is not duplicated: " + filepath, LOG_LEVEL_DEBUG);
@@ -143,7 +114,6 @@ function useTargetFilters(host) {
143
114
  services: {
144
115
  context: services.context,
145
116
  vault: services.vault,
146
- fileProcessing: services.fileProcessing,
147
117
  setting: services.setting
148
118
  },
149
119
  serviceModules: { storageAccess: serviceModules.storageAccess }
@@ -4,6 +4,8 @@ import type { IAPIService, IPathService, ISettingService, IVaultService } from "
4
4
  import { createInstanceLogFunction } from "../services/lib/logUtils.js";
5
5
  import type { FileWithFileStat } from "../common/models/fileaccess.type.js";
6
6
  import type { IFileSystemAdapter } from "./adapters/index.js";
7
+ import type { FileNameReadOptions } from "../platform/FilePathIndex.js";
8
+ import type { PathComparisonSettings } from "../platform/pathTypes.js";
7
9
  export declare function toArrayBuffer(arr: Uint8Array<ArrayBuffer> | ArrayBuffer | DataView<ArrayBuffer>): ArrayBuffer;
8
10
  export interface FileAccessBaseDependencies {
9
11
  vaultService: IVaultService;
@@ -86,6 +88,8 @@ export declare class FileAccessBase<TAdapter extends IFileSystemAdapter<any, any
86
88
  protected isStorageInsensitive(): boolean;
87
89
  getAbstractFileByPath(path: FilePath | string): Promise<ExtractAbstractFile<TAdapter> | null>;
88
90
  getFiles(): Promise<ExtractFile<TAdapter>[]>;
91
+ getFileNames(options?: FileNameReadOptions): Promise<FilePath[]>;
92
+ findPathIdentityCandidates(path: FilePath, policy: PathComparisonSettings): Promise<readonly FilePath[]> | undefined;
89
93
  ensureDirectory(fullPath: string): Promise<void>;
90
94
  touch(file: ExtractFile<TAdapter> | FilePath): Promise<void>;
91
95
  recentlyTouched(file: ExtractFile<TAdapter> | UXFileInfoStub | FileWithFileStat): boolean;
@@ -182,6 +182,16 @@ class FileAccessBase {
182
182
  async getFiles() {
183
183
  return await this.adapter.getFiles();
184
184
  }
185
+ async getFileNames(options) {
186
+ if (this.adapter.fileNameLookup) {
187
+ return await this.adapter.fileNameLookup.getFileNames(options);
188
+ }
189
+ const files = await this.getFiles();
190
+ return files.map((file) => this.getPath(file));
191
+ }
192
+ findPathIdentityCandidates(path, policy) {
193
+ return this.adapter.fileNameLookup?.findPathIdentityCandidates(path, policy);
194
+ }
185
195
  async ensureDirectory(fullPath) {
186
196
  const pathElements = fullPath.split("/");
187
197
  pathElements.pop();
@@ -181,7 +181,7 @@ Please enable them from the settings screen after setup is complete.`,
181
181
  await assertDatabasePathIdentity(this.database.localDatabase.localDatabase, settings);
182
182
  }
183
183
  if (getPathNormalizationVersion(settings) === 0) return;
184
- const paths = await this.storageAccess.getFileNames();
184
+ const paths = await this.storageAccess.getFileNames({ fresh: true });
185
185
  const selected = [];
186
186
  const databaseReady = this.database.isDatabaseReady();
187
187
  for (const path of paths) {
@@ -0,0 +1,54 @@
1
+ import { FilePathIndex, type FileNameLookup } from "../../platform/FilePathIndex.js";
2
+ import type { FilePath, PathComparisonSettings } from "../../platform/pathTypes.js";
3
+ /** The listing and invalidation inputs needed by a non-indexed storage host. */
4
+ export interface FileNameLookupDependencies {
5
+ readonly getFileNames: () => Promise<FilePath[]>;
6
+ readonly getStorageFileEventCount: () => number;
7
+ }
8
+ /** Values which make a retained name listing reusable for the active policy. */
9
+ export interface FileNameIndexSnapshot {
10
+ readonly storageEventCount: number;
11
+ readonly policy: PathComparisonSettings;
12
+ }
13
+ /** One shared pending or fulfilled listing; rejected requests are removed. */
14
+ export interface FileNameIndexRequest extends FileNameIndexSnapshot {
15
+ readonly index: Promise<FilePathIndex>;
16
+ }
17
+ /** The factory owns one active request; operations receive that ownership explicitly. */
18
+ export interface FallbackFileNameLookupState {
19
+ retained: FileNameIndexRequest | undefined;
20
+ }
21
+ /** Private fallback view used by the storage facade when its host has no index. */
22
+ export interface FallbackFileNameLookup extends Pick<FileNameLookup, "findPathIdentityCandidates"> {
23
+ /** Retire the retained request before obtaining a fresh authoritative listing. */
24
+ invalidate(): void;
25
+ }
26
+ /** Compare the host observation count and identity-policy values which permit request reuse. */
27
+ export declare function matchesSnapshot(request: FileNameIndexSnapshot, snapshot: FileNameIndexSnapshot): boolean;
28
+ /** Build an index from the host listing without retaining or publishing it. */
29
+ export declare function createFilePathIndex(dependencies: Pick<FileNameLookupDependencies, "getFileNames">): Promise<FilePathIndex>;
30
+ /** Retire reuse immediately; existing callers can still finish their own request. */
31
+ export declare function invalidateFileNameLookup(state: FallbackFileNameLookupState): void;
32
+ /** An older rejected request must not evict a newer active listing. */
33
+ export declare function discardRejectedRequest(state: FallbackFileNameLookupState, request: FileNameIndexRequest): void;
34
+ /**
35
+ * Reuse or start the request matching this snapshot, preserving its promise identity.
36
+ *
37
+ * Publish a pending request before starting host code: that code can invalidate
38
+ * or re-enter this lookup synchronously. Completion belongs to the captured
39
+ * request and cannot replace whichever request is active by then.
40
+ */
41
+ export declare function getIndex(dependencies: Pick<FileNameLookupDependencies, "getFileNames">, state: FallbackFileNameLookupState, snapshot: FileNameIndexSnapshot): Promise<FilePathIndex>;
42
+ /** Capture the host observation and policy before awaiting the matching original-name candidates. */
43
+ export declare function findPathIdentityCandidates(dependencies: FileNameLookupDependencies, state: FallbackFileNameLookupState, path: FilePath, policy: PathComparisonSettings): Promise<readonly FilePath[]>;
44
+ /**
45
+ * Retain and share the active host listing until its event count or policy changes.
46
+ *
47
+ * @param dependencies - Narrow host callbacks, resolved when a query runs.
48
+ * @returns A per-service fallback lookup with explicit fresh-read invalidation.
49
+ * @remarks
50
+ * The factory owns only the retained request state and delegates to standalone
51
+ * operations. Retiring a request fences older work: it can finish for existing
52
+ * callers without publishing over a newer request. Failed reads can be retried.
53
+ */
54
+ export declare function createFallbackFileNameLookup(dependencies: FileNameLookupDependencies): FallbackFileNameLookup;
@@ -0,0 +1,57 @@
1
+ import { promiseWithResolvers } from "octagonal-wheels/promises";
2
+ import { FilePathIndex } from "../../platform/FilePathIndex.js";
3
+ function matchesSnapshot(request, snapshot) {
4
+ return request.storageEventCount === snapshot.storageEventCount && request.policy.pathNormalizationVersion === snapshot.policy.pathNormalizationVersion && request.policy.handleFilenameCaseSensitive === snapshot.policy.handleFilenameCaseSensitive;
5
+ }
6
+ async function createFilePathIndex(dependencies) {
7
+ const paths = await dependencies.getFileNames();
8
+ const index = new FilePathIndex();
9
+ index.replaceAll(paths);
10
+ return index;
11
+ }
12
+ function invalidateFileNameLookup(state) {
13
+ state.retained = void 0;
14
+ }
15
+ function discardRejectedRequest(state, request) {
16
+ if (state.retained === request) {
17
+ invalidateFileNameLookup(state);
18
+ }
19
+ }
20
+ function getIndex(dependencies, state, snapshot) {
21
+ if (state.retained && matchesSnapshot(state.retained, snapshot)) {
22
+ return state.retained.index;
23
+ }
24
+ const pending = promiseWithResolvers();
25
+ const request = { ...snapshot, index: pending.promise };
26
+ state.retained = request;
27
+ void request.index.catch(() => discardRejectedRequest(state, request));
28
+ void createFilePathIndex(dependencies).then(pending.resolve, pending.reject);
29
+ return request.index;
30
+ }
31
+ async function findPathIdentityCandidates(dependencies, state, path, policy) {
32
+ const snapshot = {
33
+ storageEventCount: dependencies.getStorageFileEventCount(),
34
+ policy: {
35
+ pathNormalizationVersion: policy.pathNormalizationVersion,
36
+ handleFilenameCaseSensitive: policy.handleFilenameCaseSensitive
37
+ }
38
+ };
39
+ const index = await getIndex(dependencies, state, snapshot);
40
+ return index.findPathIdentityCandidates(path, snapshot.policy);
41
+ }
42
+ function createFallbackFileNameLookup(dependencies) {
43
+ const state = { retained: void 0 };
44
+ return {
45
+ invalidate: () => invalidateFileNameLookup(state),
46
+ findPathIdentityCandidates: (path, policy) => findPathIdentityCandidates(dependencies, state, path, policy)
47
+ };
48
+ }
49
+ export {
50
+ createFallbackFileNameLookup,
51
+ createFilePathIndex,
52
+ discardRejectedRequest,
53
+ findPathIdentityCandidates,
54
+ getIndex,
55
+ invalidateFileNameLookup,
56
+ matchesSnapshot
57
+ };
@@ -1,4 +1,6 @@
1
1
  import type { FilePath, FilePathWithPrefix, UXDataWriteOptions, UXFileInfo, UXFileInfoStub, UXFolderInfo, UXStat } from "../common/types.js";
2
+ import type { FileNameReadOptions } from "../platform/FilePathIndex.js";
3
+ import type { PathComparisonSettings } from "../platform/pathTypes.js";
2
4
  import { ServiceModuleBase } from "./ServiceModuleBase.js";
3
5
  import type { APIService } from "../services/base/APIService.js";
4
6
  import type { IStorageAccessManager, StorageAccess } from "../interfaces/StorageAccess.js";
@@ -25,6 +27,7 @@ export declare class ServiceFileAccessBase<TAdapter extends IFileSystemAdapter<a
25
27
  private vaultManager;
26
28
  private vault;
27
29
  private setting;
30
+ private readonly fallbackFileNames;
28
31
  constructor(services: StorageAccessBaseDependencies<TAdapter>);
29
32
  hasPendingFileEvent(path: FilePath): boolean;
30
33
  restoreState(): Promise<void>;
@@ -53,7 +56,8 @@ export declare class ServiceFileAccessBase<TAdapter extends IFileSystemAdapter<a
53
56
  readStubContent(stub: UXFileInfoStub): Promise<UXFileInfo | false>;
54
57
  getStub(path: string): Promise<UXFileInfoStub | UXFolderInfo | null>;
55
58
  getFiles(): Promise<UXFileInfoStub[]>;
56
- getFileNames(): Promise<FilePath[]>;
59
+ getFileNames(options?: FileNameReadOptions): Promise<FilePath[]>;
60
+ findPathIdentityCandidates(path: FilePath, policy: PathComparisonSettings): Promise<readonly FilePath[]>;
57
61
  getFilesIncludeHidden(basePath: string, includeFilter?: CustomRegExp[], excludeFilter?: CustomRegExp[], skipFolder?: string[]): Promise<FilePath[]>;
58
62
  touched(file: UXFileInfoStub | FilePathWithPrefix): Promise<void>;
59
63
  recentlyTouched(file: UXFileInfoStub | FilePathWithPrefix): Promise<boolean>;
@@ -2,17 +2,23 @@ import { LOG_LEVEL_INFO, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logge
2
2
  import { ServiceModuleBase } from "./ServiceModuleBase.js";
3
3
  import { StorageEventManager } from "../interfaces/StorageEventManager.js";
4
4
  import { createBlob, fireAndForget } from "../common/utils.js";
5
+ import { createFallbackFileNameLookup } from "./ServiceFileAccessBase/fileNames.js";
5
6
  class ServiceFileAccessBase extends ServiceModuleBase {
6
7
  vaultAccess;
7
8
  vaultManager;
8
9
  vault;
9
10
  setting;
11
+ fallbackFileNames;
10
12
  constructor(services) {
11
13
  super(services);
12
14
  this.vault = services.vault;
13
15
  this.setting = services.setting;
14
16
  this.vaultManager = services.storageEventManager;
15
17
  this.vaultAccess = services.vaultAccess;
18
+ this.fallbackFileNames = createFallbackFileNameLookup({
19
+ getFileNames: () => this.getFileNames(),
20
+ getStorageFileEventCount: () => services.fileProcessing.totalStorageFileEventCount
21
+ });
16
22
  services.appLifecycle.onFirstInitialise.addHandler(this._everyOnFirstInitialize.bind(this));
17
23
  services.fileProcessing.commitPendingFileEvents.addHandler(this._everyCommitPendingFileEvent.bind(this));
18
24
  services.appLifecycle.onBeforeUnload.addHandler(async () => {
@@ -214,9 +220,18 @@ class ServiceFileAccessBase extends ServiceModuleBase {
214
220
  const files = await this.vaultAccess.getFiles();
215
221
  return files.map((f) => this.vaultAccess.nativeFileToUXFileInfoStub(f));
216
222
  }
217
- async getFileNames() {
218
- const files = await this.vaultAccess.getFiles();
219
- return files.map((f) => f.path);
223
+ async getFileNames(options) {
224
+ if (options?.fresh) {
225
+ this.fallbackFileNames.invalidate();
226
+ }
227
+ return await this.vaultAccess.getFileNames(options);
228
+ }
229
+ async findPathIdentityCandidates(path, policy) {
230
+ const indexedCandidates = this.vaultAccess.findPathIdentityCandidates(path, policy);
231
+ if (indexedCandidates) {
232
+ return await indexedCandidates;
233
+ }
234
+ return await this.fallbackFileNames.findPathIdentityCandidates(path, policy);
220
235
  }
221
236
  async getFilesIncludeHidden(basePath, includeFilter, excludeFilter, skipFolder = [".git", ".trash", "node_modules"]) {
222
237
  let w;
@@ -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
  /**