@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
@@ -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";
@@ -43,5 +43,5 @@ export declare function collectDatabaseFiles(host: NecessaryServices<"database"
43
43
  quarantinedFileNamesLC: Set<FilePathWithPrefixLC>;
44
44
  }>;
45
45
  export declare function updateToDatabase(host: NecessaryServices<"vault", "fileHandler">, log: LogFunction, logLevel: LOG_LEVEL, file: UXFileInfoStub): Promise<FilePairProcessResult>;
46
- export declare function updateToStorage(host: NecessaryServices<"vault" | "path", "fileHandler">, log: LogFunction, logLevel: LOG_LEVEL, w: MetaEntry): Promise<FilePairProcessResult>;
46
+ export declare function updateToStorage(host: NecessaryServices<"vault" | "path", "fileHandler">, log: LogFunction, logLevel: LOG_LEVEL, w: MetaEntry, scanOptions?: VaultScanOptions): Promise<FilePairProcessResult>;
47
47
  export declare function syncStorageAndDatabase(host: NecessaryServices<"setting" | "vault" | "path", "storageAccess" | "fileHandler">, log: LogFunction, file: UXFileInfoStub, logLevel: LOG_LEVEL, doc: MetaEntry, scanOptions?: VaultScanOptions): Promise<FilePairProcessResult>;
