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