@livestore/common 0.5.0-dev.1 → 0.5.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 (137) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/ClientSessionLeaderThreadProxy.d.ts +89 -7
  3. package/dist/ClientSessionLeaderThreadProxy.d.ts.map +1 -1
  4. package/dist/ClientSessionLeaderThreadProxy.js +11 -0
  5. package/dist/ClientSessionLeaderThreadProxy.js.map +1 -1
  6. package/dist/EventlogSqliteDb.d.ts +10 -0
  7. package/dist/EventlogSqliteDb.d.ts.map +1 -0
  8. package/dist/EventlogSqliteDb.js +7 -0
  9. package/dist/EventlogSqliteDb.js.map +1 -0
  10. package/dist/MaterializationJournal.d.ts +9 -14
  11. package/dist/MaterializationJournal.d.ts.map +1 -1
  12. package/dist/MaterializationJournal.js +79 -50
  13. package/dist/MaterializationJournal.js.map +1 -1
  14. package/dist/StateHead.d.ts +4 -6
  15. package/dist/StateHead.d.ts.map +1 -1
  16. package/dist/StateHead.js +5 -3
  17. package/dist/StateHead.js.map +1 -1
  18. package/dist/StateSqliteDb.d.ts +10 -0
  19. package/dist/StateSqliteDb.d.ts.map +1 -0
  20. package/dist/StateSqliteDb.js +7 -0
  21. package/dist/StateSqliteDb.js.map +1 -0
  22. package/dist/adapter-types.d.ts +3 -2
  23. package/dist/adapter-types.d.ts.map +1 -1
  24. package/dist/adapter-types.js.map +1 -1
  25. package/dist/devtools/devtools-messages-leader.d.ts +120 -6
  26. package/dist/devtools/devtools-messages-leader.d.ts.map +1 -1
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +2 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/leader-thread/LeaderPersistence.d.ts +65 -0
  32. package/dist/leader-thread/LeaderPersistence.d.ts.map +1 -0
  33. package/dist/leader-thread/LeaderPersistence.js +127 -0
  34. package/dist/leader-thread/LeaderPersistence.js.map +1 -0
  35. package/dist/leader-thread/LeaderSyncProcessor.d.ts +26 -126
  36. package/dist/leader-thread/LeaderSyncProcessor.d.ts.map +1 -1
  37. package/dist/leader-thread/LeaderSyncProcessor.js +830 -658
  38. package/dist/leader-thread/LeaderSyncProcessor.js.map +1 -1
  39. package/dist/leader-thread/connection.js +8 -3
  40. package/dist/leader-thread/connection.js.map +1 -1
  41. package/dist/leader-thread/eventlog.d.ts +24 -9
  42. package/dist/leader-thread/eventlog.d.ts.map +1 -1
  43. package/dist/leader-thread/eventlog.js +34 -28
  44. package/dist/leader-thread/eventlog.js.map +1 -1
  45. package/dist/leader-thread/leader-worker-devtools.d.ts +3 -1
  46. package/dist/leader-thread/leader-worker-devtools.d.ts.map +1 -1
  47. package/dist/leader-thread/leader-worker-devtools.js +45 -3
  48. package/dist/leader-thread/leader-worker-devtools.js.map +1 -1
  49. package/dist/leader-thread/make-leader-thread-layer.d.ts +7 -5
  50. package/dist/leader-thread/make-leader-thread-layer.d.ts.map +1 -1
  51. package/dist/leader-thread/make-leader-thread-layer.js +12 -13
  52. package/dist/leader-thread/make-leader-thread-layer.js.map +1 -1
  53. package/dist/leader-thread/materialize-event.d.ts +5 -11
  54. package/dist/leader-thread/materialize-event.d.ts.map +1 -1
  55. package/dist/leader-thread/materialize-event.js +38 -86
  56. package/dist/leader-thread/materialize-event.js.map +1 -1
  57. package/dist/leader-thread/mod.d.ts +1 -0
  58. package/dist/leader-thread/mod.d.ts.map +1 -1
  59. package/dist/leader-thread/mod.js +1 -0
  60. package/dist/leader-thread/mod.js.map +1 -1
  61. package/dist/leader-thread/recreate-db.d.ts +5 -5
  62. package/dist/leader-thread/recreate-db.d.ts.map +1 -1
  63. package/dist/leader-thread/recreate-db.js +3 -2
  64. package/dist/leader-thread/recreate-db.js.map +1 -1
  65. package/dist/leader-thread/shutdown-channel.d.ts +2 -1
  66. package/dist/leader-thread/shutdown-channel.d.ts.map +1 -1
  67. package/dist/leader-thread/shutdown-channel.js +8 -1
  68. package/dist/leader-thread/shutdown-channel.js.map +1 -1
  69. package/dist/leader-thread/types.d.ts +5 -11
  70. package/dist/leader-thread/types.d.ts.map +1 -1
  71. package/dist/leader-thread/types.js.map +1 -1
  72. package/dist/rematerialize-from-eventlog.d.ts +2 -2
  73. package/dist/rematerialize-from-eventlog.d.ts.map +1 -1
  74. package/dist/rematerialize-from-eventlog.js +4 -2
  75. package/dist/rematerialize-from-eventlog.js.map +1 -1
  76. package/dist/schema/LiveStoreEvent/client.d.ts +19 -64
  77. package/dist/schema/LiveStoreEvent/client.d.ts.map +1 -1
  78. package/dist/schema/LiveStoreEvent/client.js +28 -102
  79. package/dist/schema/LiveStoreEvent/client.js.map +1 -1
  80. package/dist/schema/LiveStoreEvent/client.test.js +5 -11
  81. package/dist/schema/LiveStoreEvent/client.test.js.map +1 -1
  82. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.js +8 -1
  83. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.js.map +1 -1
  84. package/dist/schema/state/sqlite/db-schema/ast/fingerprint.test.js +2 -2
  85. package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.d.ts +6 -1
  86. package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.d.ts.map +1 -1
  87. package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.js +9 -5
  88. package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.js.map +1 -1
  89. package/dist/schema/state/sqlite/system-tables/state-tables.d.ts +8 -139
  90. package/dist/schema/state/sqlite/system-tables/state-tables.d.ts.map +1 -1
  91. package/dist/schema/state/sqlite/system-tables/state-tables.js +11 -20
  92. package/dist/schema/state/sqlite/system-tables/state-tables.js.map +1 -1
  93. package/dist/schema-management/__tests__/migrations-autoincrement-quoting.test.js +1 -1
  94. package/dist/schema-management/__tests__/migrations-autoincrement-quoting.test.js.map +1 -1
  95. package/dist/sqlite-types.d.ts +1 -1
  96. package/dist/sqlite-types.d.ts.map +1 -1
  97. package/dist/sync/ClientSessionSyncProcessor.d.ts +42 -69
  98. package/dist/sync/ClientSessionSyncProcessor.d.ts.map +1 -1
  99. package/dist/sync/ClientSessionSyncProcessor.js +611 -291
  100. package/dist/sync/ClientSessionSyncProcessor.js.map +1 -1
  101. package/dist/sync/syncstate.d.ts +407 -27
  102. package/dist/sync/syncstate.d.ts.map +1 -1
  103. package/dist/sync/syncstate.js +26 -19
  104. package/dist/sync/syncstate.js.map +1 -1
  105. package/dist/sync/syncstate.test.js +25 -5
  106. package/dist/sync/syncstate.test.js.map +1 -1
  107. package/package.json +18 -18
  108. package/src/ClientSessionLeaderThreadProxy.ts +16 -7
  109. package/src/EventlogSqliteDb.ts +11 -0
  110. package/src/MaterializationJournal.ts +106 -77
  111. package/src/StateHead.ts +6 -7
  112. package/src/StateSqliteDb.ts +9 -0
  113. package/src/adapter-types.ts +9 -2
  114. package/src/index.ts +2 -0
  115. package/src/leader-thread/LeaderPersistence.ts +244 -0
  116. package/src/leader-thread/LeaderSyncProcessor.ts +1099 -1011
  117. package/src/leader-thread/connection.ts +9 -3
  118. package/src/leader-thread/eventlog.ts +54 -39
  119. package/src/leader-thread/leader-worker-devtools.ts +73 -4
  120. package/src/leader-thread/make-leader-thread-layer.ts +24 -21
  121. package/src/leader-thread/materialize-event.ts +47 -119
  122. package/src/leader-thread/mod.ts +1 -0
  123. package/src/leader-thread/recreate-db.ts +9 -6
  124. package/src/leader-thread/shutdown-channel.ts +8 -1
  125. package/src/leader-thread/types.ts +6 -8
  126. package/src/rematerialize-from-eventlog.ts +3 -3
  127. package/src/schema/LiveStoreEvent/client.test.ts +7 -12
  128. package/src/schema/LiveStoreEvent/client.ts +38 -122
  129. package/src/schema/state/sqlite/db-schema/ast/fingerprint.test.ts +2 -2
  130. package/src/schema/state/sqlite/db-schema/ast/fingerprint.ts +8 -1
  131. package/src/schema/state/sqlite/db-schema/has-json-string-encoding.ts +11 -7
  132. package/src/schema/state/sqlite/system-tables/state-tables.ts +13 -26
  133. package/src/schema-management/__tests__/migrations-autoincrement-quoting.test.ts +1 -1
  134. package/src/sqlite-types.ts +1 -1
  135. package/src/sync/ClientSessionSyncProcessor.ts +809 -456
  136. package/src/sync/syncstate.test.ts +32 -9
  137. package/src/sync/syncstate.ts +41 -29
