@vrtmrz/livesync-commonlib 0.7.0 → 0.8.0

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 (62) hide show
  1. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  2. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  3. package/dist/managers/EntryManager/EntryManagerImpls.js +76 -4
  4. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  5. package/dist/managers/StorageEventManager/admission.js +13 -3
  6. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  7. package/dist/managers/StorageEventManager/processing.js +3 -3
  8. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  9. package/dist/managers/StorageEventManager/queue.js +70 -30
  10. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  11. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  12. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  13. package/dist/managers/StorageEventManager/state.js +9 -7
  14. package/dist/managers/StorageEventManager.d.ts +6 -0
  15. package/dist/managers/StorageEventManager.js +135 -18
  16. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  17. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  18. package/dist/managers/adapters/index.d.ts +1 -1
  19. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +5 -2
  20. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -4
  21. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +28 -0
  22. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +53 -0
  23. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +59 -3
  24. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  25. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  26. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  27. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  28. package/dist/worker/WorkerPushStreamReader.js +179 -0
  29. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  30. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  31. package/dist/worker/bg.worker.js +2 -16
  32. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  33. package/dist/worker/bg.worker.splitting.js +46 -47
  34. package/dist/worker/bgWorker.d.ts +8 -14
  35. package/dist/worker/bgWorker.direct.d.ts +5 -28
  36. package/dist/worker/bgWorker.direct.js +32 -2
  37. package/dist/worker/bgWorker.errors.d.ts +1 -0
  38. package/dist/worker/bgWorker.errors.js +12 -0
  39. package/dist/worker/bgWorker.js +716 -296
  40. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  41. package/dist/worker/bgWorker.splitting.js +115 -107
  42. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  43. package/dist/worker/outOfBandCancelIterator.js +8 -0
  44. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  45. package/dist/worker/serveBackgroundWorker.js +35 -0
  46. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  47. package/dist/worker/splitConnectionTracker.js +73 -0
  48. package/dist/worker/splitGate.d.ts +19 -0
  49. package/dist/worker/splitGate.js +71 -0
  50. package/dist/worker/universalTypes.d.ts +0 -30
  51. package/dist/worker/universalTypes.js +0 -4
  52. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  53. package/dist/worker/workerPushStreamProtocol.js +143 -0
  54. package/docs/development.md +6 -0
  55. package/docs/storage-events-and-reflection.md +30 -2
  56. package/package.json +1 -1
  57. package/dist/worker/bg.common.d.ts +0 -2
  58. package/dist/worker/bg.common.js +0 -6
  59. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  60. package/dist/worker/bg.worker.encryption.js +0 -30
  61. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  62. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -23,6 +23,7 @@ class StoredFileReflectionProvenance {
23
23
  await this.store.delete(path);
24
24
  }
