@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,4 +1,4 @@
1
- import { casesHandled, LS_DEV, TRACE_VERBOSE } from '@livestore/utils'
1
+ import { casesHandled, TRACE_VERBOSE } from '@livestore/utils'
2
2
  import {
3
3
  type HttpClient,
4
4
  type Latch,
@@ -11,79 +11,55 @@ import {
11
11
  Effect,
12
12
  Exit,
13
13
  FiberHandle,
14
+ FiberSet,
14
15
  Layer,
15
- Option,
16
- Predicate,
17
16
  Queue,
18
17
  Random,
19
18
  ReadonlyArray,
20
- References,
19
+ Ref,
21
20
  Result,
22
- Schedule,
23
21
  Schema,
24
- Semaphore,
25
22
  Stream,
26
23
  Subscribable,
27
24
  SubscriptionRef,
28
- TxQueue,
29
25
  } from '@livestore/utils/effect'
30
26
 
31
- import { MaterializeError, type SqliteDb, UnknownError } from '../adapter-types.ts'
32
- import type { UnknownEventError } from '../errors.ts'
27
+ import { type SqliteDb, UnknownError } from '../adapter-types.ts'
28
+ import { PullItem } from '../ClientSessionLeaderThreadProxy.ts'
33
29
  import { IntentionalShutdownCause } from '../errors.ts'
34
- import { makeMaterializerHash } from '../materializer-helper.ts'
30
+ import * as EventlogSqliteDb from '../EventlogSqliteDb.ts'
35
31
  import type { LiveStoreSchema } from '../schema/mod.ts'
36
- import { EventSequenceNumber, LiveStoreEvent, resolveEventDef, SystemTables } from '../schema/mod.ts'
32
+ import { EventSequenceNumber, LiveStoreEvent } from '../schema/mod.ts'
37
33
  import { EVENTLOG_META_TABLE, SYNC_STATUS_TABLE } from '../schema/state/sqlite/system-tables/eventlog-tables.ts'
38
- import * as StateHead from '../StateHead.ts'
39
- import type { BackendIdMismatchError, IsOfflineError, SyncBackend } from '../sync/sync.ts'
34
+ import * as StateSqliteDb from '../StateSqliteDb.ts'
35
+ import type { BackendIdMismatchError, IsOfflineError, ServerAheadError } from '../sync/errors.ts'
36
+ import type * as SyncBackend from '../sync/sync-backend.ts'
40
37
  import * as SyncState from '../sync/syncstate.ts'
41
38
  import { sql } from '../util.ts'
42
39
  import * as Eventlog from './eventlog.ts'
43
- import { rollback } from './materialize-event.ts'
40
+ import * as LeaderPersistence from './LeaderPersistence.ts'
44
41
  import {
45
- isRejectedPushError,
46
42
  LeaderAheadError,
47
43
  NonContiguousBatchError,
48
44
  NonMonotonicBatchError,
49
45
  type RejectedPushError,
50
46
  StaleRebaseGenerationError,
51
47
  } from './RejectedPushError.ts'
52
- import type { ShutdownChannel } from './shutdown-channel.ts'
53
- import type { InitialBlockingSyncContext, MaterializeEvent } from './types.ts'
48
+ import * as Shutdown from './shutdown-channel.ts'
49
+ import type { InitialBlockingSyncContext } from './types.ts'
54
50
 
55
51
  export const TypeId = '~@livestore/common/LeaderSyncProcessor' as const
56
52
  export type TypeId = typeof TypeId
57
53
 
58
54
  /**
59
- * The LeaderSyncProcessor manages synchronization of events between
60
- * the local state and the sync backend, ensuring efficient and orderly processing.
55
+ * Public entry point and orchestration owner for leader synchronization.
61
56
  *
62
- * In the LeaderSyncProcessor, pulling always has precedence over pushing.
57
+ * Local pushes, backend batches, retries, failures, and shutdown all enter one mailbox and are handled one at a time.
58
+ * This makes the in-memory model easier to reason about because the mailbox loop is the only place that changes it.
63
59
  *
64
- * Responsibilities:
65
- * - Queueing incoming local events in a localPushesQueue.
66
- * - Broadcasting events to client sessions via pull queues.
67
- * - Pushing events to the sync backend.
68
- *
69
- * Notes:
70
- *
71
- * local push processing:
72
- * - localPushesQueue:
73
- * - Maintains events in ascending order.
74
- * - Uses `Deferred` objects to resolve/reject events based on application success.
75
- * - Processes events from the queue, applying events in batches.
76
- * - Controlled by a mutex (`Semaphore(1)`) to ensure mutual exclusion between local push and backend pull processing.
77
- * - The backend pull side acquires the mutex before processing and releases it on post-pull completion.
78
- * - Processes up to `maxBatchSize` events per cycle.
79
- *
80
- * Currently, we're advancing the state db and eventlog in lockstep, but we could also decouple this in the future
81
- *
82
- * Tricky concurrency scenarios:
83
- * - Queued local push batches becoming invalid due to a prior local push item being rejected.
84
- * Solution: Introduce a generation number for local push batches which is used to filter out old batches items in case of rejection.
85
- *
86
- * See ClientSessionSyncProcessor for how the leader and session sync processors are similar/different.
60
+ * The processor owns lifecycle, queues, provider work, publication, and acknowledgements. Durable work is delegated to
61
+ * `LeaderPersistence`, and only a successful receipt may update observable state, publish events, schedule a backend
62
+ * push, or resolve a push acknowledgement.
87
63
  */
88
64
  export class LeaderSyncProcessor extends Context.Service<LeaderSyncProcessor, Service>()(
89
65
  '@livestore/common/LeaderSyncProcessor',
@@ -91,109 +67,28 @@ export class LeaderSyncProcessor extends Context.Service<LeaderSyncProcessor, Se
91
67
 
92
68
  export interface Service {
93
69
  readonly [TypeId]: TypeId
94
- /** Used by client sessions to subscribe to upstream sync state changes */
95
- readonly pull: (args: {
96
- cursor: EventSequenceNumber.Client.Composite
97
- }) => Stream.Stream<{ payload: typeof SyncState.PayloadUpstream.Type }>
98
- /** The `pullQueue` API can be used instead of `pull` when more convenient */
99
- readonly pullQueue: (args: {
100
- cursor: EventSequenceNumber.Client.Composite
101
- }) => Effect.Effect<Queue.Queue<{ payload: typeof SyncState.PayloadUpstream.Type }>, never, Scope.Scope>
102
-
103
- /**
104
- * Used by client sessions to push events to the leader thread.
105
- * The effect only finishes when the local push has been processed (i.e. succeeded or was rejected).
106
- * This doesn't mean the events have been pushed to the sync backend.
107
- */
108
- readonly push: (
109
- /** `batch` needs to follow the same rules as `batch` in `SyncBackend.push` */
110
- batch: ReadonlyArray<LiveStoreEvent.Client.EncodedWithMeta>,
111
- ) => Effect.Effect<void, RejectedPushError>
112
-
113
- /** Currently only used by devtools which don't provide their own event numbers */
114
- readonly pushPartial: (args: {
115
- event: LiveStoreEvent.Input.Encoded
116
- clientId: string
117
- sessionId: string
118
- }) => Effect.Effect<void, UnknownEventError>
119
-
120
70
  readonly boot: Effect.Effect<
121
71
  { initialLeaderHead: EventSequenceNumber.Client.Composite },
122
72
  never,
123
73
  Scope.Scope | HttpClient.HttpClient
124
74
  >
75
+ /** Resolves only after durable commit, publication, and backend propagation scheduling. */
76
+ readonly push: (batch: ReadonlyArray<LiveStoreEvent.Client.Encoded>) => Effect.Effect<void, RejectedPushError>
77
+ readonly pull: (args: { cursor: EventSequenceNumber.Client.Composite }) => Stream.Stream<typeof PullItem.Type>
78
+ readonly pullQueue: (args: {
79
+ cursor: EventSequenceNumber.Client.Composite
80
+ }) => Effect.Effect<Queue.Queue<typeof PullItem.Type>, never, Scope.Scope>
125
81
  readonly syncState: Subscribable.Subscribable<SyncState.SyncState>
126
82
  }
127
83
 
128
84
  interface Options {
129
85
  readonly schema: LiveStoreSchema
130
- /** Complete runtime capabilities supplied before the processor is constructed. */
131
86
  readonly runtime: Runtime
132
87
  readonly initialBlockingSyncContext: InitialBlockingSyncContext
133
- /** Initial sync state rehydrated from the persisted eventlog or initial sync state */
134
88
  readonly initialSyncState: SyncState.SyncState
135
- /**
136
- * What to do when a failure (any cause) occurs (except `BackendIdMismatchError`).
137
- *
138
- * - `'shutdown'`: Send the error to the shutdown channel and terminate the sync processor.
139
- * - `'ignore'`: Continue running.
140
- */
141
89
  readonly onError: 'shutdown' | 'ignore'
142
- /**
143
- * What to do when the sync backend identity has changed (i.e. the backend was reset).
144
- *
145
- * - `'reset'`: Clear local databases (eventlog and state) and send an intentional shutdown signal.
146
- * - `'shutdown'`: Send a shutdown signal without clearing local storage.
147
- * - `'ignore'`: Continue running with stale data.
148
- */
149
90
  readonly onBackendIdMismatch: 'reset' | 'shutdown' | 'ignore'
150
- readonly params: {
151
- /**
152
- * Maximum number of local events to process per batch cycle.
153
- *
154
- * This controls how many events from client sessions are applied to the local state
155
- * in a single iteration before yielding to allow potential backend pulls.
156
- *
157
- * **Trade-offs:**
158
- * - **Lower values (1-5):** More responsive to remote updates since pull processing can
159
- * interleave more frequently. Better for high-conflict scenarios where rebases are common.
160
- * Slightly higher per-event overhead due to more frequent transaction commits.
161
- *
162
- * - **Higher values (10-50+):** Better throughput for bulk local writes as more events are
163
- * batched into a single transaction. However, may delay remote update processing and
164
- * increase rebase complexity if many local events queue up during a slow pull.
165
- *
166
- * - **Very high values (100+):** Risk of starvation for pull processing if local pushes
167
- * arrive continuously. May cause larger rollbacks during rebases. Not recommended
168
- * unless you have a write-heavy workload with minimal remote synchronization.
169
- *
170
- * @default 10
171
- */
172
- readonly localPushBatchSize?: number
173
- /**
174
- * Maximum number of events to push to the sync backend per batch.
175
- *
176
- * This controls how many events are sent in a single push request to the remote server.
177
- *
178
- * **Trade-offs:**
179
- * - **Lower values (1-10):** Lower latency for each push operation. Faster feedback on
180
- * push success/failure. Slightly higher network overhead due to more requests.
181
- *
182
- * - **Higher values (50-100):** Better network efficiency by amortizing request overhead.
183
- * Preferred for high-throughput scenarios. May increase latency to first confirmation.
184
- *
185
- * - **Very high values (200+):** Risk of hitting server request size limits or timeouts.
186
- * A single failed request loses the entire batch (will be retried). May cause memory
187
- * pressure if events accumulate faster than they can be pushed.
188
- *
189
- * @default 50
190
- */
191
- readonly backendPushBatchSize?: number
192
- }
193
- /**
194
- * Whether the sync backend should reactively pull new events from the sync backend
195
- * When `false`, the sync processor will only do an initial pull
196
- */
91
+ readonly params: { readonly localPushBatchSize?: number; readonly backendPushBatchSize?: number }
197
92
  readonly livePull: boolean
198
93
  readonly testing: {
199
94
  readonly delays?: {
@@ -201,23 +96,18 @@ interface Options {
201
96
  readonly backendPullReconnect?: (fallbackMs: number) => number
202
97
  }
203
98
  readonly hooks?: {
204
- readonly localPushAdmitted?: (events: ReadonlyArray<LiveStoreEvent.Client.EncodedWithMeta>) => Effect.Effect<void>
99
+ readonly localPushAdmitted?: (events: ReadonlyArray<LiveStoreEvent.Client.Encoded>) => Effect.Effect<void>
100
+ /** Runs in the mailbox before it handles a backend page, allowing tests to hold the page while the pull moves on. */
101
+ readonly upstreamBatchReceived?: (events: ReadonlyArray<LiveStoreEvent.Client.Encoded>) => Effect.Effect<void>
205
102
  /** Observes connectivity after the offline wait has subscribed, allowing tests to synchronize without sleeps. */
206
103
  readonly backendPullReconnectWait?: (state: { isConnected: boolean; fallbackMs: number }) => Effect.Effect<void>
207
104
  }
208
105
  }
209
106
  }
210
107
 
211
- /**
212
- * Runtime capabilities used by sync processing. Keeping these explicit prevents the processor from
213
- * depending on the outward-facing leader aggregate that contains the processor itself.
214
- */
215
108
  interface Runtime {
216
- readonly dbState: SqliteDb
217
- readonly dbEventlog: SqliteDb
218
- readonly materializeEvent: MaterializeEvent
219
109
  readonly syncBackend: SyncBackend.SyncBackend | undefined
220
- readonly shutdownChannel: ShutdownChannel
110
+ readonly shutdownChannel: Shutdown.ShutdownChannel
221
111
  readonly devtoolsLatch: Latch.Latch | undefined
222
112
  readonly span: Tracer.Span | undefined
223
113
  }
@@ -233,772 +123,1125 @@ export const make = Effect.fnUntraced(function* ({
233
123
  params,
234
124
  testing,
235
125
  }: Options) {
236
- const stateHead = yield* StateHead.StateHead
237
- const { dbState, dbEventlog, devtoolsLatch, materializeEvent, shutdownChannel, span, syncBackend } = runtime
238
- const syncBackendPushQueue = yield* TxQueue.unbounded<LiveStoreEvent.Client.EncodedWithMeta>()
239
- const localPushBatchSize = params.localPushBatchSize ?? 10
240
- const backendPushBatchSize = params.backendPushBatchSize ?? 50
241
-
242
- const syncStateSref = yield* SubscriptionRef.make<SyncState.SyncState | undefined>(undefined)
243
-
244
- const isClientOnlyEvent = (eventEncoded: LiveStoreEvent.Client.EncodedWithMeta) =>
245
- schema.eventsDefsMap.get(eventEncoded.name)?.options.clientOnly ?? false
246
-
247
- const connectedClientSessionPullQueues = yield* makePullQueueSet
248
- const materializeEventsBatch = makeMaterializeEventsBatch({ dbState, dbEventlog, materializeEvent })
249
-
250
- type LocalPushQueueItem = [
251
- event: LiveStoreEvent.Client.EncodedWithMeta,
252
- deferred: Deferred.Deferred<void, LeaderAheadError | StaleRebaseGenerationError>,
253
- ]
254
- const localPushesQueue = yield* TxQueue.unbounded<LocalPushQueueItem>()
255
- // Reservations cover admitted pushes from validation until they are applied or rejected. The Set's
256
- // insertion order mirrors admission order, so its last relevant item is the optimistic sequence head.
257
- const reservedLocalPushItems = new Set<LocalPushQueueItem>()
258
- // Ensures mutual exclusion between local push and backend pull processing.
259
- const localPushBackendPullMutex = yield* Semaphore.make(1)
260
- // Serializes validation, queue admission, and prefix-fence reconciliation.
261
- const pushAdmissionSemaphore = yield* Semaphore.make(1)
126
+ const dbEventlog = yield* EventlogSqliteDb.EventlogSqliteDb
127
+ const dbState = yield* StateSqliteDb.StateSqliteDb
128
+ const persistence = yield* LeaderPersistence.LeaderPersistence
129
+ const { devtoolsLatch, shutdownChannel, span, syncBackend } = runtime
130
+
131
+ const mailbox = yield* Queue.unbounded<LeaderMessage>()
132
+ const syncStateRef = yield* SubscriptionRef.make(initialSyncState)
133
+ const connectedSessions = yield* makePullQueueSet
134
+ const bootDeferred = yield* Deferred.make<EventSequenceNumber.Client.Composite>()
135
+ const startedDeferred = yield* Deferred.make<void>()
136
+ const stoppedDeferred = yield* Deferred.make<void>()
137
+ const nextLocalRequestId = yield* Ref.make(1)
138
+ const nextPullBatchId = yield* Ref.make(1)
139
+ const localRequests = yield* Ref.make<LocalRequestRegistry>({ _tag: 'open', requests: new Map() })
140
+ const pullBatches = yield* Ref.make(new Map<PullBatchId, Deferred.Deferred<void>>())
141
+ const bootStarted = yield* Ref.make(false)
142
+ const pushHandle = yield* FiberHandle.make<void, never>()
143
+ const pullHandle = yield* FiberHandle.make<void, never>()
144
+ const backgroundFibers = yield* FiberSet.make<void, never>()
145
+
146
+ const config: Config = {
147
+ livePull,
148
+ localCommitBatchSize: params.localPushBatchSize ?? 10,
149
+ backendPushBatchSize: params.backendPushBatchSize ?? 50,
150
+ onError,
151
+ onBackendIdMismatch,
152
+ localWorkInitiallyBlocked: testing.delays?.localPushProcessing !== undefined,
153
+ }
154
+ const isClientOnlyEvent = (event: LiveStoreEvent.Client.Encoded) =>
155
+ schema.eventsDefsMap.get(event.name)?.options.clientOnly ?? false
156
+ // `model` is intentionally local rather than a Ref. Only the mailbox loop changes it, apart from boot and
157
+ // operation startup which also run in this scope before their asynchronous work reports back through the mailbox.
158
+ let model = initialModel(config, syncBackend !== undefined, initialSyncState, isClientOnlyEvent)
159
+
160
+ const send = (message: LeaderMessage) => Queue.offer(mailbox, message).pipe(Effect.asVoid)
161
+ const fork = (effect: Effect.Effect<void>) => FiberSet.run(backgroundFibers, effect).pipe(Effect.asVoid)
162
+ const allocateOperationId = () => {
163
+ // Completion messages carry this id so a late result from an interrupted provider call cannot affect newer work.
164
+ const operationId = model.nextOperationId
165
+ model = { ...model, nextOperationId: operationId + 1 }
166
+ return operationId
167
+ }
262
168
 
263
- /**
264
- * Admission fence for local pushes. Unlike `syncState.localHead`, this advances as soon as an event
265
- * is queued, so another session cannot claim the same sequence number while that event is waiting
266
- * to be applied. With authoritative head e0 and reserved pushes e1/e2, this points to e2.
267
- *
268
- * All reads and writes are protected by `pushAdmissionSemaphore` so validation and reservation are
269
- * one atomic operation from the perspective of concurrent sessions and backend pulls.
270
- */
271
- const pushHeadRef = { current: initialSyncState.localHead }
169
+ const interruptAllWork = Effect.all([
170
+ FiberHandle.clear(pushHandle),
171
+ FiberHandle.clear(pullHandle),
172
+ FiberSet.clear(backgroundFibers),
173
+ interruptAllLocalRequests(localRequests),
174
+ interruptAllPullBatches(pullBatches),
175
+ ])
176
+
177
+ const stop = (args: {
178
+ readonly lifecycle: 'stopping' | 'failed'
179
+ readonly error?: unknown
180
+ readonly notify: boolean
181
+ }) =>
182
+ Effect.gen(function* () {
183
+ if ((yield* Deferred.isDone(stoppedDeferred)) === true) return false
184
+ model = { ...model, lifecycle: args.lifecycle }
185
+ if (args.notify === true && args.error !== undefined) {
186
+ // A broken shutdown channel must not prevent resource cleanup or leave admitted pushes unresolved.
187
+ yield* shutdownChannel
188
+ .send(
189
+ Schema.is(Shutdown.All)(args.error) === true
190
+ ? args.error
191
+ : UnknownError.make({ cause: args.error, note: 'Leader sync loop failed' }),
192
+ )
193
+ .pipe(Effect.exit)
194
+ }
195
+ yield* interruptAllWork
196
+ yield* Deferred.succeed(stoppedDeferred, void 0)
197
+ return false
198
+ })
272
199
 
273
- /**
274
- * A backend pull may advance or rebase authoritative history while local pushes remain reserved.
275
- * Keep the fence at the newest reservation that is still valid for that history; if none remains,
276
- * fall back to the authoritative head. Stale reservations are released later by the queue worker.
277
- */
278
- const reconcilePushHead = (authoritativeHead: EventSequenceNumber.Client.Composite) =>
279
- pushAdmissionSemaphore.withPermits(1)(
280
- Effect.gen(function* () {
281
- const latestCurrentGenerationItem = [...reservedLocalPushItems].findLast(
282
- ([event]) => event.seqNum.rebaseGeneration >= authoritativeHead.rebaseGeneration,
283
- )
284
- pushHeadRef.current = latestCurrentGenerationItem?.[0].seqNum ?? authoritativeHead
285
- }).pipe(Effect.uninterruptible),
286
- )
287
- /**
288
- * Stop completed, rejected, or stale queue items from extending the admission fence, then rebuild
289
- * the fence from any pushes that are still reserved.
290
- */
291
- const releasePushReservations = (
292
- items: ReadonlyArray<LocalPushQueueItem>,
293
- authoritativeHead: EventSequenceNumber.Client.Composite,
294
- ) =>
295
- pushAdmissionSemaphore.withPermits(1)(
296
- Effect.gen(function* () {
297
- for (const item of items) reservedLocalPushItems.delete(item)
298
- const latestCurrentGenerationItem = [...reservedLocalPushItems].findLast(
299
- ([event]) => event.seqNum.rebaseGeneration >= authoritativeHead.rebaseGeneration,
300
- )
301
- pushHeadRef.current = latestCurrentGenerationItem?.[0].seqNum ?? authoritativeHead
302
- }).pipe(Effect.uninterruptible),
303
- )
200
+ const stopForSyncFailure = (cause: unknown) =>
201
+ stop({ lifecycle: 'failed', error: cause, notify: config.onError === 'shutdown' })
202
+
203
+ const startProviderPush = () =>
204
+ Effect.gen(function* () {
205
+ if (model.lifecycle !== 'running' || model.push._tag !== 'idle') return
206
+ if (model.push.queued.length === 0) return
207
+ const batch = model.push.queued.slice(0, config.backendPushBatchSize)
208
+ yield* runPushOperation({ attempt: 0, batch, queued: model.push.queued.slice(batch.length) })
209
+ })
304
210
 
305
- const backgroundApplyLocalPushes = Effect.gen(function* () {
306
- while (true) {
307
- if (testing.delays?.localPushProcessing !== undefined) {
308
- yield* testing.delays.localPushProcessing.pipe(Effect.withSpan('localPushProcessingDelay'))
211
+ /** Starts a provider push for `batch`. A retry reuses it with the attempt count of the failed operation. */
212
+ const runPushOperation = (push: { attempt: number; batch: EventBatch; queued: EventBatch }) =>
213
+ Effect.gen(function* () {
214
+ if (syncBackend === undefined) return
215
+ const operationId = allocateOperationId()
216
+ model = {
217
+ ...model,
218
+ push: { _tag: 'in-flight', operationId, attempt: push.attempt, batch: push.batch, queued: push.queued },
309
219
  }
220
+ yield* FiberHandle.run(
221
+ pushHandle,
222
+ runProviderPush({ operationId, attempt: push.attempt, batch: push.batch }, syncBackend, devtoolsLatch, send),
223
+ ).pipe(Effect.asVoid)
224
+ })
310
225
 
311
- const batchItems = yield* TxQueue.takeBetween(localPushesQueue, 1, localPushBatchSize)
226
+ /**
227
+ * Waits before retrying an offline pull. A false→true connectivity transition wakes the retry immediately; a jittered,
228
+ * capped fallback timer covers connectivity that stays stale-true. Resolves `true` when woken by a reconnect.
229
+ */
230
+ const awaitPullRetry = (attempt: number) =>
231
+ Effect.gen(function* () {
232
+ const jitteredMs = retryDelay(attempt) * (yield* Random.nextBetween(0.8, 1.2))
233
+ const fallbackMs = testing.delays?.backendPullReconnect?.(jitteredMs) ?? jitteredMs
234
+ if (syncBackend === undefined) return yield* Effect.sleep(Duration.millis(fallbackMs)).pipe(Effect.as(false))
235
+ const waitHook = testing.hooks?.backendPullReconnectWait
236
+ const changes = SubscriptionRef.changes(syncBackend.isConnected)
237
+ const observed =
238
+ waitHook === undefined
239
+ ? changes
240
+ : changes.pipe(Stream.tap((isConnected) => waitHook({ isConnected, fallbackMs })))
241
+ // A stale initial `true` is not a reconnect: wait for false→true, even while the fallback timer is pending.
242
+ return yield* observed.pipe(
243
+ Stream.dropWhile((isConnected) => isConnected === true),
244
+ Stream.filter((isConnected) => isConnected === true),
245
+ Stream.runHead,
246
+ Effect.as(true),
247
+ Effect.timeoutOrElse({ duration: Duration.millis(fallbackMs), orElse: () => Effect.succeed(false) }),
248
+ )
249
+ })
312
250
 
313
- // Applies a batch of local pushes, guarded by the localPushBackendPullMutex to ensure mutual exclusion with backend pulling
314
- yield* Effect.gen(function* () {
315
- const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(
316
- Effect.orDieDebugger,
317
- )
251
+ const startProviderPull = (attempt: number) =>
252
+ Effect.gen(function* () {
253
+ if (syncBackend === undefined || model.lifecycle !== 'running') return
254
+ const pullId = allocateOperationId()
255
+ model = { ...model, pull: { _tag: 'streaming', pullId, pagination: 'between-pages', attempt } }
256
+ yield* FiberHandle.run(
257
+ pullHandle,
258
+ runProviderPull({
259
+ pullId,
260
+ cursor: model.syncState.upstreamHead,
261
+ live: config.livePull,
262
+ syncBackend,
263
+ devtoolsLatch,
264
+ dbEventlog,
265
+ pullBatches,
266
+ nextPullBatchId,
267
+ initialBlockingSyncContext,
268
+ send,
269
+ }),
270
+ ).pipe(Effect.asVoid)
271
+ })
318
272
 
319
- const currentRebaseGeneration = syncState.localHead.rebaseGeneration
273
+ const replacePushPlan = (replacement: ReadonlyArray<LiveStoreEvent.Client.Encoded>) =>
274
+ Effect.gen(function* () {
275
+ if (model.push._tag === 'disabled') return
276
+ const inFlight = model.push._tag === 'in-flight'
277
+ // An upstream rebase may have changed every pending sequence number. Rebuild the provider queue from the
278
+ // committed sync state instead of trying to patch the old plan.
279
+ model = { ...model, push: { _tag: 'idle', queued: replacement } }
280
+ if (inFlight === true) yield* FiberHandle.clear(pushHandle)
281
+ yield* startProviderPush()
282
+ })
320
283
 
321
- // Since the rebase generation might have changed since enqueuing, we need to filter out items with older generation
322
- // It's important that we filter after acquiring the localPushBackendPullMutex, otherwise we might filter with the old generation
323
- const [filteredItems, droppedItems] = ReadonlyArray.partition(batchItems, (batchItem) =>
324
- batchItem[0].seqNum.rebaseGeneration >= currentRebaseGeneration
325
- ? Result.succeed(batchItem)
326
- : Result.fail(batchItem),
327
- )
284
+ const publish = (args: {
285
+ syncState: SyncState.SyncState
286
+ payload: typeof SyncState.PayloadUpstream.Type
287
+ materializerHashes: ReadonlyArray<LiveStoreEvent.Client.MaterializerHash>
288
+ }) =>
289
+ Effect.gen(function* () {
290
+ model = { ...model, syncState: args.syncState }
291
+ yield* SubscriptionRef.set(syncStateRef, args.syncState)
292
+ yield* connectedSessions.offer({
293
+ payload: args.payload,
294
+ globalHead: args.syncState.upstreamHead,
295
+ leaderHead: args.syncState.localHead,
296
+ materializerHashes: args.materializerHashes,
297
+ })
298
+ })
328
299
 
329
- if (droppedItems.length > 0) {
330
- yield* Effect.spanEvent(`push:drop-old-generation`, {
331
- droppedCount: droppedItems.length,
332
- currentRebaseGeneration,
300
+ const processLocalBatch = (items: ReadonlyArray<LocalItem>) =>
301
+ Effect.gen(function* () {
302
+ const mergeExit = yield* SyncState.merge({
303
+ syncState: model.syncState,
304
+ payload: { _tag: 'local-push', newEvents: items.map((item) => item.event) },
305
+ isClientOnlyEvent,
306
+ isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
307
+ }).pipe(Effect.exit)
308
+ if (Exit.isFailure(mergeExit) === true) return yield* stopForSyncFailure(Cause.squash(mergeExit.cause))
309
+ const merge = mergeExit.value
310
+ if (merge._tag === 'reject') {
311
+ // Later events in the same generation were numbered on top of this rejected batch, so they cannot remain
312
+ // valid on their own. Reject them together and let the session produce a fresh sequence.
313
+ const generation = items[0]?.event.seqNum.rebaseGeneration
314
+ const queuedSameGeneration = model.localQueue.filter(
315
+ (item) => item.event.seqNum.rebaseGeneration === generation,
316
+ )
317
+ const rejectedItems = [...items, ...queuedSameGeneration]
318
+ const rejectedKeys = new Set(rejectedItems.map(localItemKey))
319
+ const firstEvent = items[0]?.event
320
+ model = {
321
+ ...model,
322
+ localQueue: model.localQueue.filter((item) => !rejectedKeys.has(localItemKey(item))),
323
+ }
324
+ if (firstEvent !== undefined) {
325
+ const error = new LeaderAheadError({
326
+ minimumExpectedNum: merge.expectedMinimumId,
327
+ providedNum: firstEvent.seqNum,
328
+ sessionId: firstEvent.sessionId,
333
329
  })
334
-
335
- yield* Effect.forEach(droppedItems, ([eventEncoded, deferred]) =>
336
- Deferred.fail(
337
- deferred,
338
- StaleRebaseGenerationError.make({
339
- currentRebaseGeneration,
340
- providedRebaseGeneration: eventEncoded.seqNum.rebaseGeneration,
341
- sessionId: eventEncoded.sessionId,
342
- }),
343
- ),
330
+ yield* rejectLocalItems(
331
+ localRequests,
332
+ rejectedItems.map((item) => ({ item, error })),
344
333
  )
345
-
346
- yield* releasePushReservations(droppedItems, syncState.localHead)
347
- }
348
-
349
- if (filteredItems.length === 0) {
350
- return
351
334
  }
335
+ yield* send({ _tag: 'ContinueWork' })
336
+ return true
337
+ }
338
+ if (merge._tag === 'rebase') return yield* stopForSyncFailure(new Error('Local push required rebase'))
352
339
 
353
- const [newEvents, deferreds] = ReadonlyArray.unzip(filteredItems)
354
-
355
- yield* Effect.annotateCurrentSpan({
356
- batchSize: newEvents.length,
357
- ...(TRACE_VERBOSE === true ? { newEvents: jsonStringify(newEvents) } : {}),
358
- })
359
-
360
- const mergeResult = yield* SyncState.merge({
361
- syncState,
362
- payload: { _tag: 'local-push', newEvents },
363
- isClientOnlyEvent,
364
- isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
340
+ // Commit the events retained by the merge, not the input objects. This is the proposed state transition that
341
+ // LeaderPersistence must either make durable as a whole or reject.
342
+ const events = merge.newSyncState.pending.slice(model.syncState.pending.length)
343
+ if (events.length !== merge.newEvents.length) {
344
+ return yield* stopForSyncFailure(new Error('Local push was not retained as pending'))
345
+ }
346
+ const persistExit = yield* persistence.persistLocal({ events }).pipe(Effect.exit)
347
+ if (Exit.isFailure(persistExit) === true) return yield* stopForSyncFailure(Cause.squash(persistExit.cause))
348
+ const receipt = persistExit.value
349
+ if (EventSequenceNumber.Client.isEqual(receipt.stateHead, merge.newSyncState.localHead) === false) {
350
+ return yield* stopForSyncFailure({
351
+ _tag: 'PersistReceiptMismatch',
352
+ expectedStateHead: merge.newSyncState.localHead,
353
+ receipt,
365
354
  })
355
+ }
366
356
 
367
- switch (mergeResult._tag) {
368
- case 'rebase': {
369
- return yield* Effect.dieDebugger('The leader thread should never have to rebase due to a local push')
370
- }
371
- case 'reject': {
372
- yield* Effect.spanEvent(`push:reject`, {
373
- batchSize: newEvents.length,
374
- ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
375
- })
376
-
377
- // TODO: how to test this?
378
- const nextRebaseGeneration = currentRebaseGeneration + 1
379
-
380
- const providedNum = newEvents.at(0)!.seqNum
381
- // All subsequent pushes with same generation should be rejected as well
382
- // We're also handling the case where the localPushQueue already contains events
383
- // from the next generation which we preserve in the queue
384
- const remainingEventsMatchingGeneration = yield* takePrefixUntil(
385
- localPushesQueue,
386
- ([eventEncoded]) => eventEncoded.seqNum.rebaseGeneration >= nextRebaseGeneration,
387
- )
388
-
389
- // TODO we still need to better understand and handle this scenario
390
- const remainingLocalPushes = yield* snapshotTxQueue(localPushesQueue)
391
- if (LS_DEV === true && remainingLocalPushes.length > 0) {
392
- console.log('localPushesQueue is not empty', remainingLocalPushes.length)
393
- // oxlint-disable-next-line no-debugger -- intentional breakpoint for unexpected queue state
394
- debugger
395
- }
396
-
397
- const allDeferredsToReject = [
398
- ...deferreds,
399
- ...remainingEventsMatchingGeneration.map(([_, deferred]) => deferred),
400
- ]
401
-
402
- // The rejected batch and its drained same-generation suffix will never advance leader state,
403
- // so release their sequence-number reservations before clients retry from the authoritative head.
404
- yield* releasePushReservations(
405
- [...filteredItems, ...remainingEventsMatchingGeneration],
406
- syncState.localHead,
407
- )
408
-
409
- yield* Effect.forEach(allDeferredsToReject, (deferred) =>
410
- Deferred.fail(
411
- deferred,
412
- LeaderAheadError.make({
413
- minimumExpectedNum: mergeResult.expectedMinimumId,
414
- providedNum,
415
- sessionId: newEvents.at(0)!.sessionId,
416
- }),
417
- ),
418
- )
419
-
420
- // In this case we're skipping state update and down/upstream processing
421
- // We've cleared the local push queue and are now waiting for new local pushes / backend pulls
422
- return
423
- }
424
- case 'advance': {
425
- break
426
- }
427
- default: {
428
- casesHandled(mergeResult)
429
- }
430
- }
431
-
432
- // For a local-push advance, `newEvents` and the appended pending suffix describe the same logical
433
- // events but serve different roles and may be distinct instances. Materialize the retained pending
434
- // instances so their rollback metadata remains available if a later backend event causes a rebase.
435
- const acceptedPendingEvents = mergeResult.newSyncState.pending.slice(syncState.pending.length)
436
- if (acceptedPendingEvents.length !== mergeResult.newEvents.length) {
437
- return yield* Effect.dieDebugger('Local push events must be retained in pending state')
438
- }
439
-
440
- yield* materializeEventsBatch({ batchItems: acceptedPendingEvents })
441
-
442
- yield* SubscriptionRef.set(syncStateSref, mergeResult.newSyncState)
357
+ yield* publish({
358
+ syncState: merge.newSyncState,
359
+ payload: SyncState.PayloadUpstreamAdvance.make({ newEvents: receipt.persistedEvents }),
360
+ materializerHashes: receipt.materializerHashes,
361
+ })
362
+ model = enqueuePushEvents(
363
+ model,
364
+ receipt.persistedEvents.filter((event) => !isClientOnlyEvent(event)),
365
+ )
366
+ yield* startProviderPush()
367
+ yield* completeLocalItems(localRequests, items)
368
+ yield* send({ _tag: 'ContinueWork' })
369
+ return true
370
+ })
443
371
 
444
- yield* connectedClientSessionPullQueues.offer({
445
- payload: SyncState.PayloadUpstreamAdvance.make({ newEvents: acceptedPendingEvents }),
446
- leaderHead: mergeResult.newSyncState.localHead,
372
+ const processUpstreamBatch = (batch: CoalescedUpstreamBatch) =>
373
+ Effect.gen(function* () {
374
+ const mergeExit = yield* SyncState.merge({
375
+ syncState: model.syncState,
376
+ payload: SyncState.PayloadUpstreamAdvance.make({ newEvents: batch.events }),
377
+ isClientOnlyEvent,
378
+ isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
379
+ ignoreClientOnlyEvents: true,
380
+ }).pipe(Effect.exit)
381
+ if (Exit.isFailure(mergeExit) === true) return yield* stopForSyncFailure(Cause.squash(mergeExit.cause))
382
+ const merge = mergeExit.value
383
+ if (merge._tag === 'reject') return yield* stopForSyncFailure(new Error('Upstream batch rejected'))
384
+
385
+ const rollbackEvents = merge._tag === 'rebase' ? merge.rollbackEvents : []
386
+ const confirmedEvents = merge._tag === 'advance' ? merge.confirmedEvents : []
387
+ const backendHead = batch.events.at(-1)?.seqNum
388
+ if (backendHead === undefined) return yield* stopForSyncFailure(new Error('Upstream batch has no head'))
389
+ const persistExit = yield* persistence
390
+ .persistUpstream({
391
+ pulledEvents: batch.pulledEvents,
392
+ events: merge.newEvents,
393
+ rollbackEvents,
394
+ confirmedEvents,
395
+ backendHead,
447
396
  })
448
-
449
- yield* Effect.spanEvent(`push:advance`, {
450
- batchSize: newEvents.length,
451
- ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
397
+ .pipe(Effect.exit)
398
+ if (Exit.isFailure(persistExit) === true) return yield* stopForSyncFailure(Cause.squash(persistExit.cause))
399
+ const receipt = persistExit.value
400
+ // The backend reports confirmed events without their local rebase generation, so confirming a pending event
401
+ // that was rebased locally leaves the persisted state head at the same DAG position with a higher generation.
402
+ if (
403
+ LeaderPersistence.isSameSequencePosition(receipt.stateHead, merge.newSyncState.localHead) === false ||
404
+ EventSequenceNumber.Client.isEqual(receipt.backendHead, backendHead) === false
405
+ ) {
406
+ return yield* stopForSyncFailure({
407
+ _tag: 'PersistReceiptMismatch',
408
+ expectedStateHead: merge.newSyncState.localHead,
409
+ expectedBackendHead: backendHead,
410
+ receipt,
452
411
  })
412
+ }
453
413
 
454
- // Don't sync client-only events
455
- const globalOrUnknownEvents = acceptedPendingEvents.filter((e) => !isClientOnlyEvent(e))
456
-
457
- yield* TxQueue.offerAll(syncBackendPushQueue, globalOrUnknownEvents)
414
+ const payload =
415
+ merge._tag === 'rebase'
416
+ ? SyncState.PayloadUpstreamRebase.make({ rollbackEvents, newEvents: receipt.persistedEvents })
417
+ : SyncState.PayloadUpstreamAdvance.make({ newEvents: receipt.persistedEvents })
418
+ yield* publish({ syncState: merge.newSyncState, payload, materializerHashes: receipt.materializerHashes })
419
+ yield* Effect.forEach(batch.batchIds, (batchId) => completePullBatch(pullBatches, batchId), { discard: true })
420
+ yield* replacePushPlan(merge.newSyncState.pending.filter((event) => !isClientOnlyEvent(event)))
421
+ yield* send({ _tag: 'ContinueWork' })
422
+ return true
423
+ })
458
424
 
459
- yield* releasePushReservations(filteredItems, mergeResult.newSyncState.localHead)
425
+ const processNextWork = () =>
426
+ Effect.gen(function* () {
427
+ if (model.lifecycle !== 'running') return true
428
+ // Apply backend truth before more local work. This avoids assigning local events on top of a head that is
429
+ // already known to need an upstream advance or rebase.
430
+ const upstream = coalesceUpstreamBatches(model.upstreamQueue)
431
+ if (upstream !== undefined) {
432
+ model = { ...model, upstreamQueue: model.upstreamQueue.slice(upstream.batchIds.length) }
433
+ return yield* processUpstreamBatch(upstream)
434
+ }
435
+ // When a backend page says another page follows, keep local work paused until that page arrives. Together the
436
+ // pages describe one uninterrupted upstream advance.
437
+ if (model.pull._tag === 'streaming' && model.pull.pagination === 'more-expected') return true
438
+ if (model.localWorkEnabled === false || model.localQueue.length === 0) return true
439
+
440
+ const selected = model.localQueue.slice(0, config.localCommitBatchSize)
441
+ const selectedKeys = new Set(selected.map(localItemKey))
442
+ const remaining = model.localQueue.filter((item) => !selectedKeys.has(localItemKey(item)))
443
+ const currentGeneration = model.syncState.localHead.rebaseGeneration
444
+ const staleItems = selected.filter((item) => item.event.seqNum.rebaseGeneration < currentGeneration)
445
+ const activeItems = selected.filter((item) => item.event.seqNum.rebaseGeneration >= currentGeneration)
446
+ model = { ...model, localQueue: remaining }
447
+ if (staleItems.length > 0) {
448
+ model = { ...model, localQueue: [...activeItems, ...remaining] }
449
+ yield* rejectLocalItems(
450
+ localRequests,
451
+ staleItems.map((item) => ({
452
+ item,
453
+ error: new StaleRebaseGenerationError({
454
+ currentRebaseGeneration: currentGeneration,
455
+ providedRebaseGeneration: item.event.seqNum.rebaseGeneration,
456
+ sessionId: item.event.sessionId,
457
+ }),
458
+ })),
459
+ )
460
+ yield* send({ _tag: 'ContinueWork' })
461
+ return true
462
+ }
463
+ return yield* processLocalBatch(activeItems)
464
+ })
460
465
 
461
- // A push is acknowledged only after the complete batch is materialized, published in
462
- // leader sync state, exposed to sessions, and queued for backend propagation.
463
- yield* Effect.forEach(deferreds, (deferred) => Deferred.succeed(deferred, void 0))
464
- }).pipe(localPushBackendPullMutex.withPermits(1))
466
+ const handleBackendMismatch = Effect.fn('@livestore/common:LeaderSyncProcessor:handleBackendIdMismatch')(function* (
467
+ error: BackendIdMismatchError,
468
+ direction: 'pull' | 'push',
469
+ ) {
470
+ switch (config.onBackendIdMismatch) {
471
+ case 'ignore':
472
+ model = {
473
+ ...model,
474
+ ...(direction === 'pull'
475
+ ? { pull: { _tag: 'completed' } as const }
476
+ : { push: { _tag: 'disabled' } as const }),
477
+ }
478
+ if (direction === 'pull') yield* send({ _tag: 'ContinueWork' })
479
+ return true
480
+ case 'shutdown':
481
+ yield* Effect.logWarning(
482
+ 'Sync backend identity changed (backend was reset). Shutting down without clearing local storage.',
483
+ error,
484
+ )
485
+ return yield* stop({ lifecycle: 'failed', error, notify: true })
486
+ case 'reset': {
487
+ yield* Effect.logWarning(
488
+ 'Sync backend identity changed (backend was reset). Clearing local storage and shutting down.',
489
+ error,
490
+ )
491
+ // Stop all work that could still touch the databases before clearing them.
492
+ model = { ...model, lifecycle: 'stopping' }
493
+ yield* interruptAllWork
494
+ const resetExit = yield* clearLocalDatabases({ dbEventlog, dbState }).pipe(Effect.exit)
495
+ const cause =
496
+ Exit.isFailure(resetExit) === true
497
+ ? Cause.squash(resetExit.cause)
498
+ : IntentionalShutdownCause.make({ reason: 'backend-id-mismatch' })
499
+ return yield* stop({ lifecycle: 'failed', error: cause, notify: true })
500
+ }
501
+ default:
502
+ return casesHandled(config.onBackendIdMismatch)
465
503
  }
466
504
  })
467
505
 
468
- const backgroundBackendPulling = Effect.fn('@livestore/common:LeaderSyncProcessor:backend-pulling')(function* ({
469
- restartBackendPushing,
470
- onPullSuccess,
471
- }: {
472
- restartBackendPushing: (
473
- filteredRebasedPending: ReadonlyArray<LiveStoreEvent.Client.EncodedWithMeta>,
474
- ) => Effect.Effect<void, never, HttpClient.HttpClient>
475
- onPullSuccess: () => void
476
- }) {
477
- if (syncBackend === undefined) return
478
-
479
- let pullMutexHeld = false
480
-
481
- const releasePullMutexIfHeld = Effect.gen(function* () {
482
- if (pullMutexHeld === false) return
483
- pullMutexHeld = false
484
- yield* localPushBackendPullMutex.release(1)
485
- })
486
-
487
- const isPullPaginationComplete = (pageInfo: SyncBackend.PullResPageInfo) => pageInfo._tag === 'NoMore'
488
-
489
- const onNewPullChunk = (
490
- newEvents: LiveStoreEvent.Client.EncodedWithMeta[],
491
- pageInfo: SyncBackend.PullResPageInfo,
492
- ) =>
493
- Effect.gen(function* () {
494
- if (devtoolsLatch !== undefined) {
495
- yield* devtoolsLatch.await
506
+ const handleMessage = (message: LeaderMessage): Effect.Effect<boolean> =>
507
+ Effect.gen(function* () {
508
+ if (message._tag === 'ShutdownRequested') {
509
+ return yield* stop({ lifecycle: 'stopping', notify: false })
510
+ }
511
+ if (message._tag === 'Started') {
512
+ if (model.lifecycle !== 'starting') return true
513
+ // Provider work starts inside a turn, so it cannot interleave with pushes or pages that change the model.
514
+ model = { ...model, lifecycle: 'running' }
515
+ if (syncBackend !== undefined) {
516
+ yield* startProviderPull(0)
517
+ yield* startProviderPush()
496
518
  }
519
+ return true
520
+ }
521
+ if (model.lifecycle !== 'running') {
522
+ if (message._tag === 'LocalPushRequested') yield* interruptLocalRequests(localRequests, [message.requestId])
523
+ return true
524
+ }
497
525
 
498
- if (newEvents.length === 0) {
499
- if (isPullPaginationComplete(pageInfo) === true) {
500
- yield* releasePullMutexIfHeld
526
+ switch (message._tag) {
527
+ case 'LocalPushRequested': {
528
+ // The local queue holds admitted but not-yet-committed events. Validating against its tail prevents two
529
+ // callers from being admitted with the same sequence number while they wait in the queue.
530
+ const pushHead = model.localQueue.at(-1)?.event.seqNum ?? model.syncState.localHead
531
+ const validation = yield* validatePushBatch(message.events, pushHead, isClientOnlyEvent).pipe(Effect.result)
532
+ const items = message.events.map((pushedEvent, index) => ({
533
+ requestId: message.requestId,
534
+ index,
535
+ event: pushedEvent,
536
+ }))
537
+ if (Result.isFailure(validation) === true) {
538
+ yield* rejectLocalItems(
539
+ localRequests,
540
+ items.map((item) => ({ item, error: validation.failure })),
541
+ )
542
+ return true
501
543
  }
502
- return
544
+ model = { ...model, localQueue: [...model.localQueue, ...items] }
545
+ yield* testing.hooks?.localPushAdmitted?.(message.events) ?? Effect.void
546
+ yield* send({ _tag: 'ContinueWork' })
547
+ return true
503
548
  }
504
-
505
- // Prevent more local pushes from being processed until this pull pagination sequence is finished.
506
- if (pullMutexHeld === false) {
507
- yield* localPushBackendPullMutex.take(1)
508
- pullMutexHeld = true
549
+ case 'LocalWorkEnabled':
550
+ model = { ...model, localWorkEnabled: true }
551
+ yield* send({ _tag: 'ContinueWork' })
552
+ return true
553
+ case 'ContinueWork':
554
+ return yield* processNextWork()
555
+ case 'UpstreamBatchReceived': {
556
+ yield* testing.hooks?.upstreamBatchReceived?.(message.batch.events) ?? Effect.void
557
+ if (model.pull._tag !== 'streaming' || model.pull.pullId !== message.batch.pullId) {
558
+ // The provider fiber waits for every page to be released. Even a late page from an old pull must be
559
+ // released, although it must not change the current model.
560
+ yield* completePullBatch(pullBatches, message.batch.batchId)
561
+ return true
562
+ }
563
+ // Any response, including an empty page, proves backend contact even when connectivity is reported stale.
564
+ const pull = { ...model.pull, attempt: 0 }
565
+ model = { ...model, pull }
566
+ if (message.batch.events.length === 0) {
567
+ if (message.batch.pageInfo._tag === 'NoMore') {
568
+ model = { ...model, pull: { ...pull, pagination: 'between-pages' } }
569
+ }
570
+ yield* completePullBatch(pullBatches, message.batch.batchId)
571
+ yield* send({ _tag: 'ContinueWork' })
572
+ return true
573
+ }
574
+ model = {
575
+ ...model,
576
+ pull: {
577
+ ...pull,
578
+ pagination: message.batch.pageInfo._tag === 'NoMore' ? 'between-pages' : 'more-expected',
579
+ },
580
+ upstreamQueue: [...model.upstreamQueue, message.batch],
581
+ }
582
+ yield* send({ _tag: 'ContinueWork' })
583
+ return true
509
584
  }
510
-
511
- const chunkExit = yield* Effect.gen(function* () {
512
- const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(
513
- Effect.orDieDebugger,
514
- )
515
-
516
- yield* Effect.annotateCurrentSpan({
517
- 'merge.newEventsCount': newEvents.length,
518
- ...(TRACE_VERBOSE === true ? { 'merge.newEvents': jsonStringify(newEvents) } : {}),
519
- })
520
-
521
- const mergeResult = yield* SyncState.merge({
522
- syncState,
523
- payload: SyncState.PayloadUpstreamAdvance.make({ newEvents }),
524
- isClientOnlyEvent,
525
- isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
526
- ignoreClientOnlyEvents: true,
527
- })
528
-
529
- if (mergeResult._tag === 'reject') {
530
- return yield* Effect.dieDebugger('The leader thread should never reject upstream advances')
585
+ case 'PullCompleted':
586
+ if (model.pull._tag === 'streaming' && model.pull.pullId === message.pullId) {
587
+ model = { ...model, pull: { _tag: 'completed' } }
588
+ yield* send({ _tag: 'ContinueWork' })
531
589
  }
532
-
533
- const newBackendHead = newEvents.at(-1)!.seqNum
534
-
535
- Eventlog.updateBackendHead(dbEventlog, newBackendHead)
536
-
537
- if (mergeResult._tag === 'rebase') {
538
- yield* Effect.spanEvent(`pull:rebase[${mergeResult.newSyncState.localHead.rebaseGeneration}]`, {
539
- newEventsCount: newEvents.length,
540
- ...(TRACE_VERBOSE === true ? { newEvents: jsonStringify(newEvents) } : {}),
541
- rollbackCount: mergeResult.rollbackEvents.length,
542
- ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
543
- })
544
-
545
- const globalOrUnknownRebasedPendingEvents = mergeResult.newSyncState.pending.filter(
546
- (e) => !isClientOnlyEvent(e),
590
+ return true
591
+ case 'PullFailed':
592
+ if (model.pull._tag !== 'streaming' || model.pull.pullId !== message.pullId) return true
593
+ if (message.error._tag === 'IsOfflineError') {
594
+ const retryId = allocateOperationId()
595
+ const attempt = model.pull.attempt + 1
596
+ model = { ...model, pull: { _tag: 'retry-wait', retryId, attempt } }
597
+ yield* fork(
598
+ awaitPullRetry(attempt).pipe(
599
+ Effect.flatMap((reconnected) => send({ _tag: 'PullRetryElapsed', retryId, reconnected })),
600
+ ),
547
601
  )
548
- yield* restartBackendPushing(globalOrUnknownRebasedPendingEvents)
549
-
550
- if (mergeResult.rollbackEvents.length > 0) {
551
- yield* rollback({
552
- dbState,
553
- dbEventlog,
554
- eventNumsToRollback: mergeResult.rollbackEvents.map((_) => _.seqNum),
555
- })
556
- yield* stateHead
557
- .set(mergeResult.rollbackEvents[0]!.parentSeqNum)
558
- .pipe(Effect.mapError((cause) => MaterializeError.make({ cause })))
602
+ return true
603
+ }
604
+ if (message.error._tag === 'BackendIdMismatchError')
605
+ return yield* handleBackendMismatch(message.error, 'pull')
606
+ if (config.onError === 'shutdown')
607
+ return yield* stop({ lifecycle: 'failed', error: message.error, notify: true })
608
+ model = { ...model, pull: { _tag: 'completed' } }
609
+ yield* send({ _tag: 'ContinueWork' })
610
+ return true
611
+ case 'PullRetryElapsed':
612
+ if (model.pull._tag === 'retry-wait' && model.pull.retryId === message.retryId) {
613
+ // A reconnect proves the backend is reachable again, so the next outage starts from the shortest delay.
614
+ yield* startProviderPull(message.reconnected === true ? 0 : model.pull.attempt)
615
+ }
616
+ return true
617
+ case 'PushSucceeded':
618
+ if (model.push._tag === 'in-flight' && model.push.operationId === message.operationId) {
619
+ model = {
620
+ ...model,
621
+ push: { _tag: 'idle', queued: model.push.queued },
559
622
  }
560
-
561
- yield* connectedClientSessionPullQueues.offer({
562
- payload: SyncState.payloadFromMergeResult(mergeResult),
563
- leaderHead: mergeResult.newSyncState.localHead,
564
- })
565
- } else {
566
- yield* Effect.spanEvent(`pull:advance`, {
567
- newEventsCount: newEvents.length,
568
- ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
569
- })
570
-
571
- // Ensure push fiber is active after advance by restarting with current pending (non-client-only) events
572
- const globalOrUnknownPendingEvents = mergeResult.newSyncState.pending.filter((e) => !isClientOnlyEvent(e))
573
- yield* restartBackendPushing(globalOrUnknownPendingEvents)
574
-
575
- yield* connectedClientSessionPullQueues.offer({
576
- payload: SyncState.payloadFromMergeResult(mergeResult),
577
- leaderHead: mergeResult.newSyncState.localHead,
578
- })
579
-
580
- if (mergeResult.confirmedEvents.length > 0) {
581
- // `mergeResult.confirmedEvents` don't contain the correct sync metadata, so we need to use
582
- // `newEvents` instead which we filter via `mergeResult.confirmedEvents`
583
- const confirmedNewEvents = newEvents.filter((event) =>
584
- mergeResult.confirmedEvents.some((confirmedEvent) =>
585
- EventSequenceNumber.Client.isEqual(event.seqNum, confirmedEvent.seqNum),
586
- ),
587
- )
588
- yield* Eventlog.updateSyncMetadataForDb(dbEventlog, confirmedNewEvents).pipe(Effect.orDieDebugger)
623
+ yield* startProviderPush()
624
+ }
625
+ return true
626
+ case 'PushFailed':
627
+ if (model.push._tag !== 'in-flight' || model.push.operationId !== message.operationId) return true
628
+ if (message.error._tag === 'ServerAheadError') {
629
+ // Pulling first will either confirm or rebase these events. Keep them queued, but do not retry the same
630
+ // stale batch until the pull has established the new durable plan.
631
+ model = {
632
+ ...model,
633
+ push: {
634
+ _tag: 'awaiting-pull',
635
+ queued: [...model.push.batch, ...model.push.queued],
636
+ },
589
637
  }
638
+ return true
590
639
  }
640
+ if (message.error._tag === 'BackendIdMismatchError')
641
+ return yield* handleBackendMismatch(message.error, 'push')
642
+ // Provider errors are retried indefinitely. A defect is not a provider error: like a failed pull, it follows
643
+ // `onError`, so a deterministic defect stops the leader instead of retrying forever.
644
+ if (message.defect === true && config.onError === 'shutdown')
645
+ return yield* stop({ lifecycle: 'failed', error: message.error, notify: true })
646
+ const retryId = allocateOperationId()
647
+ const attempt = model.push.attempt + 1
648
+ model = {
649
+ ...model,
650
+ push: {
651
+ _tag: 'retry-wait',
652
+ retryId,
653
+ attempt,
654
+ batch: model.push.batch,
655
+ queued: model.push.queued,
656
+ },
657
+ }
658
+ yield* fork(
659
+ Effect.sleep(Duration.millis(retryDelay(attempt))).pipe(
660
+ Effect.andThen(send({ _tag: 'PushRetryElapsed', retryId })),
661
+ ),
662
+ )
663
+ return true
664
+ case 'PushRetryElapsed':
665
+ if (model.push._tag === 'retry-wait' && model.push.retryId === message.retryId) {
666
+ const { attempt, batch, queued } = model.push
667
+ yield* runPushOperation({ attempt, batch, queued })
668
+ }
669
+ return true
670
+ default:
671
+ return casesHandled(message)
672
+ }
673
+ })
591
674
 
592
- // Removes the changeset rows which are no longer needed as we'll never have to rollback beyond this point
593
- trimChangesetRows(dbState, newBackendHead)
594
-
595
- // The backend merge may advance or rebase the authoritative head. Realign the admission
596
- // fence now so newly arriving pushes are validated against that history, not the pre-pull head.
597
- yield* reconcilePushHead(mergeResult.newSyncState.localHead)
598
-
599
- // Apply the merged events to storage before publishing the new sync state below, so readers
600
- // cannot observe a leader head whose events have not yet been materialized.
601
- yield* materializeEventsBatch({ batchItems: mergeResult.newEvents })
602
-
603
- yield* SubscriptionRef.set(syncStateSref, mergeResult.newSyncState)
604
- }).pipe(Effect.exit)
605
-
606
- if (Exit.isFailure(chunkExit) === true) {
607
- yield* releasePullMutexIfHeld
608
- return yield* Effect.failCause(chunkExit.cause)
609
- }
675
+ const run = Effect.gen(function* () {
676
+ // This is the only general message consumer and therefore the single owner of transition ordering.
677
+ let running = true
678
+ while (running === true) {
679
+ const message = yield* Queue.take(mailbox)
680
+ const exit = yield* handleMessage(message).pipe(Effect.exit)
681
+ if (Exit.isFailure(exit) === true) {
682
+ running = yield* stop({ lifecycle: 'failed', error: Cause.squash(exit.cause), notify: true })
683
+ } else {
684
+ running = exit.value
685
+ }
686
+ }
687
+ yield* Queue.shutdown(mailbox)
688
+ })
610
689
 
611
- if (isPullPaginationComplete(pageInfo) === true) {
612
- yield* releasePullMutexIfHeld
613
- }
690
+ const push: Service['push'] = (events) =>
691
+ Effect.gen(function* () {
692
+ if (events.length === 0) return
693
+ const requestId = yield* Ref.modify(nextLocalRequestId, (id) => [id, id + 1])
694
+ const deferred = yield* Deferred.make<void, RejectedPushError>()
695
+ // Register the acknowledgement before waiting for boot. Shutdown can then interrupt every admitted caller,
696
+ // including one that has not reached the mailbox yet.
697
+ const admitted = yield* Ref.modify(localRequests, (registry) => {
698
+ if (registry._tag === 'closed') return [false, registry]
699
+ return [
700
+ true,
701
+ {
702
+ _tag: 'open' as const,
703
+ requests: new Map(registry.requests).set(requestId, { deferred, remaining: events.length }),
704
+ },
705
+ ]
614
706
  })
707
+ if (admitted === false) return yield* Effect.interrupt
708
+ yield* Deferred.await(startedDeferred)
709
+ yield* send({ _tag: 'LocalPushRequested', requestId, events })
710
+ yield* Deferred.await(deferred)
711
+ }).pipe(
712
+ Effect.withSpan('@livestore/common:LeaderSyncProcessor:push', {
713
+ attributes: { batchSize: events.length, batch: TRACE_VERBOSE === true ? events : undefined },
714
+ links: span !== undefined ? [{ span, attributes: {} }] : undefined,
715
+ }),
716
+ )
615
717
 
616
- const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(Effect.orDieDebugger)
617
- const cursorInfo = yield* Eventlog.getSyncBackendCursorInfoForDb(dbEventlog, {
618
- remoteHead: syncState.upstreamHead.global,
619
- })
620
-
621
- const hashMaterializerResult = makeMaterializerHash({ schema, dbState })
622
-
623
- yield* syncBackend.pull(cursorInfo, { live: livePull }).pipe(
624
- // TODO only take from queue while connected
625
- Stream.tap(({ batch, pageInfo }) =>
626
- Effect.gen(function* () {
627
- // Any response (including an empty batch) proves backend contact, even with stale connectivity.
628
- onPullSuccess()
629
- // NOTE we only want to take process events when the sync backend is connected
630
- // (e.g. needed for simulating being offline)
631
- // TODO remove when there's a better way to handle this in stream above
632
- yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true)
633
- yield* onNewPullChunk(
634
- batch.map((_) =>
635
- LiveStoreEvent.Client.EncodedWithMeta.fromGlobal(_.eventEncoded, {
636
- syncMetadata: _.metadata,
637
- // TODO we can't really know the materializer result here yet beyond the first event batch item as we need to materialize it one by one first
638
- // This is a bug and needs to be fixed https://github.com/livestorejs/livestore/issues/503#issuecomment-3114533165
639
- materializerHashLeader: hashMaterializerResult(LiveStoreEvent.Global.toClientEncoded(_.eventEncoded)),
640
- materializerHashSession: Option.none(),
641
- }),
642
- ),
643
- pageInfo,
644
- )
645
- yield* initialBlockingSyncContext.update({ processed: batch.length, pageInfo })
646
- }),
718
+ const boot: Service['boot'] = Effect.gen(function* () {
719
+ const shouldStart = yield* Ref.modify(bootStarted, (started) => [started === false, true])
720
+ if (shouldStart === false) return { initialLeaderHead: yield* Deferred.await(bootDeferred) }
721
+ yield* run.pipe(Effect.forkScoped)
722
+ yield* SubscriptionRef.set(syncStateRef, initialSyncState)
723
+ // The mailbox is FIFO: `Started` is handled before any push released below, and only the mailbox changes the model.
724
+ yield* send({ _tag: 'Started' })
725
+ yield* Deferred.succeed(startedDeferred, void 0)
726
+ if (testing.delays?.localPushProcessing !== undefined) {
727
+ yield* fork(
728
+ testing.delays.localPushProcessing.pipe(
729
+ Effect.withSpan('localPushProcessingDelay'),
730
+ Effect.andThen(send({ _tag: 'LocalWorkEnabled' })),
731
+ ),
732
+ )
733
+ }
734
+ yield* Deferred.succeed(bootDeferred, initialSyncState.localHead)
735
+ yield* Effect.addFinalizer(() =>
736
+ send({ _tag: 'ShutdownRequested', reason: 'scope-closed' }).pipe(
737
+ Effect.ignore,
738
+ Effect.andThen(Deferred.await(stoppedDeferred)),
647
739
  ),
648
- Stream.runDrain,
649
- Effect.interruptible,
650
- Effect.ensuring(releasePullMutexIfHeld),
651
740
  )
741
+ return { initialLeaderHead: initialSyncState.localHead }
742
+ }).pipe(Effect.withSpanScoped('@livestore/common:LeaderSyncProcessor:boot'), Effect.uninterruptible)
652
743
 
653
- // Should only ever happen when livePull is false
654
- yield* Effect.logDebug('backend-pulling finished', { livePull })
744
+ return LeaderSyncProcessor.of({
745
+ [TypeId]: TypeId,
746
+ boot,
747
+ push,
748
+ pull: ({ cursor }) =>
749
+ Effect.gen(function* () {
750
+ const queue = yield* connectedSessions.makeQueue(cursor)
751
+ return Stream.fromQueue(queue)
752
+ }).pipe(Stream.unwrap),
753
+ pullQueue: ({ cursor }) => connectedSessions.makeQueue(cursor),
754
+ syncState: Subscribable.make({
755
+ get: SubscriptionRef.get(syncStateRef),
756
+ changes: SubscriptionRef.changes(syncStateRef),
757
+ }),
655
758
  })
759
+ })
656
760
 
657
- const backgroundBackendPushing = Effect.gen(function* () {
658
- if (syncBackend === undefined) return
761
+ export const layer = (options: Options) => Layer.effect(LeaderSyncProcessor, make(options))
659
762
 
660
- while (true) {
661
- yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true)
763
+ type OperationId = number
764
+ type LocalRequestId = number
765
+ type PullBatchId = number
662
766
 
663
- const queueItems = yield* TxQueue.takeBetween(syncBackendPushQueue, 1, backendPushBatchSize)
767
+ interface Config {
768
+ readonly livePull: boolean
769
+ readonly localCommitBatchSize: number
770
+ readonly backendPushBatchSize: number
771
+ readonly onError: 'shutdown' | 'ignore'
772
+ readonly onBackendIdMismatch: 'reset' | 'shutdown' | 'ignore'
773
+ readonly localWorkInitiallyBlocked: boolean
774
+ }
664
775
 
665
- yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true)
776
+ interface LocalItem {
777
+ readonly requestId: LocalRequestId
778
+ readonly index: number
779
+ readonly event: LiveStoreEvent.Client.Encoded
780
+ }
666
781
 
667
- if (devtoolsLatch !== undefined) {
668
- yield* devtoolsLatch.await
669
- }
782
+ interface UpstreamBatch {
783
+ readonly pullId: OperationId
784
+ readonly batchId: PullBatchId
785
+ readonly events: ReadonlyArray<LiveStoreEvent.Client.Encoded>
786
+ readonly pulledEvents: ReadonlyArray<LeaderPersistence.PulledEvent>
787
+ readonly pageInfo: SyncBackend.PullResPageInfo
788
+ }
670
789
 
671
- yield* Effect.spanEvent('backend-push', {
672
- batchSize: queueItems.length,
673
- ...(TRACE_VERBOSE === true ? { batch: jsonStringify(queueItems) } : {}),
674
- })
790
+ /** Pages of one pull applied together; `batchIds` are released once the combined batch is durable. */
791
+ interface CoalescedUpstreamBatch {
792
+ readonly batchIds: ReadonlyArray<PullBatchId>
793
+ readonly events: ReadonlyArray<LiveStoreEvent.Client.Encoded>
794
+ readonly pulledEvents: ReadonlyArray<LeaderPersistence.PulledEvent>
795
+ }
675
796
 
676
- // Push with declarative retry/backoff using Effect schedules
677
- // - Exponential backoff starting at 1s and doubling (1s, 2s, 4s, 8s, 16s, 30s ...)
678
- // - Delay clamped at 30s (continues retrying at 30s)
679
- // - Resets automatically after successful push
680
- // TODO(metrics): expose counters/gauges for retry attempts and queue health via devtools/metrics
681
- yield* Effect.gen(function* () {
682
- const iteration = yield* Schedule.CurrentMetadata
797
+ /** Pages a pull may read ahead of the page currently being made durable. */
798
+ const MAX_PAGES_AHEAD = 16
683
799
 
684
- const pushResult = yield* syncBackend.push(queueItems.map((_) => _.toGlobal())).pipe(Effect.result)
800
+ interface OutstandingPage {
801
+ readonly completion: Deferred.Deferred<void>
802
+ readonly processed: number
803
+ readonly pageInfo: SyncBackend.PullResPageInfo
804
+ }
685
805
 
686
- const retries = iteration.attempt
687
- if (retries > 0 && Result.isSuccess(pushResult) === true) {
688
- yield* Effect.spanEvent('backend-push-retry-success', { retries, batchSize: queueItems.length })
689
- }
806
+ /**
807
+ * Combines the queued pages at the front of the upstream queue that belong to the same pull. Consecutive pages
808
+ * describe one contiguous stretch of backend history, so merging them is the same upstream advance as applying them
809
+ * one after another, without rebasing pending events and publishing to sessions in between.
810
+ */
811
+ const coalesceUpstreamBatches = (queue: ReadonlyArray<UpstreamBatch>): CoalescedUpstreamBatch | undefined => {
812
+ const first = queue[0]
813
+ if (first === undefined) return undefined
814
+ const otherPull = queue.findIndex((page) => page.pullId !== first.pullId)
815
+ const pages = otherPull === -1 ? queue : queue.slice(0, otherPull)
816
+ return {
817
+ batchIds: pages.map((page) => page.batchId),
818
+ events: pages.flatMap((page) => page.events),
819
+ pulledEvents: pages.flatMap((page) => page.pulledEvents),
820
+ }
821
+ }
690
822
 
691
- if (Result.isFailure(pushResult) === true) {
692
- yield* Effect.spanEvent('backend-push-error', {
693
- error: pushResult.failure.toString(),
694
- retries,
695
- batchSize: queueItems.length,
696
- })
697
- const error = pushResult.failure
698
- if (error._tag === 'ServerAheadError') {
699
- // It's a core part of the sync protocol that the sync backend will emit a new pull chunk alongside the ServerAheadError
700
- yield* Effect.logDebug('handled backend-push-error (waiting for interupt caused by pull)', { error })
701
- return yield* Effect.never
702
- }
823
+ type ProviderPushError = IsOfflineError | BackendIdMismatchError | UnknownError | ServerAheadError
824
+ type ProviderPullError = IsOfflineError | BackendIdMismatchError | UnknownError
703
825
 
704
- return yield* error
705
- }
706
- }).pipe(
707
- // Retry transient errors
708
- Effect.retry({
709
- schedule: Schedule.exponential(Duration.seconds(1)).pipe(
710
- Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.min(duration, Duration.seconds(30)))), // Cap delay at 30s intervals.
711
- ),
712
- while: (error) => error._tag === 'IsOfflineError' || error._tag === 'UnknownError',
713
- }),
714
- // This is needed to narrow the Error type. Our retry policy runs indefinitely, but Effect.retry does not narrow the Error type.
715
- Effect.catchIf((error) => error._tag === 'IsOfflineError' || error._tag === 'UnknownError', Effect.die),
716
- )
826
+ type LeaderMessage =
827
+ | { readonly _tag: 'ContinueWork' }
828
+ | { readonly _tag: 'LocalWorkEnabled' }
829
+ | {
830
+ readonly _tag: 'LocalPushRequested'
831
+ readonly requestId: LocalRequestId
832
+ readonly events: ReadonlyArray<LiveStoreEvent.Client.Encoded>
833
+ }
834
+ | { readonly _tag: 'UpstreamBatchReceived'; readonly batch: UpstreamBatch }
835
+ | { readonly _tag: 'PullCompleted'; readonly pullId: OperationId }
836
+ | { readonly _tag: 'PullFailed'; readonly pullId: OperationId; readonly error: ProviderPullError }
837
+ | { readonly _tag: 'PullRetryElapsed'; readonly retryId: OperationId; readonly reconnected: boolean }
838
+ | { readonly _tag: 'PushSucceeded'; readonly operationId: OperationId }
839
+ | {
840
+ readonly _tag: 'PushFailed'
841
+ readonly operationId: OperationId
842
+ readonly error: ProviderPushError
843
+ /** The provider push died rather than failing; `onError: 'shutdown'` stops the leader, as for pull failures. */
844
+ readonly defect: boolean
717
845
  }
718
- }).pipe(Effect.interruptible)
846
+ | { readonly _tag: 'PushRetryElapsed'; readonly retryId: OperationId }
847
+ | { readonly _tag: 'Started' }
848
+ | { readonly _tag: 'ShutdownRequested'; readonly reason: string }
849
+
850
+ type PullState =
851
+ | { readonly _tag: 'disabled' }
852
+ | {
853
+ readonly _tag: 'streaming'
854
+ readonly pullId: OperationId
855
+ readonly pagination: 'between-pages' | 'more-expected'
856
+ readonly attempt: number
857
+ }
858
+ | { readonly _tag: 'retry-wait'; readonly retryId: OperationId; readonly attempt: number }
859
+ | { readonly _tag: 'completed' }
860
+
861
+ type PushState =
862
+ | { readonly _tag: 'disabled' }
863
+ | { readonly _tag: 'idle'; readonly queued: EventBatch }
864
+ | {
865
+ readonly _tag: 'in-flight'
866
+ readonly operationId: OperationId
867
+ readonly attempt: number
868
+ readonly batch: EventBatch
869
+ readonly queued: EventBatch
870
+ }
871
+ | {
872
+ readonly _tag: 'retry-wait'
873
+ readonly retryId: OperationId
874
+ readonly attempt: number
875
+ readonly batch: EventBatch
876
+ readonly queued: EventBatch
877
+ }
878
+ | { readonly _tag: 'awaiting-pull'; readonly queued: EventBatch }
879
+
880
+ type EventBatch = ReadonlyArray<LiveStoreEvent.Client.Encoded>
881
+
882
+ interface Model {
883
+ readonly lifecycle: 'starting' | 'running' | 'stopping' | 'failed'
884
+ readonly syncState: SyncState.SyncState
885
+ readonly pull: PullState
886
+ readonly push: PushState
887
+ readonly localQueue: ReadonlyArray<LocalItem>
888
+ readonly upstreamQueue: ReadonlyArray<UpstreamBatch>
889
+ readonly localWorkEnabled: boolean
890
+ readonly nextOperationId: OperationId
891
+ }
719
892
 
720
- // NOTE: New events are only pushed to sync backend after successful local push processing
721
- const push: Service['push'] = (newEvents) =>
722
- Effect.gen(function* () {
723
- if (newEvents.length === 0) return
893
+ interface LocalRequest {
894
+ readonly deferred: Deferred.Deferred<void, RejectedPushError>
895
+ readonly remaining: number
896
+ }
724
897
 
725
- const deferreds = yield* Effect.forEach(newEvents, () =>
726
- Deferred.make<void, LeaderAheadError | StaleRebaseGenerationError>(),
727
- )
898
+ type LocalRequestRegistry =
899
+ | { readonly _tag: 'open'; readonly requests: Map<LocalRequestId, LocalRequest> }
900
+ | { readonly _tag: 'closed' }
901
+
902
+ const initialModel = (
903
+ config: Config,
904
+ backendEnabled: boolean,
905
+ initialSyncState: SyncState.SyncState,
906
+ isClientOnlyEvent: (event: LiveStoreEvent.Client.Encoded) => boolean,
907
+ ): Model => ({
908
+ lifecycle: 'starting',
909
+ syncState: initialSyncState,
910
+ pull: backendEnabled === true ? { _tag: 'completed' } : { _tag: 'disabled' },
911
+ push:
912
+ backendEnabled === true
913
+ ? { _tag: 'idle', queued: initialSyncState.pending.filter((event) => !isClientOnlyEvent(event)) }
914
+ : { _tag: 'disabled' },
915
+ localQueue: [],
916
+ upstreamQueue: [],
917
+ localWorkEnabled: config.localWorkInitiallyBlocked === false,
918
+ nextOperationId: 1,
919
+ })
728
920
 
729
- const items = newEvents.map((eventEncoded, i) => [eventEncoded, deferreds[i]] as LocalPushQueueItem)
921
+ const enqueuePushEvents = (model: Model, events: EventBatch): Model => {
922
+ if (model.push._tag === 'disabled' || events.length === 0) return model
923
+ return { ...model, push: { ...model.push, queued: [...model.push.queued, ...events] } }
924
+ }
730
925
 
731
- // Validation, reservation, enqueueing, and fence advancement form one admission transaction.
732
- // Serializing them prevents concurrent sessions from both validating against the same head and
733
- // prevents backend reconciliation from changing the fence midway through admission.
734
- yield* pushAdmissionSemaphore.withPermits(1)(
735
- // Cancellation must not leave reservations, queue contents, and the admission fence disagreeing.
926
+ const runProviderPush = (
927
+ operation: { readonly operationId: OperationId; readonly attempt: number; readonly batch: EventBatch },
928
+ syncBackend: SyncBackend.SyncBackend,
929
+ devtoolsLatch: Latch.Latch | undefined,
930
+ send: (message: LeaderMessage) => Effect.Effect<void>,
931
+ ) =>
932
+ Effect.gen(function* () {
933
+ yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (connected) => connected === true)
934
+ if (devtoolsLatch !== undefined) yield* devtoolsLatch.await
935
+ yield* Effect.spanEvent('backend-push', {
936
+ batchSize: operation.batch.length,
937
+ ...(TRACE_VERBOSE === true ? { batch: jsonStringify(operation.batch) } : {}),
938
+ })
939
+ yield* syncBackend.push(operation.batch.map(LiveStoreEvent.Client.toGlobal))
940
+ }).pipe(
941
+ Effect.matchEffect({
942
+ onFailure: (error) =>
943
+ Effect.spanEvent('backend-push-error', {
944
+ error: error.toString(),
945
+ retries: operation.attempt,
946
+ batchSize: operation.batch.length,
947
+ }).pipe(Effect.andThen(send({ _tag: 'PushFailed', operationId: operation.operationId, error, defect: false }))),
948
+ onSuccess: () =>
736
949
  Effect.gen(function* () {
737
- yield* validatePushBatch(newEvents, pushHeadRef.current, isClientOnlyEvent)
738
- for (const item of items) reservedLocalPushItems.add(item)
739
- yield* TxQueue.offerAll(localPushesQueue, items)
740
- pushHeadRef.current = newEvents.at(-1)!.seqNum
741
- if (testing.hooks?.localPushAdmitted !== undefined) {
742
- yield* testing.hooks.localPushAdmitted(newEvents)
950
+ if (operation.attempt > 0) {
951
+ yield* Effect.spanEvent('backend-push-retry-success', {
952
+ retries: operation.attempt,
953
+ batchSize: operation.batch.length,
954
+ })
743
955
  }
744
- }).pipe(Effect.uninterruptible),
745
- )
746
-
747
- yield* Effect.forEach(deferreds, Deferred.await)
748
- }).pipe(
749
- Effect.withSpan('@livestore/common:LeaderSyncProcessor:push', {
750
- attributes: {
751
- batchSize: newEvents.length,
752
- batch: TRACE_VERBOSE === true ? newEvents : undefined,
753
- },
754
- links: span !== undefined ? [{ span, attributes: {} }] : undefined,
956
+ yield* send({ _tag: 'PushSucceeded', operationId: operation.operationId })
957
+ }),
958
+ }),
959
+ Effect.catchCause((cause) =>
960
+ send({
961
+ _tag: 'PushFailed',
962
+ operationId: operation.operationId,
963
+ error: UnknownError.make({ cause, note: 'Sync backend push defected' }),
964
+ defect: Cause.hasInterruptsOnly(cause) === false,
755
965
  }),
756
- )
966
+ ),
967
+ Effect.interruptible,
968
+ )
757
969
 
758
- return LeaderSyncProcessor.of({
759
- [TypeId]: TypeId,
760
- // Starts various background loops
761
- boot: Effect.gen(function* () {
762
- /** State transitions need to happen atomically, so we use a Ref to track the state */
763
- yield* SubscriptionRef.set(syncStateSref, initialSyncState)
764
-
765
- // Rehydrate sync queue
766
- if (initialSyncState.pending.length > 0) {
767
- const globalOrUnknownPendingEvents = initialSyncState.pending
768
- // Don't sync client-only events
769
- .filter((eventEncoded) => !isClientOnlyEvent(eventEncoded))
770
-
771
- if (globalOrUnknownPendingEvents.length > 0) {
772
- yield* TxQueue.offerAll(syncBackendPushQueue, globalOrUnknownPendingEvents)
970
+ const runProviderPull = ({
971
+ pullId,
972
+ cursor,
973
+ live,
974
+ syncBackend,
975
+ devtoolsLatch,
976
+ dbEventlog,
977
+ pullBatches,
978
+ nextPullBatchId,
979
+ initialBlockingSyncContext,
980
+ send,
981
+ }: {
982
+ pullId: OperationId
983
+ cursor: EventSequenceNumber.Client.Composite
984
+ live: boolean
985
+ syncBackend: SyncBackend.SyncBackend
986
+ devtoolsLatch: Latch.Latch | undefined
987
+ dbEventlog: SqliteDb
988
+ pullBatches: Ref.Ref<Map<PullBatchId, Deferred.Deferred<void>>>
989
+ nextPullBatchId: Ref.Ref<number>
990
+ initialBlockingSyncContext: InitialBlockingSyncContext
991
+ send: (message: LeaderMessage) => Effect.Effect<void>
992
+ }) =>
993
+ Effect.gen(function* () {
994
+ // Pages handed to the mailbox but not yet durable. Offering blocks while MAX_PAGES_AHEAD are waiting, which is
995
+ // the provider stream's backpressure. A child fiber awaits them in order and reports initial-sync progress.
996
+ const outstanding = yield* Queue.bounded<OutstandingPage | 'end'>(MAX_PAGES_AHEAD)
997
+ const allDurable = yield* Deferred.make<void>()
998
+ yield* Effect.forkChild(
999
+ Effect.gen(function* () {
1000
+ while (true) {
1001
+ const page = yield* Queue.take(outstanding)
1002
+ if (page === 'end') return yield* Deferred.succeed(allDurable, undefined)
1003
+ yield* Deferred.await(page.completion)
1004
+ yield* initialBlockingSyncContext.update({ processed: page.processed, pageInfo: page.pageInfo })
773
1005
  }
774
- }
775
-
776
- const handleBackendIdMismatchError = (error: BackendIdMismatchError) =>
777
- handleBackendIdMismatch({ error, onBackendIdMismatch, shutdownChannel, dbEventlog, dbState })
778
-
779
- const maybeShutdownOnError = (cause: Cause.Cause<UnknownError | MaterializeError>) =>
780
- Effect.gen(function* () {
781
- if (onError === 'ignore') {
782
- if (LS_DEV === true) {
783
- yield* Effect.logDebug(
784
- `Ignoring sync error (${Option.getOrUndefined(Cause.findErrorOption(cause))?._tag ?? cause.toString()})`,
785
- Cause.pretty(cause),
786
- )
787
- }
788
- return
789
- }
790
-
791
- const error = Option.getOrUndefined(Cause.findErrorOption(cause))
792
- const errorToSend = error === undefined ? UnknownError.make({ cause }) : error
793
- yield* shutdownChannel.send(errorToSend).pipe(Effect.orDie)
794
-
795
- return yield* Effect.failCause(cause).pipe(Effect.orDie)
796
- })
797
-
798
- yield* backgroundApplyLocalPushes.pipe(Effect.catchCause(maybeShutdownOnError), Effect.forkScoped)
799
-
800
- const backendPushingFiberHandle = yield* FiberHandle.make<void, never>()
801
- const backendPushingEffect = backgroundBackendPushing.pipe(
802
- Effect.catchTag('BackendIdMismatchError', handleBackendIdMismatchError),
803
- Effect.catchCause(maybeShutdownOnError),
804
- )
805
-
806
- yield* FiberHandle.run(backendPushingFiberHandle, backendPushingEffect)
807
-
808
- let offlinePullFallbackMs = 1_000
809
-
810
- yield* backgroundBackendPulling({
811
- onPullSuccess: () => {
812
- offlinePullFallbackMs = 1_000
813
- },
814
- restartBackendPushing: (filteredRebasedPending) =>
1006
+ }),
1007
+ )
1008
+ yield* Effect.gen(function* () {
1009
+ const cursorInfo = yield* Eventlog.getSyncBackendCursorInfoForDb(dbEventlog, { remoteHead: cursor.global })
1010
+ yield* syncBackend.pull(cursorInfo, { live }).pipe(
1011
+ Stream.runForEach(({ batch, pageInfo }) =>
815
1012
  Effect.gen(function* () {
816
- // Stop current pushing fiber
817
- yield* FiberHandle.clear(backendPushingFiberHandle)
818
-
819
- // Reset the sync backend push queue
820
- yield* TxQueue.clear(syncBackendPushQueue)
821
- yield* TxQueue.offerAll(syncBackendPushQueue, filteredRebasedPending)
822
-
823
- // Restart pushing fiber
824
- yield* FiberHandle.run(backendPushingFiberHandle, backendPushingEffect)
1013
+ yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (connected) => connected === true)
1014
+ if (devtoolsLatch !== undefined) yield* devtoolsLatch.await
1015
+ const batchId = yield* Ref.modify(nextPullBatchId, (id) => [id, id + 1])
1016
+ const completion = yield* Deferred.make<void>()
1017
+ yield* Ref.update(pullBatches, (batches) => new Map(batches).set(batchId, completion))
1018
+ const pulledEvents = batch.map((item) => ({
1019
+ event: LiveStoreEvent.Client.fromGlobal(item.eventEncoded),
1020
+ syncMetadata: item.metadata,
1021
+ }))
1022
+ yield* send({
1023
+ _tag: 'UpstreamBatchReceived',
1024
+ batch: { pullId, batchId, events: pulledEvents.map(({ event }) => event), pulledEvents, pageInfo },
1025
+ })
1026
+ // Read on without waiting for this page to become durable (up to MAX_PAGES_AHEAD). Pages that are already
1027
+ // available, such as a backlog released on reconnect, then queue up while the mailbox applies one page, and
1028
+ // it applies the queued ones as one upstream batch: a leader with pending events rebases them once instead
1029
+ // of once per page, and every session applies one rebase instead of many. Pages are still applied in order,
1030
+ // and the persisted backend cursor is the head of the last page applied.
1031
+ yield* Queue.offer(outstanding, { completion, processed: batch.length, pageInfo })
1032
+ yield* Effect.yieldNow
825
1033
  }),
826
- }).pipe(
827
- Effect.tapError((error) => {
828
- if (error._tag !== 'IsOfflineError' || syncBackend === undefined) return Effect.void
829
- const isConnected = syncBackend.isConnected
830
- return Effect.gen(function* () {
831
- // Wake immediately on reconnection. Probe on a capped fallback timer if connectivity is stale.
832
- const jitter = yield* Random.nextBetween(0.8, 1.2)
833
- const fallbackMs =
834
- testing.delays?.backendPullReconnect?.(offlinePullFallbackMs * jitter) ?? offlinePullFallbackMs * jitter
835
- offlinePullFallbackMs = Math.min(offlinePullFallbackMs * 2, 30_000)
836
- // A stale initial true is not a reconnect. Watch false→true even while the fallback timer is pending.
837
- const waitHook = testing.hooks?.backendPullReconnectWait
838
- const changes = SubscriptionRef.changes(isConnected)
839
- const observedChanges =
840
- waitHook === undefined
841
- ? changes
842
- : changes.pipe(Stream.tap((value) => waitHook({ isConnected: value, fallbackMs })))
843
- const reconnected = yield* observedChanges.pipe(
844
- Stream.dropWhile((value) => value === true),
845
- Stream.filter((value) => value === true),
846
- Stream.runHead,
847
- Effect.as(true),
848
- Effect.timeoutOrElse({ duration: fallbackMs, orElse: () => Effect.succeed(false) }),
849
- )
850
- if (reconnected === true) offlinePullFallbackMs = 1_000
851
- })
852
- }),
853
- Effect.retry({
854
- // The unbounded offline-only retry keeps IsOfflineError out of the terminal error channel.
855
- until: (error): error is Exclude<typeof error, IsOfflineError> => error._tag !== 'IsOfflineError',
856
- }),
857
- Effect.catchTag('BackendIdMismatchError', handleBackendIdMismatchError),
858
- Effect.catchCause(maybeShutdownOnError),
859
- // Needed to avoid `Fiber terminated with an unhandled error` logs which seem to happen because of the `Effect.retry` above.
860
- // This might be a bug in Effect. Only seems to happen in the browser.
861
- Effect.provideService(References.UnhandledLogLevel, undefined),
862
- Effect.forkScoped,
1034
+ ),
863
1035
  )
1036
+ }).pipe(
1037
+ Effect.matchEffect({
1038
+ onFailure: (error) => send({ _tag: 'PullFailed', pullId, error }),
1039
+ onSuccess: () => Effect.void,
1040
+ }),
1041
+ Effect.catchCauseIf(
1042
+ (cause) => Cause.hasInterruptsOnly(cause) === false,
1043
+ (cause) =>
1044
+ send({ _tag: 'PullFailed', pullId, error: UnknownError.make({ cause, note: 'Sync backend pull defected' }) }),
1045
+ ),
1046
+ )
1047
+ // Pages sent before a failure are still applied, so keep reporting their progress: one of them may be the `NoMore`
1048
+ // page that ends a blocking initial sync. A retry replaces this fiber, which ends the wait.
1049
+ yield* Queue.offer(outstanding, 'end')
1050
+ yield* Deferred.await(allDurable)
1051
+ }).pipe(
1052
+ Effect.withSpan('@livestore/common:LeaderSyncProcessor:backend-pulling'),
1053
+ Effect.ensuring(send({ _tag: 'PullCompleted', pullId })),
1054
+ Effect.interruptible,
1055
+ )
864
1056
 
865
- return { initialLeaderHead: initialSyncState.localHead }
866
- }).pipe(Effect.withSpanScoped('@livestore/common:LeaderSyncProcessor:boot')),
867
- push,
868
- pushPartial: ({ event: { name, args }, clientId, sessionId }) =>
869
- Effect.gen(function* () {
870
- const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(
871
- Effect.orDieDebugger,
872
- )
1057
+ /**
1058
+ * Validate a client-provided batch before it is admitted to the leader queue.
1059
+ * Ensures the numbers form a strictly increasing chain and that the first
1060
+ * event sits ahead of the current push head.
1061
+ */
1062
+ const validatePushBatch = (
1063
+ batch: ReadonlyArray<LiveStoreEvent.Client.Encoded>,
1064
+ pushHead: EventSequenceNumber.Client.Composite,
1065
+ isClientOnlyEvent: (event: LiveStoreEvent.Client.Encoded) => boolean,
1066
+ ) =>
1067
+ Effect.gen(function* () {
1068
+ if (batch.length === 0) {
1069
+ return
1070
+ }
873
1071
 
874
- const resolution = yield* resolveEventDef(schema, {
875
- operation: '@livestore/common:LeaderSyncProcessor:pushPartial',
876
- event: {
877
- name,
878
- args,
879
- clientId,
880
- sessionId,
881
- seqNum: syncState.localHead,
882
- },
1072
+ // Defensive check: callers should already provide a strictly increasing sequence
1073
+ // of event numbers.
1074
+ for (let i = 1; i < batch.length; i++) {
1075
+ if (EventSequenceNumber.Client.isGreaterThanOrEqual(batch[i - 1]!.seqNum, batch[i]!.seqNum) === true) {
1076
+ return yield* NonMonotonicBatchError.make({
1077
+ precedingSeqNum: batch[i - 1]!.seqNum,
1078
+ violatingSeqNum: batch[i]!.seqNum,
1079
+ violationIndex: i,
1080
+ sessionId: batch[i]!.sessionId,
883
1081
  })
1082
+ }
1083
+ }
884
1084
 
885
- if (resolution._tag === 'unknown') {
886
- // Ignore partial pushes for unrecognised events – they are still
887
- // persisted server-side once a schema update ships.
888
- return
889
- }
1085
+ // Reject stale batches whose first event is at or behind the leader's push head.
1086
+ if (EventSequenceNumber.Client.isGreaterThanOrEqual(pushHead, batch[0]!.seqNum) === true) {
1087
+ return yield* LeaderAheadError.make({
1088
+ minimumExpectedNum: pushHead,
1089
+ providedNum: batch[0]!.seqNum,
1090
+ sessionId: batch[0]!.sessionId,
1091
+ })
1092
+ }
890
1093
 
891
- const eventEncoded = new LiveStoreEvent.Client.EncodedWithMeta({
892
- name,
893
- args,
894
- clientId,
895
- sessionId,
896
- ...EventSequenceNumber.Client.nextPair({
897
- seqNum: syncState.localHead,
898
- isClientOnly: resolution.eventDef.options.clientOnly,
899
- }),
1094
+ // A rebase replaces the optimistic history that the client built on. Events from an older
1095
+ // generation may now have the wrong parent and must be recreated from the leader's current head.
1096
+ if (batch[0]!.seqNum.rebaseGeneration < pushHead.rebaseGeneration) {
1097
+ return yield* StaleRebaseGenerationError.make({
1098
+ currentRebaseGeneration: pushHead.rebaseGeneration,
1099
+ providedRebaseGeneration: batch[0]!.seqNum.rebaseGeneration,
1100
+ sessionId: batch[0]!.sessionId,
1101
+ })
1102
+ }
1103
+
1104
+ // Validate the batch as one unbroken chain starting at the admission fence. Checking only that
1105
+ // numbers increase would still allow gaps or events that point at an unrelated parent.
1106
+ let precedingSeqNum = pushHead
1107
+ for (let i = 0; i < batch.length; i++) {
1108
+ const event = batch[i]!
1109
+ // Global events advance the global position; client-only events advance its client-local suffix.
1110
+ const expectedPair = EventSequenceNumber.Client.nextPair({
1111
+ seqNum: precedingSeqNum,
1112
+ isClientOnly: isClientOnlyEvent(event),
1113
+ rebaseGeneration: event.seqNum.rebaseGeneration,
1114
+ })
1115
+
1116
+ if (
1117
+ EventSequenceNumber.Client.isEqual(event.seqNum, expectedPair.seqNum) === false ||
1118
+ LeaderPersistence.isSameSequencePosition(event.parentSeqNum, expectedPair.parentSeqNum) === false
1119
+ ) {
1120
+ return yield* NonContiguousBatchError.make({
1121
+ expectedSeqNum: expectedPair.seqNum,
1122
+ providedSeqNum: event.seqNum,
1123
+ expectedParentSeqNum: expectedPair.parentSeqNum,
1124
+ providedParentSeqNum: event.parentSeqNum,
1125
+ violationIndex: i,
1126
+ sessionId: event.sessionId,
900
1127
  })
1128
+ }
901
1129
 
902
- yield* push([eventEncoded])
903
- }).pipe(
904
- // pushPartial constructs the event sequence number internally, so these errors should never happen.
905
- Effect.catchIf(isRejectedPushError, Effect.die),
906
- ),
907
- pull: ({ cursor }) =>
908
- Effect.gen(function* () {
909
- const queue = yield* connectedClientSessionPullQueues.makeQueue(cursor)
910
- return Stream.fromQueue(queue)
911
- }).pipe(Stream.unwrap),
912
- /*
913
- Notes for a potential new `LeaderSyncProcessor.pull` implementation:
914
-
915
- - Doesn't take cursor but is "atomically called" in the leader during the snapshot phase
916
- - TODO: how is this done "atomically" in the web adapter where the snapshot is read optimistically?
917
- - Would require a new kind of "boot-phase" API which is stream based:
918
- - initial message: state snapshot + seq num head
919
- - subsequent messages: sync state payloads
920
-
921
- - alternative: instead of session pulling sync state payloads from leader, we could send
922
- - events in the "advance" case
923
- - full new state db snapshot in the "rebase" case
924
- - downside: importing the snapshot is expensive
925
- */
926
- pullQueue: ({ cursor }) => connectedClientSessionPullQueues.makeQueue(cursor),
927
- syncState: Subscribable.make({
928
- get: SubscriptionRef.get(syncStateSref).pipe(Effect.flatMap(Effect.fromNullishOr), Effect.orDieDebugger),
929
- changes: SubscriptionRef.changes(syncStateSref).pipe(Stream.filter(Predicate.isNotUndefined)),
930
- }),
1130
+ precedingSeqNum = event.seqNum
1131
+ }
931
1132
  })
932
- })
933
1133
 
934
- export const layer = (options: Options) => Layer.effect(LeaderSyncProcessor, make(options))
1134
+ const completeLocalItems = (requestsRef: Ref.Ref<LocalRequestRegistry>, items: ReadonlyArray<LocalItem>) =>
1135
+ Effect.gen(function* () {
1136
+ const counts = countRequestItems(items)
1137
+ const completions: Deferred.Deferred<void, RejectedPushError>[] = []
1138
+ yield* Ref.update(requestsRef, (registry) => {
1139
+ if (registry._tag === 'closed') return registry
1140
+ const next = new Map(registry.requests)
1141
+ for (const [requestId, count] of counts) {
1142
+ const request = next.get(requestId)
1143
+ if (request === undefined) continue
1144
+ const remaining = request.remaining - count
1145
+ if (remaining === 0) {
1146
+ next.delete(requestId)
1147
+ completions.push(request.deferred)
1148
+ } else {
1149
+ next.set(requestId, { ...request, remaining })
1150
+ }
1151
+ }
1152
+ return { _tag: 'open' as const, requests: next }
1153
+ })
1154
+ yield* Effect.forEach(completions, (deferred) => Deferred.succeed(deferred, void 0), { discard: true })
1155
+ })
935
1156
 
936
- // TODO how to handle errors gracefully
937
- const makeMaterializeEventsBatch =
938
- ({
939
- dbState,
940
- dbEventlog,
941
- materializeEvent,
942
- }: {
943
- dbState: SqliteDb
944
- dbEventlog: SqliteDb
945
- materializeEvent: MaterializeEvent
946
- }) =>
947
- ({ batchItems }: { batchItems: ReadonlyArray<LiveStoreEvent.Client.EncodedWithMeta> }) =>
948
- Effect.gen(function* () {
949
- // NOTE We always start a transaction to ensure consistency between db and eventlog (even for single-item batches)
950
- dbState.execute('BEGIN TRANSACTION', undefined) // Start the transaction
951
- dbEventlog.execute('BEGIN TRANSACTION', undefined) // Start the transaction
1157
+ const rejectLocalItems = (
1158
+ requestsRef: Ref.Ref<LocalRequestRegistry>,
1159
+ items: ReadonlyArray<{ readonly item: LocalItem; readonly error: RejectedPushError }>,
1160
+ ) =>
1161
+ Effect.gen(function* () {
1162
+ const failures: Array<{ deferred: Deferred.Deferred<void, RejectedPushError>; error: RejectedPushError }> = []
1163
+ yield* Ref.update(requestsRef, (registry) => {
1164
+ if (registry._tag === 'closed') return registry
1165
+ const next = new Map(registry.requests)
1166
+ for (const { item, error } of items) {
1167
+ const request = next.get(item.requestId)
1168
+ if (request === undefined) continue
1169
+ next.delete(item.requestId)
1170
+ failures.push({ deferred: request.deferred, error })
1171
+ }
1172
+ return { _tag: 'open' as const, requests: next }
1173
+ })
1174
+ yield* Effect.forEach(failures, ({ deferred, error }) => Deferred.fail(deferred, error), { discard: true })
1175
+ })
952
1176
 
953
- yield* Effect.addFinalizer((exit) =>
954
- Effect.gen(function* () {
955
- if (Exit.isSuccess(exit) === true) return
1177
+ const interruptLocalRequests = (
1178
+ requestsRef: Ref.Ref<LocalRequestRegistry>,
1179
+ requestIds: ReadonlyArray<LocalRequestId>,
1180
+ ) =>
1181
+ Effect.gen(function* () {
1182
+ const deferreds: Deferred.Deferred<void, RejectedPushError>[] = []
1183
+ yield* Ref.update(requestsRef, (registry) => {
1184
+ if (registry._tag === 'closed') return registry
1185
+ const next = new Map(registry.requests)
1186
+ for (const requestId of new Set(requestIds)) {
1187
+ const request = next.get(requestId)
1188
+ if (request !== undefined) deferreds.push(request.deferred)
1189
+ next.delete(requestId)
1190
+ }
1191
+ return { _tag: 'open' as const, requests: next }
1192
+ })
1193
+ yield* Effect.forEach(deferreds, Deferred.interrupt, { discard: true })
1194
+ })
956
1195
 
957
- // Rollback in case of an error
958
- dbState.execute('ROLLBACK', undefined)
959
- dbEventlog.execute('ROLLBACK', undefined)
960
- }),
961
- )
1196
+ const interruptAllLocalRequests = (requestsRef: Ref.Ref<LocalRequestRegistry>) =>
1197
+ Effect.gen(function* () {
1198
+ const registry = yield* Ref.getAndSet(requestsRef, { _tag: 'closed' })
1199
+ if (registry._tag === 'closed') return
1200
+ yield* Effect.forEach(registry.requests.values(), ({ deferred }) => Deferred.interrupt(deferred), { discard: true })
1201
+ })
962
1202
 
963
- for (let i = 0; i < batchItems.length; i++) {
964
- const { sessionChangeset, hash } = yield* materializeEvent(batchItems[i]!)
965
- batchItems[i]!.meta.sessionChangeset = sessionChangeset
966
- batchItems[i]!.meta.materializerHashLeader = hash
967
- }
1203
+ const interruptAllPullBatches = (batchesRef: Ref.Ref<Map<PullBatchId, Deferred.Deferred<void>>>) =>
1204
+ Effect.gen(function* () {
1205
+ const batches = yield* Ref.getAndSet(batchesRef, new Map())
1206
+ yield* Effect.forEach(batches.values(), Deferred.interrupt, { discard: true })
1207
+ })
968
1208
 
969
- dbState.execute('COMMIT', undefined) // Commit the transaction
970
- dbEventlog.execute('COMMIT', undefined) // Commit the transaction
971
- }).pipe(
972
- Effect.uninterruptible,
973
- Effect.scoped,
974
- Effect.withSpan('@livestore/common:LeaderSyncProcessor:materializeEventItems', {
975
- attributes: { batchSize: batchItems.length },
976
- }),
977
- Effect.tapCauseLogPretty,
978
- )
1209
+ const completePullBatch = (batchesRef: Ref.Ref<Map<PullBatchId, Deferred.Deferred<void>>>, batchId: PullBatchId) =>
1210
+ Effect.gen(function* () {
1211
+ let completion: Deferred.Deferred<void> | undefined
1212
+ yield* Ref.update(batchesRef, (current) => {
1213
+ const next = new Map(current)
1214
+ completion = next.get(batchId)
1215
+ next.delete(batchId)
1216
+ return next
1217
+ })
1218
+ if (completion !== undefined) yield* Deferred.succeed(completion, void 0)
1219
+ })
979
1220
 
980
- const trimChangesetRows = (db: SqliteDb, newHead: EventSequenceNumber.Client.Composite) => {
981
- // Since we're using the session changeset rows to query for the current head,
982
- // we're keeping at least one row for the current head, and thus are using `<` instead of `<=`
983
- db.execute(sql`DELETE FROM ${SystemTables.SESSION_CHANGESET_META_TABLE} WHERE seqNumGlobal < ${newHead.global}`)
1221
+ const countRequestItems = (items: ReadonlyArray<LocalItem>) => {
1222
+ const counts = new Map<LocalRequestId, number>()
1223
+ for (const item of items) counts.set(item.requestId, (counts.get(item.requestId) ?? 0) + 1)
1224
+ return counts
984
1225
  }
985
1226
 
986
1227
  interface PullQueueSet {
987
1228
  makeQueue: (
988
1229
  cursor: EventSequenceNumber.Client.Composite,
989
- ) => Effect.Effect<Queue.Queue<{ payload: typeof SyncState.PayloadUpstream.Type }>, never, Scope.Scope>
1230
+ ) => Effect.Effect<Queue.Queue<typeof PullItem.Type>, never, Scope.Scope>
990
1231
  offer: (item: {
991
1232
  payload: typeof SyncState.PayloadUpstream.Type
1233
+ globalHead: EventSequenceNumber.Client.Composite
992
1234
  leaderHead: EventSequenceNumber.Client.Composite
1235
+ materializerHashes: ReadonlyArray<LiveStoreEvent.Client.MaterializerHash>
993
1236
  }) => Effect.Effect<void, never>
994
1237
  }
995
1238
 
996
1239
  const makePullQueueSet = Effect.gen(function* () {
997
- const set = new Set<Queue.Queue<{ payload: typeof SyncState.PayloadUpstream.Type }>>()
1240
+ const set = new Set<Queue.Queue<typeof PullItem.Type>>()
998
1241
 
999
1242
  type StringifiedSeqNum = string
1000
1243
  // NOTE this could grow unbounded for long running sessions
1001
- const cachedPayloads = new Map<StringifiedSeqNum, (typeof SyncState.PayloadUpstream.Type)[]>()
1244
+ const cachedPullItems = new Map<StringifiedSeqNum, (typeof PullItem.Type)[]>()
1002
1245
 
1003
1246
  yield* Effect.addFinalizer(() =>
1004
1247
  Effect.gen(function* () {
@@ -1012,33 +1255,32 @@ const makePullQueueSet = Effect.gen(function* () {
1012
1255
 
1013
1256
  const makeQueue: PullQueueSet['makeQueue'] = (cursor) =>
1014
1257
  Effect.gen(function* () {
1015
- const queue = yield* Effect.acquireRelease(
1016
- Queue.unbounded<{
1017
- payload: typeof SyncState.PayloadUpstream.Type
1018
- }>(),
1019
- Queue.shutdown,
1020
- )
1258
+ const queue = yield* Effect.acquireRelease(Queue.unbounded<typeof PullItem.Type>(), Queue.shutdown)
1021
1259
 
1022
1260
  yield* Effect.addFinalizer(() => Effect.sync(() => set.delete(queue)))
1023
1261
 
1024
- const payloadsSinceCursor = Array.from(cachedPayloads.entries())
1025
- .flatMap(([seqNumStr, payloads]) =>
1026
- payloads.map((payload) => ({ payload, seqNum: EventSequenceNumber.Client.fromString(seqNumStr) })),
1262
+ const pullItemsSinceCursor = Array.from(cachedPullItems.entries())
1263
+ .flatMap(([seqNumStr, items]) =>
1264
+ items.map((item) => ({ item, seqNum: EventSequenceNumber.Client.fromString(seqNumStr) })),
1027
1265
  )
1028
1266
  .filter(({ seqNum }) => EventSequenceNumber.Client.isGreaterThan(seqNum, cursor))
1029
1267
  .toSorted((a, b) => EventSequenceNumber.Client.compare(a.seqNum, b.seqNum))
1030
- .map(({ payload }) => {
1031
- if (payload._tag === 'upstream-advance') {
1032
- return {
1268
+ .map(({ item }) => {
1269
+ if (item.payload._tag === 'upstream-advance') {
1270
+ return PullItem.make({
1271
+ globalHead: item.globalHead,
1272
+ materializerHashes: item.materializerHashes.filter(({ eventNum }) =>
1273
+ EventSequenceNumber.Client.isGreaterThan(eventNum, cursor),
1274
+ ),
1033
1275
  payload: {
1034
1276
  _tag: 'upstream-advance' as const,
1035
- newEvents: ReadonlyArray.dropWhile(payload.newEvents, (eventEncoded) =>
1277
+ newEvents: ReadonlyArray.dropWhile(item.payload.newEvents, (eventEncoded) =>
1036
1278
  EventSequenceNumber.Client.isGreaterThanOrEqual(cursor, eventEncoded.seqNum),
1037
1279
  ),
1038
1280
  },
1039
- }
1281
+ })
1040
1282
  } else {
1041
- return { payload }
1283
+ return item
1042
1284
  }
1043
1285
  })
1044
1286
 
@@ -1048,9 +1290,9 @@ const makePullQueueSet = Effect.gen(function* () {
1048
1290
  // cursor,
1049
1291
  // },
1050
1292
  // '\n mergePayloads',
1051
- // ...Array.from(cachedPayloads.entries())
1052
- // .flatMap(([seqNumStr, payloads]) =>
1053
- // payloads.map((payload) => ({ payload, seqNum: EventSequenceNumber.fromString(seqNumStr) })),
1293
+ // ...Array.from(cachedPullItems.entries())
1294
+ // .flatMap(([seqNumStr, items]) =>
1295
+ // items.map(({ payload }) => ({ payload, seqNum: EventSequenceNumber.fromString(seqNumStr) })),
1054
1296
  // )
1055
1297
  // .map(({ payload, seqNum }) => [
1056
1298
  // seqNum,
@@ -1060,8 +1302,8 @@ const makePullQueueSet = Effect.gen(function* () {
1060
1302
  // 'rollbackEvents',
1061
1303
  // ...(payload._tag === 'upstream-rebase' ? payload.rollbackEvents.map((_) => _.toJSON()) : []),
1062
1304
  // ]),
1063
- // '\n payloadsSinceCursor',
1064
- // ...payloadsSinceCursor.map(({ payload }) => [
1305
+ // '\n pullItemsSinceCursor',
1306
+ // ...pullItemsSinceCursor.map(({ payload }) => [
1065
1307
  // payload._tag,
1066
1308
  // 'newEvents',
1067
1309
  // ...payload.newEvents.map((_) => _.toJSON()),
@@ -1070,7 +1312,7 @@ const makePullQueueSet = Effect.gen(function* () {
1070
1312
  // ]),
1071
1313
  // )
1072
1314
 
1073
- yield* Queue.offerAll(queue, payloadsSinceCursor)
1315
+ yield* Queue.offerAll(queue, pullItemsSinceCursor)
1074
1316
 
1075
1317
  set.add(queue)
1076
1318
 
@@ -1080,21 +1322,21 @@ const makePullQueueSet = Effect.gen(function* () {
1080
1322
  const offer: PullQueueSet['offer'] = (item) =>
1081
1323
  Effect.gen(function* () {
1082
1324
  const seqNumStr = EventSequenceNumber.Client.toString(item.leaderHead)
1083
- if (cachedPayloads.has(seqNumStr) === true) {
1084
- cachedPayloads.get(seqNumStr)!.push(item.payload)
1325
+ const pullItem = PullItem.make({
1326
+ payload: item.payload,
1327
+ globalHead: item.globalHead,
1328
+ materializerHashes: item.materializerHashes,
1329
+ })
1330
+ if (cachedPullItems.has(seqNumStr) === true) {
1331
+ cachedPullItems.get(seqNumStr)!.push(pullItem)
1085
1332
  } else {
1086
- cachedPayloads.set(seqNumStr, [item.payload])
1333
+ cachedPullItems.set(seqNumStr, [pullItem])
1087
1334
  }
1088
1335
 
1089
1336
  // console.debug(`offering to ${set.size} queues`, item.leaderHead, JSON.stringify(item.payload, null, 2))
1090
1337
 
1091
- // Short-circuit if the payload is an empty upstream advance
1092
- if (item.payload._tag === 'upstream-advance' && item.payload.newEvents.length === 0) {
1093
- return
1094
- }
1095
-
1096
1338
  for (const queue of set) {
1097
- yield* Queue.offer(queue, item)
1339
+ yield* Queue.offer(queue, pullItem)
1098
1340
  }
1099
1341
  })
1100
1342
 
@@ -1104,184 +1346,30 @@ const makePullQueueSet = Effect.gen(function* () {
1104
1346
  }
1105
1347
  })
1106
1348
 
1107
- /**
1108
- * Validate a client-provided batch before it is admitted to the leader queue.
1109
- * Ensures the numbers form a strictly increasing chain and that the first
1110
- * event sits ahead of the current push head.
1111
- */
1112
- const validatePushBatch = (
1113
- batch: ReadonlyArray<LiveStoreEvent.Client.EncodedWithMeta>,
1114
- pushHead: EventSequenceNumber.Client.Composite,
1115
- isClientOnlyEvent: (event: LiveStoreEvent.Client.EncodedWithMeta) => boolean,
1116
- ) =>
1117
- Effect.gen(function* () {
1118
- if (batch.length === 0) {
1119
- return
1120
- }
1121
-
1122
- // Defensive check: callers should already provide a strictly increasing sequence
1123
- // of event numbers.
1124
- for (let i = 1; i < batch.length; i++) {
1125
- if (EventSequenceNumber.Client.isGreaterThanOrEqual(batch[i - 1]!.seqNum, batch[i]!.seqNum) === true) {
1126
- return yield* NonMonotonicBatchError.make({
1127
- precedingSeqNum: batch[i - 1]!.seqNum,
1128
- violatingSeqNum: batch[i]!.seqNum,
1129
- violationIndex: i,
1130
- sessionId: batch[i]!.sessionId,
1131
- })
1132
- }
1133
- }
1134
-
1135
- // Reject stale batches whose first event is at or behind the leader's push head.
1136
- if (EventSequenceNumber.Client.isGreaterThanOrEqual(pushHead, batch[0]!.seqNum) === true) {
1137
- return yield* LeaderAheadError.make({
1138
- minimumExpectedNum: pushHead,
1139
- providedNum: batch[0]!.seqNum,
1140
- sessionId: batch[0]!.sessionId,
1141
- })
1142
- }
1143
-
1144
- // A rebase replaces the optimistic history that the client built on. Events from an older
1145
- // generation may now have the wrong parent and must be recreated from the leader's current head.
1146
- if (batch[0]!.seqNum.rebaseGeneration < pushHead.rebaseGeneration) {
1147
- return yield* StaleRebaseGenerationError.make({
1148
- currentRebaseGeneration: pushHead.rebaseGeneration,
1149
- providedRebaseGeneration: batch[0]!.seqNum.rebaseGeneration,
1150
- sessionId: batch[0]!.sessionId,
1151
- })
1152
- }
1153
-
1154
- // Validate the batch as one unbroken chain starting at the admission fence. Checking only that
1155
- // numbers increase would still allow gaps or events that point at an unrelated parent.
1156
- let precedingSeqNum = pushHead
1157
- for (let i = 0; i < batch.length; i++) {
1158
- const event = batch[i]!
1159
- // Global events advance the global position; client-only events advance its client-local suffix.
1160
- const expectedPair = EventSequenceNumber.Client.nextPair({
1161
- seqNum: precedingSeqNum,
1162
- isClientOnly: isClientOnlyEvent(event),
1163
- rebaseGeneration: event.seqNum.rebaseGeneration,
1164
- })
1165
-
1166
- if (
1167
- EventSequenceNumber.Client.isEqual(event.seqNum, expectedPair.seqNum) === false ||
1168
- isSameSequencePosition(event.parentSeqNum, expectedPair.parentSeqNum) === false
1169
- ) {
1170
- return yield* NonContiguousBatchError.make({
1171
- expectedSeqNum: expectedPair.seqNum,
1172
- providedSeqNum: event.seqNum,
1173
- expectedParentSeqNum: expectedPair.parentSeqNum,
1174
- providedParentSeqNum: event.parentSeqNum,
1175
- violationIndex: i,
1176
- sessionId: event.sessionId,
1177
- })
1178
- }
1179
-
1180
- precedingSeqNum = event.seqNum
1181
- }
1182
- })
1183
-
1184
- /**
1185
- * Parent linkage identifies a position in the event chain. Rebase generation describes the version
1186
- * of optimistic history, so it is validated on the event itself rather than as part of parent identity.
1187
- */
1188
- const isSameSequencePosition = (
1189
- left: EventSequenceNumber.Client.Composite,
1190
- right: EventSequenceNumber.Client.Composite,
1191
- ) => left.global === right.global && left.client === right.client
1192
-
1193
- /**
1194
- * Handles a BackendIdMismatchError based on the configured behavior.
1195
- * This occurs when the sync backend has been reset and has a new identity.
1196
- */
1197
- const handleBackendIdMismatch = Effect.fn('@livestore/common:LeaderSyncProcessor:handleBackendIdMismatch')(function* ({
1198
- error,
1199
- onBackendIdMismatch,
1200
- shutdownChannel,
1201
- dbEventlog,
1202
- dbState,
1203
- }: {
1204
- error: BackendIdMismatchError
1205
- onBackendIdMismatch: 'reset' | 'shutdown' | 'ignore'
1206
- shutdownChannel: ShutdownChannel
1207
- dbEventlog: SqliteDb
1208
- dbState: SqliteDb
1209
- }) {
1210
- if (onBackendIdMismatch === 'reset') {
1211
- yield* Effect.logWarning(
1212
- 'Sync backend identity changed (backend was reset). Clearing local storage and shutting down.',
1213
- error,
1214
- )
1215
-
1216
- // Clear local databases so the client can start fresh on next boot
1217
- yield* clearLocalDatabases({ dbEventlog, dbState })
1218
-
1219
- // Send shutdown signal with special reason
1220
- yield* shutdownChannel.send(IntentionalShutdownCause.make({ reason: 'backend-id-mismatch' })).pipe(Effect.orDie)
1221
-
1222
- return yield* Effect.die(error)
1223
- }
1224
-
1225
- if (onBackendIdMismatch === 'shutdown') {
1226
- yield* Effect.logWarning(
1227
- 'Sync backend identity changed (backend was reset). Shutting down without clearing local storage.',
1228
- error,
1229
- )
1230
-
1231
- yield* shutdownChannel.send(error).pipe(Effect.orDie)
1232
-
1233
- return yield* Effect.die(error)
1234
- }
1235
-
1236
- // ignore mode
1237
- if (LS_DEV === true) {
1238
- yield* Effect.logDebug(
1239
- 'Ignoring BackendIdMismatchError (sync backend was reset but client continues with stale data)',
1240
- error,
1241
- )
1242
- }
1243
- })
1244
-
1245
1349
  /**
1246
1350
  * Clears local databases (eventlog and state) so the client can start fresh on next boot.
1247
1351
  * This is used when the sync backend identity has changed (i.e. backend was reset).
1248
1352
  */
1249
1353
  const clearLocalDatabases = ({ dbEventlog, dbState }: { dbEventlog: SqliteDb; dbState: SqliteDb }) =>
1250
- Effect.sync(() => {
1251
- // Clear eventlog tables
1252
- dbEventlog.execute(sql`DELETE FROM ${EVENTLOG_META_TABLE}`)
1253
- dbEventlog.execute(sql`DELETE FROM ${SYNC_STATUS_TABLE}`)
1254
-
1255
- // Drop all state tables - they'll be recreated on next boot
1256
- const tables = dbState.select<{ name: string }>(
1257
- sql`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`,
1258
- )
1259
- for (const { name } of tables) {
1260
- dbState.execute(`DROP TABLE IF EXISTS "${name}"`)
1261
- }
1354
+ Effect.try({
1355
+ try: () => {
1356
+ // Clear eventlog tables
1357
+ dbEventlog.execute(sql`DELETE FROM ${EVENTLOG_META_TABLE}`)
1358
+ dbEventlog.execute(sql`DELETE FROM ${SYNC_STATUS_TABLE}`)
1359
+
1360
+ // Drop all state tables - they'll be recreated on next boot
1361
+ const tables = dbState.select<{ name: string }>(
1362
+ sql`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`,
1363
+ )
1364
+ for (const { name } of tables) {
1365
+ dbState.execute(`DROP TABLE IF EXISTS "${name}"`)
1366
+ }
1367
+ },
1368
+ catch: (cause) => UnknownError.make({ cause, note: 'Failed to reset local databases after backend mismatch' }),
1262
1369
  })
1263
1370
 
1264
- const snapshotTxQueue = <A>(queue: TxQueue.TxQueue<A>): Effect.Effect<ReadonlyArray<A>> =>
1265
- Effect.tx(
1266
- Effect.gen(function* () {
1267
- const items = yield* TxQueue.clear(queue)
1268
- yield* TxQueue.offerAll(queue, items)
1269
- return items
1270
- }),
1271
- )
1272
-
1273
- const takePrefixUntil = <A>(
1274
- queue: TxQueue.TxQueue<A>,
1275
- predicate: (value: A) => boolean,
1276
- ): Effect.Effect<ReadonlyArray<A>> =>
1277
- Effect.tx(
1278
- Effect.gen(function* () {
1279
- const items = yield* TxQueue.clear(queue)
1280
- const [prefix, rest] = ReadonlyArray.splitWhere(items, predicate)
1281
- yield* TxQueue.offerAll(queue, rest)
1282
- return prefix
1283
- }),
1284
- )
1371
+ const localItemKey = (item: LocalItem) => `${item.requestId}:${item.index}`
1372
+ const retryDelay = (attempt: number) => Math.min(30_000, 1_000 * 2 ** Math.max(0, attempt - 1))
1285
1373
 
1286
1374
  /** Serialize value to JSON string for trace attributes */
1287
1375
  const jsonStringify = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown))