@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.
Files changed (87) hide show
  1. package/README.md +17 -0
  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 +1 -1
  6. package/dist/managers/EntryManager/EntryManagerImpls.js +1 -1
  7. package/dist/managers/StorageEventManager/admission.d.ts +50 -0
  8. package/dist/managers/StorageEventManager/admission.js +129 -0
  9. package/dist/managers/StorageEventManager/batching.d.ts +93 -0
  10. package/dist/managers/StorageEventManager/batching.js +97 -0
  11. package/dist/managers/StorageEventManager/operations.d.ts +142 -0
  12. package/dist/managers/StorageEventManager/operations.js +69 -0
  13. package/dist/managers/StorageEventManager/processing.d.ts +63 -0
  14. package/dist/managers/StorageEventManager/processing.js +94 -0
  15. package/dist/managers/StorageEventManager/queue.d.ts +73 -0
  16. package/dist/managers/StorageEventManager/queue.js +113 -0
  17. package/dist/managers/StorageEventManager/retry.d.ts +33 -0
  18. package/dist/managers/StorageEventManager/retry.js +31 -0
  19. package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
  20. package/dist/managers/StorageEventManager/snapshot.js +53 -0
  21. package/dist/managers/StorageEventManager/state.d.ts +155 -0
  22. package/dist/managers/StorageEventManager/state.js +105 -0
  23. package/dist/managers/StorageEventManager/watching.d.ts +93 -0
  24. package/dist/managers/StorageEventManager/watching.js +36 -0
  25. package/dist/managers/StorageEventManager.d.ts +303 -83
  26. package/dist/managers/StorageEventManager.js +457 -547
  27. package/dist/p2p/P2PService.d.ts +10 -1
  28. package/dist/p2p/P2PService.js +25 -2
  29. package/dist/p2p/index.d.ts +4 -1
  30. package/dist/p2p/index.js +2 -0
  31. package/dist/p2p/p2pDiagnostics.d.ts +35 -0
  32. package/dist/p2p/p2pDiagnostics.js +76 -0
  33. package/dist/pouchdb/ReplicatorShim.batch.d.ts +30 -0
  34. package/dist/pouchdb/ReplicatorShim.batch.js +62 -0
  35. package/dist/pouchdb/ReplicatorShim.d.ts +14 -1
  36. package/dist/pouchdb/ReplicatorShim.js +64 -80
  37. package/dist/replication/trystero/P2PLogCollector.d.ts +12 -0
  38. package/dist/replication/trystero/P2PLogCollector.js +107 -72
  39. package/dist/replication/trystero/P2PRoomSessionOwner.d.ts +4 -0
  40. package/dist/replication/trystero/P2PRoomSessionOwner.js +39 -2
  41. package/dist/replication/trystero/TrysteroReplicator.d.ts +21 -24
  42. package/dist/replication/trystero/TrysteroReplicator.js +191 -69
  43. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +11 -0
  44. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +9 -0
  45. package/dist/replication/trystero/p2pReplicationDiagnostics.js +51 -0
  46. package/dist/replication/trystero/p2pReplicationProgress.d.ts +15 -0
  47. package/dist/replication/trystero/p2pReplicationProgress.js +37 -0
  48. package/dist/replication/trystero/types.d.ts +3 -0
  49. package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
  51. package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
  52. package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
  53. package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
  54. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
  55. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
  56. package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
  57. package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
  58. package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
  59. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
  60. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
  61. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
  62. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
  63. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
  64. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
  65. package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
  66. package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
  67. package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
  68. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
  69. package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
  70. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
  71. package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
  72. package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
  73. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
  74. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
  75. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +119 -182
  76. package/dist/serviceModules/ServiceFileHandlerBase.js +182 -1402
  77. package/dist/services/base/APIService.d.ts +10 -0
  78. package/dist/services/base/APIService.js +13 -0
  79. package/dist/services/base/IService.d.ts +2 -0
  80. package/docs/conflict-resolution.md +3 -1
  81. package/docs/development.md +36 -0
  82. package/docs/journal-receive-recovery.md +7 -4
  83. package/docs/offline-scanner.md +5 -1
  84. package/docs/p2p-transport-lifecycle.md +125 -11
  85. package/docs/releasing.md +6 -0
  86. package/docs/storage-events-and-reflection.md +203 -19
  87. package/package.json +2 -2