25
25
  async move(from, to) {
26
+ if (from === to) return;
26
27
  const record = await this.get(from);
27
28
  if (record) {
28
29
  await this.set(to, record);
@@ -8,4 +8,4 @@ export interface KeyValueDatabase {
8
8
  destroy(): Promise<void>;
9
9
  }
10
10
  /** Opens the key-value database owned by one service composition. */
11
- export type KeyValueDatabaseFactory = (databaseKey: string) => Promise<KeyValueDatabase>;
11
+ export type KeyValueDatabaseFactory<TDatabase extends KeyValueDatabase = KeyValueDatabase> = (databaseKey: string) => Promise<TDatabase>;
@@ -11,9 +11,57 @@ import { isErrorOfMissingDoc } from "../../pouchdb/utils_couchdb.js";
11
11
  import { stripAllPrefixes } from "../../string_and_binary/path.js";
12
12
  import { ICHeader, ICXHeader, PSCHeader } from "../../common/models/fileaccess.const.js";
13
13
  import { ContentReadError } from "../../common/LSError.js";
14
+ import { isOutOfBandCancellableIterator } from "../../worker/outOfBandCancelIterator.js";
15
+ const MAX_WRITE_SIZE = 2048e3;
14
16
  function readFromDatabase(readScope, operation) {
15
17
  return readScope ? readScope.run(operation) : operation();
16
18
  }
19
+ function createChunkWritePipeline(pieces, flushBufferedChunks, onWriteError) {
20
+ let pendingWrite;
21
+ let writeFailure = false;
22
+ let closing;
23
+ function closePieces() {
24
+ closing ??= (async () => {
25
+ try {
26
+ await pieces.return?.();
27
+ } catch {
28
+ }
29
+ })();
30
+ return closing;
31
+ }
32
+ function failWrite(rejected, error) {
33
+ if (!writeFailure) {
34
+ writeFailure = true;
35
+ if (rejected) {
36
+ onWriteError(error);
37
+ }
38
+ }
39
+ void closePieces();
40
+ return false;
41
+ }
42
+ async function waitForWrite() {
43
+ if (pendingWrite !== void 0) {
44
+ const ok = await pendingWrite;
45
+ pendingWrite = void 0;
46
+ return ok && !writeFailure;
47
+ }
48
+ return !writeFailure;
49
+ }
50
+ async function startWrite() {
51
+ if (pendingWrite !== void 0 && !await waitForWrite()) {
52
+ return false;
53
+ }
54
+ if (writeFailure) {
55
+ return false;
56
+ }
57
+ pendingWrite = flushBufferedChunks().then(
58
+ (ok) => ok ? true : failWrite(false),
59
+ (error) => failWrite(true, error)
60
+ );
61
+ return true;
62
+ }
63
+ return { startWrite, waitForWrite, closePieces, failed: () => writeFailure };
64
+ }
17
65
  async function createChunks(managers, dispFilename, note) {
18
66
  const { chunkManager, splitter, log = Logger } = managers;
19
67
  let bufferedChunk = [];
@@ -25,7 +73,6 @@ async function createChunks(managers, dispFilename, note) {
25
73
  let duplicatedCount = 0;
26
74
  let totalWritingCount = 0;
27
75
  let createChunkCount = 0;
28
- const MAX_WRITE_SIZE = 1e3 * 1024 * 2;
29
76
  const chunks = [];
30
77
  let writeChars = 0;
31
78
  const flushBufferedChunks = async () => {
@@ -56,9 +103,15 @@ async function createChunks(managers, dispFilename, note) {
56
103
  log(`Flushed ${writeBuf.length} (${writeChars}) chunks for ${dispFilename}`, LOG_LEVEL_VERBOSE);
57
104
  return true;
58
105
  };
106
+ const pieces = await splitter.splitContent(note);
107
+ const pipeline = isOutOfBandCancellableIterator(pieces) ? createChunkWritePipeline(pieces, flushBufferedChunks, (error) => {
108
+ log(`Error processing pieces for ${dispFilename}`);
109
+ log(error, LOG_LEVEL_VERBOSE);
110
+ }) : void 0;
59
111
  const flushIfNeeded = async () => {
60
112
  if (bufferedSize > MAX_WRITE_SIZE) {
61
- if (!await flushBufferedChunks()) {
113
+ const ok = pipeline ? await pipeline.startWrite() : await flushBufferedChunks();
114
+ if (!ok) {
62
115
  log(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE);
63
116
  return false;
64
117
  }
@@ -76,28 +129,47 @@ async function createChunks(managers, dispFilename, note) {
76
129
  bufferedSize += chunk.data.length;
77
130
  return await flushIfNeeded();
78
131
  };
79
- const pieces = await splitter.splitContent(note);
80
132
  let totalChunkCount = 0;
133
+ let complete = false;
81
134
  try {
82
135
  for await (const piece of pieces) {
136
+ if (pipeline?.failed()) {
137
+ break;
138
+ }
83
139
  totalChunkCount++;
84
140
  if (piece.length === 0) {
85
141
  continue;
86
142
  }
87
143
  createChunkCount++;
88
144
  const chunk = await prepareChunk(managers, piece);
145
+ if (pipeline?.failed()) {
146
+ break;
147
+ }
89
148
  cachedCount += chunk.isNew ? 0 : 1;
90
149
  newCount += chunk.isNew ? 1 : 0;
91
150
  if (!await addBuffer(chunk.id, chunk.piece)) {
92
151
  return false;
93
152
  }
94
153
  }
154
+ if (pipeline && (!await pipeline.startWrite() || !await pipeline.waitForWrite())) {
155
+ return false;
156
+ }
157
+ complete = true;
95
158
  } catch (ex) {
96
159
  log(`Error processing pieces for ${dispFilename}`);
97
160
  log(ex, LOG_LEVEL_VERBOSE);
98
161
  return false;
162
+ } finally {
163
+ if (pipeline) {
164
+ if (!complete) {
165
+ bufferedChunk = [];
166
+ bufferedSize = 0;
167
+ await pipeline.closePieces();
168
+ }
169
+ await pipeline.waitForWrite();
170
+ }
99
171
  }
100
- if (!await flushBufferedChunks()) {
172
+ if (!pipeline && !await flushBufferedChunks()) {
101
173
  return false;
102
174
  }
103
175
  const dataSize = note.data.size;
@@ -5,8 +5,8 @@ import { type FileEventItem, type ObsidianLiveSyncSettings } from "../../common/
5
5
  import type { FileEvent } from "../../interfaces/StorageEventManager.js";
6
6
  import type { IStorageAccessManager } from "../../interfaces/StorageAccess.js";
7
7
  import type { LogFunction } from "../../services/lib/logUtils.js";
8
- import type { StorageEventState } from "./state.js";
9
- import type { PendingFileEvent } from "./operations.js";
8
+ import type { EventAdmission, StorageEventState } from "./state.js";
9
+ import type { FileEventAttempt, PendingFileEvent } from "./operations.js";
10
10
  /**
11
11
  * Inject host settings, path and file checks, queue actions, and diagnostics into admission.
12
12
  * @remarks
@@ -38,14 +38,26 @@ type SelectedFileEvent = Pick<FileEventItem, "type" | "args">;
38
38
  * @remarks The source-only case asserts that `oldPath` and file `stat` are present; `selectRename` establishes those preconditions.
39
39
  */
40
40
  export declare function selectRenameFileEvent(param: FileEvent, oldSelected: boolean, newSelected: boolean): SelectedFileEvent | null;
41
+ /**
42
+ * Enqueue a selected item and associate its operation with the admission boundary.
43
+ * @param state - Mutable operation ownership state.
44
+ * @param admission - The batch admission record receiving this operation.
45
+ * @param item - The selected event to enqueue.
46
+ * @param effects - Queue and release actions supplied by the facade.
47
+ * @returns Nothing; a found operation receives admission time, failure boundary, and attempt tracking.
48
+ */
49
+ export declare function registerAdmission(state: StorageEventState, admission: EventAdmission, item: FileEventItem, effects: StorageEventAdmissionEffects): FileEventAttempt | undefined;
41
50
  /**
42
51
  * Start and track a batch of host events through filtering and queue admission.
43
52
  * @param state - Mutable state which owns admission and operation boundaries.
44
53
  * @param params - Host watcher events to select.
45
54
  * @param ctx - Optional host context forwarded to admitted items.
46
55
  * @param effects - Host services used during selection and enqueueing.
56
+ * @param ready - Load ordered buffers before filtering, if initial loading is still needed.
47
57
  * @returns A promise for admission completion, not handler completion; rejected admission is reported and remains rejected.
48
58
  * @remarks When the manager no longer accepts events, this returns an already-fulfilled promise without admitting them.
49
59
  */
50
- export declare function admitStorageEvents(state: StorageEventState, params: readonly FileEvent[], ctx: unknown, effects: StorageEventAdmissionEffects): Promise<void>;
60
+ export declare function admitStorageEvents(state: StorageEventState, params: readonly FileEvent[], ctx: unknown, effects: StorageEventAdmissionEffects, ready?: () => Promise<unknown> | undefined): Promise<void>;
61
+ /** Register an admission synchronously, including when it must wait for the saved buffers to load. */
62
+ export declare function trackStorageEventAdmission(state: StorageEventState, effects: StorageEventAdmissionEffects, start: (admission: EventAdmission) => Promise<void>): Promise<void>;
51
63
  export {};
@@ -97,6 +97,7 @@ function registerAdmission(state, admission, item, effects) {
97
97
  operation.failureBoundary = admission.failureBoundary;
98
98
  if (admission.flushRequested) effects.release([operation]);
99
99
  admission.operations.set(operation, operation.attempt);
100
+ return operation.attempt;
100
101
  }
101
102
  async function appendStorageEvents(state, params, ctx, admission, effects) {
102
103
  const settings = effects.settings();
@@ -107,7 +108,14 @@ async function appendStorageEvents(state, params, ctx, admission, effects) {
107
108
  if (item) registerAdmission(state, admission, item, effects);
108
109
  }
109
110
  }
110
- function admitStorageEvents(state, params, ctx, effects) {
111
+ function admitStorageEvents(state, params, ctx, effects, ready) {
112
+ return trackStorageEventAdmission(state, effects, (admission) => {
113
+ const loading = ready?.();
114
+ const append = () => appendStorageEvents(state, params, ctx, admission, effects);
115
+ return loading ? loading.then(append) : append();
116
+ });
117
+ }
118
+ function trackStorageEventAdmission(state, effects, start) {
111
119
  if (!state.acceptingEvents) return Promise.resolve();
112
120
  const admission = {
113
121
  acceptedAt: Date.now(),
@@ -117,7 +125,7 @@ function admitStorageEvents(state, params, ctx, effects) {
117
125
  flushRequested: false
118
126
  };
119
127
  state.admissions.add(admission);
120
- admission.completion = appendStorageEvents(state, params, ctx, admission, effects);
128
+ admission.completion = start(admission);
121
129
  void admission.completion.then(
122
130
  () => state.admissions.delete(admission),
123
131
  (error) => {
@@ -129,5 +137,7 @@ function admitStorageEvents(state, params, ctx, effects) {
129
137
  }
130
138
  export {
131
139
  admitStorageEvents,
132
- selectRenameFileEvent
140
+ registerAdmission,
141
+ selectRenameFileEvent,
142
+ trackStorageEventAdmission
133
143
  };
@@ -38,8 +38,8 @@ export interface StorageEventAttemptEffects extends StorageEventNotifications {
38
38
  * @param effects - Host callbacks for snapshots, dependencies, processing, failure, and status.
39
39
  * @returns A promise which resolves after the attempt's completion-snapshot step and success settlement, or after
40
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
41
+ * @remarks An ordered entry awaiting commit is observed through its current attempt. Dispatch starts that attempt
42
+ * after commit. For legacy entries, the new attempt starts before the initial intent snapshot. On failure, its batch wait
43
43
  * is cancelled, the attempt is failed, and the error is rethrown. Status is refreshed in either case.
44
44
  */
45
45
  export declare function processStorageEventAttempt(state: StorageEventState, operation: PendingFileEvent, attempt: FileEventAttempt, effects: StorageEventAttemptEffects): Promise<void>;
@@ -38,15 +38,15 @@ async function executeAttempt(state, operation, attempt, canProceed, effects) {
38
38
  });
39
39
  }
40
40
  async function processStorageEventAttempt(state, operation, attempt, effects) {
41
- if (attempt.started || attempt.result) {
41
+ const entry = state.pendingSnapshot.get(operation.event);
42
+ if (attempt.started || attempt.result || state.ordered && !entry.savedBuffer) {
42
43
  assertSuccessfulFileEvents([await attempt.completion.promise]);
43
44
  return;
44
45
  }
45
46
  attempt.started = true;
46
- const entry = state.pendingSnapshot.get(operation.event);
47
47
  try {
48
48
  const gate = prepareAttempt(state, operation, attempt, effects);
49
- await effects.takeSnapshot();
49
+ if (!state.ordered) await effects.takeSnapshot();
50
50
  assertFileEventAdmission(attempt);
51
51
  const canProceed = await gate;
52
52
  assertFileEventAdmission(attempt);
@@ -1,11 +1,12 @@
1
1
  /**
2
- * Coordinate buffer admission, finite flushes, sentinel dispatch, and snapshot restoration.
3
- * Attempt processing and persistence remain delegated through explicit host effects.
2
+ * Coordinate in-memory dispatch for both the legacy snapshot and the ordered buffer store.
3
+ * The in-memory queue advances dispatch. Persistence retains intent until acknowledgement.
4
4
  */
5
5
  import type { FileEventItem } from "../../common/types.js";
6
6
  import type { LogFunction } from "../../services/lib/logUtils.js";
7
+ import type { PendingStorageEventBuffer } from "../adapters/index.js";
7
8
  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
+ import { type PendingSnapshotEntry, type QueuedFileEvent, type RunQueuedEventsOptions, type StorageEventBuffer, type StorageEventNotifications, type StorageEventState } from "./state.js";
9
10
  /** Host callbacks used by queue ownership, dispatch, finite flush, and restoration. */
10
11
  export interface StorageEventQueueEffects extends StorageEventNotifications {
11
12
  /** Host-owned event buffer used by admission, dispatch, and retry. */
@@ -14,6 +15,8 @@ export interface StorageEventQueueEffects extends StorageEventNotifications {
14
15
  log: LogFunction;
15
16
  /** Persist the current intent snapshot. */
16
17
  takeSnapshot(): Promise<void>;
18
+ /** Mark the sentinel complete after its predecessors settle. A partially completed array remains replayable. */
19
+ acknowledgeSentinel?(entry: PendingSnapshotEntry): Promise<void>;
17
20
  /** Load the prior runtime's saved event intent, if any. */
18
21
  loadSnapshot(): Promise<QueuedFileEvent[] | null>;
19
22
  /** Enter the host event-processing route for one file event. */
@@ -30,28 +33,27 @@ export interface StorageEventQueueEffects extends StorageEventNotifications {
30
33
  fail(operation: PendingFileEvent, error: unknown, attempt: FileEventAttempt): void;
31
34
  }
32
35
  /**
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.
36
+ * Retain an accepted event and schedule persistence.
37
+ * @remarks Ordered storage stages the event and its marker together. The append owner publishes them to dispatch
38
+ * after commit and settles their attempts on failure. Legacy storage publishes before its background snapshot.
41
39
  */
42
40
  export declare function enqueueStorageEvent(state: StorageEventState, event: FileEventItem, effects: StorageEventQueueEffects): void;
41
+ /** Publish a committed array in arrival order and start dispatch. */
42
+ export declare function publishCommittedStorageEvents(state: StorageEventState, events: readonly QueuedFileEvent[], effects: StorageEventQueueEffects): void;
43
43
  /**
44
44
  * Flush the finite set of operations and admissions visible at entry.
45
45
  * @param state - The manager state containing active admissions, retained operations, and the current failure sequence.
46
46
  * @param effects - Callbacks for capturing attempts, releasing gates, dispatching, waiting, and reporting failures.
47
+ * @param loading - A pending initial load already requested at this flush boundary.
47
48
  * @returns A promise which settles after captured admissions and attempts; rejects with the first rejected admission
48
49
  * or, when admissions succeeded, the first failed operation result.
49
50
  * @remarks Flush intent is signalled before awaiting active admissions. Current buffered work is retained and batch
50
51
  * 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.
52
+ * are merged without replacing earlier captures. A load already in progress also contributes its restored
53
+ * operations. Dispatch is then started in the background. Work admitted after the initial capture can remain
54
+ * outside this finite wait.
53
55
  */
54
- export declare function flushStorageEvents(state: StorageEventState, effects: StorageEventQueueEffects): Promise<void>;
56
+ export declare function flushStorageEvents(state: StorageEventState, effects: StorageEventQueueEffects, loading?: Promise<readonly PendingFileEvent[]>): Promise<void>;
55
57
  /**
56
58
  * Share queue dispatch and optionally wait for the operations visible at call time.
57
59
  * @param state - The manager state providing retained operations and this manager's stable dispatch key.
@@ -71,3 +73,10 @@ export declare function runBufferedStorageEvents(state: StorageEventState, effec
71
73
  * failed attempt results are reported by the queue callback.
72
74
  */
73
75
  export declare function restoreStorageEvents(effects: StorageEventQueueEffects): Promise<void>;
76
+ /**
77
+ * Register already committed arrays in replay order before exposing their events to dispatch.
78
+ * @remarks Each array shares one remaining-entry count. The last acknowledgement removes its key. A partial
79
+ * failure leaves the original array available for reconciliation by the next runtime.
80
+ * @returns The restored file operations, which callers can include in a flush already in progress.
81
+ */
82
+ export declare function restoreOrderedStorageEvents(state: StorageEventState, effects: StorageEventQueueEffects, buffers: readonly PendingStorageEventBuffer[]): PendingFileEvent[];
@@ -11,15 +11,15 @@ import {
11
11
  retainFileEvent
12
12
  } from "./state.js";
13
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);
14
+ const events = event.type === "DELETE" || event.type === "RENAME" ? [{ type: TYPE_SENTINEL_FLUSH }, event] : [event];
15
+ if (state.ordered) {
16
+ for (const item of events) retainFileEvent(state, item, false);
17
+ effects.updateStatus();
18
+ fireAndForget(effects.takeSnapshot());
19
+ return;
19
20
  }
20
- const operation = retainFileEvent(state, event).operation;
21
- operation.barrierBefore ??= barrierBefore;
22
- effects.buffer.append(event);
21
+ publishBufferedEvents(state, events, effects.buffer);
22
+ const operation = state.operations.get(event);
23
23
  const attempt = operation.attempt;
24
24
  effects.updateStatus();
25
25
  fireAndForget(async () => {
@@ -34,6 +34,16 @@ function enqueueStorageEvent(state, event, effects) {
34
34
  }
35
35
  });
36
36
  }
37
+ function publishBufferedEvents(state, events, buffer) {
38
+ retainBufferedFileEvents(state, events);
39
+ for (const event of events) buffer.append(event);
40
+ }
41
+ function publishCommittedStorageEvents(state, events, effects) {
42
+ publishBufferedEvents(state, events, effects.buffer);
43
+ fireAndForget(
44
+ Promise.resolve().then(() => effects.runQueuedEvents()).catch(effects.reportFailure)
45
+ );
46
+ }
37
47
  function mergeAdmittedAttempts(boundary, admissions) {
38
48
  for (const admission of admissions) {
39
49
  for (const [operation, attempt] of admission.operations) {
@@ -41,13 +51,19 @@ function mergeAdmittedAttempts(boundary, admissions) {
41
51
  }
42
52
  }
43
53
  }
44
- async function flushStorageEvents(state, effects) {
54
+ async function flushStorageEvents(state, effects, loading) {
45
55
  const admissions = [...state.admissions];
46
56
  for (const admission of admissions) admission.flushRequested = true;
47
- retainBufferedFileEvents(state, effects.buffer.read());
57
+ if (!state.ordered) retainBufferedFileEvents(state, effects.buffer.read());
48
58
  const operations = pendingFileOperations(state);
49
59
  effects.release(operations);
50
60
  const boundary = effects.capture(operations, state.nextFailureSequence);
61
+ if (loading) {
62
+ for (const operation of await loading) {
63
+ if (!boundary.has(operation)) boundary.set(operation, operation.attempt);
64
+ }
65
+ effects.release([...boundary.keys()]);
66
+ }
51
67
  const admitted = await Promise.allSettled(admissions.map((admission) => admission.completion));
52
68
  mergeAdmittedAttempts(boundary, admissions);
53
69
  effects.release([...boundary.keys()]);
@@ -58,15 +74,21 @@ async function flushStorageEvents(state, effects) {
58
74
  assertSuccessfulFileEvents(results);
59
75
  }
60
76
  async function dispatchBufferedEvents(state, effects) {
61
- while (effects.buffer.read().length > 0) {
62
- const event = effects.buffer.shift();
77
+ while (true) {
78
+ const event = effects.buffer.peek();
79
+ if (event === void 0) {
80
+ return;
81
+ }
63
82
  const entry = retainFileEvent(state, event);
83
+ if (!effects.buffer.takeHead(event)) {
84
+ continue;
85
+ }
64
86
  if (event.type === TYPE_SENTINEL_FLUSH) {
65
87
  entry.dispatched = true;
66
88
  const results = await effects.wait(effects.capture(pendingFileOperations(state, entry.sequence)));
67
- if (results.every((result) => result.ok)) {
89
+ if (effects.acknowledgeSentinel || results.every((result) => result.ok)) {
68
90
  try {
69
- await effects.takeSnapshot();
91
+ await (effects.acknowledgeSentinel?.(entry) ?? effects.takeSnapshot());
70
92
  } catch (error) {
71
93
  effects.reportFailure(error);
72
94
  }
@@ -78,16 +100,14 @@ async function dispatchBufferedEvents(state, effects) {
78
100
  }
79
101
  }
80
102
  async function runBufferedStorageEvents(state, effects, options = {}) {
81
- retainBufferedFileEvents(state, effects.buffer.read());
82
- const accepted = pendingFileOperations(state);
103
+ if (!state.ordered) retainBufferedFileEvents(state, effects.buffer.read());
104
+ const accepted = options.waitForProcessing ? pendingFileOperations(state) : void 0;
83
105
  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
- }
106
+ if (!accepted) return;
107
+ const results = await effects.wait(effects.capture(accepted));
108
+ if (state.ordered) return;
109
+ for (const result of results) {
110
+ if (result.ok === false) effects.reportFailure(result.error);
91
111
  }
92
112
  }
93
113
  async function restoreStorageEvents(effects) {
@@ -96,18 +116,38 @@ async function restoreStorageEvents(effects) {
96
116
  effects.log("No snapshot to restore", LOG_LEVEL_VERBOSE);
97
117
  return;
98
118
  }
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();
119
+ replayStorageEvents(effects, snapshot.map(markRestoredEvent));
106
120
  await effects.runQueuedEvents({ waitForProcessing: true });
107
121
  }
122
+ function restoreOrderedStorageEvents(state, effects, buffers) {
123
+ const events = [];
124
+ const operations = [];
125
+ for (const { key, events: saved } of buffers) {
126
+ const buffer = { key, remaining: saved.length };
127
+ for (const event of saved) {
128
+ const restored = event.type === TYPE_SENTINEL_FLUSH ? { ...event } : markRestoredEvent(event);
129
+ const entry = retainFileEvent(state, restored, true, buffer);
130
+ events.push(restored);
131
+ if (entry.operation) operations.push(entry.operation);
132
+ }
133
+ }
134
+ retainBufferedFileEvents(state, events);
135
+ replayStorageEvents(effects, events);
136
+ return operations;
137
+ }
138
+ function markRestoredEvent(event) {
139
+ return event.type === TYPE_SENTINEL_FLUSH ? event : { ...event, restoredFromPreviousRuntime: true, skipBatchWait: true };
140
+ }
141
+ function replayStorageEvents(effects, events) {
142
+ effects.log(`Restoring storage operation snapshot: ${events.length} items`, LOG_LEVEL_VERBOSE);
143
+ effects.buffer.replace(events);
144
+ effects.updateStatus();
145
+ }
108
146
  export {
109
147
  enqueueStorageEvent,
110
148
  flushStorageEvents,
149
+ publishCommittedStorageEvents,
150
+ restoreOrderedStorageEvents,
111
151
  restoreStorageEvents,
112
152
  runBufferedStorageEvents
113
153
  };
@@ -3,7 +3,7 @@
3
3
  * The snapshot tail keeps provisional marking, save, rollback, and in-memory acknowledgement in one ordered step.
4
4
  */
5
5
  import type { FileEventItem } from "../../common/types.js";
6
- import { type PendingSnapshotEntry, type QueuedFileEvent, type SnapshotCompletion, type StorageEventBuffer, type StorageEventState } from "./state.js";
6
+ import { type OrderedStorageEventState, type PendingSnapshotEntry, type QueuedFileEvent, type SnapshotCompletion, type StorageEventBuffer, type StorageEventState } from "./state.js";
7
7
  /** Snapshot persistence and status callbacks supplied by the owning manager. */
8
8
  export interface StorageEventSnapshotIO {
9
9
  /** Save the currently pending event intents using the existing snapshot format. */
@@ -44,3 +44,14 @@ export declare function planFileEventSnapshot(entries: readonly PendingSnapshotE
44
44
  * this caller; the caught tail allows later saves to proceed.
45
45
  */
46
46
  export declare function persistFileEventSnapshot(state: StorageEventState, buffer: StorageEventBuffer, io: StorageEventSnapshotIO, completion?: SnapshotCompletion): Promise<void>;
47
+ /** Publish committed events and report an array that could not be queued. */
48
+ export interface OrderedStorageEventAppendEffects {
49
+ publish(events: readonly QueuedFileEvent[]): void;
50
+ reportAppendFailure(error: unknown): void;
51
+ }
52
+ /** Save the next buffer, coalescing requests until the writer detaches it. */
53
+ export declare function appendPendingEventBuffer(state: StorageEventState, ordered: OrderedStorageEventState, effects: OrderedStorageEventAppendEffects): Promise<void>;
54
+ /** Acknowledge one entry in memory, deleting its buffer only when the last entry completes. */
55
+ export declare function acknowledgeOrderedEntry(state: StorageEventState, ordered: OrderedStorageEventState, entry: PendingSnapshotEntry, updateStatus: () => void, completion?: SnapshotCompletion): Promise<void>;
56
+ /** Retire a saved buffer with no effects to replay. */
57
+ export declare function acknowledgeEmptyOrderedBuffer(state: StorageEventState, ordered: OrderedStorageEventState, key: string): Promise<void>;
@@ -1,5 +1,7 @@
1
+ import { delay } from "../../common/utils.js";
1
2
  import { assertFileEventAdmission } from "./operations.js";
2
3
  import {
4
+ failFileEventAttempt,
3
5
  retainBufferedFileEvents,
4
6
  retainFileEvent
5
7
  } from "./state.js";
@@ -47,7 +49,79 @@ async function persistFileEventSnapshot(state, buffer, io, completion) {
47
49
  });
48
50
  await save;
49
51
  }
52
+ const APPEND_YIELD_MS = 50;
53
+ function writeOrderedStore(state, write) {
54
+ const done = state.snapshotTail.then(write);
55
+ state.snapshotTail = done.catch(() => {
56
+ });
57
+ return done;
58
+ }
59
+ function discardStagedEntries(state, ordered, entries, error) {
60
+ for (const { event, operation } of entries) {
61
+ state.pendingSnapshot.delete(event);
62
+ if (operation) {
63
+ state.operations.delete(operation.event);
64
+ ordered.pendingOperations--;
65
+ failFileEventAttempt(state, operation.attempt, error);
66
+ }
67
+ }
68
+ }
69
+ function appendPendingEventBuffer(state, ordered, effects) {
70
+ if (ordered.nextWrite) return ordered.nextWrite;
71
+ const previous = ordered.appendTail;
72
+ if (ordered.nextBuffer.length === 0) return previous ?? Promise.resolve();
73
+ const write = (previous?.catch(() => {
74
+ }) ?? Promise.resolve()).then(async () => {
75
+ if (ordered.appendFinishedAt !== void 0) {
76
+ const elapsed = Math.max(0, Date.now() - ordered.appendFinishedAt);
77
+ const remainingYield = APPEND_YIELD_MS - elapsed;
78
+ if (remainingYield > 0) await delay(remainingYield);
79
+ }
80
+ await writeOrderedStore(state, async () => {
81
+ const entries = ordered.nextBuffer;
82
+ ordered.nextBuffer = [];
83
+ ordered.nextWrite = void 0;
84
+ const events = entries.map(({ event }) => event);
85
+ let key;
86
+ try {
87
+ key = await ordered.store.append(events);
88
+ } catch (error) {
89
+ discardStagedEntries(state, ordered, entries, error);
90
+ effects.reportAppendFailure(error);
91
+ throw error;
92
+ } finally {
93
+ if (ordered.appendTail === write) ordered.appendTail = void 0;
94
+ ordered.appendFinishedAt = Date.now();
95
+ }
96
+ const buffer = { key, remaining: entries.length };
97
+ for (const entry of entries) entry.savedBuffer = buffer;
98
+ effects.publish(events);
99
+ });
100
+ });
101
+ ordered.nextWrite = write;
102
+ ordered.appendTail = write;
103
+ return write;
104
+ }
105
+ function acknowledgeOrderedEntry(state, ordered, entry, updateStatus, completion) {
106
+ return writeOrderedStore(state, async () => {
107
+ if (completion) assertFileEventAdmission(completion.attempt);
108
+ if (state.pendingSnapshot.get(entry.event) !== entry) return;
109
+ if (completion && entry.operation?.attempt !== completion.attempt) return;
110
+ const buffer = entry.savedBuffer;
111
+ if (buffer.remaining === 1) await ordered.store.remove(buffer.key);
112
+ buffer.remaining--;
113
+ if (entry.operation) ordered.pendingOperations--;
114
+ state.pendingSnapshot.delete(entry.event);
115
+ updateStatus();
116
+ });
117
+ }
118
+ function acknowledgeEmptyOrderedBuffer(state, ordered, key) {
119
+ return writeOrderedStore(state, () => ordered.store.remove(key));
120
+ }
50
121
  export {
122
+ acknowledgeEmptyOrderedBuffer,
123
+ acknowledgeOrderedEntry,
124
+ appendPendingEventBuffer,
51
125
  persistFileEventSnapshot,
52
126
  planFileEventSnapshot
53
127
  };