@@ -1,269 +1,416 @@
1
1
  /// <reference lib="dom" />
2
- import { LS_DEV, TRACE_VERBOSE } from '@livestore/utils';
3
- import { Cause, Deferred, Effect, Exit, Filter, FiberHandle, Option, Queue, Schema, Semaphore, Stream, Subscribable, TxQueue, } from '@livestore/utils/effect';
4
- import { MaterializeError } from '../errors.js';
5
- import { isRejectedPushError } from '../leader-thread/RejectedPushError.js';
2
+ import { casesHandled, isDevEnv, TRACE_VERBOSE } from '@livestore/utils';
3
+ import { Cause, Deferred, Effect, Exit, FiberHandle, Option, Queue, References, Schema, Stream, Subscribable, } from '@livestore/utils/effect';
4
+ import { MaterializeError, MaterializerHashMismatchError, UnknownError } from '../errors.js';
5
+ import * as MaterializationJournal from '../MaterializationJournal.js';
6
6
  import * as EventSequenceNumber from '../schema/EventSequenceNumber/mod.js';
7
7
  import * as LiveStoreEvent from '../schema/LiveStoreEvent/mod.js';
8
+ import { SystemTables } from '../schema/mod.js';
8
9
  import { resolveSessionIdSymbolInEventArgs } from '../session-id-symbol.js';
10
+ import * as SqliteDbHelper from '../sqlite-db-helper.js';
9
11
  import * as StateHead from '../StateHead.js';
12
+ import * as StateSqliteDb from '../StateSqliteDb.js';
10
13
  import * as SyncState from './syncstate.js';
11
- /** Serialize value to JSON string for trace attributes */
12
- const jsonStringify = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
13
14
  /**
14
- * Rebase behaviour:
15
- * - We continously pull events from the leader and apply them to the local store.
16
- * - If there was a race condition (i.e. the leader and client session have both advacned),
17
- * we'll need to rebase the local pending events on top of the leader's head.
18
- * - The goal is to never block the UI, so we'll interrupt rebasing if a new events is pushed by the client session.
19
- * - We also want to avoid "backwards-jumping" in the UI, so we'll transactionally apply state changes during a rebase.
20
- * - We might need to make the rebase behaviour configurable e.g. to let users manually trigger a rebase
21
- *
22
- * Longer term we should evalutate whether we can unify the ClientSessionSyncProcessor with the LeaderSyncProcessor.
15
+ * One synchronous owner for local commits, pulled state and propagation decisions.
23
16
  *
24
- * The session and leader sync processor are different in the following ways:
25
- * - The leader sync processor pulls regular LiveStore events, while the session sync processor pulls SyncState.PayloadUpstream items
26
- * - The session sync processor has no downstream nodes.
17
+ * `commit`, each pull step and every `SessionMessage` run through `owned`, so a transition finishes its SQLite/model
18
+ * work before returning and never waits on another fiber. The asynchronous runner does the waiting: it applies one pull
19
+ * step, refreshes subscribers, then yields. Every state that affects a later decision lives in `Model`.
27
20
  */
