@vrtmrz/livesync-commonlib 0.4.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +2 -2
  2. package/dist/common/LSError.d.ts +13 -0
  3. package/dist/common/LSError.js +19 -1
  4. package/dist/diagnostics/local.d.ts +7 -2
  5. package/dist/interfaces/DatabaseFileAccess.d.ts +20 -4
  6. package/dist/interfaces/FileHandler.d.ts +67 -1
  7. package/dist/interfaces/FileHandler.js +16 -0
  8. package/dist/interfaces/StorageAccess.d.ts +8 -2
  9. package/dist/interfaces/StorageEventManager.d.ts +7 -0
  10. package/dist/managers/ChunkFetcher.d.ts +16 -0
  11. package/dist/managers/ChunkFetcher.js +190 -112
  12. package/dist/managers/EntryManager/EntryManager.d.ts +7 -0
  13. package/dist/managers/EntryManager/EntryManager.js +6 -0
  14. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +9 -5
  15. package/dist/managers/EntryManager/EntryManagerImpls.js +103 -76
  16. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.d.ts +7 -3
  17. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.js +83 -16
  18. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.d.ts +3 -2
  19. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.js +38 -36
  20. package/dist/managers/LayeredChunkManager/types.d.ts +15 -1
  21. package/dist/managers/LayeredChunkManager.d.ts +4 -0
  22. package/dist/managers/LayeredChunkManager.js +19 -6
  23. package/dist/managers/LiveSyncManagers.d.ts +2 -0
  24. package/dist/managers/LiveSyncManagers.js +6 -0
  25. package/dist/managers/StorageEventManager.d.ts +22 -0
  26. package/dist/managers/StorageEventManager.js +48 -1
  27. package/dist/platform/FilePathIndex.d.ts +110 -0
  28. package/dist/platform/FilePathIndex.js +146 -0
  29. package/dist/pouchdb/LiveSyncLocalDB.d.ts +32 -0
  30. package/dist/pouchdb/LiveSyncLocalDB.js +72 -18
  31. package/dist/pouchdb/LocalDatabaseReadScope.d.ts +24 -0
  32. package/dist/pouchdb/LocalDatabaseReadScope.js +62 -0
  33. package/dist/pouchdb/pathIdentityCompatibility.d.ts +6 -2
  34. package/dist/pouchdb/pathIdentityCompatibility.js +15 -10
  35. package/dist/replication/contentRead.d.ts +3 -0
  36. package/dist/replication/contentRead.js +4 -0
  37. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +8 -1
  38. package/dist/replication/couchdb/LiveSyncReplicator.js +187 -119
  39. package/dist/replication/index.d.ts +5 -1
  40. package/dist/replication/index.js +18 -1
  41. package/dist/replication/trystero/LiveSyncTrysteroReplicator.d.ts +3 -3
  42. package/dist/replication/trystero/P2PAutomationCoordinator.d.ts +1 -1
  43. package/dist/replication/trystero/P2PReplicationWire.d.ts +1 -1
  44. package/dist/replication/trystero/TrysteroReplicator/changeRelay.d.ts +133 -0
  45. package/dist/replication/trystero/TrysteroReplicator/changeRelay.js +176 -0
  46. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.d.ts +55 -0
  47. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.js +99 -0
  48. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.d.ts +83 -0
  49. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.js +121 -0
  50. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.d.ts +75 -0
  51. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.js +131 -0
  52. package/dist/replication/trystero/TrysteroReplicator/progress.d.ts +57 -0
  53. package/dist/replication/trystero/TrysteroReplicator/progress.js +84 -0
  54. package/dist/replication/trystero/TrysteroReplicator/relayControl.d.ts +20 -0
  55. package/dist/replication/trystero/TrysteroReplicator/relayControl.js +25 -0
  56. package/dist/replication/trystero/TrysteroReplicator/transfers.d.ts +125 -0
  57. package/dist/replication/trystero/TrysteroReplicator/transfers.js +278 -0
  58. package/dist/replication/trystero/TrysteroReplicator.d.ts +65 -483
  59. package/dist/replication/trystero/TrysteroReplicator.js +240 -673
  60. package/dist/replication/trystero/TrysteroReplicatorP2PClient.d.ts +19 -6
  61. package/dist/replication/trystero/TrysteroReplicatorP2PClient.js +29 -25
  62. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.d.ts +66 -0
  63. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.js +142 -0
  64. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +19 -16
  65. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +33 -93
  66. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +1 -1
  67. package/dist/replication/trystero/p2pReplicationProgress.d.ts +2 -11
  68. package/dist/replication/trystero/replicationTypes.d.ts +88 -0
  69. package/dist/replication/trystero/replicationTypes.js +0 -0
  70. package/dist/replication/trystero/rpcSessionProvider.d.ts +13 -0
  71. package/dist/replication/trystero/rpcSessionProvider.js +0 -0
  72. package/dist/rpc/RpcRoom/pendingInvocations.d.ts +141 -0
  73. package/dist/rpc/RpcRoom/pendingInvocations.js +225 -0
  74. package/dist/rpc/RpcRoom.d.ts +9 -4
  75. package/dist/rpc/RpcRoom.js +73 -118
  76. package/dist/rpc/RpcSession.d.ts +6 -0
  77. package/dist/rpc/RpcSession.js +11 -0
  78. package/dist/rpc/types.d.ts +2 -0
  79. package/dist/serviceFeatures/offlineScanner/files.d.ts +1 -1
  80. package/dist/serviceFeatures/offlineScanner/files.js +27 -7
  81. package/dist/serviceFeatures/offlineScanner/scan.d.ts +5 -1
  82. package/dist/serviceFeatures/offlineScanner/scan.js +2 -1
  83. package/dist/serviceFeatures/offlineScanner.d.ts +1 -1
  84. package/dist/serviceFeatures/offlineScanner.js +10 -2
  85. package/dist/serviceFeatures/targetFilter.d.ts +1 -1
  86. package/dist/serviceFeatures/targetFilter.js +8 -38
  87. package/dist/serviceModules/FileAccessBase.d.ts +4 -0
  88. package/dist/serviceModules/FileAccessBase.js +10 -0
  89. package/dist/serviceModules/Rebuilder.js +1 -1
  90. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +13 -0
  91. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +190 -123
  92. package/dist/serviceModules/ServiceFileAccessBase/fileNames.d.ts +54 -0
  93. package/dist/serviceModules/ServiceFileAccessBase/fileNames.js +57 -0
  94. package/dist/serviceModules/ServiceFileAccessBase.d.ts +5 -1
  95. package/dist/serviceModules/ServiceFileAccessBase.js +18 -3
  96. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +17 -7
  97. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +3 -2
  98. package/dist/serviceModules/ServiceFileHandlerBase/events.js +9 -9
  99. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -9
  100. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +10 -0
  101. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +28 -4
  102. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +11 -5
  103. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +144 -58
  104. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +16 -2
  105. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +1 -0
  106. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +7 -2
  107. package/dist/serviceModules/ServiceFileHandlerBase.js +13 -4
  108. package/dist/serviceModules/adapters/IFileSystemAdapter.d.ts +3 -0
  109. package/dist/services/base/ControlService.js +1 -5
  110. package/dist/services/base/DatabaseEventService.d.ts +3 -0
  111. package/dist/services/base/DatabaseEventService.js +3 -0
  112. package/dist/services/base/DatabaseService.d.ts +15 -0
  113. package/dist/services/base/DatabaseService.js +85 -4
  114. package/dist/services/base/IService.d.ts +18 -1
  115. package/dist/services/base/KeyValueDBService.d.ts +5 -4
  116. package/dist/services/base/KeyValueDBService.js +46 -48
  117. package/dist/services/base/ReplicationService.d.ts +3 -1
  118. package/dist/services/base/ReplicationService.js +3 -1
  119. package/dist/services/base/VaultScanResult.d.ts +5 -0
  120. package/dist/services/lib/HandlerUtils.d.ts +40 -5
  121. package/dist/services/lib/HandlerUtils.js +52 -4
  122. package/dist/storage.d.ts +2 -0
  123. package/dist/storage.js +2 -0
  124. package/docs/development.md +111 -0
  125. package/docs/offline-scanner.md +46 -0
  126. package/docs/p2p-transport-lifecycle.md +24 -0
  127. package/docs/platform-storage.md +22 -0
  128. package/docs/releasing.md +48 -0
  129. package/docs/settings-lifecycle.md +4 -2
  130. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { ContentReadError } from "../common/LSError.js";
