@vrtmrz/livesync-commonlib 0.5.0 → 0.6.1

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 (76) hide show
  1. package/dist/common/LSError.d.ts +13 -0
  2. package/dist/common/LSError.js +19 -1
  3. package/dist/diagnostics/local.d.ts +7 -2
  4. package/dist/interfaces/DatabaseFileAccess.d.ts +20 -4
  5. package/dist/interfaces/FileHandler.d.ts +67 -1
  6. package/dist/interfaces/FileHandler.js +16 -0
  7. package/dist/interfaces/StorageEventManager.d.ts +7 -0
  8. package/dist/managers/ChunkFetcher.d.ts +16 -0
  9. package/dist/managers/ChunkFetcher.js +190 -112
  10. package/dist/managers/EntryManager/EntryManager.d.ts +7 -0
  11. package/dist/managers/EntryManager/EntryManager.js +6 -0
  12. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +9 -5
  13. package/dist/managers/EntryManager/EntryManagerImpls.js +103 -76
  14. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.d.ts +7 -3
  15. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.js +83 -16
  16. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.d.ts +3 -2
  17. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.js +38 -36
  18. package/dist/managers/LayeredChunkManager/types.d.ts +15 -1
  19. package/dist/managers/LayeredChunkManager.d.ts +4 -0
  20. package/dist/managers/LayeredChunkManager.js +19 -6
  21. package/dist/managers/LiveSyncManagers.d.ts +2 -0
  22. package/dist/managers/LiveSyncManagers.js +6 -0
  23. package/dist/managers/StorageEventManager.d.ts +22 -0
  24. package/dist/managers/StorageEventManager.js +48 -1
  25. package/dist/pouchdb/LiveSyncLocalDB.d.ts +32 -0
  26. package/dist/pouchdb/LiveSyncLocalDB.js +72 -18
  27. package/dist/pouchdb/LocalDatabaseReadScope.d.ts +24 -0
  28. package/dist/pouchdb/LocalDatabaseReadScope.js +62 -0
  29. package/dist/pouchdb/encryption.policy.js +2 -1
  30. package/dist/pouchdb/pathIdentityCompatibility.d.ts +6 -2
  31. package/dist/pouchdb/pathIdentityCompatibility.js +15 -10
  32. package/dist/replication/UnsupportedEncryptedDocumentFormatError.d.ts +13 -0
  33. package/dist/replication/UnsupportedEncryptedDocumentFormatError.js +28 -0
  34. package/dist/replication/contentRead.d.ts +3 -0
  35. package/dist/replication/contentRead.js +4 -0
  36. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +11 -2
  37. package/dist/replication/couchdb/LiveSyncReplicator.js +207 -131
  38. package/dist/replication/index.d.ts +6 -1
  39. package/dist/replication/index.js +20 -1
  40. package/dist/serviceFeatures/offlineScanner/files.d.ts +1 -1
  41. package/dist/serviceFeatures/offlineScanner/files.js +27 -7
  42. package/dist/serviceFeatures/offlineScanner/scan.d.ts +5 -1
  43. package/dist/serviceFeatures/offlineScanner/scan.js +2 -1
  44. package/dist/serviceFeatures/offlineScanner.d.ts +1 -1
  45. package/dist/serviceFeatures/offlineScanner.js +10 -2
  46. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +13 -0
  47. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +190 -123
  48. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +17 -7
  49. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +3 -2
  50. package/dist/serviceModules/ServiceFileHandlerBase/events.js +9 -9
  51. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -9
  52. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +10 -0
  53. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +28 -4
  54. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +11 -5
  55. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +144 -58
  56. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +16 -2
  57. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +1 -0
  58. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +7 -2
  59. package/dist/serviceModules/ServiceFileHandlerBase.js +13 -4
  60. package/dist/services/base/ControlService.js +1 -5
  61. package/dist/services/base/DatabaseEventService.d.ts +3 -0
  62. package/dist/services/base/DatabaseEventService.js +3 -0
  63. package/dist/services/base/DatabaseService.d.ts +15 -0
  64. package/dist/services/base/DatabaseService.js +85 -4
  65. package/dist/services/base/IService.d.ts +18 -1
  66. package/dist/services/base/KeyValueDBService.d.ts +5 -4
  67. package/dist/services/base/KeyValueDBService.js +46 -48
  68. package/dist/services/base/ReplicationService.d.ts +4 -1
  69. package/dist/services/base/ReplicationService.js +8 -1
  70. package/dist/services/base/VaultScanResult.d.ts +5 -0
  71. package/dist/services/lib/HandlerUtils.d.ts +40 -5
  72. package/dist/services/lib/HandlerUtils.js +52 -4
  73. package/docs/development.md +8 -0
  74. package/docs/offline-scanner.md +57 -3
  75. package/docs/releasing.md +43 -0
  76. 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)) {
@@ -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>;
@@ -123,36 +123,36 @@ async function planRestoredRename(ctx, newPath, oldPath, isSameDocument) {
123
123
  if (isSameDocument) return await planSameDocumentRename(ctx, newPath, oldPath);
124
124
  return await planCrossDocumentRename(ctx, newPath, oldPath);
125
125
  }
126
- async function processReplicatedDocument(ctx, entry) {
126
+ async function processReplicatedDocument(ctx, entry, operation) {
127
127
  return await withFileEventPaths(ctx, [ctx.host.getPath(entry)], async () => {
128
128
  if (!await ctx.vault.isTargetFile(entry.path)) {
129
129
  ctx.host.log(`File ${entry.path} is not the target file`, LOG_LEVEL_VERBOSE);
130
- return false;
130
+ return { status: "policy" };
131
131
  }
132
132
  if (ctx.vault.isFileSizeTooLarge(entry.size)) {
133
133
  ctx.host.log(`File ${entry.path} is too large (on database) to be processed`, LOG_LEVEL_VERBOSE);
134
- return false;
134
+ return { status: "policy" };
135
135
  }
136
136
  if (shouldBeIgnored(entry.path)) {
137
137
  ctx.host.log(`File ${entry.path} should be ignored`, LOG_LEVEL_VERBOSE);
138
- return false;
138
+ return { status: "policy" };
139
139
  }
140
140
  const path = ctx.host.getPath(entry);
141
141
  const targetFile = await ctx.host.storage().getStub(ctx.host.getPathWithoutPrefix(entry));
142
142
  if (isFolderInfo(targetFile)) {
143
143
  ctx.host.log(`${path} is already exist as the folder`);
144
- return true;
144
+ return { status: "policy" };
145
145
  } else {
146
146
  if (targetFile && ctx.vault.isFileSizeTooLarge(targetFile.stat.size)) {
147
147
  ctx.host.log(`File ${targetFile.path} is too large (on storage) to be processed`, LOG_LEVEL_VERBOSE);
148
- return false;
148
+ return { status: "policy" };
149
149
  }
150
150
  ctx.host.log(
151
151
  `Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Started...`,
152
152
  LOG_LEVEL_VERBOSE
153
153
  );
154
154
  ctx.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
155
- const ret = await dbToStorageCore(ctx, entry, targetFile);
155
+ const ret = await dbToStorageCore(ctx, entry, targetFile, void 0, operation);
156
156
  ctx.host.log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Done`);
157
157
  return ret;
158
158
  }
@@ -163,7 +163,7 @@ async function planSameDocumentRename(ctx, newPath, oldPath) {
163
163
  if (!currentTarget || !await isCurrentFileSelected(ctx, currentTarget)) {
164
164
  return { kind: "none" };
165
165
  }
166
- const entry = await ctx.host.db().fetchEntryMeta(newPath, void 0, true);
166
+ const entry = await ctx.host.db().readEntryMeta(newPath, void 0, true);
167
167
  if (entry && !entry.deleted && !entry._deleted && ctx.host.storage().normalisePath(ctx.host.getPath(entry)) === ctx.host.storage().normalisePath(newPath)) {
168
168
  return { kind: "store", file: currentTarget };
169
169
  }
@@ -187,7 +187,7 @@ async function planCrossDocumentRename(ctx, newPath, oldPath) {
187
187
  if (!sourceWasInspected || currentSourceItem !== null || !await canApplyRestoredDeletion(ctx, oldPath)) {
188
188
  return { kind: "store", file: currentTarget, complete: sourceWasInspected };
189
189
  }
190
- const sourceEntry = await ctx.host.db().fetchEntryMeta(oldPath, void 0, true);
190
+ const sourceEntry = await ctx.host.db().readEntryMeta(oldPath, void 0, true);
191
191
  if (!sourceEntry || sourceEntry.deleted || sourceEntry._deleted) {
192
192
  return { kind: "store", file: currentTarget };
193
193
  }
@@ -1,3 +1,4 @@
1
+ import { ContentReadError } from "../../common/LSError.js";
1
2
  import {
2
3
  readProvenanceSnapshot,
3
4
  currentStorageSnapshotMatches,
@@ -19,14 +20,25 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
19
20
  if (!incomingEntry._rev) {
20
21
  return { preserved: false };
21
22
  }
22
- const classification = await classifyStorageContent(
23
- ctx,
24
- readFile,
25
- incomingEntry,
26
- void 0,
27
- observedProvenance,
28
- incomingContent ? { _rev: incomingEntry._rev, data: incomingContent } : void 0
29
- );
23
+ let classification;
24
+ let unavailableRead;
25
+ try {
26
+ classification = await classifyStorageContent(
27
+ ctx,
28
+ readFile,
29
+ incomingEntry,
30
+ void 0,
31
+ observedProvenance,
32
+ incomingContent ? { _rev: incomingEntry._rev, data: incomingContent } : void 0,
33
+ false
34
+ );
35
+ } catch (error) {
36
+ if (!(error instanceof ContentReadError)) {
37
+ throw error;
38
+ }
39
+ unavailableRead = error;
40
+ classification = { kind: "unknown" };
41
+ }
30
42
  if (!await currentStorageSnapshotMatches(ctx, readFile, observedProvenance)) {
31
43
  return { preserved: false };
32
44
  }
@@ -40,6 +52,9 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
40
52
  }
41
53
  const storedRevision = classification.kind === "edited" ? await ctx.host.db().storeWithBaseRevision(readFile, classification.revision, true) : await ctx.host.db().storeIndependentRevision(readFile, true);
42
54
  if (storedRevision === false) {
55
+ if (unavailableRead) {
56
+ throw unavailableRead;
57
+ }
43
58
  ctx.host.log(`Prevented overwriting unsynchronised local changes for ${path}`, LOG_LEVEL_NOTICE);
44
59
  return { preserved: true };
45
60
  }
@@ -55,7 +70,7 @@ async function recheckIncomingStorage(ctx, path, incomingEntry, incomingContent,
55
70
  if (!current || isFolderInfo(current)) return { preserved: false };
56
71
  const protection = await preserveUnsyncedStorageAsConflict(ctx, path, current, incomingEntry, incomingContent);
57
72
  if (protection.preserved || !protection.snapshot) return protection;
58
- if (!allowExistingConflicts && !ctx.setting.currentSettings().writeDocumentsIfConflicted && (await ctx.host.db().getConflictedRevs(path)).length > 0) {
73
+ if (!allowExistingConflicts && !ctx.setting.currentSettings().writeDocumentsIfConflicted && (await ctx.host.db().readConflictedRevs(path)).length > 0) {
59
74
  await queueConflictCheckFor(ctx, path, true);
60
75
  return { preserved: true };
61
76
  }
@@ -171,4 +171,14 @@ export type StorageContentClassification = RecordedStorageClassification | {
171
171
  } | {
172
172
  kind: "unknown";
173
173
  };
174
+ /**
175
+ * Confirm the exact displayed revision from current bytes and device-local evidence.
176
+ * @param ctx - Borrowed file-handler capabilities and provenance.
177
+ * @param path - Current Vault path of the retained reflection target.
178
+ * @param revision - Exact Metadata revision whose reflection is being checked.
179
+ * @returns True only when current bytes, provenance, and current Metadata agree.
180
+ * @remarks Uses existing document locking and snapshot validation. It fetches no
181
+ * Chunks and writes no records. Failed inspection rejects; missing evidence returns false.
182
+ */
183
+ export declare function inspectCurrentFileProvenance(ctx: FileHandlerContext, path: FilePathWithPrefix, revision: string): Promise<boolean>;
174
184
  export {};