package/README.md CHANGED
@@ -149,6 +149,23 @@ After the Self-hosted LiveSync 1.0 work, the planned high-level composition is a
149
149
 
150
150
  The factory is not implemented yet. Until it is available, service implementations exposed under `compat/*` retain their owning client's lifecycle rather than becoming a general public composition API.
151
151
 
152
+ ### Host cleanup registration
153
+
154
+ Available from 0.4.0, `services.API.registerCleanup(callback)` registers synchronous
155
+ cleanup for the owning host's normal terminal unload. The default `APIService` implementation
156
+ uses the context-owned `EVENT_PLATFORM_UNLOADED` event once per registration.
157
+ CLI and browser hosts already deliver that event through `ControlService.onUnload()`
158
+ after their asynchronous lifecycle work and local database closure. An unload
159
+ interrupted before that event does not invoke these callbacks.
160
+
161
+ The Obsidian adapter delegates to native `Component.register()` and retains that
162
+ host's unload timing. This API therefore does not promise one shared shutdown
163
+ phase across hosts. Register callbacks before terminal unload, and use it for
164
+ presentation resources and subscriptions. Returned promises are not awaited;
165
+ resources which must retire before database closure belong to
166
+ `appLifecycle.onUnload` instead. The registration does not add process signals,
167
+ browser navigation handlers, or a new shutdown/recovery path.
168
+
152
169
  ## UI commands
153
170
 
154
171
  Import `declareUICommand` and `UICommandRegistry` from `@vrtmrz/livesync-commonlib/ui-commands`. A declaration binds a stable command ID to its request and result types. Each `UIService` owns its own `commands` registry; declarations do not register global handlers.
@@ -0,0 +1,35 @@
1
+ /** Transient handler requests which reuse reconciliation without changing the persisted event schema. */
2
+ import type { FileEventItem } from "./fileaccess.type.js";
3
+ /** Keep the runtime brand private so callers construct requests through the factory. */
4
+ declare const RECONCILE_FILE_EVENT: unique symbol;
5
+ /**
6
+ * A transient request to re-evaluate an event against current storage and database state.
7
+ *
8
+ * @remarks
9
+ * This is a handler invocation, not a new durable operation. The manager retains
10
+ * the original event for snapshots; the private symbol is absent from JSON persistence.
11
+ */
12
+ export type ReconcileFileEvent = FileEventItem & {
13
+ [RECONCILE_FILE_EVENT]: true;
14
+ };
15
+ /**
16
+ * Create a marked handler invocation without changing the retained operation's event.
17
+ *
18
+ * @param event - The original accepted file event whose current effect must be reconsidered.
19
+ * @returns A shallow event copy branded as a reconciliation request; its arguments are shared with the original.
20
+ * @remarks
21
+ * Continue persisting the original event. The returned request only selects the
22
+ * current-state reconciliation route for this attempt and does not alter earlier results.
23
+ */
24
+ export declare function createReconcileEvent(event: FileEventItem): ReconcileFileEvent;
25
+ /**
26
+ * Narrow a valid file event to a transient reconciliation request.
27
+ *
28
+ * @param event - An already typed file event passed to a handler.
29
+ * @returns Whether the private reconciliation marker is present and true.
30
+ * @remarks
31
+ * This checks the invocation marker, not the full shape of an unknown payload.
32
+ * Persisted restart events use restoredFromPreviousRuntime and are checked separately.
33
+ */
34
+ export declare function isReconcileEvent(event: FileEventItem): event is ReconcileFileEvent;
35
+ export {};
@@ -0,0 +1,11 @@
1
+ const RECONCILE_FILE_EVENT = /* @__PURE__ */ Symbol("reconcileFileEvent");
2
+ function createReconcileEvent(event) {
3
+ return { ...event, [RECONCILE_FILE_EVENT]: true };
4
+ }
5
+ function isReconcileEvent(event) {
6
+ return RECONCILE_FILE_EVENT in event && event[RECONCILE_FILE_EVENT] === true;
7
+ }
8
+ export {
9
+ createReconcileEvent,
10
+ isReconcileEvent
11
+ };
@@ -1,17 +1,40 @@
1
1
  import type { DocumentID, FilePath, FilePathWithPrefix } from "./models/db.type.js";
