@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 { withFileEventPaths } from "./locking.js";
1
2
  import { isFolderInfo } from "./storage.js";
2
3
  import { LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
3
4
  import { displayRev, isDocContentSame, readContent } from "../../common/utils.js";
@@ -14,7 +15,7 @@ async function getProvenance(ctx, path) {
14
15
  try {
15
16
  const record = await ctx.provenance.get(getProvenancePath(ctx, path));
16
17
  if (!record) return void 0;
17
- const entry = await ctx.host.db().fetchEntryMeta(path, record.revision, true);
18
+ const entry = await ctx.host.db().readEntryMeta(path, record.revision, true);
18
19
  if (entry && !entry._deleted && !entry.deleted) {
19
20
  return record;
20
21
  }
@@ -141,13 +142,13 @@ async function classifyRecordedStorageContent(ctx, file, path, recorded, recorde
141
142
  return { kind: "unchanged", revision: recordedRevision };
142
143
  }
143
144
  const loadedContentIsDecoded = currentLoaded?._rev === recordedRevision;
144
- const base = loadedContentIsDecoded ? currentLoaded : await ctx.host.db().fetchEntry(file, recordedRevision, true, true, !requireReadableContent);
145
+ const base = loadedContentIsDecoded ? currentLoaded : await ctx.host.db().readEntry(file, recordedRevision, true, true, !requireReadableContent);
145
146
  if (base && base._rev === recordedRevision && !("deleted" in base && base.deleted) && !("_deleted" in base && base._deleted)) {
146
147
  const baseContent = loadedContentIsDecoded ? base.data : readContent(base);
147
148
  return await isDocContentSame(baseContent, file.body) ? { kind: "unchanged", revision: recordedRevision } : { kind: "edited", revision: recordedRevision };
148
149
  }
149
150
  if (!base) {
150
- const meta = await ctx.host.db().fetchEntryMeta(file, recordedRevision, true);
151
+ const meta = await ctx.host.db().readEntryMeta(file, recordedRevision, true);
151
152
  if (requireReadableContent && meta && !meta.deleted && !meta._deleted) {
152
153
  throw new Error(
153
154
  `Could not read the recorded file revision ${displayRev(recordedRevision)} for ${file.path}`
@@ -158,12 +159,34 @@ async function classifyRecordedStorageContent(ctx, file, path, recorded, recorde
158
159
  return void 0;
159
160
  }
160
161
  async function classifyLiveStorageContent(ctx, file, currentEntry) {
161
- const matches = currentEntry ? await ctx.host.db().findLiveContentRevisions(file, file.body) : [];
162
+ const matches = currentEntry ? await ctx.host.db().readLiveContentRevisions(file, file.body) : [];
162
163
  if (matches.length) {
163
164
  return { kind: "matching-leaf", revision: matches.length === 1 ? matches[0] : void 0 };
164
165
  }
165
166
  return { kind: "unknown" };
166
167
  }
168
+ async function inspectCurrentFileProvenance(ctx, path, revision) {
169
+ if (!ctx.provenance || !revision) {
170
+ return false;
171
+ }
172
+ return await withFileEventPaths(ctx, [path], async () => {
173
+ const recorded = await readProvenanceSnapshot(ctx, path, true);
174
+ if (!hasContentHash(recorded) || recorded.revision !== revision) {
175
+ return false;
176
+ }
177
+ const stub = await ctx.host.storage().getStub(path);
178
+ if (!stub || isFolderInfo(stub)) {
179
+ return false;
180
+ }
181
+ const file = await ctx.host.readFileFromStub(stub);
182
+ const evidence = { contentHash: await computeFileContentHash(file.body), contentSize: file.body.size };
183
+ if (evidence.contentHash !== recorded.contentHash || evidence.contentSize !== recorded.contentSize) {
184
+ return false;
185
+ }
186
+ const current = await ctx.host.db().readEntryMeta(path, void 0, true);
187
+ return !!current && current._rev === revision && !current.deleted && !current._deleted && await currentStorageSnapshotMatches(ctx, file, recorded, true);
188
+ });
189
+ }
167
190
  export {
168
191
  classifyStorageContent,
169
192
  contentEvidence,
@@ -175,6 +198,7 @@ export {
175
198
  getProvenance,
176
199
  getProvenancePath,
177
200
  hasContentHash,
201
+ inspectCurrentFileProvenance,
178
202
  readProvenanceSnapshot,
179
203
  rememberMatchingLeaf,
180
204
  sameProvenance,
@@ -1,5 +1,9 @@
1
+ import { type FileReflectionResult, type ReflectionOperationContext } from "../../interfaces/FileHandler.js";
1
2
  import type { FilePath, FilePathWithPrefix, MetaEntry, UXFileInfo, UXFileInfoStub } from "../../common/types.js";
2
3
  import type { FileHandlerContext } from "./context.js";
4
+ /** An incomplete attempt without a failed I/O boundary; its owner retains the target. */
5
+ export declare class IncompleteFileReflectionError extends Error {
6
+ }
3
7
  /**
4
8
  * Reflect one selected live revision under the storage document lock.
5
9
  *
@@ -7,7 +11,7 @@ import type { FileHandlerContext } from "./context.js";
7
11
  * @param info - The supplied file observation or path.
8
12
  * @param rev - The exact selected database revision.
9
13
  * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
10
- * @returns The selected live leaf reflection result, or false if the selected revision is no longer live.
14
+ * @returns The selected live leaf reflection result, or false if the selected revision is no longer live or its content is unreadable.
11
15
  * @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
12
16
  */
13
17
  export declare function dbToStorageWithSpecificRev(ctx: FileHandlerContext, info: UXFileInfoStub | UXFileInfo | FilePath | FilePathWithPrefix | null, rev: string, force?: boolean): Promise<boolean>;
@@ -22,6 +26,8 @@ export declare function dbToStorageWithSpecificRev(ctx: FileHandlerContext, info
22
26
  * @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
23
27
  */
24
28
  export declare function dbToStorage(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean): Promise<boolean>;
29
+ /** Run one reflection using the target owner's immutable operation premises. */
30
+ export declare function reflectDatabaseEntry(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
25
31
  /**
26
32
  * Fetch current metadata and apply its storage reflection without reacquiring the lock.
27
33
  *
@@ -29,10 +35,10 @@ export declare function dbToStorage(ctx: FileHandlerContext, entryInfo: MetaEntr
29
35
  * @param entryInfo - Current metadata or a path from which metadata is loaded.
30
36
  * @param info - The supplied file observation or path.
31
37
  * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
32
- * @returns True after reflection or a safe conflict/absence skip; false on unreadable or unsafe observations.
38
+ * @returns The ordinary completion, policy hand-off, or owner cancellation outcome; failed reads reject.
33
39
  * @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
34
40
  */
35
- export declare function dbToStorageCore(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean): Promise<boolean>;
41
+ export declare function dbToStorageCore(ctx: FileHandlerContext, entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
36
42
  /**
37
43
  * Reflect database content while protecting current storage and its provenance.
38
44
  *
@@ -42,7 +48,7 @@ export declare function dbToStorageCore(ctx: FileHandlerContext, entryInfo: Meta
42
48
  * @param force - Whether the existing force policy bypasses ordinary unchanged-content checks.
43
49
  * @param allowExistingConflicts - Whether the caller explicitly selected an existing live conflict leaf.
44
50
  * @param incomingRetry - The number of database-advancement rereads already consumed.
45
- * @returns True after reflection or a policy skip; false when content, path, or current-state validation refuses the effect.
51
+ * @returns The completed or policy outcome; incomplete content or unsafe observations reject.
46
52
  * @remarks Core operations run under the caller's document lock. Storage protection and database advancement are revalidated at their established await boundaries.
47
53
  */
48
- export declare function applyDatabaseEntryToStorage(ctx: FileHandlerContext, docEntry: MetaEntry, file: UXFileInfoStub | UXFileInfo | null, force?: boolean, allowExistingConflicts?: boolean, incomingRetry?: number): Promise<boolean>;
54
+ export declare function applyDatabaseEntryToStorage(ctx: FileHandlerContext, docEntry: MetaEntry, file: UXFileInfoStub | UXFileInfo | null, force?: boolean, allowExistingConflicts?: boolean, incomingRetry?: number, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
@@ -1,3 +1,10 @@
1
+ import { ContentReadError } from "../../common/LSError.js";
2
+ import {
3
+ FILE_REFLECTION_COMPLETED,
4
+ FILE_REFLECTION_POLICY,
5
+ FILE_REFLECTION_CANCELLED,
6
+ isReflectionCancelled
7
+ } from "../../interfaces/FileHandler.js";
1
8
  import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
2
9
  import { infoToStub, isFolderInfo, getParentPath } from "./storage.js";
3
10
  import {
@@ -15,24 +22,35 @@ import { getStoragePathFromUXFileInfo } from "../../common/typeUtils.js";
15
22
  import { EVEN } from "../../common/models/shared.const.symbols.js";
16
23
  import { tryGetFilePath } from "../../common/utils.doc.js";
17
24
  import { getPathNormalizationVersion, normalisePathForIdentity } from "../../common/pathNormalization.js";
25
+ class IncompleteFileReflectionError extends Error {
26
+ }
18
27
  async function dbToStorageWithSpecificRev(ctx, info, rev, force) {
19
28
  if (info == null) {
20
29
  ctx.host.log(`Cannot select database revision ${rev} without a file path`, LOG_LEVEL_VERBOSE);
21
30
  return false;
22
31
  }
23
- return await withFileEventPaths(
24
- ctx,
25
- [getStoragePathFromUXFileInfo(info)],
26
- () => dbToStorageWithSpecificRevCore(ctx, info, rev, force)
27
- );
32
+ let operationReturned = false;
33
+ try {
34
+ return await withFileEventPaths(ctx, [getStoragePathFromUXFileInfo(info)], async () => {
35
+ const result = await dbToStorageWithSpecificRevCore(ctx, info, rev, force);
36
+ operationReturned = true;
37
+ return result;
38
+ });
39
+ } catch (error) {
40
+ if (!operationReturned && (error instanceof ContentReadError || error instanceof IncompleteFileReflectionError)) {
41
+ ctx.host.log(error, LOG_LEVEL_VERBOSE);
42
+ return false;
43
+ }
44
+ throw error;
45
+ }
28
46
  }
29
47
  async function dbToStorageWithSpecificRevCore(ctx, info, rev, force) {
30
48
  const file = await infoToStub(ctx, info);
31
49
  const databaseTarget = file ?? info;
32
50
  const [docEntry, currentEntry, conflictedRevisions] = await Promise.all([
33
- ctx.host.db().fetchEntryMeta(databaseTarget, rev, true),
34
- ctx.host.db().fetchEntryMeta(databaseTarget, void 0, true),
35
- ctx.host.db().getConflictedRevs(databaseTarget)
51
+ ctx.host.db().readEntryMeta(databaseTarget, rev, true),
52
+ ctx.host.db().readEntryMeta(databaseTarget, void 0, true),
53
+ ctx.host.db().readConflictedRevs(databaseTarget)
36
54
  ]);
37
55
  if (!docEntry) {
38
56
  ctx.host.log(`File ${tryGetFilePath(info)} is not exist on the database`, LOG_LEVEL_VERBOSE);
@@ -49,46 +67,67 @@ async function dbToStorageWithSpecificRevCore(ctx, info, rev, force) {
49
67
  );
50
68
  return false;
51
69
  }
52
- return await applyDatabaseEntryToStorage(ctx, docEntry, file, force, true);
70
+ return !isReflectionCancelled(await applyDatabaseEntryToStorage(ctx, docEntry, file, force, true));
53
71
  }
54
72
  async function dbToStorage(ctx, entryInfo, info, force) {
55
- const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
56
- return await withFileEventPaths(ctx, [pathFromEntryInfo], () => dbToStorageCore(ctx, entryInfo, info, force));
73
+ const path = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
74
+ let operationReturned = false;
75
+ try {
76
+ const result = await withFileEventPaths(ctx, [path], async () => {
77
+ const outcome = await dbToStorageCore(ctx, entryInfo, info, force);
78
+ operationReturned = true;
79
+ return outcome;
80
+ });
81
+ return !isReflectionCancelled(result);
82
+ } catch (error) {
83
+ if (!operationReturned && (error instanceof ContentReadError || error instanceof IncompleteFileReflectionError)) {
84
+ ctx.host.log(error, LOG_LEVEL_VERBOSE);
85
+ return false;
86
+ }
87
+ throw error;
88
+ }
57
89
  }
58
- async function dbToStorageCore(ctx, entryInfo, info, force) {
90
+ async function reflectDatabaseEntry(ctx, entryInfo, info, force, operation) {
91
+ const path = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
92
+ return await withFileEventPaths(ctx, [path], () => dbToStorageCore(ctx, entryInfo, info, force, operation));
93
+ }
94
+ async function dbToStorageCore(ctx, entryInfo, info, force, operation) {
95
+ if (operation?.checkpoint?.() === false) {
96
+ return FILE_REFLECTION_CANCELLED;
97
+ }
59
98
  const file = await infoToStub(ctx, info);
60
99
  const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
61
- const docEntry = await ctx.host.db().fetchEntryMeta(pathFromEntryInfo, void 0, true);
100
+ const docEntry = await ctx.host.db().readEntryMeta(pathFromEntryInfo, void 0, true);
62
101
  if (!docEntry) {
63
102
  ctx.host.log(`File ${pathFromEntryInfo} is not exist on the database`, LOG_LEVEL_VERBOSE);
64
- return false;
103
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
65
104
  }
66
- return await applyDatabaseEntryToStorage(ctx, docEntry, file, force);
105
+ return await applyDatabaseEntryToStorage(ctx, docEntry, file, force, false, 0, operation);
67
106
  }
68
- async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0) {
107
+ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0, operation) {
69
108
  const mode = file == null ? "create" : "modify";
70
109
  const path = ctx.host.getPath(docEntry);
71
110
  const settings = ctx.setting.currentSettings();
72
- const revs = await ctx.host.db().getConflictedRevs(path);
111
+ const revs = await ctx.host.db().readConflictedRevs(path);
73
112
  if (revs.length > 0 && !allowExistingConflicts) {
74
113
  if (settings.writeDocumentsIfConflicted) {
75
114
  } else {
76
115
  await queueConflictCheckFor(ctx, path, true);
77
- return true;
116
+ return FILE_REFLECTION_POLICY;
78
117
  }
79
118
  }
80
119
  let existDoc = await ctx.host.storage().getStub(path);
81
120
  if (isFolderInfo(existDoc)) {
82
121
  ctx.host.log(`Folder ${path} is already exist on the storage as a folder`, LOG_LEVEL_VERBOSE);
83
- return true;
122
+ return FILE_REFLECTION_POLICY;
84
123
  }
85
124
  const existOnDB = !(docEntry._deleted || docEntry.deleted || false);
86
125
  if (!existOnDB && !existDoc) {
87
126
  ctx.host.log(`File ${path} seems to be deleted, but already not on storage`, LOG_LEVEL_VERBOSE);
88
127
  await deleteProvenance(ctx, path);
89
- return true;
128
+ return FILE_REFLECTION_COMPLETED;
90
129
  }
91
- if (!existOnDB && existDoc)
130
+ if (!existOnDB && existDoc) {
92
131
  return await applyIncomingDeletion(
93
132
  ctx,
94
133
  docEntry,
@@ -97,17 +136,21 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
97
136
  settings,
98
137
  force,
99
138
  allowExistingConflicts,
100
- incomingRetry
139
+ incomingRetry,
140
+ operation
101
141
  );
142
+ }
102
143
  if (existDoc && existDoc.path !== path) {
103
144
  const current = await reconcileStoragePath(ctx, existDoc, path, settings);
104
- if (current === false) return false;
145
+ if (current === false) {
146
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
147
+ }
105
148
  existDoc = current;
106
149
  }
107
- const docRead = await ctx.host.db().fetchEntryFromMeta(docEntry);
150
+ const docRead = await ctx.host.db().readEntryFromMeta(docEntry);
108
151
  if (!docRead) {
109
152
  ctx.host.log(`File ${path} is not exist on the database`, LOG_LEVEL_VERBOSE);
110
- return false;
153
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
111
154
  }
112
155
  const docData = readContent(docRead);
113
156
  const reflectedContent = createBlob(docData);
@@ -117,7 +160,7 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
117
160
  `File ${path} seems to be corrupted! Writing prevented. (${docRead.size} != ${reflectedContent.size})`,
118
161
  LOG_LEVEL_NOTICE
119
162
  );
120
- return false;
163
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
121
164
  }
122
165
  }
123
166
  const reflectedEvidence = await contentEvidence(ctx, reflectedContent);
@@ -133,35 +176,52 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
133
176
  mode,
134
177
  force,
135
178
  allowExistingConflicts,
136
- incomingRetry
179
+ incomingRetry,
180
+ operation
137
181
  };
138
182
  const preparation = await prepareIncomingStorageWrite(ctx, write);
139
183
  if (preparation.kind === "complete") return preparation.result;
140
184
  return await commitIncomingStorageWrite(ctx, write, preparation.snapshot);
141
185
  }
142
- async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force, allowExistingConflicts, incomingRetry) {
186
+ async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force, allowExistingConflicts, incomingRetry, operation) {
143
187
  if (force || allowExistingConflicts) return void 0;
144
- const current = await ctx.host.db().fetchEntryMeta(path, void 0, true);
145
- if (!current) return false;
188
+ const current = await ctx.host.db().readEntryMeta(path, void 0, true);
189
+ if (!current) {
190
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
191
+ }
146
192
  if (current._rev === incomingEntry._rev) return void 0;
147
193
  if (incomingRetry >= 2) {
148
194
  ctx.host.log(`Database kept changing while reflecting ${path}`, LOG_LEVEL_NOTICE);
149
- return false;
195
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
150
196
  }
151
197
  const storage = await ctx.host.storage().getStub(path);
152
- if (isFolderInfo(storage)) return false;
153
- return await applyDatabaseEntryToStorage(ctx, current, storage, force, allowExistingConflicts, incomingRetry + 1);
198
+ if (isFolderInfo(storage)) {
199
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
200
+ }
201
+ return await applyDatabaseEntryToStorage(
202
+ ctx,
203
+ current,
204
+ storage,
205
+ force,
206
+ allowExistingConflicts,
207
+ incomingRetry + 1,
208
+ operation
209
+ );
154
210
  }
155
- async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, force, allowExistingConflicts, incomingRetry) {
211
+ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, force, allowExistingConflicts, incomingRetry, operation) {
156
212
  let safeDeletionSnapshot;
157
213
  if (!force && !settings.writeDocumentsIfConflicted) {
158
- let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry);
159
- if (protection.preserved) return true;
214
+ let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry, void 0);
215
+ if (protection.preserved) {
216
+ return FILE_REFLECTION_POLICY;
217
+ }
160
218
  if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
161
219
  protection = await recheckIncomingStorage(ctx, path, docEntry, void 0, allowExistingConflicts);
162
- if (protection.preserved) return true;
220
+ if (protection.preserved) {
221
+ return FILE_REFLECTION_POLICY;
222
+ }
163
223
  if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
164
- return false;
224
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
165
225
  }
166
226
  }
167
227
  safeDeletionSnapshot = protection.snapshot;
@@ -172,14 +232,17 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
172
232
  path,
173
233
  force,
174
234
  allowExistingConflicts,
175
- incomingRetry
235
+ incomingRetry,
236
+ operation
176
237
  );
177
238
  if (latest !== void 0) return latest;
178
239
  if (safeDeletionSnapshot && !await currentStorageSnapshotMatches(ctx, safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
179
240
  const protection = await recheckIncomingStorage(ctx, path, docEntry, void 0, allowExistingConflicts);
180
- if (protection.preserved) return true;
241
+ if (protection.preserved) {
242
+ return FILE_REFLECTION_POLICY;
243
+ }
181
244
  if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
182
- return false;
245
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
183
246
  }
184
247
  safeDeletionSnapshot = protection.snapshot;
185
248
  latest = await reconcileAdvancedIncomingRevision(
@@ -188,16 +251,20 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
188
251
  path,
189
252
  force,
190
253
  allowExistingConflicts,
191
- incomingRetry
254
+ incomingRetry,
255
+ operation
192
256
  );
193
257
  if (latest !== void 0) return latest;
194
258
  if (!await currentStorageSnapshotMatches(ctx, safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
195
- return false;
259
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
196
260
  }
197
261
  }
262
+ if (operation?.checkpoint?.() === false) {
263
+ return FILE_REFLECTION_CANCELLED;
264
+ }
198
265
  await ctx.host.storage().deleteVaultItem(path);
199
266
  await deleteProvenance(ctx, path);
200
- return true;
267
+ return FILE_REFLECTION_COMPLETED;
201
268
  }
202
269
  async function reconcileStoragePath(ctx, existDoc, path, settings) {
203
270
  const [existingDocumentId, targetDocumentId] = await Promise.all([
@@ -236,8 +303,9 @@ async function reconcileStoragePath(ctx, existDoc, path, settings) {
236
303
  }
237
304
  async function prepareIncomingStorageWrite(ctx, write) {
238
305
  const { existDoc, force, allowExistingConflicts, docRead } = write;
239
- if (allowExistingConflicts && existDoc && !force && await acceptMatchingSelectedContent(ctx, write, existDoc))
240
- return { kind: "complete", result: true };
306
+ if (allowExistingConflicts && existDoc && !force && await acceptMatchingSelectedContent(ctx, write, existDoc)) {
307
+ return { kind: "complete", result: FILE_REFLECTION_COMPLETED };
308
+ }
241
309
  if (existDoc && !force) return await prepareExistingStorageWrite(ctx, write, existDoc);
242
310
  ctx.host.log(`File ${docRead.path} ${existDoc ? "(new) " : ""} ${force ? " (forced)" : ""}`, LOG_LEVEL_VERBOSE);
243
311
  return { kind: "write", snapshot: void 0 };
@@ -253,14 +321,17 @@ async function commitIncomingStorageWrite(ctx, write, safeSnapshot) {
253
321
  mode,
254
322
  force,
255
323
  allowExistingConflicts,
256
- incomingRetry
324
+ incomingRetry,
325
+ operation
257
326
  } = write;
258
327
  await ctx.host.storage().ensureDir(path);
259
328
  if (safeSnapshot && !await currentStorageSnapshotMatches(ctx, safeSnapshot.file, safeSnapshot.revision)) {
260
329
  const protection = await recheckIncomingStorage(ctx, path, docEntry, docData, allowExistingConflicts);
261
- if (protection.preserved) return true;
330
+ if (protection.preserved) {
331
+ return FILE_REFLECTION_POLICY;
332
+ }
262
333
  if (!protection.snapshot || !await currentStorageSnapshotMatches(ctx, protection.snapshot.file, protection.snapshot.revision)) {
263
- return false;
334
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
264
335
  }
265
336
  safeSnapshot = protection.snapshot;
266
337
  }
@@ -270,11 +341,15 @@ async function commitIncomingStorageWrite(ctx, write, safeSnapshot) {
270
341
  path,
271
342
  force,
272
343
  allowExistingConflicts,
273
- incomingRetry
344
+ incomingRetry,
345
+ operation
274
346
  );
275
347
  if (latest !== void 0) return latest;
276
348
  if (safeSnapshot && !await currentStorageSnapshotMatches(ctx, safeSnapshot.file, safeSnapshot.revision)) {
277
- return false;
349
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
350
+ }
351
+ if (operation?.checkpoint?.() === false) {
352
+ return FILE_REFLECTION_CANCELLED;
278
353
  }
279
354
  const ret = await ctx.host.storage().writeFileAuto(path, docData, { ctime: docRead.ctime, mtime: docRead.mtime });
280
355
  await ctx.host.storage().touched(path);
@@ -282,11 +357,14 @@ async function commitIncomingStorageWrite(ctx, write, safeSnapshot) {
282
357
  if (ret && ctx.provenance) {
283
358
  const storedStat = await ctx.host.storage().stat(path);
284
359
  if (safeSnapshot && !sameProvenance(await readProvenanceSnapshot(ctx, path), safeSnapshot.revision)) {
285
- return ret;
360
+ return FILE_REFLECTION_COMPLETED;
286
361
  }
287
362
  await setProvenance(ctx, path, docEntry._rev, storedStat?.mtime, reflectedContent, reflectedEvidence);
288
363
  }
289
- return ret;
364
+ if (!ret) {
365
+ throw new IncompleteFileReflectionError("Storage rejected the reflected write");
366
+ }
367
+ return FILE_REFLECTION_COMPLETED;
290
368
  }
291
369
  async function acceptMatchingSelectedContent(ctx, write, current) {
292
370
  const { docEntry, docRead, docData, reflectedContent, reflectedEvidence, path } = write;
@@ -319,7 +397,7 @@ async function prepareExistingStorageWrite(ctx, write, current) {
319
397
  if (!shouldApplied) {
320
398
  await setProvenance(ctx, path, docEntry._rev, existDoc.stat.mtime, reflectedContent, reflectedEvidence);
321
399
  ctx.host.log(`File ${docRead.path} is not changed`, LOG_LEVEL_VERBOSE);
322
- return { kind: "complete", result: true };
400
+ return { kind: "complete", result: FILE_REFLECTION_COMPLETED };
323
401
  }
324
402
  return await prepareIncomingStorageProtection(ctx, write, current);
325
403
  }
@@ -328,17 +406,25 @@ async function prepareIncomingStorageProtection(ctx, write, current) {
328
406
  const existDoc = current;
329
407
  if (force || settings.writeDocumentsIfConflicted) return { kind: "write", snapshot: void 0 };
330
408
  let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry, docData);
331
- if (protection.preserved) return { kind: "complete", result: true };
409
+ if (protection.preserved) {
410
+ return { kind: "complete", result: FILE_REFLECTION_POLICY };
411
+ }
332
412
  if (!protection.snapshot) {
333
413
  protection = await recheckIncomingStorage(ctx, path, docEntry, docData, allowExistingConflicts);
334
- if (protection.preserved) return { kind: "complete", result: true };
335
- if (!protection.snapshot) return { kind: "complete", result: false };
414
+ if (protection.preserved) {
415
+ return { kind: "complete", result: FILE_REFLECTION_POLICY };
416
+ }
417
+ if (!protection.snapshot) {
418
+ throw new IncompleteFileReflectionError("Storage changed during overwrite protection");
419
+ }
336
420
  }
337
421
  return { kind: "write", snapshot: protection.snapshot };
338
422
  }
339
423
  export {
424
+ IncompleteFileReflectionError,
340
425
  applyDatabaseEntryToStorage,
341
426
  dbToStorage,
342
427
  dbToStorageCore,
343
- dbToStorageWithSpecificRev
428
+ dbToStorageWithSpecificRev,
429
+ reflectDatabaseEntry
344
430
  };
@@ -1,3 +1,5 @@
1
+ import { isReflectionCancelled } from "../../interfaces/FileHandler.js";
2
+ import { ContentReadError } from "../../common/LSError.js";
1
3
  import { isFolderInfo, infoToStub } from "./storage.js";
2
4
  import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
3
5
  import {
@@ -146,8 +148,20 @@ async function saveClassifiedStorage(ctx, save, preferredBasePath, retryIfStorag
146
148
  );
147
149
  return false;
148
150
  }
149
- const details = await observeClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges);
150
151
  const recovery = { preferredBasePath, retryIfStorageChanges, snapshotRetry };
152
+ let details;
153
+ try {
154
+ details = await observeClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges);
155
+ } catch (error) {
156
+ if (retryIfStorageChanges || !(error instanceof ContentReadError)) {
157
+ throw error;
158
+ }
159
+ const preserved = await storeClassifiedStorageEdit(ctx, save, { kind: "unknown" }, recovery);
160
+ if (!preserved) {
161
+ throw error;
162
+ }
163
+ return true;
164
+ }
151
165
  const classification = details.classification;
152
166
  if (classification.kind === "unchanged")
153
167
  return await finishUnchangedStorageSave(ctx, save, classification.revision, details, recovery);
@@ -265,7 +279,7 @@ async function finishUnchangedStorageSave(ctx, save, revision, details, recovery
265
279
  await queueConflictCheckFor(ctx, file.path);
266
280
  } else if (!currentEntry || currentEntry.deleted || currentEntry._deleted || revision !== currentEntry._rev) {
267
281
  if (!currentEntry) return false;
268
- return await dbToStorageCore(ctx, file.path, file);
282
+ return !isReflectionCancelled(await dbToStorageCore(ctx, file.path, file));
269
283
  } else {
270
284
  if (upgradeCurrentRecord && snapshotMatches) {
271
285
  await setProvenance(ctx, file.path, revision, readFile.stat.mtime, readFile.body, evidence);
@@ -2,6 +2,7 @@ import { withFileEventPaths } from "./locking.js";
2
2
  import {
3
3
  getProvenancePath,
4
4
  sameProvenance,
5
+ readProvenanceSnapshot,
5
6
  contentEvidence,
6
7
  currentStorageSnapshotMatches,
7
8
  hasContentHash
@@ -1,3 +1,4 @@
1
+ import type { FileReflectionResult, ReflectionOperationContext } from "../interfaces/FileHandler.js";
1
2
  import type { AnyEntry, FilePath, FilePathWithPrefix, MetaEntry, UXFileInfo, UXFileInfoStub, UXInternalFileInfoStub } from "../common/types.js";
2
3
  import type { DeletionRecoveryResult, IFileHandler, StoreFileOptions } from "../interfaces/FileHandler.js";
3
4
  import type { DatabaseFileAccess } from "../interfaces/DatabaseFileAccess.js";
@@ -60,6 +61,8 @@ export declare abstract class ServiceFileHandlerBase extends ServiceModuleBase<S
60
61
  * @returns Whether the scan may skip this unchanged metadata observation.
61
62
  * @remarks Acquire the document lock while checking a metadata-only hint. No revision or file content is written; inspection failures are logged and return false.
62
63
  */
64
+ /** Confirm current bytes against existing provenance without retrieving Chunks. */
65
+ inspectCurrentFileProvenance(path: FilePathWithPrefix, revision: string): Promise<boolean>;
63
66
  canSkipUnchangedFile(info: UXFileInfoStub, expected: MetaEntry): Promise<boolean>;
64
67
  /**
65
68
  * Check the host's explicit deletion-recovery capability without store access.
@@ -161,10 +164,12 @@ export declare abstract class ServiceFileHandlerBase extends ServiceModuleBase<S
161
164
  /**
162
165
  * Select and reflect a replicated document while retaining host override dispatch.
163
166
  * @param entry - The database metadata being processed.
164
- * @returns Whether replication reflection completed; excluded or unsafe documents retain a false result.
167
+ * @returns Completion or a policy hand-off; unsuccessful reads and effects reject to the target owner.
165
168
  * @remarks Acquire the related document lock before selection and reflection. Constructor registration captures the current subclass override with bind; internal public seams remain live at use time.
166
169
  */
167
- _anyProcessReplicatedDoc(entry: MetaEntry): Promise<boolean>;
170
+ _anyProcessReplicatedDoc(entry: MetaEntry, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
171
+ /** Reflect an owner's selected target without converting terminal failures to false. */
172
+ reflectDatabaseEntry(entry: MetaEntry, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean, operation?: ReflectionOperationContext): Promise<FileReflectionResult>;
168
173
  /**
169
174
  * Repair missing chunks with at most ten acquired file operations at a time.
170
175
  * @param showingNotice - Whether progress uses notice-level messages instead of informational messages.
@@ -1,4 +1,5 @@
1
1
  import { createFileHandlerContext } from "./ServiceFileHandlerBase/context.js";
2
+ import { inspectCurrentFileProvenance } from "./ServiceFileHandlerBase/provenance.js";
2
3
  import { processFileEvent, processReplicatedDocument } from "./ServiceFileHandlerBase/events.js";
3
4
  import { getFileEntryPath, getFileStoragePath, readStorageFile } from "./ServiceFileHandlerBase/storage.js";
4
5
  import { canSkipUnchangedFile, tryRecordUntrackedFileRevision } from "./ServiceFileHandlerBase/scanning.js";
@@ -9,7 +10,7 @@ import {
9
10
  resolveConflictedByDeletingRevision
10
11
  } from "./ServiceFileHandlerBase/deletion.js";
11
12
  import { renameFileInDB } from "./ServiceFileHandlerBase/renaming.js";
12
- import { dbToStorageWithSpecificRev, dbToStorage } from "./ServiceFileHandlerBase/reflection.js";
13
+ import { dbToStorageWithSpecificRev, dbToStorage, reflectDatabaseEntry } from "./ServiceFileHandlerBase/reflection.js";
13
14
  import { recoverDatabaseDeletion } from "./ServiceFileHandlerBase/deletionRecovery.js";
14
15
  import { createAllChunks } from "./ServiceFileHandlerBase/chunks.js";
15
16
  import { ServiceModuleBase } from "./ServiceModuleBase.js";
@@ -133,6 +134,10 @@ class ServiceFileHandlerBase extends ServiceModuleBase {
133
134
  * @returns Whether the scan may skip this unchanged metadata observation.
134
135
  * @remarks Acquire the document lock while checking a metadata-only hint. No revision or file content is written; inspection failures are logged and return false.
135
136
  */
137
+ /** Confirm current bytes against existing provenance without retrieving Chunks. */
138
+ async inspectCurrentFileProvenance(path, revision) {
139
+ return await inspectCurrentFileProvenance(this.context, path, revision);
140
+ }
136
141
  async canSkipUnchangedFile(info, expected) {
137
142
  return await canSkipUnchangedFile(this.context, info, expected);
138
143
  }
@@ -261,11 +266,15 @@ class ServiceFileHandlerBase extends ServiceModuleBase {
261
266
  /**
262
267
  * Select and reflect a replicated document while retaining host override dispatch.
263
268
  * @param entry - The database metadata being processed.
264
- * @returns Whether replication reflection completed; excluded or unsafe documents retain a false result.
269
+ * @returns Completion or a policy hand-off; unsuccessful reads and effects reject to the target owner.
265
270
  * @remarks Acquire the related document lock before selection and reflection. Constructor registration captures the current subclass override with bind; internal public seams remain live at use time.
266
271
  */
267
- async _anyProcessReplicatedDoc(entry) {
268
- return await processReplicatedDocument(this.context, entry);
272
+ async _anyProcessReplicatedDoc(entry, operation) {
273
+ return await processReplicatedDocument(this.context, entry, operation);
274
+ }
275
+ /** Reflect an owner's selected target without converting terminal failures to false. */
276
+ async reflectDatabaseEntry(entry, info, force, operation) {
277
+ return await reflectDatabaseEntry(this.context, entry, info, force, operation);
269
278
  }
270
279
  /**
271
280
  * Repair missing chunks with at most ten acquired file operations at a time.
@@ -59,11 +59,7 @@ class ControlService extends ServiceBase {
59
59
  stopAllRunningProcessors();
60
60
  await this.services.appLifecycleService.onUnload();
61
61
  this._unloaded = true;
62
- const localDatabase = this.services.databaseService.localDatabaseDirect;
63
- if (localDatabase != null) {
64
- localDatabase.onunload();
65
- await localDatabase.close();
66
- }
62
+ await this.services.databaseService.closeDatabase();
67
63
  this.context.events.emitEvent(EVENT_PLATFORM_UNLOADED);
68
64
  this.context.events.offAll();
69
65
  this._log(this.context.translate("moduleLiveSyncMain.logUnloadingPlugin"));