@vrtmrz/livesync-commonlib 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +14 -2
  2. package/dist/common/models/fileaccess.definition.d.ts +35 -0
  3. package/dist/common/models/fileaccess.definition.js +11 -0
  4. package/dist/common/typeUtils.d.ts +27 -4
  5. package/dist/interfaces/FileHandler.d.ts +60 -1
  6. package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
  7. package/dist/interfaces/FileReflectionProvenance.js +11 -1
  8. package/dist/managers/StorageEventManager/admission.d.ts +50 -0
  9. package/dist/managers/StorageEventManager/admission.js +129 -0
  10. package/dist/managers/StorageEventManager/batching.d.ts +93 -0
  11. package/dist/managers/StorageEventManager/batching.js +97 -0
  12. package/dist/managers/StorageEventManager/operations.d.ts +142 -0
  13. package/dist/managers/StorageEventManager/operations.js +69 -0
  14. package/dist/managers/StorageEventManager/processing.d.ts +63 -0
  15. package/dist/managers/StorageEventManager/processing.js +94 -0
  16. package/dist/managers/StorageEventManager/queue.d.ts +73 -0
  17. package/dist/managers/StorageEventManager/queue.js +113 -0
  18. package/dist/managers/StorageEventManager/retry.d.ts +33 -0
  19. package/dist/managers/StorageEventManager/retry.js +31 -0
  20. package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
  21. package/dist/managers/StorageEventManager/snapshot.js +53 -0
  22. package/dist/managers/StorageEventManager/state.d.ts +155 -0
  23. package/dist/managers/StorageEventManager/state.js +105 -0
  24. package/dist/managers/StorageEventManager/watching.d.ts +93 -0
  25. package/dist/managers/StorageEventManager/watching.js +36 -0
  26. package/dist/managers/StorageEventManager.d.ts +303 -83
  27. package/dist/managers/StorageEventManager.js +457 -547
  28. package/dist/serviceFeatures/offlineScanner/fileStatus.d.ts +61 -0
  29. package/dist/serviceFeatures/offlineScanner/fileStatus.js +85 -0
  30. package/dist/serviceFeatures/offlineScanner/files.d.ts +47 -0
  31. package/dist/serviceFeatures/offlineScanner/files.js +218 -0
  32. package/dist/serviceFeatures/offlineScanner/metadata.d.ts +56 -0
  33. package/dist/serviceFeatures/offlineScanner/metadata.js +320 -0
  34. package/dist/serviceFeatures/offlineScanner/paths.d.ts +20 -0
  35. package/dist/serviceFeatures/offlineScanner/paths.js +16 -0
  36. package/dist/serviceFeatures/offlineScanner/scan.d.ts +35 -0
  37. package/dist/serviceFeatures/offlineScanner/scan.js +358 -0
  38. package/dist/serviceFeatures/offlineScanner/types.d.ts +134 -0
  39. package/dist/serviceFeatures/offlineScanner/types.js +66 -0
  40. package/dist/serviceFeatures/offlineScanner.d.ts +25 -251
  41. package/dist/serviceFeatures/offlineScanner.js +36 -860
  42. package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
  43. package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
  44. package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
  45. package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
  46. package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
  47. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.d.ts +13 -0
  49. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
  51. package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
  52. package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
  53. package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
  54. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
  55. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
  56. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
  57. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
  58. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
  59. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
  60. package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
  61. package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
  62. package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
  63. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
  64. package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
  65. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
  66. package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
  67. package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
  68. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
  69. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
  70. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +141 -183
  71. package/dist/serviceModules/ServiceFileHandlerBase.js +206 -1397
  72. package/dist/services/base/KeyValueDBService.d.ts +9 -0
  73. package/dist/services/base/KeyValueDBService.js +11 -1
  74. package/docs/conflict-resolution.md +3 -1
  75. package/docs/development.md +40 -0
  76. package/docs/offline-scanner.md +26 -1
  77. package/docs/p2p-transport-lifecycle.md +8 -1
  78. package/docs/storage-events-and-reflection.md +212 -22
  79. package/package.json +1 -1
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Durable file-operation contracts and pure plans for attempts and ordering.
3
+ * This module selects and correlates attempts without installing them or invoking handlers.
4
+ */
5
+ import type { FileEventItem } from "../../common/models/fileaccess.type.js";
6
+ import { type PromiseWithResolvers } from "octagonal-wheels/promises";
7
+ /** The settled outcome of one attempt; a later retry receives a different outcome promise. */
8
+ export type OperationResult = {
9
+ ok: true;
10
+ } | {
11
+ ok: false;
12
+ error: unknown;
13
+ };
14
+ /** Per-attempt execution state, separate from the durable operation that may be retried. */
15
+ export type FileEventAttempt = {
16
+ /** Settles once for this attempt, leaving earlier callers attached to their original attempt. */
17
+ completion: PromiseWithResolvers<OperationResult>;
18
+ /** Prevents concurrent dispatch from starting the same attempt twice. */
19
+ started: boolean;
20
+ /** Marks this invocation for current-state reconciliation inside the ordinary handler. */
21
+ reconcile: boolean;
22
+ /** Failure-sequence cutoff used when this attempt captures retryable dependencies. */
23
+ retryBefore?: number;
24
+ /** An admission failure which must be observed after an active handler settles. */
25
+ admissionFailure?: {
26
+ error: unknown;
27
+ };
28
+ /** Related operations whose captured attempts must succeed before this one proceeds. */
29
+ prerequisites?: Map<PendingFileEvent, FileEventAttempt>;
30
+ /** Earlier ordered work which must settle, regardless of whether it succeeded. */
31
+ orderedPredecessors?: Map<PendingFileEvent, FileEventAttempt>;
32
+ /** Successor which owns completion when this operation was coalesced away. */
33
+ successor?: FileEventAttempt;
34
+ /** Cached terminal result for this attempt. */
35
+ result?: OperationResult;
36
+ /** Position of this failure within the manager's finite failure sequence. */
37
+ failureSequence?: number;
38
+ };
39
+ /** Durable ownership of an accepted file event across one or more execution attempts. */
40
+ export type PendingFileEvent = {
41
+ /** Original event intent retained for persistence and replay. */
42
+ event: FileEventItem;
43
+ /** Manager-local ordering position used by snapshots and finite boundaries. */
44
+ sequence: number;
45
+ /** Admission time for this event; batch planning may inherit an earlier gate start. */
46
+ acceptedAt: number;
47
+ /** Failure-sequence position at admission, excluding later failures from this operation's retry scope. */
48
+ failureBoundary: number;
49
+ /** Sentinel sequence which earlier ordered work must settle before this operation. */
50
+ barrierBefore?: number;
51
+ /** Current execution attempt; replacing it does not rewrite a previously settled attempt. */
52
+ attempt: FileEventAttempt;
53
+ /** Whether initialisation has linked the operation's prerequisites. */
54
+ initialised: boolean;
55
+ /** Whether this operation has been entered into the per-path predecessor index. */
56
+ registered: boolean;
57
+ /** Latest unresolved operation for each path touched by this event. */
58
+ predecessors: Map<string, PendingFileEvent>;
59
+ /** Related operations which must succeed before this event can be processed. */
60
+ prerequisites: Set<PendingFileEvent>;
61
+ /** Whether captured work must bypass batch waiting and signal any optional handler. */
62
+ flushRequested: boolean;
63
+ /** Signal shared with optional handlers which support flush-aware completion. */
64
+ flushSignal?: PromiseWithResolvers<void>;
65
+ };
66
+ /**
67
+ * Create a fresh attempt with its own unresolved completion promise.
68
+ * @param reconcile - Whether the handler should reconcile this event against current file state.
69
+ * @returns An unstarted attempt with no result or dependency captures.
70
+ * @remarks This allocates attempt-local state only; it does not replace a durable operation's current attempt
71
+ * or schedule processing.
72
+ */
73
+ export declare function createFileEventAttempt(reconcile?: boolean): FileEventAttempt;
74
+ /**
75
+ * Enforce an admission failure recorded while an attempt's handler was active.
76
+ * @param attempt - The attempt whose admission outcome must be checked before it advances.
77
+ * @returns No value; returns normally when no admission failure is recorded.
78
+ * @throws The original admission error when present, without wrapping or replacing it.
79
+ * @remarks Does not change attempt state.
80
+ */
81
+ export declare function assertFileEventAdmission(attempt: FileEventAttempt): void;
82
+ /**
83
+ * Decide whether the manager may automatically retry an event in the current session.
84
+ * @param event - The original file-event intent.
85
+ * @returns True for a non-INTERNAL event whose file is not internal.
86
+ * @remarks Internal and optional-provider work keeps its provider-owned retry contract; this predicate is read-only.
87
+ */
88
+ export declare function canRetryFileEvent(event: FileEventItem): boolean;
89
+ /**
90
+ * Resolve the paths which establish ordering for this event.
91
+ * @param event - The original file-event intent.
92
+ * @returns The file path plus its related path when present; RENAME uses oldPath and other events use renameTarget.
93
+ * @remarks The returned paths are used for ownership and ordering only; this function does not index the event.
94
+ */
95
+ export declare function getFileEventPaths(event: FileEventItem): string[];
96
+ /** A side-effect-free selection of the attempts a caller may capture and await. */
97
+ type FileEventAttemptPlan = {
98
+ /** Attempt chosen for every operation reached within the finite plan. */
99
+ captured: Map<PendingFileEvent, FileEventAttempt>;
100
+ /** Newly allocated attempts which the caller may install and start. */
101
+ retries: Map<PendingFileEvent, FileEventAttempt>;
102
+ };
103
+ /**
104
+ * Select current and replacement attempts through a finite failure sequence without starting work.
105
+ * @param operations - The initial durable operations in the caller's boundary.
106
+ * @param retryBefore - Inclusive highest failure sequence eligible for a replacement attempt; defaults to no retries.
107
+ * @returns A map of captured attempts and a separate map containing only newly planned retries.
108
+ * @remarks Existing attempts remain installed. Eligible operations receive newly allocated attempts in the plan;
109
+ * already-initialised retries also add their prerequisites to the captured set so dependency waits use one boundary.
110
+ * The caller is responsible for installing retries and scheduling them.
111
+ */
112
+ export declare function planFileEventAttempts(operations: readonly PendingFileEvent[], retryBefore?: number): FileEventAttemptPlan;
113
+ /** One predecessor decision for a path, produced without changing gates or operation links. */
114
+ type BatchPredecessorAction = {
115
+ kind: "coalesce" | "depend";
116
+ path: string;
117
+ previous: PendingFileEvent;
118
+ };
119
+ /**
120
+ * Plan coalescing and dependency links for the operation's unresolved path predecessors.
121
+ * @param operation - The operation whose predecessor relationships are being initialised.
122
+ * @param waiting - Optional current batch gate, used only when it belongs to a coalescible predecessor.
123
+ * @returns The batch start time to use and one coalesce/depend action for each unresolved predecessor path.
124
+ * @remarks A gate is inherited only for the same event object, while it is not flush-requested, and when event
125
+ * types match or the new event is DELETE. This is a pure plan: the caller applies actions and cancels any gates.
126
+ */
127
+ export declare function planFileEventPredecessors(operation: Readonly<PendingFileEvent>, waiting?: Readonly<{
128
+ event: FileEventItem;
129
+ since: number;
130
+ }>): {
131
+ since: number;
132
+ actions: BatchPredecessorAction[];
133
+ };
134
+ /**
135
+ * Require every captured operation result to be successful.
136
+ * @param results - Results in their capture order.
137
+ * @returns No value when all results are successful or the collection is empty.
138
+ * @throws The error from the first failed result in input order, without wrapping or replacing it.
139
+ * @remarks Does not alter any result or operation.
140
+ */
141
+ export declare function assertSuccessfulFileEvents(results: readonly OperationResult[]): void;
142
+ export {};
@@ -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
+ };