2
2
  import type { UXFileInfoStub } from "./types.js";
3
+ /** Path conversion requires identity only; internal files need no storage statistics. */
4
+ type FilePathInput = string | Pick<UXFileInfoStub, "path" | "isInternal">;
3
5
  /**
4
6
  * returns is internal chunk of file
5
7
  * @param id ID
6
8
  * @returns
7
9
  */
8
10
  export declare function isInternalMetadata(id: FilePath | FilePathWithPrefix | DocumentID): boolean;
9
- export declare function isInternalFile(file: UXFileInfoStub | string | FilePathWithPrefix): boolean;
11
+ /**
12
+ * Identify the internal namespace from a path or file identity.
13
+ * @param file - A path or identity whose optional internal flag is retained.
14
+ * @returns Whether the path namespace or explicit flag denotes an internal file.
15
+ */
16
+ export declare function isInternalFile(file: FilePathInput): boolean;
10
17
  export declare function stripInternalMetadataPrefix<T extends FilePath | FilePathWithPrefix | DocumentID>(id: T): T;
11
18
  export declare function id2InternalMetadataId(id: DocumentID): DocumentID;
12
19
  export declare function isChunk(str: string): boolean;
13
20
  export declare function isPluginMetadata(str: string): boolean;
14
21
  export declare function isCustomisationSyncMetadata(str: string): boolean;
15
- export declare function getPathFromUXFileInfo(file: UXFileInfoStub | string | FilePathWithPrefix): FilePathWithPrefix;
16
- export declare function getStoragePathFromUXFileInfo(file: UXFileInfoStub | string | FilePathWithPrefix): FilePath;
17
- export declare function getDatabasePathFromUXFileInfo(file: UXFileInfoStub | string | FilePathWithPrefix): FilePathWithPrefix;
22
+ /**
23
+ * Read the supplied path without changing its namespace or spelling.
24
+ * @param file - A path or file identity; storage statistics are not required.
25
+ * @returns The original path, including any namespace prefix.
26
+ */
27
+ export declare function getPathFromUXFileInfo(file: FilePathInput): FilePathWithPrefix;
28
+ /**
29
+ * Resolve a physical storage path from a path or file identity.
30
+ * @param file - A path or file identity; internal observations may omit statistics.
31
+ * @returns The path with recognised database namespace prefixes removed.
32
+ */
33
+ export declare function getStoragePathFromUXFileInfo(file: FilePathInput): FilePath;
34
+ /**
35
+ * Resolve the database namespace from a path or file identity.
36
+ * @param file - A path or identity carrying its optional internal flag.
37
+ * @returns The existing customisation path or the path with its internal namespace applied.
38
+ */
39
+ export declare function getDatabasePathFromUXFileInfo(file: FilePathInput): FilePathWithPrefix;
40
+ export {};
@@ -9,7 +9,7 @@ export interface IFileHandler {
9
9
  /**
10
10
  * Record an untracked, unchanged file during an equal-time scan.
11
11
  * Return true only when the exact current revision was recorded. This
12
- * operation never stores a document revision or writes to storage.
12
+ * operation never stores a Metadata revision or writes to storage.
13
13
  */
14
14
  tryRecordUntrackedFileRevision(info: UXFileInfoStub | UXFileInfo, expectedRevision: string): Promise<boolean>;
15
15
  /** Metadata-only scan hint; never certifies content equality or changes provenance. */
@@ -162,7 +162,7 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
162
162
  path: note.path,
163
163
  ctime: note.ctime,
164
164
  mtime: note.mtime,
165
- size: note.size,
165
+ size: data.size,
166
166
  type: note.datatype,
167
167
  eden: {}
168
168
  };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Select host storage callbacks and admit valid events into the manager's operation queue.
