@vrtmrz/livesync-commonlib 0.4.0 → 0.4.2

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 (79) hide show
  1. package/README.md +14 -2
  2. package/dist/common/models/fileaccess.definition.d.ts +35 -0
  3. package/dist/common/models/fileaccess.definition.js +11 -0
  4. package/dist/common/typeUtils.d.ts +27 -4
  5. package/dist/interfaces/FileHandler.d.ts +60 -1
  6. package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
  7. package/dist/interfaces/FileReflectionProvenance.js +11 -1
  8. package/dist/managers/StorageEventManager/admission.d.ts +50 -0
  9. package/dist/managers/StorageEventManager/admission.js +129 -0
  10. package/dist/managers/StorageEventManager/batching.d.ts +93 -0
  11. package/dist/managers/StorageEventManager/batching.js +97 -0
  12. package/dist/managers/StorageEventManager/operations.d.ts +142 -0
  13. package/dist/managers/StorageEventManager/operations.js +69 -0
  14. package/dist/managers/StorageEventManager/processing.d.ts +63 -0
  15. package/dist/managers/StorageEventManager/processing.js +94 -0
  16. package/dist/managers/StorageEventManager/queue.d.ts +73 -0
  17. package/dist/managers/StorageEventManager/queue.js +113 -0
  18. package/dist/managers/StorageEventManager/retry.d.ts +33 -0
  19. package/dist/managers/StorageEventManager/retry.js +31 -0
  20. package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
  21. package/dist/managers/StorageEventManager/snapshot.js +53 -0
  22. package/dist/managers/StorageEventManager/state.d.ts +155 -0
  23. package/dist/managers/StorageEventManager/state.js +105 -0
  24. package/dist/managers/StorageEventManager/watching.d.ts +93 -0
  25. package/dist/managers/StorageEventManager/watching.js +36 -0
  26. package/dist/managers/StorageEventManager.d.ts +303 -83
  27. package/dist/managers/StorageEventManager.js +457 -547
  28. package/dist/serviceFeatures/offlineScanner/fileStatus.d.ts +61 -0
  29. package/dist/serviceFeatures/offlineScanner/fileStatus.js +85 -0
  30. package/dist/serviceFeatures/offlineScanner/files.d.ts +47 -0
  31. package/dist/serviceFeatures/offlineScanner/files.js +218 -0
  32. package/dist/serviceFeatures/offlineScanner/metadata.d.ts +56 -0
  33. package/dist/serviceFeatures/offlineScanner/metadata.js +320 -0
  34. package/dist/serviceFeatures/offlineScanner/paths.d.ts +20 -0
  35. package/dist/serviceFeatures/offlineScanner/paths.js +16 -0
  36. package/dist/serviceFeatures/offlineScanner/scan.d.ts +35 -0
  37. package/dist/serviceFeatures/offlineScanner/scan.js +358 -0
  38. package/dist/serviceFeatures/offlineScanner/types.d.ts +134 -0
  39. package/dist/serviceFeatures/offlineScanner/types.js +66 -0
  40. package/dist/serviceFeatures/offlineScanner.d.ts +25 -251
  41. package/dist/serviceFeatures/offlineScanner.js +36 -860
  42. package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
  43. package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
  44. package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
  45. package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
  46. package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
  47. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.d.ts +13 -0
  49. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
  51. package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
  52. package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
  53. package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
  54. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
  55. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
  56. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
  57. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
  58. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
  59. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
  60. package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
  61. package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
  62. package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
  63. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
  64. package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
  65. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
  66. package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
  67. package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
  68. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
  69. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
  70. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +141 -183
  71. package/dist/serviceModules/ServiceFileHandlerBase.js +206 -1397
  72. package/dist/services/base/KeyValueDBService.d.ts +9 -0
  73. package/dist/services/base/KeyValueDBService.js +11 -1
  74. package/docs/conflict-resolution.md +3 -1
  75. package/docs/development.md +40 -0
  76. package/docs/offline-scanner.md +26 -1
  77. package/docs/p2p-transport-lifecycle.md +8 -1
  78. package/docs/storage-events-and-reflection.md +212 -22
  79. package/package.json +1 -1
