@vrtmrz/livesync-commonlib 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- 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 +1 -1
- package/dist/managers/EntryManager/EntryManagerImpls.js +1 -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/p2p/P2PService.d.ts +10 -1
- package/dist/p2p/P2PService.js +25 -2
- package/dist/p2p/index.d.ts +4 -1
- package/dist/p2p/index.js +2 -0
- package/dist/p2p/p2pDiagnostics.d.ts +35 -0
- package/dist/p2p/p2pDiagnostics.js +76 -0
- package/dist/pouchdb/ReplicatorShim.batch.d.ts +30 -0
- package/dist/pouchdb/ReplicatorShim.batch.js +62 -0
- package/dist/pouchdb/ReplicatorShim.d.ts +14 -1
- package/dist/pouchdb/ReplicatorShim.js +64 -80
- package/dist/replication/trystero/P2PLogCollector.d.ts +12 -0
- package/dist/replication/trystero/P2PLogCollector.js +107 -72
- package/dist/replication/trystero/P2PRoomSessionOwner.d.ts +4 -0
- package/dist/replication/trystero/P2PRoomSessionOwner.js +39 -2
- package/dist/replication/trystero/TrysteroReplicator.d.ts +21 -24
- package/dist/replication/trystero/TrysteroReplicator.js +191 -69
- package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +11 -0
- package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +9 -0
- package/dist/replication/trystero/p2pReplicationDiagnostics.js +51 -0
- package/dist/replication/trystero/p2pReplicationProgress.d.ts +15 -0
- package/dist/replication/trystero/p2pReplicationProgress.js +37 -0
- package/dist/replication/trystero/types.d.ts +3 -0
- 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/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 +119 -182
- package/dist/serviceModules/ServiceFileHandlerBase.js +182 -1402
- package/dist/services/base/APIService.d.ts +10 -0
- package/dist/services/base/APIService.js +13 -0
- package/dist/services/base/IService.d.ts +2 -0
- package/docs/conflict-resolution.md +3 -1
- package/docs/development.md +36 -0
- package/docs/journal-receive-recovery.md +7 -4
- package/docs/offline-scanner.md +5 -1
- package/docs/p2p-transport-lifecycle.md +125 -11
- package/docs/releasing.md +6 -0
- package/docs/storage-events-and-reflection.md +203 -19
- package/package.json +2 -2
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { promiseWithResolvers } from "octagonal-wheels/promises";
|
|
2
|
+
function createFileEventAttempt(reconcile = false) {
|
|
3
|
+
return { completion: promiseWithResolvers(), started: false, reconcile };
|
|
4
|
+
}
|
|
5
|
+
function assertFileEventAdmission(attempt) {
|
|
6
|
+
if (attempt.admissionFailure) throw attempt.admissionFailure.error;
|
|
7
|
+
}
|
|
8
|
+
function canRetryFileEvent(event) {
|
|
9
|
+
return event.type !== "INTERNAL" && !event.args.file.isInternal;
|
|
10
|
+
}
|
|
11
|
+
function getFileEventPaths(event) {
|
|
12
|
+
const related = event.type === "RENAME" ? event.args.oldPath : event.args.renameTarget;
|
|
13
|
+
return related ? [event.args.file.path, related] : [event.args.file.path];
|
|
14
|
+
}
|
|
15
|
+
function isFileEventRetryEligible(operation, retryBefore) {
|
|
16
|
+
const attempt = operation.attempt;
|
|
17
|
+
return attempt.result?.ok === false && (attempt.failureSequence ?? Number.POSITIVE_INFINITY) <= retryBefore && canRetryFileEvent(operation.event);
|
|
18
|
+
}
|
|
19
|
+
function planFileEventAttempts(operations, retryBefore = -1) {
|
|
20
|
+
const captured = /* @__PURE__ */ new Map();
|
|
21
|
+
const retries = /* @__PURE__ */ new Map();
|
|
22
|
+
const pending = [...operations];
|
|
23
|
+
for (let index = 0; index < pending.length; index++) {
|
|
24
|
+
const operation = pending[index];
|
|
25
|
+
if (captured.has(operation)) continue;
|
|
26
|
+
let attempt = operation.attempt;
|
|
27
|
+
if (isFileEventRetryEligible(operation, retryBefore)) {
|
|
28
|
+
attempt = createFileEventAttempt(true);
|
|
29
|
+
attempt.retryBefore = retryBefore;
|
|
30
|
+
retries.set(operation, attempt);
|
|
31
|
+
if (operation.initialised) {
|
|
32
|
+
for (const previous of operation.prerequisites) pending.push(previous);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
captured.set(operation, attempt);
|
|
36
|
+
}
|
|
37
|
+
for (const [operation, attempt] of retries) {
|
|
38
|
+
if (operation.initialised) {
|
|
39
|
+
attempt.prerequisites = new Map(
|
|
40
|
+
[...operation.prerequisites].map((previous) => [previous, captured.get(previous)])
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return { captured, retries };
|
|
45
|
+
}
|
|
46
|
+
function planFileEventPredecessors(operation, waiting) {
|
|
47
|
+
let since = operation.acceptedAt;
|
|
48
|
+
const actions = [];
|
|
49
|
+
for (const [path, previous] of operation.predecessors) {
|
|
50
|
+
if (previous.attempt.result?.ok) continue;
|
|
51
|
+
const coalesce = waiting?.event === previous.event && !previous.flushRequested && (previous.event.type === operation.event.type || operation.event.type === "DELETE");
|
|
52
|
+
if (coalesce) since = waiting.since;
|
|
53
|
+
actions.push({ kind: coalesce ? "coalesce" : "depend", path, previous });
|
|
54
|
+
}
|
|
55
|
+
return { since, actions };
|
|
56
|
+
}
|
|
57
|
+
function assertSuccessfulFileEvents(results) {
|
|
58
|
+
const failure = results.find((result) => !result.ok);
|
|
59
|
+
if (failure?.ok === false) throw failure.error;
|
|
60
|
+
}
|
|
61
|
+
export {
|
|
62
|
+
assertFileEventAdmission,
|
|
63
|
+
assertSuccessfulFileEvents,
|
|
64
|
+
canRetryFileEvent,
|
|
65
|
+
createFileEventAttempt,
|
|
66
|
+
getFileEventPaths,
|
|
67
|
+
planFileEventAttempts,
|
|
68
|
+
planFileEventPredecessors
|
|
69
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Own each attempt's dependency waits, handler invocation, and terminal settlement.
|
|
3
|
+
* Ordered predecessors need only settle; related prerequisites must succeed before processing starts.
|
|
4
|
+
*/
|
|
5
|
+
import type { FileEventItem } from "../../common/types.js";
|
|
6
|
+
import type { FileProcessingService } from "../../services/base/FileProcessingService.js";
|
|
7
|
+
import { type SemaphoreObject } from "octagonal-wheels/concurrency/semaphore";
|
|
8
|
+
import { type FileEventAttempt, type OperationResult, type PendingFileEvent } from "./operations.js";
|
|
9
|
+
import { type SnapshotCompletion, type StorageEventNotifications, type StorageEventState } from "./state.js";
|
|
10
|
+
/** Host callbacks which connect attempt ownership to batching, snapshots, and file processing. */
|
|
11
|
+
export interface StorageEventAttemptEffects extends StorageEventNotifications {
|
|
12
|
+
/** Capture attempts for dependencies at an optional failure cutoff. */
|
|
13
|
+
capture(operations: readonly PendingFileEvent[], retryBefore?: number): Map<PendingFileEvent, FileEventAttempt>;
|
|
14
|
+
/** Release batch gates before initialisation or predecessor processing can admit a successor. */
|
|
15
|
+
release(operations: readonly PendingFileEvent[]): void;
|
|
16
|
+
/** Wait for captured attempts and return their terminal outcomes. */
|
|
17
|
+
wait(attempts: Map<PendingFileEvent, FileEventAttempt>): Promise<OperationResult[]>;
|
|
18
|
+
/** Initialise dependency links and report whether this operation still owns processing. */
|
|
19
|
+
initialise(operation: PendingFileEvent): Promise<boolean>;
|
|
20
|
+
/** Persist current intent before handler execution. */
|
|
21
|
+
takeSnapshot(): Promise<void>;
|
|
22
|
+
/** Persist the completion acknowledgement for this exact snapshot entry and attempt. */
|
|
23
|
+
completeSnapshot(completion: SnapshotCompletion): Promise<void>;
|
|
24
|
+
/** Obtain the host semaphore which limits concurrent file handling. */
|
|
25
|
+
semaphore(): SemaphoreObject;
|
|
26
|
+
/** Submit an event to the host file-processing queue. */
|
|
27
|
+
requestProcessQueue(event: FileEventItem): Promise<void>;
|
|
28
|
+
/** Cancel any batch wait owned by the event after its attempt fails. */
|
|
29
|
+
cancelWaiting(event: FileEventItem): void;
|
|
30
|
+
/** Settle an operation attempt as failed. */
|
|
31
|
+
fail(operation: PendingFileEvent, error: unknown, attempt: FileEventAttempt): void;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Run one attempt or join an attempt already in progress.
|
|
35
|
+
* @param state - The manager state owning the operation, current attempt, and snapshot entry.
|
|
36
|
+
* @param operation - The durable operation whose handler is being run.
|
|
37
|
+
* @param attempt - The specific attempt to start or observe.
|
|
38
|
+
* @param effects - Host callbacks for snapshots, dependencies, processing, failure, and status.
|
|
39
|
+
* @returns A promise which resolves after the attempt's completion-snapshot step and success settlement, or after
|
|
40
|
+
* a joined attempt settles successfully; rejects with the attempt failure otherwise.
|
|
41
|
+
* @remarks A new attempt is marked started before its initial intent snapshot. Admission is checked around awaited
|
|
42
|
+
* gates and before completion; completion is settled only after completeSnapshot returns. On failure, its batch wait
|
|
43
|
+
* is cancelled, the attempt is failed, and the error is rethrown. Status is refreshed in either case.
|
|
44
|
+
*/
|
|
45
|
+
export declare function processStorageEventAttempt(state: StorageEventState, operation: PendingFileEvent, attempt: FileEventAttempt, effects: StorageEventAttemptEffects): Promise<void>;
|
|
46
|
+
/** Live host service lookups used by the final file-event handler. */
|
|
47
|
+
export interface StorageEventHandlerEffects {
|
|
48
|
+
/** Resolve the current file-processing service when the event is handled. */
|
|
49
|
+
processing(): FileProcessingService;
|
|
50
|
+
/** Resolve the operation associated with the original or transient reconciliation event. */
|
|
51
|
+
operation(event: FileEventItem): PendingFileEvent | undefined;
|
|
52
|
+
/** Refresh host status after handler completion. */
|
|
53
|
+
updateStatus(): void;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Serialise one file-event handler by path and select ordinary or optional-provider processing.
|
|
57
|
+
* @param event - The file event passed to the host handler.
|
|
58
|
+
* @param effects - Live host processing, operation, and status lookups.
|
|
59
|
+
* @returns A promise which resolves after the keyed lock is released and status is updated on success.
|
|
60
|
+
* @remarks A cancelled event, optional-provider veto, or false ordinary-handler result rejects. The keyed lock is
|
|
61
|
+
* released by withLock on either outcome; this function does not own snapshot persistence or attempt settlement.
|
|
62
|
+
*/
|
|
63
|
+
export declare function handleStorageFileEvent(event: FileEventItem, effects: StorageEventHandlerEffects): Promise<void>;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createReconcileEvent } from "../../common/models/fileaccess.definition.js";
|
|
2
|
+
import { withLock } from "octagonal-wheels/concurrency/lock";
|
|
3
|
+
import { withSemaphore } from "octagonal-wheels/concurrency/semaphore";
|
|
4
|
+
import { promiseWithResolvers } from "octagonal-wheels/promises";
|
|
5
|
+
import {
|
|
6
|
+
canRetryFileEvent,
|
|
7
|
+
assertFileEventAdmission,
|
|
8
|
+
assertSuccessfulFileEvents
|
|
9
|
+
} from "./operations.js";
|
|
10
|
+
import {
|
|
11
|
+
completeFileEventAttempt,
|
|
12
|
+
pendingFileOperations
|
|
13
|
+
} from "./state.js";
|
|
14
|
+
function prepareAttempt(state, operation, attempt, effects) {
|
|
15
|
+
attempt.orderedPredecessors ??= operation.barrierBefore === void 0 ? /* @__PURE__ */ new Map() : effects.capture(pendingFileOperations(state, operation.barrierBefore));
|
|
16
|
+
effects.release([...attempt.orderedPredecessors.keys()]);
|
|
17
|
+
const gate = operation.initialised ? Promise.resolve(true) : effects.initialise(operation);
|
|
18
|
+
attempt.prerequisites ??= effects.capture(
|
|
19
|
+
[...operation.prerequisites],
|
|
20
|
+
canRetryFileEvent(operation.event) ? attempt.retryBefore ?? operation.failureBoundary : -1
|
|
21
|
+
);
|
|
22
|
+
return gate;
|
|
23
|
+
}
|
|
24
|
+
async function executeAttempt(state, operation, attempt, canProceed, effects) {
|
|
25
|
+
if (!canProceed) {
|
|
26
|
+
if (!attempt.successor)
|
|
27
|
+
throw new Error(`Storage operation cancelled without a successor: ${operation.event.args.file.path}`);
|
|
28
|
+
assertSuccessfulFileEvents([await attempt.successor.completion.promise]);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
await effects.wait(attempt.orderedPredecessors);
|
|
32
|
+
assertSuccessfulFileEvents(await effects.wait(attempt.prerequisites));
|
|
33
|
+
await withSemaphore(effects.semaphore(), async () => {
|
|
34
|
+
assertFileEventAdmission(attempt);
|
|
35
|
+
const event = attempt.reconcile ? createReconcileEvent(operation.event) : operation.event;
|
|
36
|
+
state.operations.set(event, operation);
|
|
37
|
+
await effects.requestProcessQueue(event);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
async function processStorageEventAttempt(state, operation, attempt, effects) {
|
|
41
|
+
if (attempt.started || attempt.result) {
|
|
42
|
+
assertSuccessfulFileEvents([await attempt.completion.promise]);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
attempt.started = true;
|
|
46
|
+
const entry = state.pendingSnapshot.get(operation.event);
|
|
47
|
+
try {
|
|
48
|
+
const gate = prepareAttempt(state, operation, attempt, effects);
|
|
49
|
+
await effects.takeSnapshot();
|
|
50
|
+
assertFileEventAdmission(attempt);
|
|
51
|
+
const canProceed = await gate;
|
|
52
|
+
assertFileEventAdmission(attempt);
|
|
53
|
+
await executeAttempt(state, operation, attempt, canProceed, effects);
|
|
54
|
+
assertFileEventAdmission(attempt);
|
|
55
|
+
await effects.completeSnapshot({ entry, attempt });
|
|
56
|
+
completeFileEventAttempt(state, operation, attempt);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
effects.cancelWaiting(operation.event);
|
|
59
|
+
effects.fail(operation, error, attempt);
|
|
60
|
+
throw error;
|
|
61
|
+
} finally {
|
|
62
|
+
effects.updateStatus();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function flushSignal(operation) {
|
|
66
|
+
if (!operation) return void 0;
|
|
67
|
+
operation.flushSignal ??= promiseWithResolvers();
|
|
68
|
+
if (operation.flushRequested) operation.flushSignal.resolve();
|
|
69
|
+
return operation.flushSignal.promise;
|
|
70
|
+
}
|
|
71
|
+
async function processOptionalEvent(event, effects) {
|
|
72
|
+
const path = event.args.file.path;
|
|
73
|
+
const handler = effects.processing().processOptionalFileEventWithResult;
|
|
74
|
+
if (handler && handler.hasHandlers !== false) {
|
|
75
|
+
const outcome = await handler(path, { whenFlushRequested: flushSignal(effects.operation(event)) });
|
|
76
|
+
if (outcome.kind === "veto") throw new Error(`Optional storage operation declined: ${path} (${outcome.value})`);
|
|
77
|
+
} else {
|
|
78
|
+
await effects.processing().processOptionalFileEvent(path);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function handleStorageFileEvent(event, effects) {
|
|
82
|
+
const file = event.args.file;
|
|
83
|
+
await withLock(`handleFile:${file.path}`, async () => {
|
|
84
|
+
if (event.cancelled) throw new Error(`Storage operation has no confirmed result: ${file.path}`);
|
|
85
|
+
if (event.type === "INTERNAL" || file.isInternal) await processOptionalEvent(event, effects);
|
|
86
|
+
else if (!await effects.processing().processFileEvent(event))
|
|
87
|
+
throw new Error(`Storage operation failed: ${file.path}`);
|
|
88
|
+
});
|
|
89
|
+
effects.updateStatus();
|
|
90
|
+
}
|
|
91
|
+
export {
|
|
92
|
+
handleStorageFileEvent,
|
|
93
|
+
processStorageEventAttempt
|
|
94
|
+
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coordinate buffer admission, finite flushes, sentinel dispatch, and snapshot restoration.
|
|
3
|
+
* Attempt processing and persistence remain delegated through explicit host effects.
|
|
4
|
+
*/
|
|
5
|
+
import type { FileEventItem } from "../../common/types.js";
|
|
6
|
+
import type { LogFunction } from "../../services/lib/logUtils.js";
|
|
7
|
+
import { type FileEventAttempt, type OperationResult, type PendingFileEvent } from "./operations.js";
|
|
8
|
+
import { type QueuedFileEvent, type RunQueuedEventsOptions, type StorageEventBuffer, type StorageEventNotifications, type StorageEventState } from "./state.js";
|
|
9
|
+
/** Host callbacks used by queue ownership, dispatch, finite flush, and restoration. */
|
|
10
|
+
export interface StorageEventQueueEffects extends StorageEventNotifications {
|
|
11
|
+
/** Host-owned event buffer used by admission, dispatch, and retry. */
|
|
12
|
+
readonly buffer: StorageEventBuffer;
|
|
13
|
+
/** Host logger for restoration diagnostics. */
|
|
14
|
+
log: LogFunction;
|
|
15
|
+
/** Persist the current intent snapshot. */
|
|
16
|
+
takeSnapshot(): Promise<void>;
|
|
17
|
+
/** Load the prior runtime's saved event intent, if any. */
|
|
18
|
+
loadSnapshot(): Promise<QueuedFileEvent[] | null>;
|
|
19
|
+
/** Enter the host event-processing route for one file event. */
|
|
20
|
+
processFileEvent(event: FileEventItem): Promise<void>;
|
|
21
|
+
/** Run the shared queue dispatcher, optionally waiting for processing. */
|
|
22
|
+
runQueuedEvents(options?: RunQueuedEventsOptions): Promise<void>;
|
|
23
|
+
/** Capture attempts at the supplied failure boundary. */
|
|
24
|
+
capture(operations: readonly PendingFileEvent[], retryBefore?: number): Map<PendingFileEvent, FileEventAttempt>;
|
|
25
|
+
/** Release batch gates associated with the supplied operations. */
|
|
26
|
+
release(operations: readonly PendingFileEvent[]): void;
|
|
27
|
+
/** Wait for a captured set and return results in its map order. */
|
|
28
|
+
wait(attempts: Map<PendingFileEvent, FileEventAttempt>): Promise<OperationResult[]>;
|
|
29
|
+
/** Settle and report a failure for one operation attempt. */
|
|
30
|
+
fail(operation: PendingFileEvent, error: unknown, attempt: FileEventAttempt): void;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Append an accepted event and schedule its snapshot and queue dispatch.
|
|
34
|
+
* @param state - The manager state which owns the retained intent and operation attempt.
|
|
35
|
+
* @param event - The accepted file event to enqueue.
|
|
36
|
+
* @param effects - Host buffer, persistence, dispatch, status, and failure callbacks.
|
|
37
|
+
* @returns Nothing; appends a sentinel before DELETE/RENAME, appends the event, and refreshes status synchronously.
|
|
38
|
+
* @remarks Persistence and dispatch run in a background task whose failures are handled here rather than returned.
|
|
39
|
+
* If that task fails while a handler is active, its error is recorded on that attempt and its operation is released
|
|
40
|
+
* so the handler can settle before retry ownership changes; otherwise the attempt is failed immediately.
|
|
41
|
+
*/
|
|
42
|
+
export declare function enqueueStorageEvent(state: StorageEventState, event: FileEventItem, effects: StorageEventQueueEffects): void;
|
|
43
|
+
/**
|
|
44
|
+
* Flush the finite set of operations and admissions visible at entry.
|
|
45
|
+
* @param state - The manager state containing active admissions, retained operations, and the current failure sequence.
|
|
46
|
+
* @param effects - Callbacks for capturing attempts, releasing gates, dispatching, waiting, and reporting failures.
|
|
47
|
+
* @returns A promise which settles after captured admissions and attempts; rejects with the first rejected admission
|
|
48
|
+
* or, when admissions succeeded, the first failed operation result.
|
|
49
|
+
* @remarks Flush intent is signalled before awaiting active admissions. Current buffered work is retained and batch
|
|
50
|
+
* gates are released before the failure sequence is read for capture; attempts later registered by those admissions
|
|
51
|
+
* are merged without replacing earlier captures. Dispatch is then started in the background. Work admitted after the
|
|
52
|
+
* initial admission snapshot can remain outside this finite wait.
|
|
53
|
+
*/
|
|
54
|
+
export declare function flushStorageEvents(state: StorageEventState, effects: StorageEventQueueEffects): Promise<void>;
|
|
55
|
+
/**
|
|
56
|
+
* Share queue dispatch and optionally wait for the operations visible at call time.
|
|
57
|
+
* @param state - The manager state providing retained operations and this manager's stable dispatch key.
|
|
58
|
+
* @param effects - Queue, dispatch, and result-reporting callbacks.
|
|
59
|
+
* @param options - Whether to wait for accepted attempts after buffer dispatch.
|
|
60
|
+
* @returns A promise which resolves after dispatch and, when requested, after the captured attempts settle.
|
|
61
|
+
* @remarks The accepted set is captured before joining the shared dispatcher, so later arrivals are not added to
|
|
62
|
+
* the processing completion set. With waitForProcessing enabled, failed results are reported and do not themselves reject this promise.
|
|
63
|
+
*/
|
|
64
|
+
export declare function runBufferedStorageEvents(state: StorageEventState, effects: StorageEventQueueEffects, options?: RunQueuedEventsOptions): Promise<void>;
|
|
65
|
+
/**
|
|
66
|
+
* Load saved intents, replace the host buffer, and wait for restored operations to be processed.
|
|
67
|
+
* @param effects - Snapshot, buffer, status, logging, and queue callbacks supplied by the host.
|
|
68
|
+
* @returns A promise which resolves when restoration is empty or the restored queue has finished its captured work.
|
|
69
|
+
* @remarks Restored file events are copied with reconciliation and batch-wait bypass markers; sentinels are retained
|
|
70
|
+
* as-is. Empty snapshots only log and return. Load, buffer-replacement, and dispatcher errors propagate; ordinary
|
|
71
|
+
* failed attempt results are reported by the queue callback.
|
|
72
|
+
*/
|
|
73
|
+
export declare function restoreStorageEvents(effects: StorageEventQueueEffects): Promise<void>;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { LOG_LEVEL_VERBOSE } from "../../common/types.js";
|
|
2
|
+
import { fireAndForget } from "../../common/utils.js";
|
|
3
|
+
import { shareRunningResult } from "octagonal-wheels/concurrency/lock";
|
|
4
|
+
import {
|
|
5
|
+
assertSuccessfulFileEvents
|
|
6
|
+
} from "./operations.js";
|
|
7
|
+
import {
|
|
8
|
+
TYPE_SENTINEL_FLUSH,
|
|
9
|
+
pendingFileOperations,
|
|
10
|
+
retainBufferedFileEvents,
|
|
11
|
+
retainFileEvent
|
|
12
|
+
} from "./state.js";
|
|
13
|
+
function enqueueStorageEvent(state, event, effects) {
|
|
14
|
+
let barrierBefore;
|
|
15
|
+
if (event.type === "DELETE" || event.type === "RENAME") {
|
|
16
|
+
const sentinel = { type: TYPE_SENTINEL_FLUSH };
|
|
17
|
+
barrierBefore = retainFileEvent(state, sentinel).sequence;
|
|
18
|
+
effects.buffer.append(sentinel);
|
|
19
|
+
}
|
|
20
|
+
const operation = retainFileEvent(state, event).operation;
|
|
21
|
+
operation.barrierBefore ??= barrierBefore;
|
|
22
|
+
effects.buffer.append(event);
|
|
23
|
+
const attempt = operation.attempt;
|
|
24
|
+
effects.updateStatus();
|
|
25
|
+
fireAndForget(async () => {
|
|
26
|
+
try {
|
|
27
|
+
await effects.takeSnapshot();
|
|
28
|
+
await effects.runQueuedEvents();
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (attempt.started && !attempt.result) {
|
|
31
|
+
attempt.admissionFailure ??= { error };
|
|
32
|
+
effects.release([operation]);
|
|
33
|
+
} else effects.fail(operation, error, attempt);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function mergeAdmittedAttempts(boundary, admissions) {
|
|
38
|
+
for (const admission of admissions) {
|
|
39
|
+
for (const [operation, attempt] of admission.operations) {
|
|
40
|
+
if (!boundary.has(operation)) boundary.set(operation, attempt);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function flushStorageEvents(state, effects) {
|
|
45
|
+
const admissions = [...state.admissions];
|
|
46
|
+
for (const admission of admissions) admission.flushRequested = true;
|
|
47
|
+
retainBufferedFileEvents(state, effects.buffer.read());
|
|
48
|
+
const operations = pendingFileOperations(state);
|
|
49
|
+
effects.release(operations);
|
|
50
|
+
const boundary = effects.capture(operations, state.nextFailureSequence);
|
|
51
|
+
const admitted = await Promise.allSettled(admissions.map((admission) => admission.completion));
|
|
52
|
+
mergeAdmittedAttempts(boundary, admissions);
|
|
53
|
+
effects.release([...boundary.keys()]);
|
|
54
|
+
fireAndForget(effects.runQueuedEvents().catch(effects.reportFailure));
|
|
55
|
+
const results = await effects.wait(boundary);
|
|
56
|
+
const failure = admitted.find((result) => result.status === "rejected");
|
|
57
|
+
if (failure?.status === "rejected") throw failure.reason;
|
|
58
|
+
assertSuccessfulFileEvents(results);
|
|
59
|
+
}
|
|
60
|
+
async function dispatchBufferedEvents(state, effects) {
|
|
61
|
+
while (effects.buffer.read().length > 0) {
|
|
62
|
+
const event = effects.buffer.shift();
|
|
63
|
+
const entry = retainFileEvent(state, event);
|
|
64
|
+
if (event.type === TYPE_SENTINEL_FLUSH) {
|
|
65
|
+
entry.dispatched = true;
|
|
66
|
+
const results = await effects.wait(effects.capture(pendingFileOperations(state, entry.sequence)));
|
|
67
|
+
if (results.every((result) => result.ok)) {
|
|
68
|
+
try {
|
|
69
|
+
await effects.takeSnapshot();
|
|
70
|
+
} catch (error) {
|
|
71
|
+
effects.reportFailure(error);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
} else if (!entry.operation.attempt.result) {
|
|
75
|
+
fireAndForget(effects.processFileEvent(event).catch(() => {
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async function runBufferedStorageEvents(state, effects, options = {}) {
|
|
81
|
+
retainBufferedFileEvents(state, effects.buffer.read());
|
|
82
|
+
const accepted = pendingFileOperations(state);
|
|
83
|
+
await shareRunningResult(state.dispatchKey, () => dispatchBufferedEvents(state, effects));
|
|
84
|
+
if (options.waitForProcessing) {
|
|
85
|
+
const results = await effects.wait(effects.capture(accepted));
|
|
86
|
+
for (const result of results) {
|
|
87
|
+
if (result.ok === false) {
|
|
88
|
+
effects.reportFailure(result.error);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function restoreStorageEvents(effects) {
|
|
94
|
+
const snapshot = await effects.loadSnapshot();
|
|
95
|
+
if (!snapshot || !Array.isArray(snapshot) || snapshot.length === 0) {
|
|
96
|
+
effects.log("No snapshot to restore", LOG_LEVEL_VERBOSE);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
effects.log(`Restoring storage operation snapshot: ${snapshot.length} items`, LOG_LEVEL_VERBOSE);
|
|
100
|
+
effects.buffer.replace(
|
|
101
|
+
snapshot.map(
|
|
102
|
+
(event) => event.type === TYPE_SENTINEL_FLUSH ? event : { ...event, restoredFromPreviousRuntime: true, skipBatchWait: true }
|
|
103
|
+
)
|
|
104
|
+
);
|
|
105
|
+
effects.updateStatus();
|
|
106
|
+
await effects.runQueuedEvents({ waitForProcessing: true });
|
|
107
|
+
}
|
|
108
|
+
export {
|
|
109
|
+
enqueueStorageEvent,
|
|
110
|
+
flushStorageEvents,
|
|
111
|
+
restoreStorageEvents,
|
|
112
|
+
runBufferedStorageEvents
|
|
113
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type FileEventAttempt, type OperationResult, type PendingFileEvent } from "./operations.js";
|
|
2
|
+
import type { StorageEventBuffer } from "./state.js";
|
|
3
|
+
/** Host-owned queue and processing callbacks required to apply and start a retry plan. */
|
|
4
|
+
export interface StorageEventRetryEffects {
|
|
5
|
+
/** Host-owned queue whose sentinels and retry events must be reconciled with the new attempts. */
|
|
6
|
+
readonly buffer: StorageEventBuffer;
|
|
7
|
+
/** Process one captured operation attempt. */
|
|
8
|
+
processOperation(operation: PendingFileEvent, attempt: FileEventAttempt): Promise<void>;
|
|
9
|
+
/** Dispatch any remaining queued items after retry events have been removed. */
|
|
10
|
+
runQueuedEvents(): Promise<void>;
|
|
11
|
+
/** Report a background dispatch failure which has no direct waiter. */
|
|
12
|
+
reportFailure(error: unknown): void;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Plan a finite set of attempts, install all replacement ownership, then start retries in a microtask.
|
|
16
|
+
* @param operations - Operations accepted into the caller's finite boundary.
|
|
17
|
+
* @param retryBefore - Inclusive highest failure sequence eligible for a replacement attempt.
|
|
18
|
+
* @param effects - Host queue and processing callbacks used to install and run the plan.
|
|
19
|
+
* @returns The attempt captured for each planned operation, including newly installed retries.
|
|
20
|
+
* @remarks Planning failure leaves existing attempts untouched. When retries exist, their buffered events are
|
|
21
|
+
* removed and every replacement attempt is installed before any handler starts, so dependency callbacks see one
|
|
22
|
+
* coherent ownership set. Handlers start in a later microtask; their rejected promises are consumed here while
|
|
23
|
+
* their attempt results remain available to captured waiters. Remaining buffer items are dispatched separately.
|
|
24
|
+
*/
|
|
25
|
+
export declare function captureFileEventAttempts(operations: readonly PendingFileEvent[], retryBefore: number, effects: StorageEventRetryEffects): Map<PendingFileEvent, FileEventAttempt>;
|
|
26
|
+
/**
|
|
27
|
+
* Release batch waits for a captured operation set, then await those attempts.
|
|
28
|
+
* @param attempts - The fixed operation-to-attempt boundary selected by the caller.
|
|
29
|
+
* @param release - Callback which signals flush intent and releases matching batch gates.
|
|
30
|
+
* @returns The captured attempt outcomes in map iteration order.
|
|
31
|
+
* @remarks Release runs before waiting so batch-gated work can proceed. New operations are not added to this wait.
|
|
32
|
+
*/
|
|
33
|
+
export declare function waitForFileEventAttempts(attempts: ReadonlyMap<PendingFileEvent, FileEventAttempt>, release: (operations: readonly PendingFileEvent[]) => void): Promise<OperationResult[]>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { fireAndForget } from "../../common/utils.js";
|
|
2
|
+
import {
|
|
3
|
+
planFileEventAttempts
|
|
4
|
+
} from "./operations.js";
|
|
5
|
+
function captureFileEventAttempts(operations, retryBefore, effects) {
|
|
6
|
+
const { captured, retries } = planFileEventAttempts(operations, retryBefore);
|
|
7
|
+
if (retries.size === 0) return captured;
|
|
8
|
+
const retryEvents = new Set([...retries.keys()].map((operation) => operation.event));
|
|
9
|
+
effects.buffer.replace(effects.buffer.read().filter((event) => !retryEvents.has(event)));
|
|
10
|
+
for (const [operation, attempt] of retries) operation.attempt = attempt;
|
|
11
|
+
for (const [operation, attempt] of retries) {
|
|
12
|
+
fireAndForget(
|
|
13
|
+
Promise.resolve().then(() => effects.processOperation(operation, attempt)).catch(() => {
|
|
14
|
+
})
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
if (effects.buffer.read().length > 0) {
|
|
18
|
+
fireAndForget(
|
|
19
|
+
Promise.resolve().then(() => effects.runQueuedEvents()).catch(effects.reportFailure)
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
return captured;
|
|
23
|
+
}
|
|
24
|
+
async function waitForFileEventAttempts(attempts, release) {
|
|
25
|
+
release([...attempts.keys()]);
|
|
26
|
+
return await Promise.all([...attempts.values()].map((attempt) => attempt.completion.promise));
|
|
27
|
+
}
|
|
28
|
+
export {
|
|
29
|
+
captureFileEventAttempts,
|
|
30
|
+
waitForFileEventAttempts
|
|
31
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plan and serialise durable event-intent snapshots, including completion rollback on save failure.
|
|
3
|
+
* The snapshot tail keeps provisional marking, save, rollback, and in-memory acknowledgement in one ordered step.
|
|
4
|
+
*/
|
|
5
|
+
import type { FileEventItem } from "../../common/types.js";
|
|
6
|
+
import { type PendingSnapshotEntry, type QueuedFileEvent, type SnapshotCompletion, type StorageEventBuffer, type StorageEventState } from "./state.js";
|
|
7
|
+
/** Snapshot persistence and status callbacks supplied by the owning manager. */
|
|
8
|
+
export interface StorageEventSnapshotIO {
|
|
9
|
+
/** Save the currently pending event intents using the existing snapshot format. */
|
|
10
|
+
save(events: QueuedFileEvent[]): Promise<void>;
|
|
11
|
+
/** Enumerate host-queued events not necessarily present in the visible event buffer. */
|
|
12
|
+
waitingEvents(): Iterable<FileEventItem>;
|
|
13
|
+
/** Refresh host status after a snapshot has been committed. */
|
|
14
|
+
updateStatus(): void;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Select pending intents and sentinel acknowledgements without mutating ownership or performing I/O.
|
|
18
|
+
* @param entries - Snapshot entries in their retained insertion order.
|
|
19
|
+
* @returns Entries eligible for removal after save, event intents to write, and sentinel completion marks to apply.
|
|
20
|
+
* @remarks This is a pure plan. Operation completion flags are read as provisional state from the enclosing
|
|
21
|
+
* serialised snapshot step; a sentinel is acknowledged only after dispatch and acknowledgement of every preceding
|
|
22
|
+
* operation. This function neither changes entry state nor saves the returned snapshot.
|
|
23
|
+
*/
|
|
24
|
+
export declare function planFileEventSnapshot(entries: readonly PendingSnapshotEntry[]): {
|
|
25
|
+
completed: PendingSnapshotEntry[];
|
|
26
|
+
snapshot: QueuedFileEvent[];
|
|
27
|
+
sentinels: {
|
|
28
|
+
entry: PendingSnapshotEntry;
|
|
29
|
+
completed: boolean;
|
|
30
|
+
}[];
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Retain current intent and serialise its completion mark, save, and rollback on the manager's snapshot tail.
|
|
34
|
+
* @param state - The manager state whose retained entries and snapshot tail are updated.
|
|
35
|
+
* @param buffer - The visible host buffer whose events must be included in the durable intent.
|
|
36
|
+
* @param io - Host persistence, waiting-event enumeration, and status callbacks.
|
|
37
|
+
* @param completion - Optional exact entry/attempt whose completion should be included in this save.
|
|
38
|
+
* @returns A promise which resolves after a successful save and in-memory acknowledgement, or after a stale
|
|
39
|
+
* completion is ignored; rejects if admission checks, persistence, or the post-save status callback fails.
|
|
40
|
+
* @remarks Visible-buffer events use normal path registration. Batch-waiting events are retained with registration
|
|
41
|
+
* disabled so snapshot discovery cannot introduce path ordering. Completion marking, sentinel acknowledgement,
|
|
42
|
+
* saving, failed-save rollback, entry removal, and status update are serialised as one tail step. The first save
|
|
43
|
+
* keeps its microtask start. A failed save restores provisional completion before the next queued step and rejects
|
|
44
|
+
* this caller; the caught tail allows later saves to proceed.
|
|
45
|
+
*/
|
|
46
|
+
export declare function persistFileEventSnapshot(state: StorageEventState, buffer: StorageEventBuffer, io: StorageEventSnapshotIO, completion?: SnapshotCompletion): Promise<void>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { assertFileEventAdmission } from "./operations.js";
|
|
2
|
+
import {
|
|
3
|
+
retainBufferedFileEvents,
|
|
4
|
+
retainFileEvent
|
|
5
|
+
} from "./state.js";
|
|
6
|
+
function planFileEventSnapshot(entries) {
|
|
7
|
+
const completed = [];
|
|
8
|
+
const snapshot = [];
|
|
9
|
+
const sentinels = [];
|
|
10
|
+
let predecessorsCompleted = true;
|
|
11
|
+
for (const entry of entries) {
|
|
12
|
+
const acknowledged = entry.operation ? entry.completed : entry.dispatched === true && predecessorsCompleted;
|
|
13
|
+
if (entry.operation) predecessorsCompleted &&= acknowledged;
|
|
14
|
+
else sentinels.push({ entry, completed: acknowledged });
|
|
15
|
+
if (acknowledged) completed.push(entry);
|
|
16
|
+
else snapshot.push(entry.event);
|
|
17
|
+
}
|
|
18
|
+
return { completed, snapshot, sentinels };
|
|
19
|
+
}
|
|
20
|
+
function markCompletion(state, completion) {
|
|
21
|
+
if (!completion) return true;
|
|
22
|
+
const { entry, attempt } = completion;
|
|
23
|
+
assertFileEventAdmission(attempt);
|
|
24
|
+
if (state.pendingSnapshot.get(entry.event) !== entry || entry.operation?.attempt !== attempt) return false;
|
|
25
|
+
entry.completed = true;
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
async function persistFileEventSnapshot(state, buffer, io, completion) {
|
|
29
|
+
retainBufferedFileEvents(state, buffer.read());
|
|
30
|
+
for (const event of io.waitingEvents()) retainFileEvent(state, event, false);
|
|
31
|
+
const save = state.snapshotTail.then(async () => {
|
|
32
|
+
if (!markCompletion(state, completion)) return;
|
|
33
|
+
const plan = planFileEventSnapshot([...state.pendingSnapshot.values()]);
|
|
34
|
+
for (const sentinel of plan.sentinels) sentinel.entry.completed = sentinel.completed;
|
|
35
|
+
try {
|
|
36
|
+
await io.save(plan.snapshot);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
for (const entry of plan.completed) entry.completed = false;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
for (const entry of plan.completed) {
|
|
42
|
+
if (state.pendingSnapshot.get(entry.event) === entry) state.pendingSnapshot.delete(entry.event);
|
|
43
|
+
}
|
|
44
|
+
io.updateStatus();
|
|
45
|
+
});
|
|
46
|
+
state.snapshotTail = save.catch(() => {
|
|
47
|
+
});
|
|
48
|
+
await save;
|
|
49
|
+
}
|
|
50
|
+
export {
|
|
51
|
+
persistFileEventSnapshot,
|
|
52
|
+
planFileEventSnapshot
|
|
53
|
+
};
|