3
+ */
4
+ import { type FileEventItem, type ObsidianLiveSyncSettings } from "../../common/types.js";
5
+ import type { FileEvent } from "../../interfaces/StorageEventManager.js";
6
+ import type { IStorageAccessManager } from "../../interfaces/StorageAccess.js";
7
+ import type { LogFunction } from "../../services/lib/logUtils.js";
8
+ import type { StorageEventState } from "./state.js";
9
+ import type { PendingFileEvent } from "./operations.js";
10
+ /**
11
+ * Inject host settings, path and file checks, queue actions, and diagnostics into admission.
12
+ * @remarks
13
+ * Admission owns event selection; the facade supplies platform services and asynchronous target checks.
14
+ * Settings are read once for each appended batch, while enqueueing and reporting remain host effects.
15
+ */
16
+ export interface StorageEventAdmissionEffects {
17
+ settings(): ObsidianLiveSyncSettings;
18
+ isFolder(file: FileEvent["file"]): boolean;
19
+ isFile(file: FileEvent["file"]): boolean;
20
+ isTarget(path: string): Promise<boolean>;
21
+ isTooLarge(size: number): boolean;
22
+ recentlyTouched: IStorageAccessManager["recentlyTouched"];
23
+ onStorageFileEvent(): void;
24
+ enqueue(event: FileEventItem): void;
25
+ release(operations: readonly PendingFileEvent[]): void;
26
+ reportFailure(error: unknown): void;
27
+ log: LogFunction;
28
+ }
29
+ /** Normalised event intent before cache data and host context are attached. */
30
+ type SelectedFileEvent = Pick<FileEventItem, "type" | "args">;
31
+ /**
32
+ * Convert old and new path selection into the operation which preserves the selected side.
33
+ * @param param - The host rename event.
34
+ * @param oldSelected - Whether the source path is a sync target.
35
+ * @param newSelected - Whether the destination path is a sync target and within the size limit.
36
+ * @returns `null` when neither path is selected; otherwise a CREATE, RENAME, or source-path DELETE intent.
37
+ * @remarks The source-only case asserts that `oldPath` and file `stat` are present; `selectRename` establishes those preconditions.
38
+ */
39
+ export declare function selectRenameFileEvent(param: FileEvent, oldSelected: boolean, newSelected: boolean): SelectedFileEvent | null;
40
+ /**
41
+ * Start and track a batch of host events through filtering and queue admission.
42
+ * @param state - Mutable state which owns admission and operation boundaries.
43
+ * @param params - Host watcher events to select.
44
+ * @param ctx - Optional host context forwarded to admitted items.
45
+ * @param effects - Host services used during selection and enqueueing.
46
+ * @returns A promise for admission completion, not handler completion; rejected admission is reported and remains rejected.
47
+ * @remarks When the manager no longer accepts events, this returns an already-fulfilled promise without admitting them.
48
+ */
49
+ export declare function admitStorageEvents(state: StorageEventState, params: readonly FileEvent[], ctx: unknown, effects: StorageEventAdmissionEffects): Promise<void>;
50
+ export {};
@@ -0,0 +1,129 @@
1
+ import {
2
+ LOG_LEVEL_NOTICE,
3
+ LOG_LEVEL_VERBOSE
4
+ } from "../../common/types.js";
5
+ import { shouldBeIgnored } from "../../string_and_binary/path.js";
6
+ import { delay, isRemediationModeActive } from "../../common/utils.js";
7
+ async function isSelectedPath(path, settings, effects) {
8
+ if (shouldBeIgnored(path)) return false;
9
+ if (!settings.syncInternalFiles && path.startsWith(".")) return false;
10
+ return await effects.isTarget(path);
11
+ }
12
+ function logOversizedEvent(path, effects) {
13
+ effects.log(`The storage file has been changed but exceeds the maximum size. Skipping: ${path}`, LOG_LEVEL_NOTICE);
14
+ }
15
+ function selectRenameFileEvent(param, oldSelected, newSelected) {
16
+ if (!oldSelected && !newSelected) return null;
17
+ if (oldSelected && !newSelected) {
18
+ const oldPath = param.oldPath;
19
+ return {
20
+ type: "DELETE",
21
+ args: {
22
+ file: {
23
+ path: oldPath,
24
+ name: oldPath.split("/").pop() ?? param.file.name,
25
+ stat: param.file.stat,
26
+ deleted: true
27
+ },
28
+ oldPath: void 0,
29
+ renameTarget: param.file.path
30
+ }
31
+ };
32
+ }
33
+ return {
34
+ type: oldSelected ? "RENAME" : "CREATE",
35
+ args: {
36
+ file: param.file,
37
+ oldPath: oldSelected ? param.oldPath : void 0
38
+ }
39
+ };
40
+ }
41
+ async function selectRename(param, settings, effects) {
42
+ const file = param.file;
43
+ if (!param.oldPath || !effects.isFile(file) || !file.stat) {
44
+ effects.log(`Invalid rename event skipped: ${file.path}`, LOG_LEVEL_VERBOSE);
45
+ return null;
46
+ }
47
+ const oldSelected = await isSelectedPath(param.oldPath, settings, effects);
48
+ let newSelected = await isSelectedPath(file.path, settings, effects);
49
+ if (newSelected && effects.isTooLarge(file.stat.size)) {
50
+ logOversizedEvent(param.file.path, effects);
51
+ newSelected = false;
52
+ }
53
+ return selectRenameFileEvent(param, oldSelected, newSelected);
54
+ }
55
+ async function selectOrdinaryEvent(param, settings, effects) {
56
+ if (!await isSelectedPath(param.file.path, settings, effects)) return null;
57
+ if (param.type !== "INTERNAL") {
58
+ const size = param.file.stat.size;
59
+ if (effects.isTooLarge(size) && (param.type === "CREATE" || param.type === "CHANGED")) {
60
+ logOversizedEvent(param.file.path, effects);
61
+ return null;
62
+ }
63
+ }
64
+ return { type: param.type, args: { file: param.file, oldPath: void 0 } };
65
+ }
66
+ async function wasRecentlyTouched(event, effects) {
67
+ if (!effects.isFile(event.args.file)) return false;
68
+ if (event.type !== "CREATE" && event.type !== "CHANGED" && event.type !== "RENAME") return false;
69
+ await delay(10);
70
+ const file = event.args.file;
71
+ return effects.recentlyTouched({ path: file.path, stat: file.stat ?? { ctime: 0, mtime: 0, size: 0 } });
72
+ }
73
+ async function prepareEvent(param, settings, ctx, effects) {
74
+ const key = [0, 0, 0, 0, 0, 0].map(() => `${Math.floor(Math.random() * 1e5)}`).join("-");
75
+ if (effects.isFolder(param.file)) {
76
+ effects.log(`Folder event skipped: ${param.file.path}`, LOG_LEVEL_VERBOSE);
77
+ return null;
78
+ }
79
+ const selected = param.type === "RENAME" ? await selectRename(param, settings, effects) : await selectOrdinaryEvent(param, settings, effects);
80
+ if (!selected || await wasRecentlyTouched(selected, effects)) return null;
81
+ return {
82
+ ...selected,
83
+ args: { ...selected.args, cache: param.cachedData || void 0, ctx },
84
+ skipBatchWait: param.skipBatchWait,
85
+ key
86
+ };
87
+ }
88
+ function registerAdmission(state, admission, item, effects) {
89
+ effects.enqueue(item);
90
+ const operation = state.operations.get(item);
91
+ if (!operation) return;
92
+ operation.acceptedAt = admission.acceptedAt;
93
+ operation.failureBoundary = admission.failureBoundary;
94
+ if (admission.flushRequested) effects.release([operation]);
95
+ admission.operations.set(operation, operation.attempt);
96
+ }
97
+ async function appendStorageEvents(state, params, ctx, admission, effects) {
98
+ const settings = effects.settings();
99
+ if (!settings.isConfigured || settings.suspendFileWatching || isRemediationModeActive(settings)) return;
100
+ effects.onStorageFileEvent();
101
+ for (const param of params) {
102
+ const item = await prepareEvent(param, settings, ctx, effects);
103
+ if (item) registerAdmission(state, admission, item, effects);
104
+ }
105
+ }
106
+ function admitStorageEvents(state, params, ctx, effects) {
107
+ if (!state.acceptingEvents) return Promise.resolve();
108
+ const admission = {
109
+ acceptedAt: Date.now(),
110
+ completion: Promise.resolve(),
111
+ operations: /* @__PURE__ */ new Map(),
112
+ failureBoundary: state.nextFailureSequence,
113
+ flushRequested: false
114
+ };
115
+ state.admissions.add(admission);
116
+ admission.completion = appendStorageEvents(state, params, ctx, admission, effects);
117
+ void admission.completion.then(
118
+ () => state.admissions.delete(admission),
119
+ (error) => {
120
+ state.admissions.delete(admission);
121
+ effects.reportFailure(error);
122
+ }
123
+ );
124
+ return admission.completion;
125
+ }
126
+ export {
127
+ admitStorageEvents,
128
+ selectRenameFileEvent
129
+ };
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Manage batch gates, deadlines, and predecessor coalescing for storage-event operations.
3
+ */
4
+ import type { FileEventItem, FileEventType } from "../../common/types.js";
5
+ import type { LogFunction } from "../../services/lib/logUtils.js";
6
+ import { type DeferredAction } from "octagonal-wheels/concurrency/deferredAction";
7
+ import { type PromiseWithResolvers } from "octagonal-wheels/promises";
8
+ import { type PendingFileEvent } from "./operations.js";
9
+ /** One path's pending batch gate, its deadline, and the event which owns the gate. */
10
+ export type WaitInfo = {
11
+ since: number;
12
+ type: FileEventType;
13
+ canProceed: PromiseWithResolvers<boolean>;
14
+ deadline: DeferredAction;
15
+ event: FileEventItem;
16
+ };
17
+ /**
18
+ * Inject waiting state, live delay settings, logging, snapshots, and gate control into batching.
19
+ * @remarks The facade provides dynamic setting accessors so each new gate observes current host settings.
20
+ */
21
+ export interface StorageEventBatching {
22
+ waiting(): Map<string, WaitInfo>;
23
+ operation(event: FileEventItem): PendingFileEvent | undefined;
24
+ minimumDelay(): number;
25
+ maximumDelay(): number;
26
+ enabled(): boolean;
27
+ log: LogFunction;
28
+ requestSnapshot(): void;
29
+ proceed(path: string): void;
30
+ cancel(path: string): void;
31
+ add(path: string, event: FileEventItem, since?: number): WaitInfo;
32
+ }
33
+ /**
34
+ * Resolve and remove a path's current gate, dispose its timer, and request a snapshot.
35
+ * @param batching - Host effects for waiting state and snapshot requests.
36
+ * @param path - The path whose gate should be completed.
37
+ * @param proceed - Whether the waiting event may proceed or has been cancelled.
38
+ * @returns Nothing; snapshotting is requested even when the path has no current gate, and processing is not awaited.
39
+ */
40
+ export declare function finishBatchWaiting(batching: StorageEventBatching, path: string, proceed: boolean): void;
41
+ /**
42
+ * Calculate a gate delay which honours both minimum and maximum batch windows.
43
+ * @param now - The current time in milliseconds.
44
+ * @param acceptedAt - When the operation entered admission, used for the minimum delay.
45
+ * @param since - The inherited start of the maximum-delay window.
46
+ * @param minimum - The minimum delay in milliseconds.
47
+ * @param maximum - The maximum delay in milliseconds.
48
+ * @returns Whether the maximum window has expired and the non-negative delay to schedule.
49
+ * @remarks The original timing sketch follows; each row shows an event arriving within the same maximum window.
50
+ * ```text
51
+ * x*<------- maxDelay --------->*
52
+ * x*<-- minDelay -->*
53
+ * x* x<-- nextDelay -->*
54
+ * x* x<-- Capped-->*
55
+ * x* x.......*
56
+ * x: event
57
+ * *: batch gate becomes eligible for processing
58
+ * ```
59
+ * The quiet delay is measured from the latest accepted event. Coalescing inherits the first uncommitted event's
60
+ * maximum window, so repeated events cannot postpone eligibility indefinitely. Filtering time already spent since
61
+ * acceptance counts towards both delays. The maximum caps intentional batching, not semaphore, I/O, or snapshot
62
+ * completion time; it does not guarantee a minimum interval between completed saves.
63
+ */
64
+ export declare function planBatchDeadline(now: number, acceptedAt: number, since: number, minimum: number, maximum: number): {
65
+ expired: boolean;
66
+ delay: number;
67
+ };
68
+ /**
69
+ * Create and schedule a timed gate for one path, then request a snapshot.
70
+ * @param batching - Host effects for state, settings, logging, and gate control.
71
+ * @param path - The key which must not already own a gate.
72
+ * @param event - The event which will wait at this gate.
73
+ * @param waitedSince - Optional inherited start for the maximum-delay window.
74
+ * @returns The gate and its `canProceed` promise; its boolean result is not handler completion.
75
+ * @throws An error when a gate already exists for `path`.
76
+ */
77
+ export declare function addBatchWaiting(batching: StorageEventBatching, path: string, event: FileEventItem, waitedSince?: number): WaitInfo;
78
+ /**
79
+ * Mark operations for flushing, signal active optional handlers, and release matching gates.
80
+ * @param batching - Host effects for waiting state and gate control.
81
+ * @param operations - The operations whose flush requests should be applied.
82
+ * @returns Nothing; this opens gates but does not wait for handlers or operation completion.
83
+ */
84
+ export declare function releaseFileEventBatches(batching: StorageEventBatching, operations: readonly PendingFileEvent[]): void;
85
+ /**
86
+ * Initialise predecessor relationships and obtain this operation's batch-gate result.
87
+ * @param batching - Host effects for operation lookup, current settings, deadlines, and gate control.
88
+ * @param operation - The operation whose predecessor plan and gate are being prepared.
89
+ * @returns A promise resolving to the gate's boolean proceed result, not file-handler completion.
90
+ * @remarks A coalesced predecessor's eventual completion follows its successor attempt.
91
+ * @throws An error if the path already has a batch gate when this operation needs one.
92
+ */
93
+ export declare function initialiseFileEventBatch(batching: StorageEventBatching, operation: PendingFileEvent): Promise<boolean>;
@@ -0,0 +1,97 @@
1
+ import { LOG_LEVEL_DEBUG } from "../../common/types.js";
2
+ import { compatGlobal } from "../../common/coreEnvFunctions.js";
3
+ import {
4
+ createDeferredAction
5
+ } from "octagonal-wheels/concurrency/deferredAction";
6
+ import { promiseWithResolvers } from "octagonal-wheels/promises";
7
+ import { planFileEventPredecessors } from "./operations.js";
8
+ const scheduleStorageTimeout = (callback, delayMs) => {
9
+ const handle = compatGlobal.setTimeout(callback, delayMs);
10
+ return () => compatGlobal.clearTimeout(handle);
11
+ };
12
+ function finishBatchWaiting(batching, path, proceed) {
13
+ const waiting = batching.waiting();
14
+ const waitInfo = waiting.get(path);
15
+ if (waitInfo) {
16
+ waitInfo.canProceed.resolve(proceed);
17
+ waitInfo.deadline.dispose();
18
+ waiting.delete(path);
19
+ }
20
+ batching.requestSnapshot();
21
+ }
22
+ function planBatchDeadline(now, acceptedAt, since, minimum, maximum) {
23
+ const elapsed = now - since;
24
+ return {
25
+ expired: elapsed >= maximum,
26
+ delay: Math.min(Math.max(0, maximum - elapsed), Math.max(0, minimum - (now - acceptedAt)))
27
+ };
28
+ }
29
+ function addBatchWaiting(batching, path, event, waitedSince) {
30
+ const waiting = batching.waiting();
31
+ if (waiting.has(path)) throw new Error(`Already waiting for key: ${path}`);
32
+ const now = Date.now();
33
+ const acceptedAt = batching.operation(event)?.acceptedAt ?? now;
34
+ const since = waitedSince ?? acceptedAt;
35
+ const maximum = batching.maximumDelay() * 1e3;
36
+ const minimum = batching.minimumDelay() * 1e3;
37
+ const plan = planBatchDeadline(now, acceptedAt, since, minimum, maximum);
38
+ batching.log(
39
+ plan.expired ? `Processing ${path}: Batch save maximum delay already exceeded: ${event.type}` : `Processing ${path}: Adding waiting for batch save: ${event.type} (${plan.delay}ms)`,
40
+ LOG_LEVEL_DEBUG
41
+ );
42
+ const deadline = createDeferredAction(() => {
43
+ batching.log(`Processing ${path}: Batch save timeout reached: ${event.type}`, LOG_LEVEL_DEBUG);
44
+ batching.proceed(path);
45
+ }, scheduleStorageTimeout);
46
+ const waitInfo = {
47
+ since,
48
+ type: event.type,
49
+ event,
50
+ canProceed: promiseWithResolvers(),
51
+ deadline
52
+ };
53
+ deadline.schedule(plan.delay);
54
+ waiting.set(path, waitInfo);
55
+ batching.requestSnapshot();
56
+ return waitInfo;
57
+ }
58
+ function releaseFileEventBatches(batching, operations) {
59
+ for (const operation of operations) {
60
+ operation.flushRequested = true;
61
+ operation.flushSignal?.resolve();
62
+ const path = operation.event.args.file.path;
63
+ if (batching.waiting().get(path)?.event === operation.event) batching.proceed(path);
64
+ }
65
+ }
66
+ function applyPredecessorPlan(batching, operation, plan) {
67
+ for (const action of plan.actions) {
68
+ const { previous, path } = action;
69
+ if (action.kind === "coalesce") {
70
+ previous.attempt.successor = operation.attempt;
71
+ for (const dependency of previous.prerequisites) operation.prerequisites.add(dependency);
72
+ batching.cancel(path);
73
+ } else {
74
+ operation.prerequisites.add(previous);
75
+ if (batching.waiting().get(path)?.event === previous.event) batching.proceed(path);
76
+ }
77
+ }
78
+ }
79
+ function initialiseFileEventBatch(batching, operation) {
80
+ operation.initialised = true;
81
+ const event = operation.event;
82
+ const path = event.args.file.path;
83
+ const waiting = batching.waiting().get(path);
84
+ const plan = planFileEventPredecessors(operation, waiting);
85
+ applyPredecessorPlan(batching, operation, plan);
86
+ if (batching.waiting().get(path) === waiting && waiting) batching.proceed(path);
87
+ if (operation.flushRequested) releaseFileEventBatches(batching, [...operation.prerequisites]);
88
+ const shouldWait = batching.enabled() && !event.skipBatchWait && !operation.flushRequested && (event.type === "CREATE" || event.type === "CHANGED");
89
+ return shouldWait ? batching.add(path, event, plan.since).canProceed.promise : Promise.resolve(true);
90
+ }
91
+ export {
92
+ addBatchWaiting,
93
+ finishBatchWaiting,
94
+ initialiseFileEventBatch,
95
+ planBatchDeadline,
96
+ releaseFileEventBatches
97
+ };
@@ -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 {};