1
2
  import { shouldBeIgnored, isPlainText, stripAllPrefixes } from "../string_and_binary/path.js";
2
3
  import { LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
3
4
  import { serialized } from "octagonal-wheels/concurrency/lock_v2";
@@ -120,15 +121,33 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
120
121
  return await this.__store(dummyUXFileInfo, true, false, false) !== false;
121
122
  }
122
123
  async __store(file, force = false, skipCheck, onlyChunks, revisionTarget = { mode: "default" }) {
123
- if (!skipCheck) {
124
- if (!await this.checkIsTargetFile(file)) {
125
- return true;
126
- }
124
+ if (!skipCheck && !await this.checkIsTargetFile(file)) {
125
+ return true;
127
126
  }
128
127
  if (!file) {
129
128
  this._log("File seems bad", LOG_LEVEL_VERBOSE);
130
129
  return false;
131
130
  }
131
+ const preparation = await this.prepareStoreEntry(file);
132
+ if (!preparation) {
133
+ return false;
134
+ }
135
+ const { entry, fullPath, message } = preparation;
136
+ const isNotChanged = await serialized("file-" + fullPath, async () => {
137
+ return await this.shouldSkipStoreEntryWrite(entry, fullPath, message, force, revisionTarget);
138
+ });
139
+ if (isNotChanged) {
140
+ this._log(message + " Skip " + fullPath, LOG_LEVEL_VERBOSE);
141
+ return true;
142
+ }
143
+ const ret = await this.writeStoreEntry(entry, onlyChunks, revisionTarget);
144
+ if (ret !== false) {
145
+ this._log(message + fullPath);
146
+ this.events.emitEvent(EVENT_FILE_SAVED);
147
+ }
148
+ return ret;
149
+ }
150
+ async prepareStoreEntry(file) {
132
151
  const isPlain = isPlainText(file.name);
133
152
  const possiblyLarge = !isPlain;
134
153
  const content = file.body;
@@ -136,7 +155,9 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
136
155
  const idPrefix = file.isInternal ? ICHeader : "";
137
156
  const fullPath = getStoragePathFromUXFileInfo(file);
138
157
  const fullPathOnDB = getDatabasePathFromUXFileInfo(file);
139
- if (possiblyLarge) this._log(`Processing: ${fullPath}`, LOG_LEVEL_VERBOSE);
158
+ if (possiblyLarge) {
159
+ this._log(`Processing: ${fullPath}`, LOG_LEVEL_VERBOSE);
160
+ }
140
161
  if (file.isInternal) {
141
162
  if (file.deleted) {
142
163
  file.stat = {
@@ -169,56 +190,60 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
169
190
  eden: {}
170
191
  };
171
192
  const msg = `STORAGE -> DB (${datatype}) `;
172
- const isNotChanged = await serialized("file-" + fullPath, async () => {
173
- if (revisionTarget.mode !== "default") {
174
- return false;
175
- }
176
- if (force) {
177
- this._log(msg + "Force writing " + fullPath, LOG_LEVEL_VERBOSE);
178
- return false;
179
- }
180
- try {
181
- const old = await this.database.localDatabase.getDBEntry(d.path, void 0, false, true, false);
182
- if (old !== false) {
183
- const oldData = { data: old.data, deleted: old._deleted || old.deleted };
184
- const newData = { data: d.data, deleted: d._deleted || d.deleted };
185
- if (oldData.deleted != newData.deleted) return false;
186
- if (!await isDocContentSame(old.data, newData.data)) return false;
187
- this._log(
188
- msg + "Skipped (not changed) " + fullPath + (d._deleted || d.deleted ? " (deleted)" : ""),
189
- LOG_LEVEL_VERBOSE
190
- );
191
- this.path.markChangesAreSame(old, d.mtime, old.mtime);
192
- return true;
193
+ return { entry: d, fullPath, message: msg };
194
+ }
195
+ async shouldSkipStoreEntryWrite(entry, fullPath, message, force, revisionTarget) {
196
+ if (revisionTarget.mode !== "default") {
197
+ return false;
198
+ }
199
+ if (force) {
200
+ this._log(message + "Force writing " + fullPath, LOG_LEVEL_VERBOSE);
201
+ return false;
202
+ }
203
+ try {
204
+ const old = await this.database.localDatabase.getDBEntry(entry.path, void 0, false, true, false);
205
+ if (old !== false) {
206
+ const oldData = { data: old.data, deleted: old._deleted || old.deleted };
207
+ const newData = { data: entry.data, deleted: entry._deleted || entry.deleted };
208
+ if (oldData.deleted != newData.deleted) {
209
+ return false;
210
+ }
211
+ if (!await isDocContentSame(old.data, newData.data)) {
212
+ return false;
193
213
  }
194
- } catch (ex) {
195
214
  this._log(
196
- msg + "Error, Could not check the diff for the old one." + (force ? "force writing." : "") + fullPath + (d._deleted || d.deleted ? " (deleted)" : ""),
215
+ message + "Skipped (not changed) " + fullPath + (entry._deleted || entry.deleted ? " (deleted)" : ""),
197
216
  LOG_LEVEL_VERBOSE
198
217
  );
199
- this._log(ex, LOG_LEVEL_VERBOSE);
200
- return !force;
218
+ this.path.markChangesAreSame(old, entry.mtime, old.mtime);
219
+ return true;
201
220
  }
202
- return false;
203
- });
204
- if (isNotChanged) {
205
- this._log(msg + " Skip " + fullPath, LOG_LEVEL_VERBOSE);
206
- return true;
221
+ } catch (ex) {
222
+ this._log(
223
+ message + "Error, Could not check the diff for the old one." + (force ? "force writing." : "") + fullPath + (entry._deleted || entry.deleted ? " (deleted)" : ""),
224
+ LOG_LEVEL_VERBOSE
225
+ );
226
+ this._log(ex, LOG_LEVEL_VERBOSE);
227
+ return !force;
228
+ }
229
+ return false;
230
+ }
231
+ async writeStoreEntry(entry, onlyChunks, revisionTarget) {
232
+ if (revisionTarget.mode === "independent-root") {
233
+ return await this.database.localDatabase.putDBEntryAsIndependentRoot(entry);
207
234
  }
208
- const ret = revisionTarget.mode === "independent-root" ? await this.database.localDatabase.putDBEntryAsIndependentRoot(d) : revisionTarget.mode === "live-base" ? await this.database.localDatabase.putDBEntryWithLiveBaseRevision(
209
- d,
210
- revisionTarget.baseRevision,
211
- onlyChunks
212
- ) : await this.database.localDatabase.putDBEntry(
213
- d,
235
+ if (revisionTarget.mode === "live-base") {
236
+ return await this.database.localDatabase.putDBEntryWithLiveBaseRevision(
237
+ entry,
238
+ revisionTarget.baseRevision,
239
+ onlyChunks
240
+ );
241
+ }
242
+ return await this.database.localDatabase.putDBEntry(
243
+ entry,
214
244
  onlyChunks,
215
245
  revisionTarget.mode === "force-base" ? revisionTarget.baseRevision : void 0
216
246
  );
217
- if (ret !== false) {
218
- this._log(msg + fullPath);
219
- this.events.emitEvent(EVENT_FILE_SAVED);
220
- }
221
- return ret;
222
247
  }
223
248
  /** Reconstruct the immediate parent ID from revision history, or return `false` if unavailable. */
224
249
  async getParentRev(file, rev) {
@@ -255,53 +280,60 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
255
280
  if (doc === false) {
256
281
  return [];
257
282
  }
258
- const revisions = doc._revs_info;
259
- const availableRevs = new Set((revisions || []).filter((e) => e.status === "available").map((e) => e.rev));
260
- if (currentRev) {
261
- availableRevs.add(currentRev);
283
+ const availableRevs = await this.collectAvailableHistoryRevisions(filename, doc, currentRev);
284
+ return await this.matchRevisionContent(filename, availableRevs, content, stopAfterFirstMatch);
285
+ } catch (ex) {
286
+ this._log(`Could not check revision history for ${filename}`, LOG_LEVEL_VERBOSE);
287
+ this._log(ex, LOG_LEVEL_VERBOSE);
288
+ }
289
+ return [];
290
+ }
291
+ async collectAvailableHistoryRevisions(filename, doc, currentRev) {
292
+ const revisions = doc._revs_info;
293
+ const availableRevs = new Set((revisions || []).filter((e) => e.status === "available").map((e) => e.rev));
294
+ if (currentRev) {
295
+ availableRevs.add(currentRev);
296
+ }
297
+ const leaves = await this.database.localDatabase.getRaw(doc._id, {
298
+ open_revs: "all"
299
+ });
300
+ if (!Array.isArray(leaves)) {
301
+ return [];
302
+ }
303
+ for (const leaf of leaves) {
304
+ const leafRev = leaf.ok?._rev;
305
+ if (!leafRev) {
306
+ continue;
262
307
  }
263
- const leaves = await this.database.localDatabase.getRaw(doc._id, {
264
- open_revs: "all"
265
- });
266
- if (!Array.isArray(leaves)) {
267
- return [];
308
+ const branch = await this.database.localDatabase.getDBEntryMeta(
309
+ filename,
310
+ { rev: leafRev, revs_info: true },
311
+ true
312
+ );
313
+ if (branch === false) {
314
+ continue;
268
315
  }
269
- for (const leaf of leaves) {
270
- const leafRev = leaf.ok?._rev;
271
- if (!leafRev) {
272
- continue;
273
- }
274
- const branch = await this.database.localDatabase.getDBEntryMeta(
275
- filename,
276
- { rev: leafRev, revs_info: true },
277
- true
278
- );
279
- if (branch === false) {
280
- continue;
281
- }
282
- const branchRevisions = branch._revs_info;
283
- for (const revision of branchRevisions || []) {
284
- if (revision.status === "available") {
285
- availableRevs.add(revision.rev);
286
- }
316
+ const branchRevisions = branch._revs_info;
317
+ for (const revision of branchRevisions || []) {
318
+ if (revision.status === "available") {
319
+ availableRevs.add(revision.rev);
287
320
  }
288
321
  }
289
- const matchingRevisions = [];
290
- for (const rev of availableRevs) {
291
- const entry = await this.database.localDatabase.getDBEntry(filename, { rev }, false, true, true);
292
- if (entry !== false && !entry._deleted && await isDocContentSame(readContent(entry), content)) {
293
- matchingRevisions.push(rev);
294
- if (stopAfterFirstMatch) {
295
- return matchingRevisions;
296
- }
322
+ }
323
+ return [...availableRevs];
324
+ }
325
+ async matchRevisionContent(filename, availableRevs, content, stopAfterFirstMatch) {
326
+ const matchingRevisions = [];
327
+ for (const rev of availableRevs) {
328
+ const entry = await this.database.localDatabase.getDBEntry(filename, { rev }, false, true, true);
329
+ if (entry !== false && !entry._deleted && await isDocContentSame(readContent(entry), content)) {
330
+ matchingRevisions.push(rev);
331
+ if (stopAfterFirstMatch) {
332
+ return matchingRevisions;
297
333
  }
298
334
  }
299
- return matchingRevisions;
300
- } catch (ex) {
301
- this._log(`Could not check revision history for ${filename}`, LOG_LEVEL_VERBOSE);
302
- this._log(ex, LOG_LEVEL_VERBOSE);
303
335
  }
304
- return [];
336
+ return matchingRevisions;
305
337
  }
306
338
  /** Find matching content throughout available history, including non-leaf revisions. */
307
339
  async findContentRevisions(file, content, currentRev) {
@@ -318,30 +350,58 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
318
350
  * unique origin; this method does not mutate provenance or hold the revision tree stable.
319
351
  */
320
352
  async findLiveContentRevisions(file, content) {
321
- if (!await this.checkIsTargetFile(file)) return [];
353
+ try {
354
+ return await this.readLiveContentRevisions(file, content);
355
+ } catch (error) {
356
+ this._log(error, LOG_LEVEL_VERBOSE);
357
+ return [];
358
+ }
359
+ }
360
+ /** Select current live leaves, independently of historical ancestor lookup. */
361
+ async selectLiveContentLeaves(file) {
322
362
  const filename = getDatabasePathFromUXFileInfo(file);
363
+ const current = await this.readEntryMeta(file, void 0, true);
364
+ if (!current) {
365
+ return [];
366
+ }
367
+ let leaves;
323
368
  try {
324
- const current = await this.database.localDatabase.getDBEntryMeta(filename, void 0, true);
325
- if (current === false) return [];
326
- const leaves = await this.database.localDatabase.getRaw(current._id, {
369
+ leaves = await this.database.localDatabase.getRaw(current._id, {
327
370
  open_revs: "all"
328
371
  });
329
- if (!Array.isArray(leaves)) return [];
330
- const matches = [];
331
- for (const leaf of leaves) {
332
- const rev = leaf.ok?._rev;
333
- if (!rev || leaf.ok?.deleted || leaf.ok?._deleted) continue;
334
- const entry = await this.database.localDatabase.getDBEntry(filename, { rev }, false, true, true, true);
335
- if (entry !== false && !entry.deleted && !entry._deleted && await isDocContentSame(readContent(entry), content)) {
336
- matches.push(rev);
337
- }
338
- }
339
- return matches;
340
- } catch (ex) {
341
- this._log(`Could not check live revision content for ${filename}`, LOG_LEVEL_VERBOSE);
342
- this._log(ex, LOG_LEVEL_VERBOSE);
372
+ } catch (error) {
373
+ throw new ContentReadError({ documentId: current._id, resources: ["local-database"], cause: error });
374
+ }
375
+ if (!Array.isArray(leaves)) {
376
+ throw new ContentReadError({
377
+ documentId: current._id,
378
+ resources: [],
379
+ cause: new Error(`Invalid live revision response for ${filename}`)
380
+ });
381
+ }
382
+ return leaves.flatMap(({ ok }) => ok?._rev && !ok.deleted && !ok._deleted ? [ok._rev] : []);
383
+ }
384
+ /** Compare selected leaves using local Chunks only; unreadable content rejects. */
385
+ async readLiveContentRevisions(file, content) {
386
+ if (!await this.checkIsTargetFile(file)) {
343
387
  return [];
344
388
  }
389
+ const revisions = await this.selectLiveContentLeaves(file);
390
+ const matches = [];
391
+ for (const revision of revisions) {
392
+ const entry = await this.database.localDatabase.readDBEntry(
393
+ getDatabasePathFromUXFileInfo(file),
394
+ { rev: revision },
395
+ false,
396
+ true,
397
+ true,
398
+ true
399
+ );
400
+ if (entry && !entry.deleted && !entry._deleted && await isDocContentSame(readContent(entry), content)) {
401
+ matches.push(revision);
402
+ }
403
+ }
404
+ return matches;
345
405
  }
346
406
  async hasContentInRevisionHistory(file, content, currentRev) {
347
407
  if (!await this.checkIsTargetFile(file)) {
@@ -350,15 +410,15 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
350
410
  return (await this.findContentRevisionsInternal(file, content, currentRev, true)).length > 0;
351
411
  }
352
412
  async getConflictedRevs(file) {
413
+ return await this.readConflictedRevs(file);
414
+ }
415
+ async readConflictedRevs(file) {
353
416
  if (!await this.checkIsTargetFile(file)) {
354
417
  return [];
355
418
  }
356
419
  const filename = getDatabasePathFromUXFileInfo(file);
357
420
  const doc = await this.database.localDatabase.getDBEntryMeta(filename, { conflicts: true }, true);
358
- if (doc === false) {
359
- return [];
360
- }
361
- return doc._conflicts || [];
421
+ return doc ? doc._conflicts || [] : [];
362
422
  }
363
423
  async fetch(file, rev, waitForReady, skipCheck = false) {
364
424
  if (skipCheck && !await this.checkIsTargetFile(file)) {
@@ -388,36 +448,43 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
388
448
  return fileInfo;
389
449
  }
390
450
  async fetchEntryMeta(file, rev, skipCheck = false) {
391
- const dbFileName = getDatabasePathFromUXFileInfo(file);
451
+ return await this.readEntryMeta(file, rev, skipCheck);
452
+ }
453
+ async readEntryMeta(file, rev, skipCheck = false) {
454
+ const filename = getDatabasePathFromUXFileInfo(file);
392
455
  if (skipCheck && !await this.checkIsTargetFile(file)) {
393
456
  return false;
394
457
  }
395
- const doc = await this.database.localDatabase.getDBEntryMeta(dbFileName, rev ? { rev } : void 0, true);
396
- if (doc === false) {
397
- return false;
398
- }
399
- return doc;
458
+ return await this.database.localDatabase.getDBEntryMeta(filename, rev ? { rev } : void 0, true);
400
459
  }
401
460
  async fetchEntryFromMeta(meta, waitForReady = true, skipCheck = false, localOnly = false) {
402
- if (skipCheck && !await this.checkIsTargetFile(meta.path)) {
461
+ try {
462
+ return await this.readEntryFromMeta(meta, waitForReady, skipCheck, localOnly);
463
+ } catch (error) {
464
+ this._log(error, LOG_LEVEL_VERBOSE);
403
465
  return false;
404
466
  }
405
- const doc = await this.database.localDatabase.getDBEntryFromMeta(meta, false, waitForReady, localOnly);
406
- if (doc === false) {
467
+ }
468
+ async readEntryFromMeta(meta, waitForReady = true, skipCheck = false, localOnly = false) {
469
+ if (skipCheck && !await this.checkIsTargetFile(meta.path)) {
407
470
  return false;
408
471
  }
409
- return doc;
472
+ return await this.database.localDatabase.readDBEntryFromMeta(meta, false, waitForReady, localOnly);
410
473
  }
411
474
  async fetchEntry(file, rev, waitForReady = true, skipCheck = false, localOnly = false) {
412
- if (skipCheck && !await this.checkIsTargetFile(file)) {
475
+ try {
476
+ return await this.readEntry(file, rev, waitForReady, skipCheck, localOnly);
477
+ } catch (error) {
478
+ this._log(error, LOG_LEVEL_VERBOSE);
413
479
  return false;
414
480
  }
415
- const entry = await this.fetchEntryMeta(file, rev, true);
416
- if (entry === false) {
481
+ }
482
+ async readEntry(file, rev, waitForReady = true, skipCheck = false, localOnly = false) {
483
+ if (skipCheck && !await this.checkIsTargetFile(file)) {
417
484
  return false;
418
485
  }
419
- const doc = await this.fetchEntryFromMeta(entry, waitForReady, true, localOnly);
420
- return doc;
486
+ const entry = await this.readEntryMeta(file, rev, true);
487
+ return entry ? await this.readEntryFromMeta(entry, waitForReady, true, localOnly) : false;
421
488
  }
422
489
  async deleteFromDBbyPath(fullPath, rev) {
423
490
  if (!await this.checkIsTargetFile(fullPath)) {
@@ -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;
@@ -1,7 +1,9 @@
1
+ import { isReflectionCompleted } from "../../interfaces/FileHandler.js";
2
+ import { ContentReadError } from "../../common/LSError.js";
1
3
  import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
2
4
  import { infoToStub } from "./storage.js";
3
5
  import { deleteProvenance, getProvenance, findUniqueContentRevision } from "./provenance.js";
4
- import { applyDatabaseEntryToStorage } from "./reflection.js";
6
+ import { applyDatabaseEntryToStorage, IncompleteFileReflectionError } from "./reflection.js";
5
7
  import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
6
8
  import { getStoragePathFromUXFileInfo, getDatabasePathFromUXFileInfo } from "../../common/typeUtils.js";
7
9
  import { tryGetFilePath } from "../../common/utils.doc.js";
@@ -75,11 +77,19 @@ async function deleteRevisionFromDBCore(ctx, info, rev) {
75
77
  return deleted;
76
78
  }
77
79
  async function resolveConflictedByDeletingRevision(ctx, info, rev) {
78
- return await withFileEventPaths(
79
- ctx,
80
- [getStoragePathFromUXFileInfo(info)],
81
- () => resolveConflictedByDeletingRevisionCore(ctx, info, rev)
82
- );
80
+ let operationReturned = false;
81
+ try {
82
+ return await withFileEventPaths(ctx, [getStoragePathFromUXFileInfo(info)], async () => {
83
+ const result = await resolveConflictedByDeletingRevisionCore(ctx, info, rev);
84
+ operationReturned = true;
85
+ return result;
86
+ });
87
+ } catch (error) {
88
+ if (!operationReturned && (error instanceof ContentReadError || error instanceof IncompleteFileReflectionError)) {
89
+ return false;
90
+ }
91
+ throw error;
92
+ }
83
93
  }
84
94
  async function resolveConflictedByDeletingRevisionCore(ctx, info, rev) {
85
95
  const path = getStoragePathFromUXFileInfo(info);
@@ -93,7 +103,7 @@ async function resolveConflictedByDeletingRevisionCore(ctx, info, rev) {
93
103
  ctx.host.log(`Failed to delete the conflicted revision ${rev} of ${path}`, LOG_LEVEL_VERBOSE);
94
104
  return false;
95
105
  }
96
- if (!await applyDatabaseEntryToStorage(ctx, docEntry, file, true)) {
106
+ if (!isReflectionCompleted(await applyDatabaseEntryToStorage(ctx, docEntry, file, true))) {
97
107
  ctx.host.log(`Failed to apply the resolved revision ${rev} of ${path} to the storage`, LOG_LEVEL_VERBOSE);
98
108
  return false;
99
109
  }
@@ -1,3 +1,4 @@
1
+ import type { FileReflectionResult, ReflectionOperationContext } from "../../interfaces/FileHandler.js";
1
2
  import type { FileEventItem, MetaEntry } from "../../common/types.js";
2
3
  import type { FileHandlerContext } from "./context.js";
3
4
  /**
@@ -14,7 +15,7 @@ export declare function processFileEvent(ctx: FileHandlerContext, item: FileEven
14
15
  *
15
16
  * @param ctx - The captured services, per-instance state, and dynamic host seams.
16
17
  * @param entry - The database metadata being processed.
17
- * @returns Whether replication reflection completed; excluded or unsafe documents retain a false result.
18
+ * @returns Completion or a policy hand-off; unsuccessful reads and effects reject to the target owner.
18
19
  * @remarks Operation intent is revalidated under related document locks. Policy skips, retained failures, and conservative conflict handling retain their original meanings.
19
20
  */
20
- export declare function processReplicatedDocument(ctx: FileHandlerContext, entry: MetaEntry): Promise<boolean>;
21
+ export declare function processReplicatedDocument(ctx: FileHandlerContext, entry: MetaEntry, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;