@@ -1,3 +1,4 @@
1
+ import { isReflectionCompleted } from "../../interfaces/FileHandler.js";
1
2
  import {
2
3
  LOG_LEVEL_DEBUG,
3
4
  LOG_LEVEL_INFO,
@@ -10,6 +11,23 @@ import { shouldBeIgnored, stripAllPrefixes } from "../../string_and_binary/path.
10
11
  import { inspectMetadataDocumentIdentity } from "./metadata.js";
11
12
  import { getPathFromEntry, convertCase } from "./paths.js";
12
13
  import { FilePairProcessResults, MetadataDocumentIdentityStatuses } from "./types.js";
14
+ async function reflectScannedEntry(host, entry, file, force, options) {
15
+ const target = entry._rev ? { documentId: entry._id, revision: entry._rev } : void 0;
16
+ try {
17
+ const result = await host.serviceModules.fileHandler.reflectDatabaseEntry(
18
+ entry,
19
+ file,
20
+ force,
21
+ options?.reflectionOperation ?? (target ? { target, source: "scan" } : void 0)
22
+ );
23
+ return isReflectionCompleted(result) ? FilePairProcessResults.COMPLETED : FilePairProcessResults.SKIPPED;
24
+ } catch (error) {
25
+ if (target && options?.onReflectionFailed) {
26
+ await options.onReflectionFailed(target, error);
27
+ }
28
+ return FilePairProcessResults.FAILED;
29
+ }
30
+ }
13
31
  async function syncFileBetweenDBandStorage(host, log, file, doc, scanOptions) {
14
32
  const docPath = getPathFromEntry(host, doc);
15
33
  if (!doc) {
@@ -31,16 +49,16 @@ async function syncFileBetweenDBandStorage(host, log, file, doc, scanOptions) {
31
49
  case TARGET_IS_NEW:
32
50
  if (!host.services.vault.isFileSizeTooLarge(doc.size)) {
33
51
  log("STORAGE <- DB :" + docPath);
34
- if (await host.serviceModules.fileHandler.dbToStorage(doc, stripAllPrefixes(docPath), false)) {
52
+ const reflection = await reflectScannedEntry(host, doc, stripAllPrefixes(docPath), false, scanOptions);
53
+ if (reflection === FilePairProcessResults.COMPLETED) {
35
54
  host.services.context.events.emitEvent("event-file-changed", {
36
55
  file: file.path,
37
56
  automated: true
38
57
  });
39
- return FilePairProcessResults.COMPLETED;
40
- } else {
58
+ } else if (reflection === FilePairProcessResults.FAILED) {
41
59
  log(`STORAGE <- DB : Cloud not read ${file.path}, possibly deleted`, LOG_LEVEL_NOTICE);
42
- return FilePairProcessResults.FAILED;
43
60
  }
61
+ return reflection;
44
62
  } else {
45
63
  log(
46
64
  `STORAGE <- DB : ${file.path} has been skipped due to file size exceeding the limit`,
@@ -165,7 +183,7 @@ async function updateToDatabase(host, log, logLevel, file) {
165
183
  return FilePairProcessResults.SKIPPED;
166
184
  }
167
185
  }
168
- async function updateToStorage(host, log, logLevel, w) {
186
+ async function updateToStorage(host, log, logLevel, w, scanOptions) {
169
187
  const path = getPathFromEntry(host, w);
170
188
  if (w && !(w.deleted || w._deleted)) {
171
189
  if (!host.services.vault.isFileSizeTooLarge(w.size)) {
@@ -173,8 +191,10 @@ async function updateToStorage(host, log, logLevel, w) {
173
191
  log(`UPDATE STORAGE: ${path} has conflicts. skipped (x)`, LOG_LEVEL_INFO);
174
192
  return FilePairProcessResults.SKIPPED;
175
193
  }
176
- const reflected = await host.serviceModules.fileHandler.dbToStorage(path, null, true);
177
- if (!reflected) return FilePairProcessResults.FAILED;
194
+ const reflected = await reflectScannedEntry(host, w, null, true, scanOptions);
195
+ if (reflected !== FilePairProcessResults.COMPLETED) {
196
+ return reflected;
197
+ }
178
198
  host.services.context.events.emitEvent("event-file-changed", {
179
199
  file: path,
180
200
  automated: true
@@ -2,7 +2,7 @@ import type { NecessaryServices } from "../../interfaces/ServiceModule.js";
2
2
  import type { LogFunction } from "../../services/lib/logUtils.js";
3
3
  import type { UnresolvedErrorManager } from "../../services/base/UnresolvedErrorManager.js";
4
4
  import { type VaultScanResult } from "../../services/base/VaultScanResult.js";
5
- import { type FullScanOptions, type FilePair, type FilePairState, type FilePairAction } from "./types.js";
5
+ import { type FullScanOptions, type FilePair, type FilePairState, type FilePairAction, type FilePairProcessResult } from "./types.js";
6
6
  /**
7
7
  * Classify the storage and retained-Metadata observations of one pair.
8
8
  * @param pair - Selected observations from the shared scan collection.
@@ -19,6 +19,10 @@ export declare function getFilePairState(pair: FilePair): FilePairState;
19
19
  * this matrix retains its established explicit extra-file policies.
20
20
  */
21
21
  export declare function resolveFilePairAction(state: FilePairState, options: FullScanOptions): FilePairAction;
22
+ /**
23
+ * Process a single file pair based on the determined action from the file pair state and scan options.
24
+ */
25
+ export declare function processFilePair(host: NecessaryServices<"setting" | "vault" | "path" | "keyValueDB", "storageAccess" | "fileHandler">, log: LogFunction, pair: FilePair, options: FullScanOptions): Promise<FilePairProcessResult>;
22
26
  /**
23
27
  * Run one scan at a time for each backing-store owner.
24
28
  * @param host - Borrowed scan services and file-operation capabilities.
@@ -128,7 +128,7 @@ async function processFilePair(host, log, pair, options) {
128
128
  if (!doc) {
129
129
  throw new Error(`Missing database entry for ${path}`);
130
130
  }
131
- const updateStorageResult = await updateToStorage(host, log, LOG_LEVEL_INFO, doc);
131
+ const updateStorageResult = await updateToStorage(host, log, LOG_LEVEL_INFO, doc, options);
132
132
  if (updateStorageResult === FilePairProcessResults.COMPLETED) {
133
133
  updateFileMTimeInMap(host, fileMapKey, doc.mtime);
134
134
  }
@@ -353,6 +353,7 @@ async function synchroniseFilePairs(host, log, errorManager, options) {
353
353
  }
354
354
  export {
355
355
  getFilePairState,
356
+ processFilePair,
356
357
  resolveFilePairAction,
357
358
  synchroniseAllFilesBetweenDBandStorage
358
359
  };
@@ -11,7 +11,7 @@ export { getMetadataDocumentNamespace, inspectMetadataDocumentIdentity, inspectM
11
11
  export { getPathFromEntry, convertCase } from "./offlineScanner/paths.js";
12
12
  export { clearOfflineScannerLastSeen } from "./offlineScanner/fileStatus.js";
13
13
  export { syncFileBetweenDBandStorage, collectFilesOnStorage, collectDatabaseFiles, updateToDatabase, updateToStorage, syncStorageAndDatabase, } from "./offlineScanner/files.js";
14
- export { getFilePairState, resolveFilePairAction, synchroniseAllFilesBetweenDBandStorage } from "./offlineScanner/scan.js";
14
+ export { getFilePairState, resolveFilePairAction, processFilePair, synchroniseAllFilesBetweenDBandStorage, } from "./offlineScanner/scan.js";
15
15
  /**
16
16
  * Check configuration, suspension, and remediation policy before a full scan.
17
17
  * @param host - Borrowed settings and store capabilities.
@@ -33,7 +33,12 @@ import {
33
33
  updateToStorage,
34
34
  syncStorageAndDatabase
35
35
  } from "./offlineScanner/files.js";
36
- import { getFilePairState, resolveFilePairAction, synchroniseAllFilesBetweenDBandStorage as synchroniseAllFilesBetweenDBandStorage2 } from "./offlineScanner/scan.js";
36
+ import {
37
+ getFilePairState,
38
+ resolveFilePairAction,
39
+ processFilePair,
40
+ synchroniseAllFilesBetweenDBandStorage as synchroniseAllFilesBetweenDBandStorage2
41
+ } from "./offlineScanner/scan.js";
37
42
  function canProceedScan(host, errorManager, log, showingNotice = false, ignoreSuspending = false) {
38
43
  const settings = host.services.setting.currentSettings();
39
44
  const ERR_NOT_CONFIGURED = "LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.";
@@ -106,7 +111,9 @@ function useOfflineScanner(host) {
106
111
  showingNotice,
107
112
  ignoreSuspending,
108
113
  continueOnFileFailure,
109
- strictContentCheck: scanOptions?.strictContentCheck
114
+ strictContentCheck: scanOptions?.strictContentCheck,
115
+ onReflectionFailed: scanOptions?.onReflectionFailed,
116
+ reflectionOperation: scanOptions?.reflectionOperation
110
117
  });
111
118
  };
112
119
  host.services.vault.scanVault.addHandler(handleScanVault);
@@ -134,6 +141,7 @@ export {
134
141
  inspectMetadataDocumentIdentity,
135
142
  normaliseFullScanOptions,
136
143
  performFullScan,
144
+ processFilePair,
137
145
  repairMetadataDocumentIdentity,
138
146
  resolveFilePairAction,
139
147
  syncFileBetweenDBandStorage,
@@ -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) {
@@ -42,6 +42,9 @@ export declare class ServiceDatabaseFileAccessBase extends ServiceModuleBase<Ser
42
42
  storeDeletionWithBaseRevision(file: UXFileInfoStub | FilePathWithPrefix, baseRevision: string): Promise<string | false>;
43
43
  storeContent(path: FilePathWithPrefix, content: string): Promise<boolean>;
44
44
  private __store;
45
+ private prepareStoreEntry;
46
+ private shouldSkipStoreEntryWrite;
47
+ private writeStoreEntry;
45
48
  /** Reconstruct the immediate parent ID from revision history, or return `false` if unavailable. */
46
49
  private getParentRev;
47
50
  /**
@@ -50,6 +53,8 @@ export declare class ServiceDatabaseFileAccessBase extends ServiceModuleBase<Ser
50
53
  * Historical matches alone do not establish the origin of current storage content.
51
54
  */
52
55
  private findContentRevisionsInternal;
56
+ private collectAvailableHistoryRevisions;
57
+ private matchRevisionContent;
53
58
  /** Find matching content throughout available history, including non-leaf revisions. */
54
59
  findContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, currentRev?: string): Promise<string[]>;
55
60
  /**
@@ -60,11 +65,19 @@ export declare class ServiceDatabaseFileAccessBase extends ServiceModuleBase<Ser
60
65
  * unique origin; this method does not mutate provenance or hold the revision tree stable.
61
66
  */
62
67
  findLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer): Promise<string[]>;
68
+ /** Select current live leaves, independently of historical ancestor lookup. */
69
+ private selectLiveContentLeaves;
70
+ /** Compare selected leaves using local Chunks only; unreadable content rejects. */
71
+ readLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer): Promise<string[]>;
63
72
  hasContentInRevisionHistory(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, currentRev?: string): Promise<boolean>;
64
73
  getConflictedRevs(file: UXFileInfoStub | FilePathWithPrefix): Promise<string[]>;
74
+ readConflictedRevs(file: UXFileInfoStub | FilePathWithPrefix): Promise<string[]>;
65
75
  fetch(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, waitForReady?: boolean, skipCheck?: boolean): Promise<UXFileInfo | false>;
66
76
  fetchEntryMeta(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, skipCheck?: boolean): Promise<MetaEntry | false>;
77
+ readEntryMeta(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, skipCheck?: boolean): Promise<MetaEntry | false>;
67
78
  fetchEntryFromMeta(meta: MetaEntry, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean): Promise<LoadedEntry | false>;
79
+ readEntryFromMeta(meta: MetaEntry, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean): Promise<LoadedEntry | false>;
68
80
  fetchEntry(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean): Promise<LoadedEntry | false>;
81
+ readEntry(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean): Promise<LoadedEntry | false>;
69
82
  deleteFromDBbyPath(fullPath: FilePath | FilePathWithPrefix, rev?: string): Promise<boolean>;
70
83
  }