28
- export const makeClientSessionSyncProcessor = Effect.fn('makeClientSessionSyncProcessor')(function* ({ schema, clientSession, materializeEvent, rollback, refreshTables, params, confirmUnsavedChanges, }) {
21
+ export const makeClientSessionSyncProcessor = Effect.fn('makeClientSessionSyncProcessor')(function* ({ schema, clientSession, materializeEvent, refreshTables, params, confirmUnsavedChanges, }) {
22
+ const materializationJournal = yield* MaterializationJournal.MaterializationJournal;
29
23
  const stateHead = yield* StateHead.StateHead;
24
+ const dbState = yield* StateSqliteDb.StateSqliteDb;
30
25
  const eventSchema = LiveStoreEvent.Client.makeSchemaMemo(schema);
31
- const rebaseBarrier = (point) => params.rebaseBarriers?.[point] ?? Effect.void;
32
- const syncStateRef = {
33
- // The initial state is identical to the leader's initial state
34
- current: new SyncState.SyncState({
35
- localHead: clientSession.leaderThread.initialState.leaderHead,
36
- upstreamHead: clientSession.leaderThread.initialState.leaderHead,
37
- // Given we're starting with the leader's snapshot, we don't have any pending events intially
38
- pending: [],
39
- }),
40
- };
41
- /** Only used for debugging / observability / testing, it's not relied upon for correctness of the sync processor. */
26
+ const jobs = yield* Queue.unbounded();
42
27
  const syncStateUpdateQueue = yield* Queue.unbounded();
43
- const isClientOnlyEvent = (eventEncoded) => schema.eventsDefsMap.get(eventEncoded.name)?.options.clientOnly ?? false;
44
- /** We're queuing push requests to reduce the number of messages sent to the leader by batching them */
45
- const leaderPushQueue = yield* TxQueue.unbounded();
46
- /**
47
- * Prevents pull reconciliation, push-rejection handling, and shutdown from running concurrently.
48
- * These transitions inspect or update the pending events, leader push queue, and rejection state,
49
- * so each must observe the others either fully before or fully after—not midway through bookkeeping.
50
- *
51
- * Regular local commits do not acquire this mutex; they remain synchronous and are incorporated
52
- * when `reconcileLeaderPushQueue` reads the current pending events transactionally.
53
- */
54
- const pullReconciliationMutex = yield* Semaphore.make(1);
55
28
  const shutdownDone = yield* Deferred.make();
56
29
  const drainStartedSignal = yield* Deferred.make();
57
30
  const rejectionObserved = yield* Deferred.make();
58
- let shutdownStarted = false;
59
- let terminalPushCause;
60
- let unresolvedRejection;
61
- let leaderPushingFiberHandle;
62
- let pullingFiberHandle;
63
- /** Rebuild the leader push queue from the current pending events without racing synchronous commits. */
64
- const reconcileLeaderPushQueue = Effect.tx(Effect.gen(function* () {
65
- const livePending = syncStateRef.current.pending;
66
- yield* TxQueue.clear(leaderPushQueue);
67
- yield* TxQueue.offerAll(leaderPushQueue, livePending);
68
- }));
69
- const boot = Effect.gen(function* () {
70
- if (confirmUnsavedChanges === true &&
71
- typeof window !== 'undefined' &&
72
- typeof window.addEventListener === 'function') {
73
- const onBeforeUnload = (event) => {
74
- if (syncStateRef.current.pending.length > 0) {
75
- // Trigger the default browser dialog
76
- event.preventDefault();
31
+ const leaderHead = clientSession.leaderThread.initialState.leaderHead;
32
+ let model = {
33
+ lifecycle: { _tag: 'starting' },
34
+ syncState: new SyncState.SyncState({ localHead: leaderHead, upstreamHead: leaderHead, pending: [] }),
35
+ push: { _tag: 'idle', queued: [] },
36
+ nextOperationId: 1,
37
+ };
38
+ const debugInfo = { rebaseCount: 0, advanceCount: 0, rejectCount: 0 };
39
+ /**
40
+ * Development-only materializer hashes of this session's pending events. The leader confirms each event with its own
41
+ * hash, so comparing them catches a side-effecting materializer even though confirmed events aren't re-materialized.
42
+ */
43
+ const pendingMaterializerHashes = new Map();
44
+ /** Routes every message to its workflow. Runs inside the owner. */
45
+ const transition = (message) => Effect.gen(function* () {
46
+ switch (message._tag) {
47
+ case 'Started':
48
+ if (model.lifecycle._tag === 'starting') {
49
+ model = { ...model, lifecycle: { _tag: 'running', reconciliation: undefined } };
77
50
  }
51
+ break;
52
+ case 'PullReceived':
53
+ yield* acceptPull(message);
54
+ break;
55
+ case 'PullFinished':
56
+ finishPull(message);
57
+ break;
58
+ case 'PushCancelled':
59
+ finishPushCancellation(message);
60
+ break;
61
+ case 'PushSucceeded':
62
+ case 'PushRejected':
63
+ case 'PushFailed':
64
+ completePush(message);
65
+ break;
66
+ case 'Failed':
67
+ failSession(message.cause);
68
+ break;
69
+ case 'ShutdownRequested':
70
+ requestShutdown(message.exit);
71
+ break;
72
+ case 'DrainStarted':
73
+ startDrain(message.exit);
74
+ break;
75
+ case 'Stopped':
76
+ model = { ...model, lifecycle: { _tag: 'stopped' } };
77
+ addToOutbox(Deferred.done(shutdownDone, message.exit));
78
+ break;
79
+ default:
80
+ casesHandled(message);
81
+ }
82
+ });
83
+ /**
84
+ * Notifications and jobs held back by the owner body currently running, or `undefined` while the owner is free.
85
+ * Like a transactional outbox: delivered after the owner is released, dropped if the body fails.
86
+ */
87
+ let outbox;
88
+ /** Set when the owner body currently running has suspended, which breaks the exclusion `owned` relies on. */
89
+ let ownerSuspended = false;
90
+ /**
91
+ * Runs `body` as the only code allowed to change `model`.
92
+ *
93
+ * Exclusion relies on the body being synchronous, so a microtask that still finds the body holding the owner proves it
94
+ * suspended; the session then fails with a named defect (see failIfSuspended). Completing a Deferred or offering a
95
+ * Queue resumes the waiting fiber inline, so the body adds those to its outbox, delivered only after the owner is
96
+ * released. A failed body drops its outbox.
97
+ */
98
+ const owned = (body) => Effect.suspend(() => {
99
+ if (outbox !== undefined) {
100
+ return Effect.die(ownerSuspended === true ? suspendedOwnerError() : new Error(REENTRANT_OWNER_MESSAGE));
101
+ }
102
+ const entries = [];
103
+ outbox = entries;
104
+ queueMicrotask(() => {
105
+ if (outbox === entries)
106
+ ownerSuspended = true;
107
+ });
108
+ return body.pipe(Effect.tap(() => (isDevEnv() === true ? checkModelInvariants : Effect.void)), Effect.ensuring(Effect.sync(() => {
109
+ outbox = undefined;
110
+ })), Effect.exit, Effect.flatMap((exit) => Effect.andThen(failIfSuspended, exit)), Effect.tap(() => Effect.forEach(entries, (effect) => effect, { discard: true })));
111
+ }).pipe(
112
+ // Exclusion relies on synchronous storage/materializers; this only avoids needless scheduler yields.
113
+ Effect.provideService(References.PreventSchedulerYield, true),
114
+ // A caller interrupted after the body finished must still deliver the outbox.
115
+ Effect.uninterruptible);
116
+ const dispatch = (message) => owned(transition(message));
117
+ /**
118
+ * A body that suspended may already have written the model and had its outbox dropped, so the session can
119
+ * no longer be trusted. Fail it with the named defect, which also lets shutdown finish instead of awaiting lost work.
120
+ */
121
+ const failIfSuspended = Effect.suspend(() => {
122
+ if (ownerSuspended === false)
123
+ return Effect.void;
124
+ ownerSuspended = false;
125
+ const error = suspendedOwnerError();
126
+ return dispatch({ _tag: 'Failed', cause: Cause.die(error) }).pipe(Effect.orDie, Effect.andThen(Effect.die(error)));
127
+ });
128
+ /** Adds a notification or job to the outbox, delivered after the current owner body releases the owner. */
129
+ const addToOutbox = (effect) => {
130
+ if (outbox === undefined)
131
+ throw new Error('The session outbox can only be used inside the owner');
132
+ outbox.push(effect);
133
+ };
134
+ // Synchronous owner workflows. Waiting and subscriber callbacks belong to the runner below.
135
+ const commitLocalEvents = (events) => Effect.gen(function* () {
136
+ if (model.lifecycle._tag !== 'running') {
137
+ return yield* Effect.die(new Error('Cannot push events after the client session sync processor starts shutting down'));
138
+ }
139
+ const encoded = yield* encodeEvents(events);
140
+ const result = yield* merge({ _tag: 'local-push', newEvents: encoded });
141
+ if (result._tag !== 'advance')
142
+ return yield* Effect.die(new Error('Expected advance from local-push merge'));
143
+ yield* Effect.annotateCurrentSpan({
144
+ batchSize: encoded.length,
145
+ mergeResultTag: result._tag,
146
+ eventCounts: encoded.reduce((counts, item) => {
147
+ counts[item.name] = (counts[item.name] ?? 0) + 1;
148
+ return counts;
149
+ }, {}),
150
+ ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(result) } : {}),
151
+ });
152
+ const { writeTables } = yield* materializeEvents(encoded).pipe(SqliteDbHelper.withSavepoint(dbState), Effect.mapError((cause) => (cause._tag === 'SqliteError' ? new UnknownError({ cause }) : cause)));
153
+ model = {
154
+ ...model,
155
+ syncState: result.newSyncState,
156
+ // While awaiting reconciliation, finishPull rebuilds the queue from live pending events instead.
157
+ push: model.push._tag === 'awaiting-reconciliation'
158
+ ? model.push
159
+ : { ...model.push, queued: [...model.push.queued, ...result.newEvents] },
160
+ };
161
+ addToOutbox(Queue.offer(syncStateUpdateQueue, model.syncState));
162
+ reserveNextPush();
163
+ return { writeTables };
164
+ });
165
+ const acceptPull = (message) => Effect.gen(function* () {
166
+ if (model.lifecycle._tag !== 'running') {
167
+ addToOutbox(Deferred.succeed(message.completed, undefined));
168
+ return;
169
+ }
170
+ // Validate the whole payload before applying a prefix; never retain this as a materialization plan.
171
+ const result = yield* merge(message.item.payload);
172
+ if (result._tag === 'reject')
173
+ return yield* Effect.die(new Error('Unexpected rejected pull'));
174
+ if (model.lifecycle.reconciliation !== undefined)
175
+ return yield* Effect.die(new Error('Pull backpressure was bypassed'));
176
+ const id = model.nextOperationId;
177
+ const minimumEnd = message.item.payload._tag === 'upstream-rebase'
178
+ ? message.item.payload.newEvents.findIndex((item) => EventSequenceNumber.Client.isGreaterThanOrEqual(item.seqNum, model.syncState.upstreamHead)) + 1
179
+ : 0;
180
+ model = {
181
+ ...model,
182
+ nextOperationId: id + 1,
183
+ lifecycle: { _tag: 'running', reconciliation: { id, rebased: false } },
184
+ };
185
+ addToOutbox(Queue.offer(jobs, { _tag: 'Reconcile', id, item: message.item, minimumEnd, completed: message.completed }));
186
+ });
187
+ const applyPullStep = (step) => Effect.gen(function* () {
188
+ const reconciliation = activeReconciliation();
189
+ if (reconciliation?.id !== step.id)
190
+ return { _tag: 'obsolete' };
191
+ const result = yield* merge(step.payload);
192
+ if (result._tag === 'reject')
193
+ return yield* Effect.die(new Error('Unexpected rejected pull'));
194
+ if (result._tag === 'rebase' && model.push._tag === 'in-flight') {
195
+ // The push fiber must stop before its batch is rebased. Record that here and change nothing else, so local
196
+ // commits during the asynchronous interrupt still land on the previous coherent state.
197
+ const { operationId } = model.push;
198
+ model = { ...model, push: { ...model.push, _tag: 'cancelling' } };
199
+ return { _tag: 'cancel-push', operationId };
200
+ }
201
+ if (result._tag === 'rebase' && model.push._tag === 'cancelling') {
202
+ return yield* Effect.die(new Error('Pull step retried before its push cancellation finished'));
203
+ }
204
+ const { writeTables } = yield* applyPullToSqlite(result, step);
205
+ model = {
206
+ ...model,
207
+ syncState: result.newSyncState,
208
+ // Invalidate the old operation before any queued completion can run. No replacement starts mid-pull.
209
+ push: result._tag === 'rebase' ? { _tag: 'idle', queued: result.newSyncState.pending } : model.push,
210
+ };
211
+ if (result._tag === 'rebase')
212
+ setReconciliation({ ...reconciliation, rebased: true });
213
+ addToOutbox(Queue.offer(syncStateUpdateQueue, model.syncState));
214
+ return { _tag: 'applied', writeTables };
215
+ });
216
+ const finishPull = (message) => {
217
+ const reconciliation = activeReconciliation();
218
+ if (reconciliation?.id !== message.id)
219
+ return;
220
+ // A push can finish between steps now. Judge rejection recovery against its current state, not a
221
+ // snapshot taken when the pull started (the later prefixes may have confirmed the rejected batch).
222
+ const recovered = model.push._tag === 'awaiting-reconciliation' &&
223
+ isRejectedBatchRecovered(model.push.rejectedEvents, model.syncState.pending);
224
+ // After a rebase, later prefixes can confirm events that the rebase step queued; rebuild from live pending.
225
+ const rebuild = reconciliation.rebased === true || recovered === true;
226
+ if (rebuild === true)
227
+ model = { ...model, push: { _tag: 'idle', queued: model.syncState.pending } };
228
+ setReconciliation(undefined);
229
+ if (reconciliation.rebased === true)
230
+ debugInfo.rebaseCount++;
231
+ else
232
+ debugInfo.advanceCount++;
233
+ reserveNextPush();
234
+ };
235
+ const finishPushCancellation = (message) => {
236
+ if (model.push._tag !== 'cancelling' || model.push.operationId !== message.operationId)
237
+ return;
238
+ // The batch was never confirmed by this operation, so it goes back in front of the queue. The rebase step
239
+ // that follows rebuilds the queue from live pending events anyway.
240
+ model = { ...model, push: { _tag: 'idle', queued: [...model.push.batch, ...model.push.queued] } };
241
+ };
242
+ const completePush = (message) => {
243
+ if (propagates(model.lifecycle) === false)
244
+ return;
245
+ const push = model.push;
246
+ if (message._tag === 'PushFailed') {
247
+ // A fatal leader failure still counts while the operation is being cancelled.
248
+ const current = (push._tag === 'in-flight' || push._tag === 'cancelling') && push.operationId === message.operationId;
249
+ if (current === true)
250
+ failSession(message.cause);
251
+ return;
252
+ }
253
+ // A cancelling operation's success or rejection is superseded by the rebase that cancelled it.
254
+ if (push._tag !== 'in-flight' || push.operationId !== message.operationId)
255
+ return;
256
+ if (message._tag === 'PushSucceeded') {
257
+ model = { ...model, push: { _tag: 'idle', queued: push.queued } };
258
+ }
259
+ else {
260
+ debugInfo.rejectCount++;
261
+ addToOutbox(Deferred.succeed(rejectionObserved, undefined));
262
+ model = {
263
+ ...model,
264
+ push: isRejectedBatchRecovered(push.batch, model.syncState.pending) === true
265
+ ? { _tag: 'idle', queued: model.syncState.pending }
266
+ : { _tag: 'awaiting-reconciliation', rejectedEvents: push.batch, error: message.error },
78
267
  };
79
- yield* Effect.acquireRelease(Effect.sync(() => window.addEventListener('beforeunload', onBeforeUnload)), () => Effect.sync(() => window.removeEventListener('beforeunload', onBeforeUnload)));
268
+ if (model.lifecycle._tag === 'stopping' && model.push._tag === 'awaiting-reconciliation') {
269
+ addToOutbox(Queue.offer(jobs, { _tag: 'FinishShutdown', exit: Exit.die(model.push.error) }));
270
+ }
80
271
  }
81
- const leaderPushingHandle = yield* FiberHandle.make();
82
- const pullingHandle = yield* FiberHandle.make();
83
- leaderPushingFiberHandle = leaderPushingHandle;
84
- pullingFiberHandle = pullingHandle;
85
- const backgroundLeaderPushing = Effect.gen(function* () {
86
- while (true) {
87
- const batch = yield* TxQueue.takeBetween(leaderPushQueue, 1, params.leaderPushBatchSize).pipe(Effect.catchIf(Cause.isDone, () => Effect.void));
88
- if (batch === undefined)
272
+ reserveNextPush();
273
+ };
274
+ /** Reserve the operation before its job becomes visible to the asynchronous runner. */
275
+ const reserveNextPush = () => {
276
+ if (propagates(model.lifecycle) === false || activeReconciliation() !== undefined)
277
+ return;
278
+ if (model.push._tag !== 'idle')
279
+ return;
280
+ if (model.push.queued.length === 0) {
281
+ if (model.lifecycle._tag === 'stopping')
282
+ addToOutbox(Queue.offer(jobs, { _tag: 'FinishShutdown', exit: Exit.void }));
283
+ return;
284
+ }
285
+ const operationId = model.nextOperationId;
286
+ const batch = model.push.queued.slice(0, params.leaderPushBatchSize);
287
+ model = {
288
+ ...model,
289
+ nextOperationId: operationId + 1,
290
+ push: { _tag: 'in-flight', operationId, batch, queued: model.push.queued.slice(batch.length) },
291
+ };
292
+ addToOutbox(Queue.offer(jobs, { _tag: 'Push', operationId, batch }));
293
+ };
294
+ const requestShutdown = (exit) => {
295
+ const lifecycle = model.lifecycle;
296
+ switch (lifecycle._tag) {
297
+ case 'starting':
298
+ case 'running':
299
+ // Close admission now, but finish the already-accepted pull before starting the graceful drain.
300
+ model = {
301
+ ...model,
302
+ lifecycle: {
303
+ _tag: 'shutdown-requested',
304
+ exit,
305
+ reconciliation: lifecycle._tag === 'running' ? lifecycle.reconciliation : undefined,
306
+ },
307
+ };
308
+ addToOutbox(Queue.offer(jobs, { _tag: 'BeginShutdown', exit }));
309
+ break;
310
+ case 'failed':
311
+ // Nothing is left to drain; stop the runner and report the failure unless the caller already knows it.
312
+ if (lifecycle.shutdownExit !== undefined)
89
313
  return;
90
- yield* clientSession.leaderThread.events.push(batch).pipe(Effect.catchIf(isRejectedPushError, (error) =>
91
- // A pull carrying the leader's corrective history can complete before or after this
92
- // rejection response. Use the same mutex as pull reconciliation so this decision uses
93
- // one stable view of pending events and cannot install a stale rejection fence after recovery.
94
- pullReconciliationMutex
95
- .withPermits(1)(Effect.gen(function* () {
96
- debugInfo.rejectCount++;
97
- if (shutdownStarted === true)
98
- return yield* Effect.die(error);
99
- // A concurrent pull may have already confirmed or rebased this batch while the
100
- // push response was in flight. In that case, rebuild the queue from the reconciled
101
- // pending events instead of creating a fence that no future pull could release.
102
- if (isRejectedBatchRecovered(batch, syncStateRef.current.pending) === true) {
103
- yield* reconcileLeaderPushQueue;
104
- yield* Deferred.succeed(rejectionObserved, undefined);
105
- return false;
106
- }
107
- unresolvedRejection = { error, events: batch };
108
- yield* TxQueue.clear(leaderPushQueue);
109
- yield* Deferred.succeed(rejectionObserved, undefined);
110
- return true;
111
- }))
112
- .pipe(Effect.flatMap((shouldFence) =>
113
- // Local commits remain synchronous and continue accumulating in pending/the FIFO,
114
- // but this sole drain worker stays parked until pull reconciliation reseeds it.
115
- shouldFence === true ? Effect.never : Effect.void))));
116
- }
117
- }).pipe(Effect.interruptible, Effect.tapCauseLogPretty, Effect.catchCause((cause) => {
118
- if (Cause.hasInterruptsOnly(cause) === true)
119
- return Effect.void;
120
- terminalPushCause ??= cause;
121
- return shutdownStarted === true
122
- ? Effect.void
123
- : clientSession.shutdown(Exit.failCause(cause)).pipe(Effect.forkDetach, Effect.asVoid);
124
- }));
125
- yield* FiberHandle.run(leaderPushingHandle, backgroundLeaderPushing);
126
- // NOTE We need to lazily call `.pull` as we want the cursor to be updated
127
- const backgroundPulling = Stream.suspend(() => clientSession.leaderThread.events.pull({ cursor: syncStateRef.current.upstreamHead })).pipe(Stream.tap(() => clientSession.devtools.enabled === true ? clientSession.devtools.pullLatch.await : Effect.void), Stream.tap(({ payload }) => Effect.gen(function* () {
128
- // yield* Effect.logDebug('ClientSessionSyncProcessor:pull', payload)
129
- const rejectionAtPullStart = unresolvedRejection;
130
- const mergeResult = yield* SyncState.merge({
131
- syncState: syncStateRef.current,
132
- payload,
133
- isClientOnlyEvent,
134
- isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
135
- }).pipe(Effect.filterOrElse((r) => r._tag !== 'reject', () => Effect.die(new Error('Unexpected reject in client-session-sync-processor'))));
136
- syncStateRef.current = mergeResult.newSyncState;
137
- const recoveredRejection = rejectionAtPullStart !== undefined &&
138
- unresolvedRejection === rejectionAtPullStart &&
139
- isRejectedBatchRecovered(rejectionAtPullStart.events, mergeResult.newSyncState.pending) === true;
140
- if (mergeResult._tag === 'rebase') {
141
- yield* Effect.spanEvent('merge:pull:rebase', {
142
- payloadTag: payload._tag,
143
- ...(TRACE_VERBOSE === true ? { payload: jsonStringify(payload) } : {}),
144
- newEventsCount: mergeResult.newEvents.length,
145
- rollbackCount: mergeResult.rollbackEvents.length,
146
- ...(TRACE_VERBOSE === true ? { res: jsonStringify(mergeResult) } : {}),
147
- });
148
- debugInfo.rebaseCount++;
149
- // Barrier: before we interrupt the in-flight leader-push worker.
150
- yield* rebaseBarrier('before_leader_push_fiber_interrupt');
151
- yield* FiberHandle.clear(leaderPushingHandle);
152
- if (LS_DEV === true) {
153
- yield* Effect.logDebug('merge:pull:rebase: rollback', mergeResult.rollbackEvents.length, ...mergeResult.rollbackEvents.slice(0, 10).map((_) => _.toJSON()));
154
- }
155
- // Roll back the optimistic session changesets for the events this rebase discards.
156
- // (Independent of the push queue below; order relative to the queue reconcile is irrelevant.)
157
- for (let i = mergeResult.rollbackEvents.length - 1; i >= 0; i--) {
158
- const event = mergeResult.rollbackEvents[i];
159
- if (event.meta.sessionChangeset._tag !== 'no-op' && event.meta.sessionChangeset._tag !== 'unset') {
160
- rollback(event.meta.sessionChangeset.data);
161
- event.meta.sessionChangeset = { _tag: 'unset' };
162
- }
163
- }
164
- if (mergeResult.rollbackEvents.length > 0) {
165
- yield* stateHead
166
- .set(mergeResult.rollbackEvents[0].parentSeqNum)
167
- .pipe(Effect.mapError((cause) => MaterializeError.make({ cause })));
168
- }
169
- // Barrier: before the atomic queue reconciliation (the "discard + re-offer" step).
170
- // A `push` admitted here appends its event to `syncStateRef.current.pending` AND to
171
- // `leaderPushQueue`; the reconciliation below re-reads the current pending events, so
172
- // that event is preserved rather than removed by the queue clear.
173
- yield* rebaseBarrier('before_queue_reconcile');
174
- // Atomic queue reconciliation. `push` runs via `Effect.runSyncWith` (a synchronous run,
175
- // per the store's fully-synchronous commit contract), so it executes as an indivisible
176
- // unit that can only interleave in THIS fiber's async gaps — never inside a synchronous
177
- // stretch. By reading the current pending events, clearing, and re-offering with no async
178
- // park between them, this block is atomic w.r.t. `push`. This replaces the blocking
179
- // `pullReconciliationMutex` permit that previously forced `push` to wait: queue rebuilding
180
- // and synchronous commits cannot interleave, without suspending the commit path.
181
- //
182
- // We re-read the current `syncStateRef.current.pending` instead of the stale
183
- // `mergeResult.newSyncState.pending` snapshot captured at merge time, so any event a
184
- // concurrent push appended during the async steps above (fiber interrupt / rollback /
185
- // barriers) is included. `Effect.tx` commits the clear+offer as one transaction.
186
- yield* reconcileLeaderPushQueue;
187
- // Barrier: before restarting the leader-push worker.
188
- yield* rebaseBarrier('before_leader_push_fiber_run');
189
- if (recoveredRejection === true)
190
- unresolvedRejection = undefined;
191
- yield* FiberHandle.run(leaderPushingHandle, backgroundLeaderPushing);
192
- }
193
- else {
194
- yield* Effect.spanEvent('merge:pull:advance', {
195
- payloadTag: payload._tag,
196
- ...(TRACE_VERBOSE === true ? { payload: jsonStringify(payload) } : {}),
197
- newEventsCount: mergeResult.newEvents.length,
198
- ...(TRACE_VERBOSE === true ? { res: jsonStringify(mergeResult) } : {}),
199
- });
200
- debugInfo.advanceCount++;
201
- if (recoveredRejection === true) {
202
- yield* FiberHandle.clear(leaderPushingHandle);
203
- yield* reconcileLeaderPushQueue;
204
- unresolvedRejection = undefined;
205
- yield* FiberHandle.run(leaderPushingHandle, backgroundLeaderPushing);
206
- }
207
- }
208
- if (mergeResult.newEvents.length === 0) {
209
- // If there are no new events, we need to update the sync state as well
210
- yield* Queue.offer(syncStateUpdateQueue, mergeResult.newSyncState);
211
- return;
212
- }
213
- const writeTables = new Set();
214
- for (const event of mergeResult.newEvents) {
215
- const { writeTables: newWriteTables, sessionChangeset, materializerHash, } = yield* materializeEvent(event, {
216
- materializerHashLeader: event.meta.materializerHashLeader,
217
- });
218
- for (const table of newWriteTables) {
219
- writeTables.add(table);
220
- }
221
- event.meta.sessionChangeset = sessionChangeset;
222
- event.meta.materializerHashSession = materializerHash;
223
- }
224
- refreshTables(writeTables);
225
- // We're only triggering the sync state update after all events have been materialized
226
- yield* Queue.offer(syncStateUpdateQueue, mergeResult.newSyncState);
227
- }).pipe(pullReconciliationMutex.withPermits(1), Effect.tapCauseLogPretty, Effect.catchCause((cause) => clientSession.shutdown(Exit.failCause(cause))))), Stream.runDrain, Effect.forever, // NOTE Whenever the leader changes, we need to re-start the stream
228
- Effect.interruptible, Effect.withSpan('client-session-sync-processor:pull'), Effect.tapCauseLogPretty);
229
- yield* FiberHandle.run(pullingHandle, backgroundPulling);
230
- }).pipe(Effect.withSpan('client-session-sync-processor:boot'));
231
- const runShutdown = Effect.fn('client-session-sync-processor:shutdown')(function* (exit) {
314
+ model = { ...model, lifecycle: { ...lifecycle, shutdownExit: exit } };
315
+ addToOutbox(Queue.offer(jobs, { _tag: 'FinishShutdown', exit: failedShutdownExit(exit, lifecycle.cause) }));
316
+ break;
317
+ case 'shutdown-requested':
318
+ case 'stopping':
319
+ case 'stopped':
320
+ break;
321
+ default:
322
+ casesHandled(lifecycle);
323
+ }
324
+ };
325
+ const startDrain = (exit) => {
326
+ const lifecycle = model.lifecycle;
327
+ if (lifecycle._tag === 'failed') {
328
+ // The session failed while the accepted pull finished; there is nothing left to drain.
329
+ addToOutbox(Queue.offer(jobs, { _tag: 'FinishShutdown', exit: failedShutdownExit(exit, lifecycle.cause) }));
330
+ return;
331
+ }
332
+ if (lifecycle._tag !== 'shutdown-requested')
333
+ return;
334
+ model = { ...model, lifecycle: { _tag: 'stopping', exit } };
232
335
  if (Exit.isFailure(exit) === true) {
233
- if (pullingFiberHandle !== undefined)
234
- yield* FiberHandle.clear(pullingFiberHandle);
235
- yield* pullReconciliationMutex.withPermits(1)(TxQueue.end(leaderPushQueue));
236
- if (leaderPushingFiberHandle !== undefined)
237
- yield* FiberHandle.clear(leaderPushingFiberHandle);
336
+ addToOutbox(Queue.offer(jobs, { _tag: 'FinishShutdown', exit: Exit.void }));
238
337
  return;
239
338
  }
240
- yield* pullReconciliationMutex.withPermits(1)(Effect.gen(function* () {
241
- if (pullingFiberHandle !== undefined)
242
- yield* FiberHandle.clear(pullingFiberHandle);
243
- yield* TxQueue.end(leaderPushQueue);
244
- yield* Deferred.succeed(drainStartedSignal, undefined);
245
- }));
246
- if (leaderPushingFiberHandle !== undefined) {
247
- if (unresolvedRejection === undefined) {
248
- yield* FiberHandle.awaitEmpty(leaderPushingFiberHandle);
249
- }
250
- else {
251
- yield* FiberHandle.clear(leaderPushingFiberHandle);
252
- }
339
+ addToOutbox(Deferred.succeed(drainStartedSignal, undefined));
340
+ if (model.push._tag === 'awaiting-reconciliation') {
341
+ addToOutbox(Queue.offer(jobs, { _tag: 'FinishShutdown', exit: Exit.die(model.push.error) }));
342
+ }
343
+ else
344
+ reserveNextPush();
345
+ };
346
+ const failSession = (cause) => {
347
+ const lifecycle = model.lifecycle;
348
+ if (lifecycle._tag === 'failed' || lifecycle._tag === 'stopped')
349
+ return;
350
+ const terminalCause = Cause.die(Cause.squash(cause));
351
+ if (lifecycle._tag === 'stopping') {
352
+ model = { ...model, lifecycle: { _tag: 'failed', cause: terminalCause, shutdownExit: lifecycle.exit } };
353
+ addToOutbox(Queue.offer(jobs, { _tag: 'FinishShutdown', exit: Exit.failCause(terminalCause) }));
354
+ return;
355
+ }
356
+ model = {
357
+ ...model,
358
+ lifecycle: {
359
+ _tag: 'failed',
360
+ cause: terminalCause,
361
+ // A requested shutdown still finishes through its BeginShutdown job; see startDrain.
362
+ shutdownExit: lifecycle._tag === 'shutdown-requested' ? lifecycle.exit : undefined,
363
+ },
364
+ };
365
+ addToOutbox(Queue.offer(jobs, { _tag: 'NotifyFailure', cause }));
366
+ };
367
+ // Model accessors and invariants.
368
+ const activeReconciliation = () => model.lifecycle._tag === 'running' || model.lifecycle._tag === 'shutdown-requested'
369
+ ? model.lifecycle.reconciliation
370
+ : undefined;
371
+ const setReconciliation = (reconciliation) => {
372
+ const lifecycle = model.lifecycle;
373
+ if (lifecycle._tag === 'running')
374
+ model = { ...model, lifecycle: { ...lifecycle, reconciliation } };
375
+ else if (lifecycle._tag === 'shutdown-requested')
376
+ model = { ...model, lifecycle: { ...lifecycle, reconciliation } };
377
+ };
378
+ /** Development-only check of the propagation bookkeeping that commitLocalEvents and finishPull rely on. */
379
+ const checkModelInvariants = Effect.suspend(() => {
380
+ const push = model.push;
381
+ const reconciling = activeReconciliation() !== undefined;
382
+ if (push._tag === 'cancelling' && reconciling === false) {
383
+ return Effect.die(new Error('A push can only be cancelled by an active reconciliation'));
384
+ }
385
+ // During reconciliation, a later prefix may confirm a queued event until finishPull rebuilds the queue.
386
+ if (push._tag === 'awaiting-reconciliation' || reconciling === true || propagates(model.lifecycle) === false) {
387
+ return Effect.void;
253
388
  }
254
- if (terminalPushCause !== undefined)
255
- return yield* Effect.failCause(terminalPushCause);
256
- if (unresolvedRejection !== undefined)
257
- return yield* Effect.die(unresolvedRejection.error);
389
+ const pending = model.syncState.pending;
390
+ const offset = pending.length - push.queued.length;
391
+ const isSuffix = offset >= 0 &&
392
+ push.queued.every((event, index) => {
393
+ const pendingEvent = pending[offset + index];
394
+ return pendingEvent !== undefined && EventSequenceNumber.Client.isEqual(event.seqNum, pendingEvent.seqNum);
395
+ });
396
+ return isSuffix === true
397
+ ? Effect.void
398
+ : Effect.die(new Error('Queued leader pushes must be the unpushed suffix of pending events'));
258
399
  });
259
- const shutdown = (exit) => Effect.suspend(() => {
260
- if (shutdownStarted === true)
261
- return Deferred.await(shutdownDone);
262
- shutdownStarted = true;
263
- return runShutdown(exit).pipe(Effect.exit, Effect.tap((shutdownExit) => Deferred.done(shutdownDone, shutdownExit)), Effect.forkDetach, Effect.andThen(Deferred.await(shutdownDone)));
400
+ // Synchronous admission, encoding and persistence. These helpers never install or publish the session model.
401
+ const recordPendingHash = (event, hash) => {
402
+ if (hash._tag === 'Some')
403
+ pendingMaterializerHashes.set(EventSequenceNumber.Client.toString(event.seqNum), hash.value);
404
+ };
405
+ const isClientOnlyEvent = (event) => schema.eventsDefsMap.get(event.name)?.options.clientOnly ?? false;
406
+ const merge = (payload) => SyncState.merge({
407
+ syncState: model.syncState,
408
+ payload,
409
+ isClientOnlyEvent,
410
+ isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
264
411
  });
265
412
  const encodeEvents = Effect.fn('client-session-sync-processor:encode-events')(function* (events) {
266
- let baseEventSequenceNumber = syncStateRef.current.localHead;
413
+ let baseEventSequenceNumber = model.syncState.localHead;
267
414
  return yield* Effect.forEach(events, ({ name, args }) => Effect.gen(function* () {
268
415
  const eventDef = yield* Effect.fromNullishOr(schema.eventsDefsMap.get(name)).pipe(Effect.orDieDebugger);
269
416
  const nextNumPair = EventSequenceNumber.Client.nextPair({
@@ -283,84 +430,257 @@ export const makeClientSessionSyncProcessor = Effect.fn('makeClientSessionSyncPr
283
430
  clientId: clientSession.clientId,
284
431
  sessionId: clientSession.sessionId,
285
432
  }).pipe(Effect.orDie);
286
- return new LiveStoreEvent.Client.EncodedWithMeta(encoded);
433
+ return LiveStoreEvent.Client.Encoded.make(encoded);
287
434
  }));
288
435
  });
289
436
  const materializeEvents = Effect.fn('client-session-sync-processor:materialize-events')(function* (events) {
290
437
  const writeTables = new Set();
291
438
  for (const event of events) {
292
- const { writeTables: newWriteTables, sessionChangeset, materializerHash, } = yield* materializeEvent(event, {
439
+ const { writeTables: newWriteTables, materializerHash } = yield* materializeEvent(event, {
293
440
  materializerHashLeader: Option.none(),
294
441
  });
442
+ recordPendingHash(event, materializerHash);
295
443
  for (const table of newWriteTables) {
296
444
  writeTables.add(table);
297
445
  }
298
- event.meta.sessionChangeset = sessionChangeset;
299
- event.meta.materializerHashSession = materializerHash;
300
446
  }
447
+ // One head write per batch: the savepoint commits the events and the head together.
448
+ const last = events.at(-1);
449
+ if (last !== undefined)
450
+ yield* stateHead.set(last.seqNum);
301
451
  return { writeTables };
302
452
  });
303
- const push = Effect.fn('client-session-sync-processor:push')(function* (encodedEvents) {
304
- if (shutdownStarted === true) {
305
- return yield* Effect.die(new Error('Cannot push events after the client session sync processor starts shutting down'));
453
+ /** Complete the SQLite step before the owner installs its matching model or delivers its outbox. */
454
+ const applyPullToSqlite = (result, step) => Effect.gen(function* () {
455
+ const writeTables = new Set();
456
+ // A rebase step can materialize thousands of events, so look up per-event data by sequence number instead of
457
+ // scanning the payload for each event.
458
+ const leaderHashOf = (event) => step.leaderHashes.get(EventSequenceNumber.Client.toString(event.seqNum)) ?? Option.none();
459
+ const incomingByPosition = new Map();
460
+ for (const event of step.payload.newEvents) {
461
+ const key = positionKey(event);
462
+ const events = incomingByPosition.get(key);
463
+ if (events === undefined)
464
+ incomingByPosition.set(key, [event]);
465
+ else
466
+ events.push(event);
306
467
  }
307
- const mergeResult = yield* SyncState.merge({
308
- syncState: syncStateRef.current,
309
- payload: { _tag: 'local-push', newEvents: encodedEvents },
310
- isClientOnlyEvent,
311
- isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
312
- }).pipe(Effect.filterMapOrElse(Filter.tagged()('advance'), () => Effect.die(new Error('Expected advance from local-push merge'))));
313
- yield* Effect.annotateCurrentSpan({
314
- batchSize: encodedEvents.length,
315
- mergeResultTag: mergeResult._tag,
316
- eventCounts: encodedEvents.reduce((acc, event) => {
317
- acc[event.name] = (acc[event.name] ?? 0) + 1;
318
- return acc;
319
- }, {}),
320
- ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
321
- });
322
- syncStateRef.current = mergeResult.newSyncState;
323
- yield* Queue.offer(syncStateUpdateQueue, mergeResult.newSyncState);
324
- const rejectedEvents = yield* TxQueue.offerAll(leaderPushQueue, mergeResult.newEvents);
325
- if (rejectedEvents.length > 0) {
326
- return yield* Effect.die(new Error('Leader push queue closed while accepting events'));
468
+ if (result._tag === 'advance') {
469
+ for (const event of result.confirmedEvents) {
470
+ const key = EventSequenceNumber.Client.toString(event.seqNum);
471
+ const sessionHash = pendingMaterializerHashes.get(key);
472
+ pendingMaterializerHashes.delete(key);
473
+ const leaderHash = leaderHashOf(event);
474
+ if (sessionHash !== undefined && leaderHash._tag === 'Some' && leaderHash.value !== sessionHash) {
475
+ return yield* new MaterializeError({
476
+ cause: MaterializerHashMismatchError.make({ eventName: event.name }),
477
+ });
478
+ }
479
+ }
480
+ }
481
+ if (result._tag === 'rebase') {
482
+ for (const event of result.rollbackEvents) {
483
+ pendingMaterializerHashes.delete(EventSequenceNumber.Client.toString(event.seqNum));
484
+ }
485
+ yield* materializationJournal.rollback(result.rollbackEvents.map((item) => item.seqNum));
486
+ // Rollback may touch tables absent from replacement events. Refresh all user tables in that case.
487
+ if (result.rollbackEvents.length > 0) {
488
+ for (const table of schema.state.sqlite.tables.keys()) {
489
+ if (SystemTables.isStateSystemTable(table) === false)
490
+ writeTables.add(table);
491
+ }
492
+ }
327
493
  }
494
+ for (const item of result.newEvents) {
495
+ // A replayed pending event can temporarily share a sequence number with a later incoming event.
496
+ const incoming = incomingByPosition
497
+ .get(positionKey(item))
498
+ ?.some((event) => LiveStoreEvent.Client.isEqualEncoded(event, item)) === true;
499
+ const materialized = yield* materializeEvent(item, {
500
+ materializerHashLeader: incoming === true ? leaderHashOf(item) : Option.none(),
501
+ });
502
+ if (incoming === false)
503
+ recordPendingHash(item, materialized.materializerHash);
504
+ for (const table of materialized.writeTables)
505
+ writeTables.add(table);
506
+ }
507
+ yield* stateHead.set(result.newSyncState.localHead);
508
+ if (step.last === true)
509
+ yield* materializationJournal.discardUpTo(step.globalHead);
510
+ return { writeTables };
511
+ }).pipe(SqliteDbHelper.withSavepoint(dbState), Effect.mapError((cause) => (cause._tag === 'SqliteError' ? new UnknownError({ cause }) : cause)), Effect.withSpan('client-session-sync-processor:apply-pull-step', {
512
+ attributes: {
513
+ mergeResultTag: result._tag,
514
+ newEvents: result.newEvents.length,
515
+ rollbackEvents: result._tag === 'rebase' ? result.rollbackEvents.length : 0,
516
+ },
517
+ }));
518
+ // Asynchronous runner. It reads current state and enters the owner through dispatch or a pull step.
519
+ const rebaseBarrier = (point) => params.rebaseBarriers?.[point] ?? Effect.void;
520
+ const reportFailure = (cause) => dispatch({ _tag: 'Failed', cause }).pipe(Effect.catchCause((recordCause) => escalateUnrecordedFailure(cause, recordCause)));
521
+ /**
522
+ * Last resort when the owner cannot even record a failure, for example because a suspended body still holds it.
523
+ * Nothing in the session can be trusted to report the failure, so log it and shut down the Store directly instead of
524
+ * letting the defect die unobserved in a runner or push fiber. The shutdown is forked because Store teardown calls
525
+ * back into this processor and may need the runner that is reporting this failure.
526
+ */
527
+ let unrecordedFailureEscalated = false;
528
+ const escalateUnrecordedFailure = (cause, recordCause) => Effect.suspend(() => {
529
+ if (unrecordedFailureEscalated === true)
530
+ return Effect.void;
531
+ unrecordedFailureEscalated = true;
532
+ return Effect.logError('Client session sync processor could not record a failure; shutting down the store', cause, recordCause).pipe(Effect.andThen(Effect.forkDetach(clientSession.shutdown(Exit.failCause(cause)))), Effect.asVoid);
328
533
  });
329
- const debugInfo = {
330
- rebaseCount: 0,
331
- advanceCount: 0,
332
- rejectCount: 0,
534
+ const report = (message) => dispatch(message).pipe(Effect.catchCause(reportFailure), Effect.asVoid);
535
+ /**
536
+ * A step that rebases replays every pending event, so it costs O(pending) however few incoming events it applies.
537
+ * Such a step takes at least as many incoming events as there are pending events. This keeps the replay work of a
538
+ * whole pull proportional to its size, instead of replaying the pending suffix once per `PULL_CHUNK_SIZE` events.
539
+ * A step that starts by confirming the oldest pending event replays nothing, so it keeps the normal size. The
540
+ * choice only affects step size: each step still merges against the live pending events.
541
+ */
542
+ const stepSize = (firstIncoming) => {
543
+ const oldestPending = model.syncState.pending[0];
544
+ const replaysPending = oldestPending !== undefined &&
545
+ firstIncoming !== undefined &&
546
+ LiveStoreEvent.Client.isEqualEncoded(firstIncoming, oldestPending) === false;
547
+ return replaysPending === true ? Math.max(PULL_CHUNK_SIZE, model.syncState.pending.length) : PULL_CHUNK_SIZE;
333
548
  };
549
+ const reconcile = (job, pushHandle) => Effect.gen(function* () {
550
+ const leaderHashes = new Map(job.item.materializerHashes.map(({ eventNum, hash }) => [EventSequenceNumber.Client.toString(eventNum), hash]));
551
+ const newEvents = job.item.payload.newEvents;
552
+ let offset = 0;
553
+ while (true) {
554
+ const chunk = newEvents.slice(offset, Math.max(offset + stepSize(newEvents[offset]), job.minimumEnd));
555
+ const last = offset + chunk.length === newEvents.length;
556
+ const result = yield* owned(applyPullStep({
557
+ id: job.id,
558
+ last,
559
+ payload: offset === 0 ? { ...job.item.payload, newEvents: chunk } : { _tag: 'upstream-advance', newEvents: chunk },
560
+ leaderHashes,
561
+ globalHead: job.item.globalHead,
562
+ }));
563
+ if (result._tag === 'obsolete')
564
+ return;
565
+ if (result._tag === 'cancel-push') {
566
+ // The owner already marked the push as cancelling; wait for the fiber outside it, then retry this prefix.
567
+ yield* rebaseBarrier('before_leader_push_fiber_interrupt');
568
+ yield* FiberHandle.clear(pushHandle);
569
+ yield* dispatch({ _tag: 'PushCancelled', operationId: result.operationId });
570
+ continue;
571
+ }
572
+ // The owner is released before callbacks: subscribers can commit against the completed prefix.
573
+ if (result.writeTables.size > 0)
574
+ refreshTables(result.writeTables);
575
+ offset += chunk.length;
576
+ if (last === true)
577
+ break;
578
+ yield* Effect.yieldNow;
579
+ }
580
+ if (activeReconciliation()?.rebased === true)
581
+ yield* rebaseBarrier('before_leader_push_fiber_run');
582
+ yield* dispatch({ _tag: 'PullFinished', id: job.id });
583
+ }).pipe(Effect.ensuring(Deferred.succeed(job.completed, undefined)));
584
+ const startLeaderPush = (job, pushHandle) => Effect.gen(function* () {
585
+ // A job can wait behind reconciliation and become obsolete before its fiber even starts.
586
+ if (model.push._tag !== 'in-flight' ||
587
+ model.push.operationId !== job.operationId ||
588
+ propagates(model.lifecycle) === false)
589
+ return;
590
+ yield* FiberHandle.run(pushHandle, Effect.suspend(() => clientSession.leaderThread.events.push(job.batch)).pipe(Effect.matchEffect({
591
+ onFailure: (error) => report({ _tag: 'PushRejected', operationId: job.operationId, error }),
592
+ onSuccess: () => report({ _tag: 'PushSucceeded', operationId: job.operationId }),
593
+ }), Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) === true
594
+ ? Effect.void
595
+ : report({ _tag: 'PushFailed', operationId: job.operationId, cause })), Effect.interruptible));
596
+ });
597
+ const runJob = (job, handles) => Effect.gen(function* () {
598
+ switch (job._tag) {
599
+ case 'Push':
600
+ yield* startLeaderPush(job, handles.push);
601
+ break;
602
+ case 'Reconcile':
603
+ yield* reconcile(job, handles.push);
604
+ break;
605
+ case 'BeginShutdown':
606
+ yield* FiberHandle.clear(handles.pull);
607
+ yield* dispatch({ _tag: 'DrainStarted', exit: job.exit });
608
+ break;
609
+ case 'FinishShutdown':
610
+ yield* FiberHandle.clear(handles.pull);
611
+ yield* FiberHandle.clear(handles.push);
612
+ yield* dispatch({ _tag: 'Stopped', exit: job.exit });
613
+ break;
614
+ case 'NotifyFailure':
615
+ yield* FiberHandle.clear(handles.pull);
616
+ yield* FiberHandle.clear(handles.push);
617
+ // Store shutdown may call back into this processor. Supervise it without blocking the runner it needs.
618
+ yield* FiberHandle.run(handles.shutdown, clientSession.shutdown(Exit.failCause(job.cause)));
619
+ break;
620
+ default:
621
+ casesHandled(job);
622
+ }
623
+ });
624
+ const runJobs = (handles) => Effect.gen(function* () {
625
+ while (model.lifecycle._tag !== 'stopped') {
626
+ yield* runJob(yield* Queue.take(jobs), handles).pipe(Effect.catchCause(reportFailure));
627
+ }
628
+ yield* Queue.shutdown(jobs);
629
+ });
630
+ const pull = Stream.suspend(() => clientSession.leaderThread.events.pull({ cursor: model.syncState.upstreamHead })).pipe(Stream.tap(() => (clientSession.devtools.enabled === true ? clientSession.devtools.pullLatch.await : Effect.void)), Stream.tap((item) => Effect.gen(function* () {
631
+ const completed = yield* Deferred.make();
632
+ // A failed acceptance drops its outbox, including `completed`, so fail the pull instead of awaiting it.
633
+ yield* dispatch({ _tag: 'PullReceived', item, completed });
634
+ yield* Deferred.await(completed);
635
+ })), Stream.runDrain, Effect.forever, Effect.interruptible, Effect.catchCause((cause) => (Cause.hasInterruptsOnly(cause) === true ? Effect.void : reportFailure(cause))), Effect.withSpan('client-session-sync-processor:pull'), Effect.tapCauseLogPretty);
636
+ const installBeforeUnloadWarning = Effect.gen(function* () {
637
+ if (confirmUnsavedChanges === true &&
638
+ typeof window !== 'undefined' &&
639
+ typeof window.addEventListener === 'function') {
640
+ const onBeforeUnload = (event) => {
641
+ if (model.syncState.pending.length > 0)
642
+ event.preventDefault();
643
+ };
644
+ yield* Effect.acquireRelease(Effect.sync(() => window.addEventListener('beforeunload', onBeforeUnload)), () => Effect.sync(() => window.removeEventListener('beforeunload', onBeforeUnload)));
645
+ }
646
+ });
647
+ const boot = Effect.gen(function* () {
648
+ const handles = {
649
+ push: yield* FiberHandle.make(),
650
+ pull: yield* FiberHandle.make(),
651
+ shutdown: yield* FiberHandle.make(),
652
+ };
653
+ yield* installBeforeUnloadWarning;
654
+ yield* dispatch({ _tag: 'Started' }).pipe(Effect.orDie);
655
+ yield* runJobs(handles).pipe(Effect.forkScoped);
656
+ yield* FiberHandle.run(handles.pull, pull.pipe(Effect.asVoid));
657
+ }).pipe(Effect.withSpan('client-session-sync-processor:boot'));
334
658
  return {
335
659
  boot,
336
- shutdown,
337
- encodeEvents,
338
- materializeEvents,
339
- push,
660
+ shutdown: (exit) => dispatch({ _tag: 'ShutdownRequested', exit }).pipe(Effect.orDie, Effect.andThen(Deferred.await(shutdownDone)), Effect.withSpan('client-session-sync-processor:shutdown')),
661
+ commit: Effect.fn('client-session-sync-processor:commit')((events) => owned(commitLocalEvents(events))),
340
662
  syncState: Subscribable.make({
341
- get: Effect.sync(() => syncStateRef.current),
663
+ get: Effect.sync(() => model.syncState),
342
664
  changes: Stream.fromQueue(syncStateUpdateQueue),
343
665
  }),
344
666
  debug: {
345
667
  awaitDrainStarted: Deferred.await(drainStartedSignal),
346
668
  awaitRejection: Deferred.await(rejectionObserved),
347
- print: () => Effect.gen(function* () {
348
- console.log('debugInfo', debugInfo);
349
- console.log('syncState', syncStateRef.current);
350
- const pushQueueItems = yield* snapshotTxQueue(leaderPushQueue);
351
- console.log('pushQueueSize', pushQueueItems.length);
352
- console.log('pushQueueItems', pushQueueItems.map((_) => _.toJSON()));
353
- }).pipe(Effect.runSync),
669
+ print: () => console.log('ClientSessionSyncProcessor', { debugInfo, model }),
354
670
  debugInfo: () => debugInfo,
355
671
  },
356
672
  };
357
673
  });
358
- const snapshotTxQueue = (queue) => Effect.tx(Effect.gen(function* () {
359
- if ((yield* TxQueue.isOpen(queue)) === false)
360
- return [];
361
- const items = yield* TxQueue.clear(queue);
362
- yield* TxQueue.offerAll(queue, items);
363
- return items;
364
- }));
365
- const isRejectedBatchRecovered = (rejectedEvents, pendingEvents) => rejectedEvents.every((rejectedEvent) => pendingEvents.some((pendingEvent) => LiveStoreEvent.Client.isEqualEncoded(pendingEvent, rejectedEvent)) === false);
674
+ /** Global and client position, without the rebase generation, which `isEqualEncoded` also ignores. */
675
+ const positionKey = (event) => `${event.seqNum.global},${event.seqNum.client}`;
676
+ /** Pulled events applied per reconciliation step before subscribers run and the runner yields. */
677
+ export const PULL_CHUNK_SIZE = 32;
678
+ const REENTRANT_OWNER_MESSAGE = 'Reentrant session transition from materialization';
679
+ const jsonStringify = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
680
+ const suspendedOwnerError = () => new Error('Session owner work suspended; materializers and SQLite services must be synchronous');
681
+ /** Whether leader pushes may still start or complete in this lifecycle state. */
682
+ const propagates = (lifecycle) => lifecycle._tag === 'running' || lifecycle._tag === 'shutdown-requested' || lifecycle._tag === 'stopping';
683
+ /** A shutdown requested with a failure exit already carries the failure; otherwise report the session's cause. */
684
+ const failedShutdownExit = (exit, cause) => Exit.isFailure(exit) === true ? Exit.void : Exit.failCause(cause);
685
+ const isRejectedBatchRecovered = (rejectedEvents, pendingEvents) => rejectedEvents.every((rejected) => pendingEvents.some((pending) => LiveStoreEvent.Client.isEqualEncoded(pending, rejected)) === false);
366
686
  //# sourceMappingURL=ClientSessionSyncProcessor.js.map