@@ -0,0 +1,10 @@
1
+ import type { FileHandlerContext } from "./context.js";
2
+ /**
3
+ * Repair missing chunks with at most ten acquired file operations at a time.
4
+ *
5
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
6
+ * @param showingNotice - Whether progress uses notice-level messages instead of informational messages.
7
+ * @returns Completion after all selected tasks settle. Per-file save errors are logged and swallowed; listing, selection, acquisition, progress, or logger failures can still reject.
8
+ * @remarks Each file uses the dynamic public save seam and its document lock. Up to ten permits are acquired; progress remains before the original guarded body, preserving its existing cleanup semantics.
9
+ */
10
+ export declare function createAllChunks(ctx: FileHandlerContext, showingNotice?: boolean): Promise<void>;
@@ -0,0 +1,51 @@
1
+ import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
2
+ import { shouldBeIgnored } from "../../string_and_binary/path.js";
3
+ import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
4
+ async function createAllChunks(ctx, showingNotice) {
5
+ ctx.host.log("Collecting local files on the storage", LOG_LEVEL_VERBOSE);
6
+ const semaphore = Semaphore(10);
7
+ let processed = 0;
8
+ const filesStorageSrc = await ctx.host.storage().getFiles();
9
+ const incProcessed = () => {
10
+ processed++;
11
+ if (processed % 25 == 0)
12
+ ctx.host.log(
13
+ `Creating missing chunks: ${processed} of ${total} files`,
14
+ showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
15
+ "chunkCreation"
16
+ );
17
+ };
18
+ const total = filesStorageSrc.length;
19
+ const procAllChunks = filesStorageSrc.map(async (file) => {
20
+ if (!await ctx.vault.isTargetFile(file)) {
21
+ incProcessed();
22
+ return true;
23
+ }
24
+ if (ctx.vault.isFileSizeTooLarge(file.stat.size)) {
25
+ incProcessed();
26
+ return true;
27
+ }
28
+ if (shouldBeIgnored(file.path)) {
29
+ incProcessed();
30
+ return true;
31
+ }
32
+ const release = await semaphore.acquire();
33
+ incProcessed();
34
+ try {
35
+ await ctx.host.storeFileToDB(file, false, true);
36
+ } catch (ex) {
37
+ ctx.host.log(ex, LOG_LEVEL_VERBOSE);
38
+ } finally {
39
+ release();
40
+ }
41
+ });
42
+ await Promise.all(procAllChunks);
43
+ ctx.host.log(
44
+ `Creating chunks Done: ${processed} of ${total} files`,
45
+ showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
46
+ "chunkCreation"
47
+ );
48
+ }
49
+ export {
50
+ createAllChunks
51
+ };
@@ -0,0 +1,168 @@
1
+ import type { AnyEntry, FilePath, FilePathWithPrefix, UXFileInfo, UXFileInfoStub, UXInternalFileInfoStub } from "../../common/types.js";
2
+ import type { LiveSyncEventHub } from "../../hub/hub.js";
3
+ import type { StoreFileOptions } from "../../interfaces/FileHandler.js";
4
+ import type { APIService } from "../../services/base/APIService.js";
5
+ import type { DatabaseFileAccess } from "../../interfaces/DatabaseFileAccess.js";
6
+ import type { StorageAccess } from "../../interfaces/StorageAccess.js";
7
+ import type { FileProcessingService } from "../../services/base/FileProcessingService.js";
8
+ import type { ReplicationService } from "../../services/base/ReplicationService.js";
9
+ import type { ConflictService } from "../../services/base/ConflictService.js";
10
+ import type { PathService } from "../../services/base/PathService.js";
11
+ import type { SettingService } from "../../services/base/SettingService.js";
12
+ import type { VaultService } from "../../services/base/VaultService.js";
13
+ import type { FileReflectionProvenance, FileReflectionProvenanceRecord } from "../../interfaces/FileReflectionProvenance.js";
14
+ import type { LogFunction } from "../../services/lib/logUtils.js";
15
+ /** Services captured when the host constructs its file-handler facade. */
16
+ export interface ServiceFileHandlerDependencies {
17
+ /** Host event hub used for conflict-cancellation notifications. */
18
+ events: LiveSyncEventHub;
19
+ /** Host logging service used by the inherited module logger. */
20
+ API: APIService;
21
+ /** Database access captured by the facade at construction. */
22
+ databaseFileAccess: DatabaseFileAccess;
23
+ /** Storage access captured by the facade at construction. */
24
+ storageAccess: StorageAccess;
25
+ /** Storage-event handler registration owned by the host. */
26
+ fileProcessing: FileProcessingService;
27
+ /** Replicated-document handler registration owned by the host. */
28
+ replication: ReplicationService;
29
+ /** Conflict review hooks delivered outside document locks. */
30
+ conflict: ConflictService;
31
+ /** Path identity and freshness service captured at construction. */
32
+ path: PathService;
33
+ /** Live settings service captured at construction. */
34
+ setting: SettingService;
35
+ /** Current vault selection and size policy service. */
36
+ vault: VaultService;
37
+ /**
38
+ * Device-local record of the exact database revision reflected in storage.
39
+ *
40
+ * This is optional for compatibility hosts. Maintained hosts should provide
41
+ * it so edits made while a document is conflicted extend the displayed
42
+ * branch instead of whichever branch PouchDB currently selects as winner.
43
+ * The host must finish opening its backing store before it dispatches file
44
+ * or replication events; provenance does not hide lifecycle violations by
45
+ * waiting for readiness.
46
+ */
47
+ fileReflectionProvenance?: FileReflectionProvenance;
48
+ }
49
+ /** Exact storage bytes and the provenance observed alongside them. */
50
+ export type StorageSnapshot = {
51
+ /** Immutable body and raw file statistics captured from storage. */
52
+ file: UXFileInfo;
53
+ /** Copied device-local revision evidence captured with those bytes. */
54
+ revision: FileReflectionProvenanceRecord | undefined;
55
+ };
56
+ /** Result controlling whether an incoming effect must stop or revalidate a candidate. */
57
+ export interface PreservationResult {
58
+ /** Stop the incoming write, including when a preservation branch write was refused. */
59
+ preserved: boolean;
60
+ /** Candidate bytes/provenance requiring final revalidation; absence can mean unstable or unproven safety. */
61
+ snapshot?: StorageSnapshot;
62
+ }
63
+ /** A conflict review retained until its document lock is released. */
64
+ export type DeferredConflictCheck = {
65
+ /** Storage path to review after unlocking. */
66
+ path: FilePathWithPrefix;
67
+ /** Whether only an existing open review should be refreshed. */
68
+ ifOpen: boolean;
69
+ };
70
+ /** Remaining effect of a saved operation after inspecting current storage. */
71
+ export type RestoredFileEventAction = {
72
+ kind: "none";
73
+ } | {
74
+ kind: "unresolved";
75
+ } | {
76
+ kind: "store";
77
+ file: UXFileInfoStub;
78
+ complete?: boolean;
79
+ } | {
80
+ kind: "delete";
81
+ path: FilePath;
82
+ } | {
83
+ kind: "rename";
84
+ file: UXFileInfoStub;
85
+ oldPath: FilePathWithPrefix;
86
+ };
87
+ /** Dynamic public seams retained for host subclasses and runtime replacements. */
88
+ export interface FileHandlerHost {
89
+ /**
90
+ * Resolve the current virtual database getter.
91
+ * @returns Current database access.
92
+ * @remarks Getter overrides and later host replacements remain visible at each access site.
93
+ */
94
+ db(): DatabaseFileAccess;
95
+ /**
96
+ * Resolve the current virtual storage getter.
97
+ * @returns Current storage access.
98
+ * @remarks Getter overrides and later host replacements remain visible at each access site.
99
+ */
100
+ storage(): StorageAccess;
101
+ /** Route diagnostics through the current public logger. */
102
+ log: LogFunction;
103
+ /**
104
+ * Resolve metadata through the current virtual path method.
105
+ * @param entry - Metadata to resolve.
106
+ * @returns Its host path.
107
+ * @remarks This seam does not acquire a document lock.
108
+ */
109
+ getPath(entry: AnyEntry): FilePathWithPrefix;
110
+ /**
111
+ * Resolve a storage path through the current virtual method.
112
+ * @param entry - Metadata to resolve.
113
+ * @returns Its unprefixed host path.
114
+ * @remarks This seam remains independent of the virtual metadata-path method.
115
+ */
116
+ getPathWithoutPrefix(entry: AnyEntry): FilePathWithPrefix;
117
+ /**
118
+ * Read through the current virtual reader.
119
+ * @param file - The supplied observation.
120
+ * @returns Its supplied or current body.
121
+ * @remarks Callers retain their surrounding document lock and original read count.
122
+ */
123
+ readFileFromStub(file: UXFileInfoStub | UXFileInfo): Promise<UXFileInfo>;
124
+ /**
125
+ * Invoke the virtual save boundary used by chunk repair.
126
+ * @param info - File observation or path to save.
127
+ * @param force - Existing force policy.
128
+ * @param onlyChunks - Whether only missing chunks should be created.
129
+ * @param options - Existing recovery revalidation option.
130
+ * @returns Whether the requested save completed or safely skipped.
131
+ * @remarks The public save method owns document locking.
132
+ */
133
+ storeFileToDB(info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean, options?: StoreFileOptions): Promise<boolean>;
134
+ }
135
+ /** Mutable state belonging to one facade instance, never shared across hosts. */
136
+ export interface FileHandlerState {
137
+ /** Hashes reused only for the same immutable Blob object. */
138
+ readonly contentHashes: WeakMap<Blob, Promise<string>>;
139
+ /** Pending post-lock hooks keyed by normalised document identity. */
140
+ readonly deferredConflictChecks: Map<string, DeferredConflictCheck[]>;
141
+ }
142
+ /** Captured service values, per-instance state, and the small virtual host boundary. */
143
+ export interface FileHandlerContext {
144
+ /** Existing host event hub. */
145
+ readonly events: LiveSyncEventHub;
146
+ /** Existing conflict-review hooks. */
147
+ readonly conflict: ConflictService;
148
+ /** Existing path identity and freshness policy. */
149
+ readonly path: PathService;
150
+ /** Existing settings service; settings remain live when its getter is called. */
151
+ readonly setting: SettingService;
152
+ /** Existing vault selection and size policy. */
153
+ readonly vault: VaultService;
154
+ /** Optional device-local record store captured at construction. */
155
+ readonly provenance?: FileReflectionProvenance;
156
+ /** Per-instance mutable hashes and deferred hooks. */
157
+ readonly state: FileHandlerState;
158
+ /** Public methods and getters resolved dynamically at use time. */
159
+ readonly host: FileHandlerHost;
160
+ }
161
+ /**
162
+ * Capture service values and allocate the facade's existing per-instance state.
163
+ * @param services - Services supplied at construction; later property replacement does not change this context.
164
+ * @param host - Dynamic public seams; internal helpers are called directly rather than mirrored here.
165
+ * @returns The isolated context used by responsibility functions.
166
+ * @remarks No I/O, document locking, handler registration, or provenance access occurs here.
167
+ */
168
+ export declare function createFileHandlerContext(services: ServiceFileHandlerDependencies, host: FileHandlerHost): FileHandlerContext;
@@ -0,0 +1,15 @@
1
+ function createFileHandlerContext(services, host) {
2
+ return {
3
+ events: services.events,
4
+ conflict: services.conflict,
5
+ path: services.path,
6
+ setting: services.setting,
7
+ vault: services.vault,
8
+ provenance: services.fileReflectionProvenance,
9
+ host,
10
+ state: { contentHashes: /* @__PURE__ */ new WeakMap(), deferredConflictChecks: /* @__PURE__ */ new Map() }
11
+ };
12
+ }
13
+ export {
14
+ createFileHandlerContext
15
+ };
@@ -0,0 +1,40 @@
1
+ import type { FilePath, FilePathWithPrefix, UXFileInfoStub, UXInternalFileInfoStub } from "../../common/types.js";
2
+ import type { FileHandlerContext } from "./context.js";
3
+ /**
4
+ * Record a storage deletion under the corresponding document lock.
5
+ *
6
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
7
+ * @param info - The supplied file observation or path.
8
+ * @returns True after deletion or conservative conflict preservation; false for absent/deleted records or a refused write.
9
+ * @remarks Core operations require source and destination document locks as applicable. Unknown conflict ancestry is preserved for review rather than guessed.
10
+ */
11
+ export declare function deleteFileFromDB(ctx: FileHandlerContext, info: UXFileInfoStub | UXInternalFileInfoStub | FilePath): Promise<boolean>;
12
+ /**
13
+ * Accept an already represented deletion before applying any remaining database effect.
14
+ *
15
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
16
+ * @param info - The supplied file observation or path.
17
+ * @returns True if deletion is already represented or the remaining effect is accepted; false on refusal.
18
+ * @remarks Core operations require source and destination document locks as applicable. Unknown conflict ancestry is preserved for review rather than guessed.
19
+ */
20
+ export declare function deleteFileFromDBIfPresent(ctx: FileHandlerContext, info: UXFileInfoStub | UXInternalFileInfoStub | FilePath): Promise<boolean>;
21
+ /**
22
+ * Delete a selected revision under its document lock.
23
+ *
24
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
25
+ * @param info - The supplied file observation or path.
26
+ * @param rev - The exact selected database revision.
27
+ * @returns The database deletion result; matching provenance is cleared only after success.
28
+ * @remarks Core operations require source and destination document locks as applicable. Unknown conflict ancestry is preserved for review rather than guessed.
29
+ */
30
+ export declare function deleteRevisionFromDB(ctx: FileHandlerContext, info: UXFileInfoStub | FilePath | FilePathWithPrefix, rev: string): Promise<boolean | undefined>;
31
+ /**
32
+ * Run the legacy delete-and-reflect resolution under one document lock.
33
+ *
34
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
35
+ * @param info - The supplied file observation or path.
36
+ * @param rev - The exact selected database revision.
37
+ * @returns False on refusal; the existing undefined result on successful legacy completion.
38
+ * @remarks Core operations require source and destination document locks as applicable. Unknown conflict ancestry is preserved for review rather than guessed.
39
+ */
40
+ export declare function resolveConflictedByDeletingRevision(ctx: FileHandlerContext, info: UXFileInfoStub | FilePath, rev: string): Promise<boolean | undefined>;
@@ -0,0 +1,142 @@
1
+ import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
2
+ import { infoToStub } from "./storage.js";
3
+ import { deleteProvenance, getProvenance, findUniqueContentRevision } from "./provenance.js";
4
+ import { applyDatabaseEntryToStorage } from "./reflection.js";
5
+ import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
6
+ import { getStoragePathFromUXFileInfo, getDatabasePathFromUXFileInfo } from "../../common/typeUtils.js";
7
+ import { tryGetFilePath } from "../../common/utils.doc.js";
8
+ async function deleteFileFromDB(ctx, info) {
9
+ return await withFileEventPaths(ctx, [getStoragePathFromUXFileInfo(info)], () => deleteFileFromDBCore(ctx, info));
10
+ }
11
+ async function deleteFileFromDBIfPresent(ctx, info) {
12
+ const target = typeof info !== "string" && info.isInternal ? getDatabasePathFromUXFileInfo(info) : info;
13
+ const entry = await ctx.host.db().fetchEntryMeta(target, void 0, true);
14
+ if (!entry || entry.deleted || entry._deleted) return true;
15
+ return await deleteFileFromDBCore(ctx, info);
16
+ }
17
+ async function deleteFileFromDBCore(ctx, info) {
18
+ const file = await infoToStub(ctx, info);
19
+ const path = typeof info === "string" ? info : tryGetFilePath(info);
20
+ if (file == null) return await deleteMissingStorageFile(ctx, info, path);
21
+ if (file.isInternal) {
22
+ ctx.host.log(
23
+ `Internal file ${file.path} is not allowed to be processed on processFileEvent`,
24
+ LOG_LEVEL_VERBOSE
25
+ );
26
+ return false;
27
+ }
28
+ const entry = await ctx.host.db().fetchEntry(file, void 0, true, true);
29
+ if (!entry || entry.deleted || entry._deleted) {
30
+ ctx.host.log(`File ${file.path} is not exist or already deleted on the database`, LOG_LEVEL_VERBOSE);
31
+ return false;
32
+ }
33
+ const conflictedRevs = await ctx.host.db().getConflictedRevs(file);
34
+ if (conflictedRevs.length === 0) {
35
+ const deleted = await ctx.host.db().delete(file);
36
+ if (deleted) await deleteProvenance(ctx, file.path);
37
+ return deleted;
38
+ }
39
+ let baseRevision = (await getProvenance(ctx, file.path))?.revision;
40
+ if (!baseRevision) {
41
+ try {
42
+ const readFile = await ctx.host.readFileFromStub(file);
43
+ baseRevision = await findUniqueContentRevision(ctx, readFile);
44
+ } catch {
45
+ }
46
+ }
47
+ if (!baseRevision) {
48
+ ctx.host.log(
49
+ `The deleted storage file ${file.path} has conflicts, but its displayed revision is unknown; preserving every database branch`,
50
+ LOG_LEVEL_NOTICE
51
+ );
52
+ await queueConflictCheckFor(ctx, file.path);
53
+ return true;
54
+ }
55
+ const storedRevision = await ctx.host.db().storeDeletionWithBaseRevision(file.path, baseRevision);
56
+ if (storedRevision === false) return false;
57
+ await deleteProvenance(ctx, file.path);
58
+ await queueConflictCheckFor(ctx, file.path);
59
+ return true;
60
+ }
61
+ async function deleteRevisionFromDB(ctx, info, rev) {
62
+ return await withFileEventPaths(
63
+ ctx,
64
+ [getStoragePathFromUXFileInfo(info)],
65
+ () => deleteRevisionFromDBCore(ctx, info, rev)
66
+ );
67
+ }
68
+ async function deleteRevisionFromDBCore(ctx, info, rev) {
69
+ const path = getStoragePathFromUXFileInfo(info);
70
+ const provenance = await getProvenance(ctx, path);
71
+ const deleted = await ctx.host.db().delete(info, rev);
72
+ if (deleted && provenance?.revision === rev) {
73
+ await deleteProvenance(ctx, path);
74
+ }
75
+ return deleted;
76
+ }
77
+ async function resolveConflictedByDeletingRevision(ctx, info, rev) {
78
+ return await withFileEventPaths(
79
+ ctx,
80
+ [getStoragePathFromUXFileInfo(info)],
81
+ () => resolveConflictedByDeletingRevisionCore(ctx, info, rev)
82
+ );
83
+ }
84
+ async function resolveConflictedByDeletingRevisionCore(ctx, info, rev) {
85
+ const path = getStoragePathFromUXFileInfo(info);
86
+ const file = await infoToStub(ctx, info);
87
+ const docEntry = await ctx.host.db().fetchEntryMeta(file ?? info, rev, true);
88
+ if (!docEntry) {
89
+ ctx.host.log(`Failed to read the conflicted revision ${rev} of ${path}`, LOG_LEVEL_VERBOSE);
90
+ return false;
91
+ }
92
+ if (!await deleteRevisionFromDBCore(ctx, info, rev)) {
93
+ ctx.host.log(`Failed to delete the conflicted revision ${rev} of ${path}`, LOG_LEVEL_VERBOSE);
94
+ return false;
95
+ }
96
+ if (!await applyDatabaseEntryToStorage(ctx, docEntry, file, true)) {
97
+ ctx.host.log(`Failed to apply the resolved revision ${rev} of ${path} to the storage`, LOG_LEVEL_VERBOSE);
98
+ return false;
99
+ }
100
+ await deleteProvenance(ctx, path);
101
+ }
102
+ async function deleteMissingStorageFile(ctx, info, path) {
103
+ if (path === void 0) {
104
+ ctx.host.log(`File ${tryGetFilePath(info)} is not exist on the storage`, LOG_LEVEL_VERBOSE);
105
+ return false;
106
+ }
107
+ const entryByPath = await ctx.host.db().fetchEntry(path, void 0, true, true);
108
+ if (!entryByPath || entryByPath.deleted || entryByPath._deleted) {
109
+ ctx.host.log(
110
+ `File ${path} is not exist on the storage nor the database (or already deleted)`,
111
+ LOG_LEVEL_VERBOSE
112
+ );
113
+ return false;
114
+ }
115
+ const conflictedRevs = await ctx.host.db().getConflictedRevs(path);
116
+ if (conflictedRevs.length > 0) {
117
+ const provenance = await getProvenance(ctx, path);
118
+ if (!provenance) {
119
+ ctx.host.log(
120
+ `The deleted storage file ${path} has conflicts, but its displayed revision is unknown; preserving every database branch`,
121
+ LOG_LEVEL_NOTICE
122
+ );
123
+ await queueConflictCheckFor(ctx, path);
124
+ return true;
125
+ }
126
+ const storedRevision = await ctx.host.db().storeDeletionWithBaseRevision(path, provenance.revision);
127
+ if (storedRevision === false) return false;
128
+ await deleteProvenance(ctx, path);
129
+ await queueConflictCheckFor(ctx, path);
130
+ return true;
131
+ }
132
+ ctx.host.log(`File ${path} is missing on storage; deleting from the database by path`, LOG_LEVEL_INFO);
133
+ const deleted = await ctx.host.db().delete(path);
134
+ if (deleted) await deleteProvenance(ctx, path);
135
+ return deleted;
136
+ }
137
+ export {
138
+ deleteFileFromDB,
139
+ deleteFileFromDBIfPresent,
140
+ deleteRevisionFromDB,
141
+ resolveConflictedByDeletingRevision
142
+ };
@@ -0,0 +1,13 @@
1
+ import type { MetaEntry } from "../../common/types.js";
2
+ import type { DeletionRecoveryResult } from "../../interfaces/FileHandler.js";
3
+ import type { FileHandlerContext } from "./context.js";
4
+ /**
5
+ * Verify and recover one retained logical deletion without creating revision history.
6
+ * @param ctx - Captured services, state, and dynamic host boundaries.
7
+ * @param expected - The exact logical deletion selected by the ordinary scan.
8
+ * @param cleanupOnly - Require current absence and clear bookkeeping without reading or deleting a file.
9
+ * @returns Separate observed file, provenance, and completion outcomes, including verification failures.
10
+ * @remarks A shared three-operation permit precedes the document lock and all I/O. The lock
11
+ * excludes other handlers, while final observations conservatively detect external changes.
12
+ */
13
+ export declare function recoverDatabaseDeletion(ctx: FileHandlerContext, expected: MetaEntry, cleanupOnly?: boolean): Promise<DeletionRecoveryResult>;
@@ -0,0 +1,194 @@
1
+ import { Semaphore, withSemaphore } from "octagonal-wheels/concurrency/semaphore";
2
+ import { TARGET_IS_NEW } from "../../common/models/shared.const.symbols.js";
3
+ import { isDocContentSame, readContent } from "../../common/utils.js";
4
+ import { isFilePath } from "../../string_and_binary/path.js";
5
+ import { withFileEventPaths } from "./locking.js";
6
+ import {
7
+ contentEvidence,
8
+ getProvenancePath,
9
+ hasContentHash,
10
+ readProvenanceSnapshot,
11
+ sameProvenance
12
+ } from "./provenance.js";
13
+ import { isCurrentFileSelected, isCurrentPathSelected } from "./selection.js";
14
+ import { isFolderInfo } from "./storage.js";
15
+ const recoveryPermits = /* @__PURE__ */ new WeakMap();
16
+ function progressAttempt(attempt, progress) {
17
+ Object.assign(attempt, progress);
18
+ }
19
+ async function recoverDatabaseDeletion(ctx, expected, cleanupOnly = false) {
20
+ const attempt = {
21
+ ctx,
22
+ expected,
23
+ path: expected.path,
24
+ file: "unknown",
25
+ provenance: "unchanged",
26
+ phase: "admission"
27
+ };
28
+ if (!ctx.provenance?.listPaths) return outcome(attempt, "deferred", "capability-unavailable");
29
+ let semaphore = recoveryPermits.get(ctx.provenance);
30
+ if (!semaphore) {
31
+ semaphore = Semaphore(3);
32
+ recoveryPermits.set(ctx.provenance, semaphore);
33
+ }
34
+ try {
35
+ return await withSemaphore(semaphore, () => {
36
+ progressAttempt(attempt, { path: ctx.host.getPath(expected) });
37
+ return withFileEventPaths(ctx, [attempt.path], () => recoverUnderLock(attempt, cleanupOnly));
38
+ });
39
+ } catch (error) {
40
+ return { ...outcome(attempt, "failed", `${attempt.phase}-failed`), error };
41
+ }
42
+ }
43
+ async function recoverUnderLock(attempt, cleanupOnly) {
44
+ const { ctx, expected, path } = attempt;
45
+ progressAttempt(attempt, { phase: "eligibility" });
46
+ if (!validDeletion(expected) || !isFilePath(path) || await ctx.path.path2id(path) !== expected._id) {
47
+ return outcome(attempt, "deferred", "invalid-deletion");
48
+ }
49
+ if (!await isCurrentPathSelected(ctx, path)) return outcome(attempt, "deferred", "not-selected");
50
+ if (!await sameCurrentDeletion(attempt)) return outcome(attempt, "deferred", "database-changed");
51
+ const stub = await ctx.host.storage().getStub(path);
52
+ progressAttempt(attempt, {
53
+ file: stub === null ? "absent" : "present",
54
+ provenance: stub === null ? "pending" : "unchanged"
55
+ });
56
+ if (isFolderInfo(stub)) return outcome(attempt, "deferred", "storage-identity-changed");
57
+ if (stub !== null && (stub.isInternal || stub.path !== path)) {
58
+ return outcome(attempt, "deferred", "storage-identity-changed");
59
+ }
60
+ if (cleanupOnly && stub !== null) return outcome(attempt, "deferred", "file-present");
61
+ if (stub && (!await isCurrentFileSelected(ctx, stub) || ctx.path.compareFileFreshness(stub, expected) !== TARGET_IS_NEW)) {
62
+ return outcome(attempt, "deferred", "file-not-eligible");
63
+ }
64
+ progressAttempt(attempt, { phase: "provenance-read" });
65
+ const record = await readProvenanceSnapshot(ctx, path, true);
66
+ if (!stub) return await clearAbsentProvenance(attempt, record);
67
+ if (!record?.revision) return outcome(attempt, "deferred", "provenance-missing");
68
+ if (hasContentHash(record) && record.contentSize !== stub.stat.size) {
69
+ return outcome(attempt, "deferred", "content-size-mismatch");
70
+ }
71
+ return await verifyPresentFile(attempt, { ...stub, stat: { ...stub.stat } }, record);
72
+ }
73
+ async function verifyPresentFile(attempt, stub, record) {
74
+ const { ctx, path } = attempt;
75
+ let base;
76
+ if (!hasContentHash(record)) {
77
+ progressAttempt(attempt, { phase: "base-read" });
78
+ base = await ctx.host.db().fetchEntry(path, record.revision, true, true, false);
79
+ if (!base) return outcome(attempt, "failed", "base-unavailable");
80
+ if (base._rev !== record.revision || base.deleted || base._deleted || ctx.host.getPath(base) !== path) {
81
+ return outcome(attempt, "deferred", "base-not-usable");
82
+ }
83
+ }
84
+ progressAttempt(attempt, { phase: "body-read" });
85
+ const observed = await ctx.host.readFileFromStub(stub);
86
+ const file = { ...observed, stat: { ...observed.stat } };
87
+ if (!sameFileObservation(stub, file)) return outcome(attempt, "deferred", "storage-changed");
88
+ if (hasContentHash(record)) {
89
+ progressAttempt(attempt, { phase: "content-hash" });
90
+ const evidence = await contentEvidence(ctx, file.body);
91
+ if (!evidence.contentHash) return outcome(attempt, "failed", "content-hash-unavailable");
92
+ if (evidence.contentSize !== record.contentSize || evidence.contentHash !== record.contentHash) {
93
+ return outcome(attempt, "deferred", "content-hash-mismatch");
94
+ }
95
+ } else if (!base || !await isDocContentSame(readContent(base), file.body)) {
96
+ return outcome(attempt, "deferred", "base-content-mismatch");
97
+ }
98
+ base = void 0;
99
+ progressAttempt(attempt, { phase: "final-verification" });
100
+ const latest = await ctx.host.storage().getStub(path);
101
+ if (!latest || isFolderInfo(latest) || !sameFileObservation(latest, file)) {
102
+ progressAttempt(attempt, { file: latest === null ? "absent" : "present", provenance: "unchanged" });
103
+ return outcome(attempt, "deferred", "storage-changed");
104
+ }
105
+ const readFinal = await ctx.host.readFileFromStub(latest);
106
+ const final = { ...readFinal, stat: { ...readFinal.stat } };
107
+ if (!sameFileObservation(final, file) || !await isDocContentSame(final.body, file.body)) {
108
+ return outcome(attempt, "deferred", "storage-changed");
109
+ }
110
+ if (!sameProvenance(await readProvenanceSnapshot(ctx, path, true), record)) {
111
+ return outcome(attempt, "deferred", "provenance-changed");
112
+ }
113
+ if (!await sameCurrentDeletion(attempt)) return outcome(attempt, "deferred", "database-changed");
114
+ if (!await isCurrentFileSelected(ctx, final)) return outcome(attempt, "deferred", "not-selected");
115
+ if (ctx.path.compareFileFreshness(final, attempt.expected) !== TARGET_IS_NEW) {
116
+ return outcome(attempt, "deferred", "file-not-eligible");
117
+ }
118
+ const target = await ctx.host.storage().getStub(path);
119
+ if (!target || isFolderInfo(target) || !sameFileObservation(target, file)) {
120
+ progressAttempt(attempt, { file: target === null ? "absent" : "present", provenance: "unchanged" });
121
+ return outcome(attempt, "deferred", "storage-changed");
122
+ }
123
+ return await removeAndConfirm(attempt, record);
124
+ }
125
+ async function removeAndConfirm(attempt, record) {
126
+ const { ctx, path } = attempt;
127
+ progressAttempt(attempt, { phase: "remove", file: "unknown", provenance: "pending" });
128
+ try {
129
+ await ctx.host.storage().deleteVaultItem(path);
130
+ } catch (error) {
131
+ progressAttempt(attempt, { error, warning: "storage-post-removal-error" });
132
+ }
133
+ progressAttempt(attempt, { phase: "removal-verification" });
134
+ const current = await ctx.host.storage().getStub(path);
135
+ if (current !== null) {
136
+ progressAttempt(attempt, { file: "present", provenance: "unchanged", warning: void 0 });
137
+ return outcome(attempt, "failed", attempt.error ? "removal-failed" : "removal-no-effect");
138
+ }
139
+ progressAttempt(attempt, { file: "absent", provenance: "pending" });
140
+ return await clearAbsentProvenance(attempt, record);
141
+ }
142
+ async function clearAbsentProvenance(attempt, record) {
143
+ const { ctx, path } = attempt;
144
+ progressAttempt(attempt, { phase: "provenance-cleanup" });
145
+ if (!await isCurrentPathSelected(ctx, path)) return outcome(attempt, "deferred", "not-selected");
146
+ if (!await sameCurrentDeletion(attempt)) return outcome(attempt, "deferred", "database-changed");
147
+ const latest = await readProvenanceSnapshot(ctx, path, true);
148
+ if (!sameProvenance(latest, record)) return outcome(attempt, "deferred", "provenance-changed");
149
+ const target = await ctx.host.storage().getStub(path);
150
+ if (target !== null) {
151
+ progressAttempt(attempt, { file: "present", provenance: "unchanged" });
152
+ return outcome(attempt, "deferred", "file-recreated");
153
+ }
154
+ if (latest) await ctx.provenance.delete(getProvenancePath(ctx, path));
155
+ progressAttempt(attempt, { file: "absent", provenance: "cleared" });
156
+ return outcome(attempt, "applied", "deletion-confirmed");
157
+ }
158
+ async function sameCurrentDeletion({ ctx, expected, path }) {
159
+ const current = await ctx.host.db().fetchEntryMeta(path, void 0, true);
160
+ if (!current || !validDeletion(current)) return false;
161
+ if (current._id !== expected._id || current._rev !== expected._rev) return false;
162
+ if (ctx.host.getPath(current) !== path) return false;
163
+ if (await ctx.path.path2id(path) !== current._id) return false;
164
+ return (await ctx.host.db().getConflictedRevs(path)).length === 0;
165
+ }
166
+ function validDeletion(entry) {
167
+ return !!entry._id && !!entry._rev && entry.deleted === true && !entry._deleted && ["notes", "plain", "newnote"].includes(entry.type) && Array.isArray(entry.children) && Number.isFinite(entry.mtime) && Number.isFinite(entry.ctime) && Number.isSafeInteger(entry.size) && entry.size >= 0 && !entry._conflicts?.length;
168
+ }
169
+ function sameFileObservation(left, right) {
170
+ return !left.isInternal && !left.isFolder && left.path === right.path && left.stat.type === "file" && left.stat.mtime === right.stat.mtime && left.stat.ctime === right.stat.ctime && left.stat.size === right.stat.size;
171
+ }
172
+ function outcome(attempt, status, reason) {
173
+ const diagnostics = {
174
+ reason,
175
+ phase: attempt.phase,
176
+ ...attempt.warning ? { warning: attempt.warning } : {},
177
+ ...attempt.error ? { error: attempt.error } : {}
178
+ };
179
+ const { file, provenance } = attempt;
180
+ if (file === "absent" && provenance === "cleared" && status !== "deferred") {
181
+ return { ...diagnostics, status, file, provenance };
182
+ }
183
+ if (provenance === "unchanged" && status !== "applied") {
184
+ return { ...diagnostics, status, file, provenance };
185
+ }
186
+ if (provenance === "pending" && status !== "applied") {
187
+ if (file === "absent") return { ...diagnostics, status, file, provenance };
188
+ if (file === "unknown" && status === "failed") return { ...diagnostics, status, file, provenance };
189
+ }
190
+ throw new Error("Inconsistent deletion recovery outcome");
191
+ }
192
+ export {
193
+ recoverDatabaseDeletion
194
+ };
@@ -0,0 +1,20 @@
1
+ import type { FileEventItem, MetaEntry } from "../../common/types.js";
2
+ import type { FileHandlerContext } from "./context.js";
3
+ /**
4
+ * Reconcile an ordinary or recovery storage event under every related document lock.
5
+ *
6
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
7
+ * @param item - The admitted operation intent and related paths.
8
+ * @returns Whether the event completed or safely skipped; unsupported or unresolved work returns false and inspection errors retain their original propagation.
9
+ * @remarks Operation intent is revalidated under related document locks. Policy skips, retained failures, and conservative conflict handling retain their original meanings.
10
+ */
11
+ export declare function processFileEvent(ctx: FileHandlerContext, item: FileEventItem): Promise<boolean>;
12
+ /**
13
+ * Select and reflect a replicated document while retaining host override dispatch.
14
+ *
15
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
16
+ * @param entry - The database metadata being processed.
17
+ * @returns Whether replication reflection completed; excluded or unsafe documents retain a false result.
18
+ * @remarks Operation intent is revalidated under related document locks. Policy skips, retained failures, and conservative conflict handling retain their original meanings.
19
+ */
20
+ export declare function processReplicatedDocument(ctx: FileHandlerContext, entry: MetaEntry): Promise<boolean>;