@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.
- package/README.md +14 -2
- package/dist/common/models/fileaccess.definition.d.ts +35 -0
- package/dist/common/models/fileaccess.definition.js +11 -0
- package/dist/common/typeUtils.d.ts +27 -4
- package/dist/interfaces/FileHandler.d.ts +60 -1
- package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
- package/dist/interfaces/FileReflectionProvenance.js +11 -1
- package/dist/managers/StorageEventManager/admission.d.ts +50 -0
- package/dist/managers/StorageEventManager/admission.js +129 -0
- package/dist/managers/StorageEventManager/batching.d.ts +93 -0
- package/dist/managers/StorageEventManager/batching.js +97 -0
- package/dist/managers/StorageEventManager/operations.d.ts +142 -0
- package/dist/managers/StorageEventManager/operations.js +69 -0
- package/dist/managers/StorageEventManager/processing.d.ts +63 -0
- package/dist/managers/StorageEventManager/processing.js +94 -0
- package/dist/managers/StorageEventManager/queue.d.ts +73 -0
- package/dist/managers/StorageEventManager/queue.js +113 -0
- package/dist/managers/StorageEventManager/retry.d.ts +33 -0
- package/dist/managers/StorageEventManager/retry.js +31 -0
- package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
- package/dist/managers/StorageEventManager/snapshot.js +53 -0
- package/dist/managers/StorageEventManager/state.d.ts +155 -0
- package/dist/managers/StorageEventManager/state.js +105 -0
- package/dist/managers/StorageEventManager/watching.d.ts +93 -0
- package/dist/managers/StorageEventManager/watching.js +36 -0
- package/dist/managers/StorageEventManager.d.ts +303 -83
- package/dist/managers/StorageEventManager.js +457 -547
- package/dist/serviceFeatures/offlineScanner/fileStatus.d.ts +61 -0
- package/dist/serviceFeatures/offlineScanner/fileStatus.js +85 -0
- package/dist/serviceFeatures/offlineScanner/files.d.ts +47 -0
- package/dist/serviceFeatures/offlineScanner/files.js +218 -0
- package/dist/serviceFeatures/offlineScanner/metadata.d.ts +56 -0
- package/dist/serviceFeatures/offlineScanner/metadata.js +320 -0
- package/dist/serviceFeatures/offlineScanner/paths.d.ts +20 -0
- package/dist/serviceFeatures/offlineScanner/paths.js +16 -0
- package/dist/serviceFeatures/offlineScanner/scan.d.ts +35 -0
- package/dist/serviceFeatures/offlineScanner/scan.js +358 -0
- package/dist/serviceFeatures/offlineScanner/types.d.ts +134 -0
- package/dist/serviceFeatures/offlineScanner/types.js +66 -0
- package/dist/serviceFeatures/offlineScanner.d.ts +25 -251
- package/dist/serviceFeatures/offlineScanner.js +36 -860
- package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
- package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
- package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
- package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.d.ts +13 -0
- package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
- package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
- package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
- package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
- package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
- package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
- package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
- package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
- package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
- package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
- package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
- package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
- package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
- package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
- package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
- package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
- package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
- package/dist/serviceModules/ServiceFileHandlerBase.d.ts +141 -183
- package/dist/serviceModules/ServiceFileHandlerBase.js +206 -1397
- package/dist/services/base/KeyValueDBService.d.ts +9 -0
- package/dist/services/base/KeyValueDBService.js +11 -1
- package/docs/conflict-resolution.md +3 -1
- package/docs/development.md +40 -0
- package/docs/offline-scanner.md +26 -1
- package/docs/p2p-transport-lifecycle.md +8 -1
- package/docs/storage-events-and-reflection.md +212 -22
- package/package.json +1 -1
|
@@ -1,27 +1,45 @@
|
|
|
1
|
-
import { shouldBeIgnored } from "../string_and_binary/path.js";
|
|
2
1
|
import {
|
|
3
2
|
DEFAULT_SETTINGS,
|
|
4
|
-
LOG_LEVEL_DEBUG,
|
|
5
|
-
LOG_LEVEL_INFO,
|
|
6
3
|
LOG_LEVEL_NOTICE,
|
|
7
4
|
LOG_LEVEL_VERBOSE
|
|
8
5
|
} from "../common/types.js";
|
|
9
|
-
import {
|
|
10
|
-
import {} from "../common/types.js";
|
|
11
|
-
import { serialized } from "octagonal-wheels/concurrency/lock";
|
|
6
|
+
import { fireAndForget, throttle } from "../common/utils.js";
|
|
12
7
|
import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
|
|
13
|
-
import {
|
|
14
|
-
createDeferredAction
|
|
15
|
-
} from "octagonal-wheels/concurrency/deferredAction";
|
|
16
|
-
import { promiseWithResolvers } from "octagonal-wheels/promises";
|
|
17
8
|
import { StorageEventManager } from "../interfaces/StorageEventManager.js";
|
|
18
9
|
import { createInstanceLogFunction } from "../services/lib/logUtils.js";
|
|
19
|
-
import {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
10
|
+
import { admitStorageEvents } from "./StorageEventManager/admission.js";
|
|
11
|
+
import {
|
|
12
|
+
forwardVaultEvent,
|
|
13
|
+
hasEditorChangePath,
|
|
14
|
+
readEditorFileChange
|
|
15
|
+
} from "./StorageEventManager/watching.js";
|
|
16
|
+
import {
|
|
17
|
+
addBatchWaiting,
|
|
18
|
+
finishBatchWaiting,
|
|
19
|
+
initialiseFileEventBatch,
|
|
20
|
+
releaseFileEventBatches
|
|
21
|
+
} from "./StorageEventManager/batching.js";
|
|
22
|
+
import {
|
|
23
|
+
enqueueStorageEvent,
|
|
24
|
+
flushStorageEvents,
|
|
25
|
+
restoreStorageEvents,
|
|
26
|
+
runBufferedStorageEvents
|
|
27
|
+
} from "./StorageEventManager/queue.js";
|
|
28
|
+
import {
|
|
29
|
+
captureFileEventAttempts,
|
|
30
|
+
waitForFileEventAttempts
|
|
31
|
+
} from "./StorageEventManager/retry.js";
|
|
32
|
+
import { persistFileEventSnapshot } from "./StorageEventManager/snapshot.js";
|
|
33
|
+
import {
|
|
34
|
+
handleStorageFileEvent,
|
|
35
|
+
processStorageEventAttempt
|
|
36
|
+
} from "./StorageEventManager/processing.js";
|
|
37
|
+
import {
|
|
38
|
+
createStorageEventState,
|
|
39
|
+
failFileEventAttempt,
|
|
40
|
+
hasPendingStorageEvent,
|
|
41
|
+
retainFileEvent
|
|
42
|
+
} from "./StorageEventManager/state.js";
|
|
25
43
|
class StorageEventManagerBase extends StorageEventManager {
|
|
26
44
|
_log;
|
|
27
45
|
setting;
|
|
@@ -29,560 +47,447 @@ class StorageEventManagerBase extends StorageEventManager {
|
|
|
29
47
|
fileProcessing;
|
|
30
48
|
storageAccess;
|
|
31
49
|
adapter;
|
|
50
|
+
bufferedQueuedItems = [];
|
|
51
|
+
concurrentProcessing = Semaphore(5);
|
|
52
|
+
_waitingMap = /* @__PURE__ */ new Map();
|
|
53
|
+
processingCount = 0;
|
|
54
|
+
eventState = createStorageEventState();
|
|
55
|
+
buffer = {
|
|
56
|
+
read: () => this.bufferedQueuedItems,
|
|
57
|
+
replace: (events) => {
|
|
58
|
+
this.bufferedQueuedItems = events;
|
|
59
|
+
},
|
|
60
|
+
append: (event) => {
|
|
61
|
+
this.bufferedQueuedItems.push(event);
|
|
62
|
+
},
|
|
63
|
+
shift: () => this.bufferedQueuedItems.shift()
|
|
64
|
+
};
|
|
65
|
+
notifications = {
|
|
66
|
+
updateStatus: () => this.updateStatus(),
|
|
67
|
+
reportFailure: (error) => this.reportOperationFailure(error)
|
|
68
|
+
};
|
|
69
|
+
log = (...args) => this._log(...args);
|
|
70
|
+
batching = {
|
|
71
|
+
waiting: () => this._waitingMap,
|
|
72
|
+
operation: (event) => this.operations.get(event),
|
|
73
|
+
minimumDelay: () => this.batchSaveMinimumDelay,
|
|
74
|
+
maximumDelay: () => this.batchSaveMaximumDelay,
|
|
75
|
+
enabled: () => this.shouldBatchSave,
|
|
76
|
+
log: this.log,
|
|
77
|
+
requestSnapshot: () => this.triggerTakeSnapshot(),
|
|
78
|
+
proceed: (path) => this._proceedWaiting(path),
|
|
79
|
+
cancel: (path) => this._cancelWaiting(path),
|
|
80
|
+
add: (path, event, since) => this._addWaiting(path, event, since)
|
|
81
|
+
};
|
|
82
|
+
retry = {
|
|
83
|
+
buffer: this.buffer,
|
|
84
|
+
processOperation: (operation, attempt) => this.processOperation(operation, attempt),
|
|
85
|
+
runQueuedEvents: () => this.runQueuedEvents(),
|
|
86
|
+
reportFailure: this.notifications.reportFailure
|
|
87
|
+
};
|
|
88
|
+
snapshotIO = {
|
|
89
|
+
save: (events) => this._saveSnapshot(events),
|
|
90
|
+
waitingEvents: () => [...this._waitingMap.values()].map((waiting) => waiting.event),
|
|
91
|
+
updateStatus: this.notifications.updateStatus
|
|
92
|
+
};
|
|
93
|
+
queue = {
|
|
94
|
+
...this.notifications,
|
|
95
|
+
buffer: this.buffer,
|
|
96
|
+
log: this.log,
|
|
97
|
+
takeSnapshot: () => this._takeSnapshot(),
|
|
98
|
+
loadSnapshot: () => this._loadSnapshot(),
|
|
99
|
+
processFileEvent: (event) => this.processFileEvent(event),
|
|
100
|
+
runQueuedEvents: (options) => this.runQueuedEvents(options),
|
|
101
|
+
capture: (operations, before) => this.captureAttempts(operations, before),
|
|
102
|
+
release: (operations) => this.releaseOperations(operations),
|
|
103
|
+
wait: (attempts) => this.waitForAttempts(attempts),
|
|
104
|
+
fail: (operation, error, attempt) => this.failOperation(operation, error, attempt)
|
|
105
|
+
};
|
|
106
|
+
admission = {
|
|
107
|
+
settings: () => this.settings,
|
|
108
|
+
isFolder: (file) => this.isFolder(file),
|
|
109
|
+
isFile: (file) => this.isFile(file),
|
|
110
|
+
isTarget: (path) => this.vaultService.isTargetFile(path),
|
|
111
|
+
isTooLarge: (size) => this.vaultService.isFileSizeTooLarge(size),
|
|
112
|
+
recentlyTouched: (file) => this.storageAccess.recentlyTouched(file),
|
|
113
|
+
onStorageFileEvent: () => this.fileProcessing.onStorageFileEvent(),
|
|
114
|
+
enqueue: (event) => this.enqueue(event),
|
|
115
|
+
release: this.queue.release,
|
|
116
|
+
reportFailure: this.notifications.reportFailure,
|
|
117
|
+
log: this.log
|
|
118
|
+
};
|
|
119
|
+
attempts = {
|
|
120
|
+
...this.notifications,
|
|
121
|
+
capture: this.queue.capture,
|
|
122
|
+
release: this.queue.release,
|
|
123
|
+
wait: this.queue.wait,
|
|
124
|
+
initialise: (operation) => this.initialiseOperation(operation),
|
|
125
|
+
takeSnapshot: this.queue.takeSnapshot,
|
|
126
|
+
completeSnapshot: (completion) => this.persistSnapshot(completion),
|
|
127
|
+
semaphore: () => this.concurrentProcessing,
|
|
128
|
+
requestProcessQueue: (event) => this.requestProcessQueue(event),
|
|
129
|
+
cancelWaiting: (event) => {
|
|
130
|
+
const path = event.args.file.path;
|
|
131
|
+
if (this._waitingMap.get(path)?.event === event) this._cancelWaiting(path);
|
|
132
|
+
},
|
|
133
|
+
fail: this.queue.fail
|
|
134
|
+
};
|
|
135
|
+
handler = {
|
|
136
|
+
processing: () => this.fileProcessing,
|
|
137
|
+
operation: (event) => this.operations.get(event),
|
|
138
|
+
updateStatus: this.notifications.updateStatus
|
|
139
|
+
};
|
|
140
|
+
/** Preserve adapter receivers and virtual admission when forwarding watcher notifications. */
|
|
141
|
+
watching = {
|
|
142
|
+
adapter: () => this.adapter,
|
|
143
|
+
isProcessing: (path) => this.storageAccess.isFileProcessing(path),
|
|
144
|
+
append: (events, ctx) => this.appendQueue(events, ctx)
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* Bind the platform adapter and host services to this manager instance.
|
|
148
|
+
* @param adapter - The host adapter for file conversion, persistence, status, and watching.
|
|
149
|
+
* @param dependencies - Settings, vault, processing, storage-access, and API services used by the facade.
|
|
150
|
+
*/
|
|
151
|
+
constructor(adapter, dependencies) {
|
|
152
|
+
super();
|
|
153
|
+
this.adapter = adapter;
|
|
154
|
+
this.setting = dependencies.setting;
|
|
155
|
+
this.vaultService = dependencies.vaultService;
|
|
156
|
+
this.fileProcessing = dependencies.fileProcessing;
|
|
157
|
+
this.storageAccess = dependencies.storageAccessManager;
|
|
158
|
+
this._log = createInstanceLogFunction("StorageEventManager", dependencies.APIService);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Read the setting service's current settings.
|
|
162
|
+
* @returns The current settings value; each access can observe live changes.
|
|
163
|
+
*/
|
|
164
|
+
get settings() {
|
|
165
|
+
return this.setting.currentSettings();
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Resolve whether batching is enabled from the settings active at this access.
|
|
169
|
+
* @returns The live-sync batching value while LiveSync is active, or the general batching value otherwise.
|
|
170
|
+
* @remarks Protected so a host subclass can provide its batching policy.
|
|
171
|
+
*/
|
|
32
172
|
get shouldBatchSave() {
|
|
33
173
|
const settings = this.settings;
|
|
34
174
|
return settings?.liveSync === true ? settings.batchSaveInLiveSync === true : settings?.batchSave;
|
|
35
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Resolve the minimum batch delay from the current settings.
|
|
178
|
+
* @returns The configured delay value, or the default when the setting is absent.
|
|
179
|
+
*/
|
|
36
180
|
get batchSaveMinimumDelay() {
|
|
37
181
|
return this.settings?.batchSaveMinimumDelay ?? DEFAULT_SETTINGS.batchSaveMinimumDelay;
|
|
38
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* Resolve the maximum batch delay from the current settings.
|
|
185
|
+
* @returns The configured delay value, or the default when the setting is absent.
|
|
186
|
+
*/
|
|
39
187
|
get batchSaveMaximumDelay() {
|
|
40
188
|
return this.settings?.batchSaveMaximumDelay ?? DEFAULT_SETTINGS.batchSaveMaximumDelay;
|
|
41
189
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
this.
|
|
48
|
-
this.setting = dependencies.setting;
|
|
49
|
-
this.vaultService = dependencies.vaultService;
|
|
50
|
-
this.fileProcessing = dependencies.fileProcessing;
|
|
51
|
-
this.storageAccess = dependencies.storageAccessManager;
|
|
52
|
-
this._log = createInstanceLogFunction("StorageEventManager", dependencies.APIService);
|
|
190
|
+
/**
|
|
191
|
+
* Expose the manager's event-to-operation identity map to its internal effects.
|
|
192
|
+
* @returns The weak map used to find an operation from its event object.
|
|
193
|
+
*/
|
|
194
|
+
get operations() {
|
|
195
|
+
return this.eventState.operations;
|
|
53
196
|
}
|
|
54
|
-
|
|
197
|
+
/**
|
|
198
|
+
* Save the supplied queued-event snapshot through the host adapter.
|
|
199
|
+
* @param snapshot - File events and flush sentinels to persist.
|
|
200
|
+
* @returns A promise fulfilled when the adapter saves the snapshot; adapter failures reject it.
|
|
201
|
+
*/
|
|
55
202
|
_saveSnapshot(snapshot) {
|
|
56
203
|
return this.adapter.persistence.saveSnapshot(snapshot);
|
|
57
204
|
}
|
|
205
|
+
/**
|
|
206
|
+
* Load the queued-event snapshot through the host adapter.
|
|
207
|
+
* @returns A promise for the saved events, or `null` when no snapshot exists; adapter failures reject it.
|
|
208
|
+
*/
|
|
58
209
|
_loadSnapshot() {
|
|
59
210
|
return this.adapter.persistence.loadSnapshot();
|
|
60
211
|
}
|
|
61
|
-
|
|
212
|
+
/**
|
|
213
|
+
* Ask the host adapter to classify a supplied file or folder value.
|
|
214
|
+
* @param file - A host value or one of the shared file and folder representations.
|
|
215
|
+
* @returns Whether the adapter recognises the value as a folder.
|
|
216
|
+
*/
|
|
62
217
|
isFolder(file) {
|
|
63
218
|
return this.adapter.typeGuard.isFolder(file);
|
|
64
219
|
}
|
|
220
|
+
/**
|
|
221
|
+
* Ask the host adapter to classify a supplied file or folder value.
|
|
222
|
+
* @param file - A host value or one of the shared file and folder representations.
|
|
223
|
+
* @returns Whether the adapter recognises the value as a file.
|
|
224
|
+
*/
|
|
65
225
|
isFile(file) {
|
|
66
226
|
return this.adapter.typeGuard.isFile(file);
|
|
67
227
|
}
|
|
228
|
+
/**
|
|
229
|
+
* Publish the current batch, processing, and unfinished-operation counts through the adapter.
|
|
230
|
+
* @returns Nothing; the adapter's status surface is updated synchronously.
|
|
231
|
+
*/
|
|
68
232
|
updateStatus() {
|
|
69
233
|
this.adapter.status.updateStatus({
|
|
70
234
|
batched: this._waitingMap.size,
|
|
71
235
|
processing: this.processingCount,
|
|
72
|
-
totalQueued: [...this.pendingSnapshot.values()].filter(
|
|
236
|
+
totalQueued: [...this.eventState.pendingSnapshot.values()].filter(
|
|
237
|
+
(entry) => entry.operation && !entry.completed
|
|
238
|
+
).length
|
|
73
239
|
});
|
|
74
240
|
}
|
|
75
|
-
/**
|
|
76
|
-
* Snapshot restoration promise.
|
|
77
|
-
* It resolves after the restored file operations have finished, before Vault watching begins.
|
|
78
|
-
*/
|
|
241
|
+
/** Completes restored operations before the host starts watching. */
|
|
79
242
|
snapShotRestored = null;
|
|
80
243
|
/**
|
|
81
|
-
*
|
|
244
|
+
* Start snapshot restoration and retain the promise used by watcher startup.
|
|
245
|
+
* @returns A promise fulfilled after restoration and replay attempts settle; snapshot or dispatch errors reject it, while failed operation results are reported and retained.
|
|
82
246
|
*/
|
|
83
247
|
restoreState() {
|
|
84
248
|
this.snapShotRestored = this._restoreFromSnapshot();
|
|
85
249
|
return this.snapShotRestored;
|
|
86
250
|
}
|
|
87
|
-
|
|
88
|
-
|
|
251
|
+
/**
|
|
252
|
+
* Filter and admit host watcher events into the operation queue.
|
|
253
|
+
* @param params - The watcher events to select and enqueue.
|
|
254
|
+
* @param ctx - Optional host context forwarded with each admitted event.
|
|
255
|
+
* @returns A promise for filtering and queue admission, not for file-handler completion; admission failures are reported and reject it.
|
|
256
|
+
* @remarks The promise may resolve while admitted handlers are still pending. Use `waitForIdle` for the captured processing boundary.
|
|
257
|
+
*/
|
|
89
258
|
appendQueue(params, ctx) {
|
|
90
|
-
|
|
91
|
-
const admission = { acceptedAt: Date.now(), completion: Promise.resolve(), operations: [], flushRequested: false };
|
|
92
|
-
this.admissions.add(admission);
|
|
93
|
-
admission.completion = this.appendQueueInternal(params, ctx, admission);
|
|
94
|
-
void admission.completion.then(
|
|
95
|
-
() => this.admissions.delete(admission),
|
|
96
|
-
(error) => {
|
|
97
|
-
this.admissions.delete(admission);
|
|
98
|
-
this.reportOperationFailure(error);
|
|
99
|
-
}
|
|
100
|
-
);
|
|
101
|
-
return admission.completion;
|
|
102
|
-
}
|
|
103
|
-
async appendQueueInternal(params, ctx, admission) {
|
|
104
|
-
const settings = this.settings;
|
|
105
|
-
if (!settings.isConfigured) return;
|
|
106
|
-
if (settings.suspendFileWatching) return;
|
|
107
|
-
if (isRemediationModeActive(settings)) {
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
this.fileProcessing.onStorageFileEvent();
|
|
111
|
-
for (const param of params) {
|
|
112
|
-
const atomicKey = [0, 0, 0, 0, 0, 0].map((e) => `${Math.floor(Math.random() * 1e5)}`).join("-");
|
|
113
|
-
let type = param.type;
|
|
114
|
-
let file = param.file;
|
|
115
|
-
const oldPath = param.oldPath;
|
|
116
|
-
if (this.isFolder(file)) {
|
|
117
|
-
this._log(`Folder event skipped: ${file.path}`, LOG_LEVEL_VERBOSE);
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
const isTargetPath = async (path) => {
|
|
121
|
-
if (shouldBeIgnored(path)) return false;
|
|
122
|
-
if (!settings.syncInternalFiles && path.startsWith(".")) return false;
|
|
123
|
-
return await this.vaultService.isTargetFile(path);
|
|
124
|
-
};
|
|
125
|
-
if (type === "RENAME") {
|
|
126
|
-
const renamedFile = file;
|
|
127
|
-
if (!oldPath || !this.isFile(file) || !renamedFile.stat) {
|
|
128
|
-
this._log(`Invalid rename event skipped: ${file.path}`, LOG_LEVEL_VERBOSE);
|
|
129
|
-
continue;
|
|
130
|
-
}
|
|
131
|
-
const oldPathIsTarget = await isTargetPath(oldPath);
|
|
132
|
-
let newPathIsTarget = await isTargetPath(file.path);
|
|
133
|
-
if (newPathIsTarget && this.vaultService.isFileSizeTooLarge(renamedFile.stat.size)) {
|
|
134
|
-
this._log(
|
|
135
|
-
`The storage file has been changed but exceeds the maximum size. Skipping: ${param.file.path}`,
|
|
136
|
-
LOG_LEVEL_NOTICE
|
|
137
|
-
);
|
|
138
|
-
newPathIsTarget = false;
|
|
139
|
-
}
|
|
140
|
-
if (!oldPathIsTarget && !newPathIsTarget) {
|
|
141
|
-
continue;
|
|
142
|
-
}
|
|
143
|
-
if (oldPathIsTarget && !newPathIsTarget) {
|
|
144
|
-
type = "DELETE";
|
|
145
|
-
file = {
|
|
146
|
-
path: oldPath,
|
|
147
|
-
name: oldPath.split("/").pop() ?? file.name,
|
|
148
|
-
stat: renamedFile.stat,
|
|
149
|
-
deleted: true
|
|
150
|
-
};
|
|
151
|
-
} else if (!oldPathIsTarget && newPathIsTarget) {
|
|
152
|
-
type = "CREATE";
|
|
153
|
-
}
|
|
154
|
-
} else {
|
|
155
|
-
if (!await isTargetPath(file.path)) continue;
|
|
156
|
-
if (type !== "INTERNAL") {
|
|
157
|
-
const size = file.stat.size;
|
|
158
|
-
if (this.vaultService.isFileSizeTooLarge(size) && (type == "CREATE" || type == "CHANGED")) {
|
|
159
|
-
this._log(
|
|
160
|
-
`The storage file has been changed but exceeds the maximum size. Skipping: ${param.file.path}`,
|
|
161
|
-
LOG_LEVEL_NOTICE
|
|
162
|
-
);
|
|
163
|
-
continue;
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
if (this.isFile(file)) {
|
|
168
|
-
if (type == "CREATE" || type == "CHANGED" || type == "RENAME") {
|
|
169
|
-
await delay(10);
|
|
170
|
-
if (this.storageAccess.recentlyTouched({
|
|
171
|
-
path: file.path,
|
|
172
|
-
stat: file.stat ?? { ctime: 0, mtime: 0, size: 0 }
|
|
173
|
-
})) {
|
|
174
|
-
continue;
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
let cache = void 0;
|
|
179
|
-
if (param.cachedData) {
|
|
180
|
-
cache = param.cachedData;
|
|
181
|
-
}
|
|
182
|
-
const item = {
|
|
183
|
-
type,
|
|
184
|
-
args: {
|
|
185
|
-
file,
|
|
186
|
-
oldPath: type === "RENAME" ? oldPath : void 0,
|
|
187
|
-
...param.type === "RENAME" && type === "DELETE" ? { renameTarget: param.file.path } : {},
|
|
188
|
-
cache,
|
|
189
|
-
ctx
|
|
190
|
-
},
|
|
191
|
-
skipBatchWait: param.skipBatchWait,
|
|
192
|
-
key: atomicKey
|
|
193
|
-
};
|
|
194
|
-
this.enqueue(item);
|
|
195
|
-
const operation = this.operations.get(item);
|
|
196
|
-
if (operation) {
|
|
197
|
-
operation.acceptedAt = admission.acceptedAt;
|
|
198
|
-
if (admission.flushRequested) this.releaseOperations([operation]);
|
|
199
|
-
admission.operations.push(operation);
|
|
200
|
-
}
|
|
201
|
-
}
|
|
259
|
+
return admitStorageEvents(this.eventState, params, ctx, this.admission);
|
|
202
260
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
this.
|
|
261
|
+
/**
|
|
262
|
+
* Add an already selected event to the buffer and start background snapshotting and dispatch.
|
|
263
|
+
* @param event - The event which has already passed host admission checks.
|
|
264
|
+
* @returns Nothing; processing and persistence failures are reported through manager effects.
|
|
265
|
+
*/
|
|
266
|
+
enqueue(event) {
|
|
267
|
+
enqueueStorageEvent(this.eventState, event, this.queue);
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Flush the admissions and operations captured when this call begins.
|
|
271
|
+
* @returns A promise fulfilled when those attempts settle; it rejects with an admission or operation failure.
|
|
272
|
+
* @remarks Later admissions are outside this flush boundary. Batch gates in the captured work are released before waiting.
|
|
273
|
+
*/
|
|
274
|
+
async waitForIdle() {
|
|
275
|
+
await flushStorageEvents(this.eventState, this.queue);
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Stop accepting events, flush current work, and persist the remaining snapshot.
|
|
279
|
+
* @returns A promise fulfilled after the final snapshot write; a flush failure is logged, while a final snapshot failure rejects it.
|
|
280
|
+
*/
|
|
281
|
+
async stopWatching() {
|
|
282
|
+
this.eventState.acceptingEvents = false;
|
|
283
|
+
try {
|
|
284
|
+
await this.waitForIdle();
|
|
285
|
+
} catch (error) {
|
|
286
|
+
this.reportOperationFailure(error);
|
|
227
287
|
}
|
|
228
|
-
this.
|
|
229
|
-
|
|
288
|
+
await this._takeSnapshot();
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Check whether an unfinished event refers to this path or one of its ancestors.
|
|
292
|
+
* @param filename - The vault-relative path to check.
|
|
293
|
+
* @returns Whether a pending event names the path, an ancestor, or either side of a rename.
|
|
294
|
+
*/
|
|
295
|
+
hasPendingFileEvent(filename) {
|
|
296
|
+
return hasPendingStorageEvent(this.eventState, filename);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Check whether the path currently owns an unresolved batching gate.
|
|
300
|
+
* @param filename - The vault-relative path to check.
|
|
301
|
+
* @returns Whether a batch gate is present; this does not indicate whether a handler is still running.
|
|
302
|
+
*/
|
|
303
|
+
isWaiting(filename) {
|
|
304
|
+
return this._waitingMap.has(filename);
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Reuse or create the snapshot entry for a queued event.
|
|
308
|
+
* @param event - A file event or flush sentinel to retain.
|
|
309
|
+
* @param register - Whether to register path-ordering relationships for a file event; defaults to `true`.
|
|
310
|
+
* @returns The retained snapshot entry for the event.
|
|
311
|
+
*/
|
|
312
|
+
retainEvent(event, register = true) {
|
|
313
|
+
return retainFileEvent(this.eventState, event, register);
|
|
230
314
|
}
|
|
315
|
+
/**
|
|
316
|
+
* Log an operation failure which remains pending for retry or recovery.
|
|
317
|
+
* @param error - The failure reported by admission, processing, or persistence.
|
|
318
|
+
* @returns Nothing; the error is logged at notice and verbose levels.
|
|
319
|
+
*/
|
|
231
320
|
reportOperationFailure(error) {
|
|
232
321
|
this._log("Storage operation remains pending after a failure", LOG_LEVEL_NOTICE);
|
|
233
322
|
this._log(error, LOG_LEVEL_VERBOSE);
|
|
234
323
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
324
|
+
/**
|
|
325
|
+
* Record an unsettled attempt as failed and refresh the manager status.
|
|
326
|
+
* @param operation - The pending operation associated with the attempt.
|
|
327
|
+
* @param error - The failure to retain and report.
|
|
328
|
+
* @param attempt - The attempt to fail; defaults to the operation's current attempt.
|
|
329
|
+
* @returns Nothing; an already settled attempt is left unchanged.
|
|
330
|
+
*/
|
|
331
|
+
failOperation(operation, error, attempt = operation.attempt) {
|
|
332
|
+
if (!failFileEventAttempt(this.eventState, attempt, error)) return;
|
|
239
333
|
this.reportOperationFailure(error);
|
|
240
334
|
this.updateStatus();
|
|
241
335
|
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
this.
|
|
250
|
-
this.updateStatus();
|
|
251
|
-
fireAndForget(async () => {
|
|
252
|
-
try {
|
|
253
|
-
await this._takeSnapshot();
|
|
254
|
-
await this.runQueuedEvents();
|
|
255
|
-
} catch (error) {
|
|
256
|
-
this.failOperation(operation, error);
|
|
257
|
-
}
|
|
258
|
-
});
|
|
336
|
+
/**
|
|
337
|
+
* Capture attempts for a finite set of operations and start eligible retries.
|
|
338
|
+
* @param operations - The operations whose current attempts form the capture boundary.
|
|
339
|
+
* @param retryBefore - The latest failure sequence eligible for retry; defaults to no prior failure.
|
|
340
|
+
* @returns The operation-to-attempt map for this boundary.
|
|
341
|
+
*/
|
|
342
|
+
captureAttempts(operations, retryBefore = -1) {
|
|
343
|
+
return captureFileEventAttempts(operations, retryBefore, this.retry);
|
|
259
344
|
}
|
|
260
|
-
|
|
261
|
-
|
|
345
|
+
/**
|
|
346
|
+
* Mark the supplied operations for flushing and release their current batch gates.
|
|
347
|
+
* @param operations - The operations to release.
|
|
348
|
+
* @returns Nothing; no handler completion is awaited here.
|
|
349
|
+
*/
|
|
350
|
+
releaseOperations(operations) {
|
|
351
|
+
releaseFileEventBatches(this.batching, operations);
|
|
262
352
|
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
);
|
|
353
|
+
/**
|
|
354
|
+
* Release and await the attempts in the supplied capture.
|
|
355
|
+
* @param attempts - The operation-to-attempt capture to settle.
|
|
356
|
+
* @returns A promise for one success or failure result per captured attempt.
|
|
357
|
+
*/
|
|
358
|
+
waitForAttempts(attempts) {
|
|
359
|
+
return waitForFileEventAttempts(attempts, this.queue.release);
|
|
271
360
|
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
361
|
+
/**
|
|
362
|
+
* Resolve the current gate for a path as eligible to proceed.
|
|
363
|
+
* @param path - The event path whose gate should proceed.
|
|
364
|
+
* @returns Nothing; the gate is resolved and a snapshot is requested.
|
|
365
|
+
*/
|
|
366
|
+
_proceedWaiting(path) {
|
|
367
|
+
finishBatchWaiting(this.batching, path, true);
|
|
279
368
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
369
|
+
/**
|
|
370
|
+
* Resolve the current gate for a path as cancelled.
|
|
371
|
+
* @param path - The event path whose gate should be cancelled.
|
|
372
|
+
* @returns Nothing; a coalesced successor may take over the cancelled attempt.
|
|
373
|
+
*/
|
|
374
|
+
_cancelWaiting(path) {
|
|
375
|
+
finishBatchWaiting(this.batching, path, false);
|
|
283
376
|
}
|
|
284
377
|
/**
|
|
285
|
-
*
|
|
286
|
-
*
|
|
378
|
+
* Create a timed batch gate for an event, optionally inheriting a predecessor's wait start.
|
|
379
|
+
* @param path - The path used as the gate key.
|
|
380
|
+
* @param event - The event which owns the gate.
|
|
381
|
+
* @param since - Optional inherited time from which the maximum delay is measured.
|
|
382
|
+
* @returns The gate, including its deadline and proceed promise.
|
|
383
|
+
* @throws An error if another gate already exists for the path.
|
|
287
384
|
*/
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
for (const admission of admissions) admission.flushRequested = true;
|
|
291
|
-
for (const item of this.bufferedQueuedItems) this.retainEvent(item);
|
|
292
|
-
const operations = this.pendingOperations();
|
|
293
|
-
this.releaseOperations(operations);
|
|
294
|
-
const admitted = await Promise.allSettled(admissions.map((admission) => admission.completion));
|
|
295
|
-
const boundary = [.../* @__PURE__ */ new Set([...operations, ...admissions.flatMap((admission) => admission.operations)])];
|
|
296
|
-
this.releaseOperations(boundary);
|
|
297
|
-
fireAndForget(this.runQueuedEvents().catch((error) => this.reportOperationFailure(error)));
|
|
298
|
-
const results = await this.waitForOperations(boundary);
|
|
299
|
-
const admissionFailure = admitted.find((result) => result.status === "rejected");
|
|
300
|
-
if (admissionFailure?.status === "rejected") throw admissionFailure.reason;
|
|
301
|
-
const failure = results.find((result) => !result.ok);
|
|
302
|
-
if (failure?.ok === false) throw failure.error;
|
|
303
|
-
}
|
|
304
|
-
/** Stop watcher admission before draining or preserving accepted work. */
|
|
305
|
-
async stopWatching() {
|
|
306
|
-
this.acceptingEvents = false;
|
|
307
|
-
try {
|
|
308
|
-
await this.waitForIdle();
|
|
309
|
-
} catch (error) {
|
|
310
|
-
this.reportOperationFailure(error);
|
|
311
|
-
}
|
|
312
|
-
await this._takeSnapshot();
|
|
385
|
+
_addWaiting(path, event, since) {
|
|
386
|
+
return addBatchWaiting(this.batching, path, event, since);
|
|
313
387
|
}
|
|
314
388
|
/**
|
|
315
|
-
*
|
|
389
|
+
* Initialise predecessor ordering and obtain this operation's batch-gate result.
|
|
390
|
+
* @param operation - The operation whose predecessors and gate are being prepared.
|
|
391
|
+
* @returns A promise resolving to the gate's proceed or cancel result, not handler completion.
|
|
316
392
|
*/
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
if (waitInfo) {
|
|
320
|
-
waitInfo.canProceed.resolve(true);
|
|
321
|
-
waitInfo.deadline.dispose();
|
|
322
|
-
this._waitingMap.delete(key);
|
|
323
|
-
}
|
|
324
|
-
this.triggerTakeSnapshot();
|
|
393
|
+
initialiseOperation(operation) {
|
|
394
|
+
return initialiseFileEventBatch(this.batching, operation);
|
|
325
395
|
}
|
|
326
396
|
/**
|
|
327
|
-
*
|
|
397
|
+
* Run one attempt through gate preparation, ordering, handler dispatch, and snapshot completion.
|
|
398
|
+
* @param operation - The pending event operation to process.
|
|
399
|
+
* @param attempt - The captured attempt whose completion is being driven.
|
|
400
|
+
* @returns A promise fulfilled on successful completion; attempt failures are recorded and rethrown.
|
|
328
401
|
*/
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
if (waitInfo) {
|
|
332
|
-
waitInfo.canProceed.resolve(false);
|
|
333
|
-
waitInfo.deadline.dispose();
|
|
334
|
-
this._waitingMap.delete(key);
|
|
335
|
-
}
|
|
336
|
-
this.triggerTakeSnapshot();
|
|
402
|
+
async processOperation(operation, attempt) {
|
|
403
|
+
await processStorageEventAttempt(this.eventState, operation, attempt, this.attempts);
|
|
337
404
|
}
|
|
338
405
|
/**
|
|
339
|
-
*
|
|
340
|
-
* @param
|
|
341
|
-
* @
|
|
342
|
-
* @param waitedSince Optional waited since timestamp to calculate the remaining delay.
|
|
406
|
+
* Retain an event and await its current processing attempt.
|
|
407
|
+
* @param event - The already selected event to process.
|
|
408
|
+
* @returns A promise fulfilled when the attempt completes; a failed attempt rejects it.
|
|
343
409
|
*/
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
}
|
|
348
|
-
const resolver = promiseWithResolvers();
|
|
349
|
-
const now = Date.now();
|
|
350
|
-
const acceptedAt = this.operations.get(event)?.acceptedAt ?? now;
|
|
351
|
-
const since = waitedSince ?? acceptedAt;
|
|
352
|
-
const elapsed = now - since;
|
|
353
|
-
const maxDelay = this.batchSaveMaximumDelay * 1e3;
|
|
354
|
-
const remainingDelay = Math.max(0, maxDelay - elapsed);
|
|
355
|
-
const quietDelay = Math.max(0, this.batchSaveMinimumDelay * 1e3 - (now - acceptedAt));
|
|
356
|
-
const nextDelay = Math.min(remainingDelay, quietDelay);
|
|
357
|
-
if (elapsed >= maxDelay) {
|
|
358
|
-
this._log(`Processing ${key}: Batch save maximum delay already exceeded: ${event.type}`, LOG_LEVEL_DEBUG);
|
|
359
|
-
} else {
|
|
360
|
-
this._log(
|
|
361
|
-
`Processing ${key}: Adding waiting for batch save: ${event.type} (${nextDelay}ms)`,
|
|
362
|
-
LOG_LEVEL_DEBUG
|
|
363
|
-
);
|
|
364
|
-
}
|
|
365
|
-
const deadline = createDeferredAction(() => {
|
|
366
|
-
this._log(`Processing ${key}: Batch save timeout reached: ${event.type}`, LOG_LEVEL_DEBUG);
|
|
367
|
-
this._proceedWaiting(key);
|
|
368
|
-
}, scheduleStorageTimeout);
|
|
369
|
-
const waitInfo = {
|
|
370
|
-
since,
|
|
371
|
-
type: event.type,
|
|
372
|
-
event,
|
|
373
|
-
canProceed: resolver,
|
|
374
|
-
deadline
|
|
375
|
-
};
|
|
376
|
-
deadline.schedule(nextDelay);
|
|
377
|
-
this._waitingMap.set(key, waitInfo);
|
|
378
|
-
this.triggerTakeSnapshot();
|
|
379
|
-
return waitInfo;
|
|
410
|
+
async processFileEvent(event) {
|
|
411
|
+
const operation = this.retainEvent(event).operation;
|
|
412
|
+
await this.processOperation(operation, operation.attempt);
|
|
380
413
|
}
|
|
381
414
|
/**
|
|
382
|
-
*
|
|
415
|
+
* Persist the manager snapshot and optionally acknowledge one attempt in that snapshot.
|
|
416
|
+
* @param completion - Optional entry and attempt whose completion should be committed.
|
|
417
|
+
* @returns A promise for the serialised save; snapshot I/O failures reject it.
|
|
383
418
|
*/
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
const operation = entry.operation;
|
|
387
|
-
if (operation.started || operation.result) {
|
|
388
|
-
const result = await operation.completion.promise;
|
|
389
|
-
if (result.ok === false) throw result.error;
|
|
390
|
-
return;
|
|
391
|
-
}
|
|
392
|
-
operation.started = true;
|
|
393
|
-
const path = fei.args.file.path;
|
|
394
|
-
const relatedPath = fei.type === "RENAME" ? fei.args.oldPath : fei.args.renameTarget;
|
|
395
|
-
const paths = relatedPath ? [path, relatedPath] : [path];
|
|
396
|
-
const waiting = this._waitingMap.get(path);
|
|
397
|
-
let since = operation.acceptedAt;
|
|
398
|
-
for (const eventPath of paths) {
|
|
399
|
-
const previous = this.latestByPath.get(eventPath);
|
|
400
|
-
if (!previous || previous.result?.ok) continue;
|
|
401
|
-
const canReplace = waiting?.event === previous.event && !previous.flushRequested && (previous.event.type === fei.type || fei.type === "DELETE");
|
|
402
|
-
if (canReplace) {
|
|
403
|
-
since = waiting.since;
|
|
404
|
-
previous.successor = operation;
|
|
405
|
-
for (const dependency of previous.prerequisites) operation.prerequisites.add(dependency);
|
|
406
|
-
this._cancelWaiting(eventPath);
|
|
407
|
-
} else {
|
|
408
|
-
operation.prerequisites.add(previous);
|
|
409
|
-
if (this._waitingMap.get(eventPath)?.event === previous.event) this._proceedWaiting(eventPath);
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
if (this._waitingMap.get(path) === waiting && waiting) this._proceedWaiting(path);
|
|
413
|
-
for (const eventPath of paths) this.latestByPath.set(eventPath, operation);
|
|
414
|
-
if (operation.flushRequested) this.releaseOperations([...operation.prerequisites]);
|
|
415
|
-
const shouldWait = this.shouldBatchSave && !fei.skipBatchWait && !operation.flushRequested && (fei.type === "CREATE" || fei.type === "CHANGED");
|
|
416
|
-
const gate = shouldWait ? this._addWaiting(path, fei, since).canProceed.promise : Promise.resolve(true);
|
|
417
|
-
try {
|
|
418
|
-
await this._takeSnapshot();
|
|
419
|
-
const canProceed = await gate;
|
|
420
|
-
if (!canProceed) {
|
|
421
|
-
if (!operation.successor) throw new Error(`Storage operation cancelled without a successor: ${path}`);
|
|
422
|
-
const result = await operation.successor.completion.promise;
|
|
423
|
-
if (result.ok === false) throw result.error;
|
|
424
|
-
} else {
|
|
425
|
-
for (const prerequisite of operation.prerequisites) {
|
|
426
|
-
const result = await prerequisite.completion.promise;
|
|
427
|
-
if (result.ok === false) throw result.error;
|
|
428
|
-
}
|
|
429
|
-
const release = await this.concurrentProcessing.acquire();
|
|
430
|
-
try {
|
|
431
|
-
await this.requestProcessQueue(fei);
|
|
432
|
-
} finally {
|
|
433
|
-
release();
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
entry.completed = true;
|
|
437
|
-
try {
|
|
438
|
-
await this._takeSnapshot();
|
|
439
|
-
} catch (error) {
|
|
440
|
-
entry.completed = false;
|
|
441
|
-
throw error;
|
|
442
|
-
}
|
|
443
|
-
operation.result = { ok: true };
|
|
444
|
-
operation.completion.resolve(operation.result);
|
|
445
|
-
for (const eventPath of paths) {
|
|
446
|
-
if (this.latestByPath.get(eventPath) === operation) this.latestByPath.delete(eventPath);
|
|
447
|
-
}
|
|
448
|
-
} catch (error) {
|
|
449
|
-
if (this._waitingMap.get(path)?.event === fei) this._cancelWaiting(path);
|
|
450
|
-
this.failOperation(operation, error);
|
|
451
|
-
throw error;
|
|
452
|
-
} finally {
|
|
453
|
-
this.updateStatus();
|
|
454
|
-
}
|
|
419
|
+
persistSnapshot(completion) {
|
|
420
|
+
return persistFileEventSnapshot(this.eventState, this.buffer, this.snapshotIO, completion);
|
|
455
421
|
}
|
|
422
|
+
/**
|
|
423
|
+
* Wait for the next serialised snapshot write.
|
|
424
|
+
* @returns A promise fulfilled after persistence; save failures reject it.
|
|
425
|
+
*/
|
|
456
426
|
async _takeSnapshot() {
|
|
457
|
-
|
|
458
|
-
for (const waiting of this._waitingMap.values()) this.retainEvent(waiting.event);
|
|
459
|
-
const save = this.snapshotTail.then(async () => {
|
|
460
|
-
const entries = [...this.pendingSnapshot.values()];
|
|
461
|
-
const completed = entries.filter((entry) => entry.completed);
|
|
462
|
-
const snapshot = entries.filter((entry) => !entry.completed).map((entry) => entry.event);
|
|
463
|
-
await this._saveSnapshot(snapshot);
|
|
464
|
-
for (const entry of completed) this.pendingSnapshot.delete(entry.event);
|
|
465
|
-
this.updateStatus();
|
|
466
|
-
});
|
|
467
|
-
this.snapshotTail = save.catch(() => {
|
|
468
|
-
});
|
|
469
|
-
await save;
|
|
427
|
+
await this.persistSnapshot();
|
|
470
428
|
}
|
|
429
|
+
/**
|
|
430
|
+
* Load persisted events, dispatch them, and wait for their replay attempts.
|
|
431
|
+
* @returns A promise for restoration; storage or dispatch errors reject it, while failed attempt results are reported and retained.
|
|
432
|
+
*/
|
|
471
433
|
async _restoreFromSnapshot() {
|
|
472
|
-
|
|
473
|
-
if (snapShot && Array.isArray(snapShot) && snapShot.length > 0) {
|
|
474
|
-
this._log(`Restoring storage operation snapshot: ${snapShot.length} items`, LOG_LEVEL_VERBOSE);
|
|
475
|
-
this.bufferedQueuedItems = snapShot.map(
|
|
476
|
-
(event) => event.type === TYPE_SENTINEL_FLUSH ? event : { ...event, restoredFromPreviousRuntime: true, skipBatchWait: true }
|
|
477
|
-
);
|
|
478
|
-
this.updateStatus();
|
|
479
|
-
await this.runQueuedEvents({ waitForProcessing: true });
|
|
480
|
-
} else {
|
|
481
|
-
this._log(`No snapshot to restore`, LOG_LEVEL_VERBOSE);
|
|
482
|
-
}
|
|
434
|
+
await restoreStorageEvents(this.queue);
|
|
483
435
|
}
|
|
484
436
|
/**
|
|
485
|
-
* Dispatch
|
|
486
|
-
*
|
|
487
|
-
*
|
|
488
|
-
* Snapshot restoration requests completion so its caller can use the replay as
|
|
489
|
-
* a lifecycle boundary. In that mode, a sentinel also waits for every operation
|
|
490
|
-
* dispatched before it, preserving the ordering represented by the snapshot.
|
|
491
|
-
* An individual restored operation failure is logged but does not prevent the
|
|
492
|
-
* following Offline Scanner from reconciling the resulting current state.
|
|
437
|
+
* Dispatch events in the buffer and optionally wait for captured processing attempts.
|
|
438
|
+
* @param options - Queue-run options, including whether to wait for processing.
|
|
439
|
+
* @returns A promise for dispatch; with `waitForProcessing`, failed attempt results are reported rather than thrown as operation errors.
|
|
493
440
|
*/
|
|
494
441
|
async runQueuedEvents(options = {}) {
|
|
495
|
-
|
|
496
|
-
const accepted = this.pendingOperations();
|
|
497
|
-
if (!this.dispatching) {
|
|
498
|
-
const dispatch = async () => {
|
|
499
|
-
while (this.bufferedQueuedItems.length > 0) {
|
|
500
|
-
const event = this.bufferedQueuedItems.shift();
|
|
501
|
-
const entry = this.retainEvent(event);
|
|
502
|
-
if (event.type === TYPE_SENTINEL_FLUSH) {
|
|
503
|
-
const results = await this.waitForOperations(this.pendingOperations(entry.sequence));
|
|
504
|
-
if (results.every((result) => result.ok)) {
|
|
505
|
-
entry.completed = true;
|
|
506
|
-
try {
|
|
507
|
-
await this._takeSnapshot();
|
|
508
|
-
} catch (error) {
|
|
509
|
-
entry.completed = false;
|
|
510
|
-
this.reportOperationFailure(error);
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
} else if (!entry.operation.result) {
|
|
514
|
-
fireAndForget(this.processFileEvent(event).catch(() => {
|
|
515
|
-
}));
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
};
|
|
519
|
-
this.dispatching = dispatch().finally(() => {
|
|
520
|
-
this.dispatching = null;
|
|
521
|
-
});
|
|
522
|
-
}
|
|
523
|
-
await this.dispatching;
|
|
524
|
-
if (options.waitForProcessing) {
|
|
525
|
-
const results = await this.waitForOperations(accepted);
|
|
526
|
-
for (const result of results) {
|
|
527
|
-
if (result.ok === false) this.reportOperationFailure(result.error);
|
|
528
|
-
}
|
|
529
|
-
}
|
|
442
|
+
await runBufferedStorageEvents(this.eventState, this.queue, options);
|
|
530
443
|
}
|
|
531
|
-
|
|
532
|
-
|
|
444
|
+
/**
|
|
445
|
+
* Start a background snapshot write and report any persistence failure.
|
|
446
|
+
* @returns Nothing; the write is deliberately not awaited by the caller.
|
|
447
|
+
*/
|
|
448
|
+
_triggerTakeSnapshot() {
|
|
449
|
+
fireAndForget(() => this._takeSnapshot().catch((error) => this.reportOperationFailure(error)));
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Throttled callback for requesting a background snapshot write.
|
|
453
|
+
* @returns The callback bound to `_triggerTakeSnapshot` with a 100 ms throttle interval.
|
|
454
|
+
*/
|
|
455
|
+
triggerTakeSnapshot = throttle(() => this._triggerTakeSnapshot(), 100);
|
|
456
|
+
/**
|
|
457
|
+
* Track a handler dispatch in status and restore the processing count in a `finally` block.
|
|
458
|
+
* @param event - The event passed to the host processing hook.
|
|
459
|
+
* @returns A promise fulfilled after handling; handler or status-update failures reject it.
|
|
460
|
+
*/
|
|
461
|
+
async requestProcessQueue(event) {
|
|
533
462
|
try {
|
|
534
463
|
this.processingCount++;
|
|
535
464
|
this.updateStatus();
|
|
536
|
-
await this.handleFileEvent(
|
|
465
|
+
await this.handleFileEvent(event);
|
|
537
466
|
} finally {
|
|
538
467
|
this.processingCount--;
|
|
539
468
|
this.updateStatus();
|
|
540
469
|
}
|
|
541
470
|
}
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
}
|
|
551
|
-
isWaiting(filename) {
|
|
552
|
-
return this._waitingMap.has(filename);
|
|
553
|
-
}
|
|
554
|
-
async handleFileEvent(queue) {
|
|
555
|
-
const file = queue.args.file;
|
|
556
|
-
await serialized(`handleFile:${file.path}`, async () => {
|
|
557
|
-
if (queue.cancelled) throw new Error(`Storage operation has no confirmed result: ${file.path}`);
|
|
558
|
-
if (queue.type === "INTERNAL" || file.isInternal) {
|
|
559
|
-
const handler = this.fileProcessing.processOptionalFileEventWithResult;
|
|
560
|
-
if (handler && handler.hasHandlers !== false) {
|
|
561
|
-
const operation = this.operations.get(queue);
|
|
562
|
-
let whenFlushRequested;
|
|
563
|
-
if (operation) {
|
|
564
|
-
operation.flushSignal ??= promiseWithResolvers();
|
|
565
|
-
if (operation.flushRequested) operation.flushSignal.resolve();
|
|
566
|
-
whenFlushRequested = operation.flushSignal.promise;
|
|
567
|
-
}
|
|
568
|
-
const outcome = await handler(file.path, { whenFlushRequested });
|
|
569
|
-
if (outcome.kind === "veto") {
|
|
570
|
-
throw new Error(`Optional storage operation declined: ${file.path} (${outcome.value})`);
|
|
571
|
-
}
|
|
572
|
-
} else {
|
|
573
|
-
await this.fileProcessing.processOptionalFileEvent(file.path);
|
|
574
|
-
}
|
|
575
|
-
} else if (!await this.fileProcessing.processFileEvent(queue)) {
|
|
576
|
-
throw new Error(`Storage operation failed: ${file.path}`);
|
|
577
|
-
}
|
|
578
|
-
});
|
|
579
|
-
this.updateStatus();
|
|
471
|
+
/**
|
|
472
|
+
* Delegate one event to the shared file-processing handler.
|
|
473
|
+
* @param event - The event to process.
|
|
474
|
+
* @returns A promise fulfilled after handling; processing failures propagate to the attempt.
|
|
475
|
+
* @remarks Protected so hosts can override event handling while retaining the queue lifecycle.
|
|
476
|
+
*/
|
|
477
|
+
async handleFileEvent(event) {
|
|
478
|
+
await handleStorageFileEvent(event, this.handler);
|
|
580
479
|
}
|
|
581
|
-
|
|
582
|
-
|
|
480
|
+
/**
|
|
481
|
+
* Cancel the batch gate associated with a relative event's path.
|
|
482
|
+
* @param event - The event whose path identifies the gate.
|
|
483
|
+
* @returns Nothing; cancelling the gate does not itself complete the operation.
|
|
484
|
+
*/
|
|
485
|
+
cancelRelativeEvent(event) {
|
|
486
|
+
this._cancelWaiting(event.args.file.path);
|
|
583
487
|
}
|
|
584
488
|
/**
|
|
585
|
-
*
|
|
489
|
+
* Wait for stored restoration to finish, then register the host watcher callbacks.
|
|
490
|
+
* @returns A promise fulfilled when watcher registration finishes; a restoration failure prevents registration and rejects it.
|
|
586
491
|
*/
|
|
587
492
|
async beginWatch() {
|
|
588
493
|
await this.snapShotRestored;
|
|
@@ -596,82 +501,82 @@ class StorageEventManagerBase extends StorageEventManager {
|
|
|
596
501
|
});
|
|
597
502
|
}
|
|
598
503
|
/**
|
|
599
|
-
*
|
|
504
|
+
* Admit an editor change for a selected file with an active batch gate.
|
|
505
|
+
* @typeParam TEditor - The platform editor type carried by the watcher callback.
|
|
506
|
+
* @typeParam TInfo - The platform editor-change payload type.
|
|
507
|
+
* @param editor - The editor callback value, retained for the host watcher signature.
|
|
508
|
+
* @param info - The editor-change envelope used to resolve file, path, and cached text.
|
|
509
|
+
* @returns Nothing; invalid payloads, disabled batching, active processing, and absent gates are skipped, and admission is not awaited.
|
|
510
|
+
* @remarks Protected so host subclasses can customise editor watcher handling.
|
|
600
511
|
*/
|
|
601
512
|
watchEditorChange(editor, info) {
|
|
602
|
-
if (
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
if (
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
if (!this.shouldBatchSave) {
|
|
609
|
-
return;
|
|
610
|
-
}
|
|
611
|
-
if (!("file" in info)) {
|
|
612
|
-
return;
|
|
613
|
-
}
|
|
614
|
-
const file = info?.file;
|
|
615
|
-
if (!file) return;
|
|
616
|
-
const path = this.adapter.typeGuard.isFile(file) ? file.path : info.path;
|
|
617
|
-
if (!path) return;
|
|
618
|
-
if (this.storageAccess.isFileProcessing(path)) {
|
|
619
|
-
return;
|
|
620
|
-
}
|
|
621
|
-
if (!this.isWaiting(path)) {
|
|
622
|
-
return;
|
|
623
|
-
}
|
|
624
|
-
const data = info?.data;
|
|
625
|
-
const fi = {
|
|
513
|
+
if (!hasEditorChangePath(info) || !this.shouldBatchSave) return;
|
|
514
|
+
const change = readEditorFileChange(info, (file) => this.adapter.typeGuard.isFile(file));
|
|
515
|
+
if (!change) return;
|
|
516
|
+
if (this.storageAccess.isFileProcessing(change.path)) return;
|
|
517
|
+
if (!this.isWaiting(change.path)) return;
|
|
518
|
+
const event = {
|
|
626
519
|
type: "CHANGED",
|
|
627
|
-
file: this.adapter.converter.toFileInfo(file),
|
|
628
|
-
cachedData: data
|
|
520
|
+
file: this.adapter.converter.toFileInfo(change.file),
|
|
521
|
+
cachedData: change.data
|
|
629
522
|
};
|
|
630
|
-
void this.appendQueue([
|
|
523
|
+
void this.appendQueue([event]);
|
|
631
524
|
}
|
|
525
|
+
/**
|
|
526
|
+
* Forward a host create notification to facade admission.
|
|
527
|
+
* @typeParam TFile - The host file payload type.
|
|
528
|
+
* @typeParam TCtx - The host watcher context type.
|
|
529
|
+
* @param file - The untrusted host notification payload.
|
|
530
|
+
* @param ctx - Optional host context forwarded to admission.
|
|
531
|
+
* @returns Nothing; unrecognised payloads and paths reported as already processing are skipped, and admission is not awaited.
|
|
532
|
+
* @remarks This remains a protected override point; the base implementation shares validation and conversion through `forwardVaultEvent`.
|
|
533
|
+
*/
|
|
632
534
|
watchVaultCreate(file, ctx) {
|
|
633
|
-
|
|
634
|
-
const path = file.path;
|
|
635
|
-
if (this.storageAccess.isFileProcessing(path)) {
|
|
636
|
-
return;
|
|
637
|
-
}
|
|
638
|
-
const fileInfo = this.adapter.converter.toFileInfo(file);
|
|
639
|
-
void this.appendQueue([{ type: "CREATE", file: fileInfo }], ctx);
|
|
535
|
+
forwardVaultEvent({ type: "CREATE", file }, ctx, this.watching);
|
|
640
536
|
}
|
|
537
|
+
/**
|
|
538
|
+
* Forward a host change notification to facade admission.
|
|
539
|
+
* @typeParam TFile - The host file payload type.
|
|
540
|
+
* @typeParam TCtx - The host watcher context type.
|
|
541
|
+
* @param file - The untrusted host notification payload.
|
|
542
|
+
* @param ctx - Optional host context forwarded to admission.
|
|
543
|
+
* @returns Nothing; unrecognised payloads and paths reported as already processing are skipped, and admission is not awaited.
|
|
544
|
+
* @remarks This remains a protected override point; the base implementation shares validation and conversion through `forwardVaultEvent`.
|
|
545
|
+
*/
|
|
641
546
|
watchVaultChange(file, ctx) {
|
|
642
|
-
|
|
643
|
-
const path = file.path;
|
|
644
|
-
if (this.storageAccess.isFileProcessing(path)) {
|
|
645
|
-
return;
|
|
646
|
-
}
|
|
647
|
-
const fileInfo = this.adapter.converter.toFileInfo(file);
|
|
648
|
-
void this.appendQueue([{ type: "CHANGED", file: fileInfo }], ctx);
|
|
547
|
+
forwardVaultEvent({ type: "CHANGED", file }, ctx, this.watching);
|
|
649
548
|
}
|
|
549
|
+
/**
|
|
550
|
+
* Forward a host delete notification to facade admission.
|
|
551
|
+
* @typeParam TFile - The host file payload type.
|
|
552
|
+
* @typeParam TCtx - The host watcher context type.
|
|
553
|
+
* @param file - The untrusted host notification payload.
|
|
554
|
+
* @param ctx - Optional host context forwarded to admission.
|
|
555
|
+
* @returns Nothing; unrecognised payloads and paths reported as already processing are skipped, and admission is not awaited.
|
|
556
|
+
* @remarks This remains a protected override point; the base implementation shares validation and conversion through `forwardVaultEvent`.
|
|
557
|
+
*/
|
|
650
558
|
watchVaultDelete(file, ctx) {
|
|
651
|
-
|
|
652
|
-
const path = file.path;
|
|
653
|
-
if (this.storageAccess.isFileProcessing(path)) {
|
|
654
|
-
return;
|
|
655
|
-
}
|
|
656
|
-
const fileInfo = this.adapter.converter.toFileInfo(file, true);
|
|
657
|
-
void this.appendQueue([{ type: "DELETE", file: fileInfo }], ctx);
|
|
559
|
+
forwardVaultEvent({ type: "DELETE", file }, ctx, this.watching);
|
|
658
560
|
}
|
|
561
|
+
/**
|
|
562
|
+
* Forward a host rename as one operation with its source path.
|
|
563
|
+
* @typeParam TFile - The host file payload type.
|
|
564
|
+
* @typeParam TCtx - The host watcher context type.
|
|
565
|
+
* @param file - The untrusted host notification payload.
|
|
566
|
+
* @param oldPath - The path the file was renamed from.
|
|
567
|
+
* @param ctx - Optional host context forwarded to admission.
|
|
568
|
+
* @returns Nothing; unrecognised payloads are skipped, and admission is not awaited.
|
|
569
|
+
* @remarks Rename bypasses processing-path suppression and batching. This protected hook remains overridable by host subclasses.
|
|
570
|
+
*/
|
|
659
571
|
watchVaultRename(file, oldPath, ctx) {
|
|
660
|
-
|
|
661
|
-
const fileInfo = this.adapter.converter.toFileInfo(file);
|
|
662
|
-
void this.appendQueue(
|
|
663
|
-
[
|
|
664
|
-
{
|
|
665
|
-
type: "RENAME",
|
|
666
|
-
file: fileInfo,
|
|
667
|
-
oldPath,
|
|
668
|
-
skipBatchWait: true
|
|
669
|
-
}
|
|
670
|
-
],
|
|
671
|
-
ctx
|
|
672
|
-
);
|
|
673
|
-
}
|
|
572
|
+
forwardVaultEvent({ type: "RENAME", file, oldPath }, ctx, this.watching);
|
|
674
573
|
}
|
|
574
|
+
/**
|
|
575
|
+
* Route a raw internal-file callback to the host-specific raw-event hook.
|
|
576
|
+
* @param path - The vault-relative path reported by the host watcher.
|
|
577
|
+
* @returns Nothing; while ignore-file handling is enabled, the target check is started before the hook.
|
|
578
|
+
* @remarks Protected so platform subclasses can provide their raw-event policy.
|
|
579
|
+
*/
|
|
675
580
|
watchVaultRawEvents(path) {
|
|
676
581
|
if (this.storageAccess.isFileProcessing(path)) {
|
|
677
582
|
return;
|
|
@@ -683,6 +588,11 @@ class StorageEventManagerBase extends StorageEventManager {
|
|
|
683
588
|
void this._watchVaultRawEvents(path);
|
|
684
589
|
}
|
|
685
590
|
}
|
|
591
|
+
/**
|
|
592
|
+
* Host extension point for platform-specific raw internal-file handling.
|
|
593
|
+
* @param path - The vault-relative internal-file path to inspect.
|
|
594
|
+
* @returns A resolved promise in the base implementation; subclasses may perform asynchronous handling.
|
|
595
|
+
*/
|
|
686
596
|
async _watchVaultRawEvents(path) {
|
|
687
597
|
}
|
|
688
598
|
}
|