@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.
- package/dist/.tsbuildinfo +1 -1
- package/dist/ClientSessionLeaderThreadProxy.d.ts +89 -7
- package/dist/ClientSessionLeaderThreadProxy.d.ts.map +1 -1
- package/dist/ClientSessionLeaderThreadProxy.js +11 -0
- package/dist/ClientSessionLeaderThreadProxy.js.map +1 -1
- package/dist/EventlogSqliteDb.d.ts +10 -0
- package/dist/EventlogSqliteDb.d.ts.map +1 -0
- package/dist/EventlogSqliteDb.js +7 -0
- package/dist/EventlogSqliteDb.js.map +1 -0
- package/dist/MaterializationJournal.d.ts +9 -14
- package/dist/MaterializationJournal.d.ts.map +1 -1
- package/dist/MaterializationJournal.js +79 -50
- package/dist/MaterializationJournal.js.map +1 -1
- package/dist/StateHead.d.ts +4 -6
- package/dist/StateHead.d.ts.map +1 -1
- package/dist/StateHead.js +5 -3
- package/dist/StateHead.js.map +1 -1
- package/dist/StateSqliteDb.d.ts +10 -0
- package/dist/StateSqliteDb.d.ts.map +1 -0
- package/dist/StateSqliteDb.js +7 -0
- package/dist/StateSqliteDb.js.map +1 -0
- package/dist/adapter-types.d.ts +3 -2
- package/dist/adapter-types.d.ts.map +1 -1
- package/dist/adapter-types.js.map +1 -1
- package/dist/devtools/devtools-messages-leader.d.ts +120 -6
- package/dist/devtools/devtools-messages-leader.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/leader-thread/LeaderPersistence.d.ts +65 -0
- package/dist/leader-thread/LeaderPersistence.d.ts.map +1 -0
- package/dist/leader-thread/LeaderPersistence.js +127 -0
- package/dist/leader-thread/LeaderPersistence.js.map +1 -0
- package/dist/leader-thread/LeaderSyncProcessor.d.ts +26 -126
- package/dist/leader-thread/LeaderSyncProcessor.d.ts.map +1 -1
- package/dist/leader-thread/LeaderSyncProcessor.js +830 -658
- package/dist/leader-thread/LeaderSyncProcessor.js.map +1 -1
- package/dist/leader-thread/connection.js +8 -3
- package/dist/leader-thread/connection.js.map +1 -1
- package/dist/leader-thread/eventlog.d.ts +24 -9
- package/dist/leader-thread/eventlog.d.ts.map +1 -1
- package/dist/leader-thread/eventlog.js +34 -28
- package/dist/leader-thread/eventlog.js.map +1 -1
- package/dist/leader-thread/leader-worker-devtools.d.ts +3 -1
- package/dist/leader-thread/leader-worker-devtools.d.ts.map +1 -1
- package/dist/leader-thread/leader-worker-devtools.js +45 -3
- package/dist/leader-thread/leader-worker-devtools.js.map +1 -1
- package/dist/leader-thread/make-leader-thread-layer.d.ts +7 -5
- package/dist/leader-thread/make-leader-thread-layer.d.ts.map +1 -1
- package/dist/leader-thread/make-leader-thread-layer.js +12 -13
- package/dist/leader-thread/make-leader-thread-layer.js.map +1 -1
- package/dist/leader-thread/materialize-event.d.ts +5 -11
- package/dist/leader-thread/materialize-event.d.ts.map +1 -1
- package/dist/leader-thread/materialize-event.js +38 -86
- package/dist/leader-thread/materialize-event.js.map +1 -1
- package/dist/leader-thread/mod.d.ts +1 -0
- package/dist/leader-thread/mod.d.ts.map +1 -1
- package/dist/leader-thread/mod.js +1 -0
- package/dist/leader-thread/mod.js.map +1 -1
- package/dist/leader-thread/recreate-db.d.ts +5 -5
- package/dist/leader-thread/recreate-db.d.ts.map +1 -1
- package/dist/leader-thread/recreate-db.js +3 -2
- package/dist/leader-thread/recreate-db.js.map +1 -1
- package/dist/leader-thread/shutdown-channel.d.ts +2 -1
- package/dist/leader-thread/shutdown-channel.d.ts.map +1 -1
- package/dist/leader-thread/shutdown-channel.js +8 -1
- package/dist/leader-thread/shutdown-channel.js.map +1 -1
- package/dist/leader-thread/types.d.ts +5 -11
- package/dist/leader-thread/types.d.ts.map +1 -1
- package/dist/leader-thread/types.js.map +1 -1
- package/dist/rematerialize-from-eventlog.d.ts +2 -2
- package/dist/rematerialize-from-eventlog.d.ts.map +1 -1
- package/dist/rematerialize-from-eventlog.js +4 -2
- package/dist/rematerialize-from-eventlog.js.map +1 -1
- package/dist/schema/LiveStoreEvent/client.d.ts +19 -64
- package/dist/schema/LiveStoreEvent/client.d.ts.map +1 -1
- package/dist/schema/LiveStoreEvent/client.js +28 -102
- package/dist/schema/LiveStoreEvent/client.js.map +1 -1
- package/dist/schema/LiveStoreEvent/client.test.js +5 -11
- package/dist/schema/LiveStoreEvent/client.test.js.map +1 -1
- package/dist/schema/state/sqlite/db-schema/ast/fingerprint.js +8 -1
- package/dist/schema/state/sqlite/db-schema/ast/fingerprint.js.map +1 -1
- package/dist/schema/state/sqlite/db-schema/ast/fingerprint.test.js +2 -2
- package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.d.ts +6 -1
- package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.d.ts.map +1 -1
- package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.js +9 -5
- package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.js.map +1 -1
- package/dist/schema/state/sqlite/system-tables/state-tables.d.ts +8 -139
- package/dist/schema/state/sqlite/system-tables/state-tables.d.ts.map +1 -1
- package/dist/schema/state/sqlite/system-tables/state-tables.js +11 -20
- package/dist/schema/state/sqlite/system-tables/state-tables.js.map +1 -1
- package/dist/schema-management/__tests__/migrations-autoincrement-quoting.test.js +1 -1
- package/dist/schema-management/__tests__/migrations-autoincrement-quoting.test.js.map +1 -1
- package/dist/sqlite-types.d.ts +1 -1
- package/dist/sqlite-types.d.ts.map +1 -1
- package/dist/sync/ClientSessionSyncProcessor.d.ts +42 -69
- package/dist/sync/ClientSessionSyncProcessor.d.ts.map +1 -1
- package/dist/sync/ClientSessionSyncProcessor.js +611 -291
- package/dist/sync/ClientSessionSyncProcessor.js.map +1 -1
- package/dist/sync/syncstate.d.ts +407 -27
- package/dist/sync/syncstate.d.ts.map +1 -1
- package/dist/sync/syncstate.js +26 -19
- package/dist/sync/syncstate.js.map +1 -1
- package/dist/sync/syncstate.test.js +25 -5
- package/dist/sync/syncstate.test.js.map +1 -1
- package/package.json +18 -18
- package/src/ClientSessionLeaderThreadProxy.ts +16 -7
- package/src/EventlogSqliteDb.ts +11 -0
- package/src/MaterializationJournal.ts +106 -77
- package/src/StateHead.ts +6 -7
- package/src/StateSqliteDb.ts +9 -0
- package/src/adapter-types.ts +9 -2
- package/src/index.ts +2 -0
- package/src/leader-thread/LeaderPersistence.ts +244 -0
- package/src/leader-thread/LeaderSyncProcessor.ts +1099 -1011
- package/src/leader-thread/connection.ts +9 -3
- package/src/leader-thread/eventlog.ts +54 -39
- package/src/leader-thread/leader-worker-devtools.ts +73 -4
- package/src/leader-thread/make-leader-thread-layer.ts +24 -21
- package/src/leader-thread/materialize-event.ts +47 -119
- package/src/leader-thread/mod.ts +1 -0
- package/src/leader-thread/recreate-db.ts +9 -6
- package/src/leader-thread/shutdown-channel.ts +8 -1
- package/src/leader-thread/types.ts +6 -8
- package/src/rematerialize-from-eventlog.ts +3 -3
- package/src/schema/LiveStoreEvent/client.test.ts +7 -12
- package/src/schema/LiveStoreEvent/client.ts +38 -122
- package/src/schema/state/sqlite/db-schema/ast/fingerprint.test.ts +2 -2
- package/src/schema/state/sqlite/db-schema/ast/fingerprint.ts +8 -1
- package/src/schema/state/sqlite/db-schema/has-json-string-encoding.ts +11 -7
- package/src/schema/state/sqlite/system-tables/state-tables.ts +13 -26
- package/src/schema-management/__tests__/migrations-autoincrement-quoting.test.ts +1 -1
- package/src/sqlite-types.ts +1 -1
- package/src/sync/ClientSessionSyncProcessor.ts +809 -456
- package/src/sync/syncstate.test.ts +32 -9
- package/src/sync/syncstate.ts +41 -29
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { casesHandled,
|
|
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
|
-
|
|
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 {
|
|
32
|
-
import
|
|
27
|
+
import { type SqliteDb, UnknownError } from '../adapter-types.ts'
|
|
28
|
+
import { PullItem } from '../ClientSessionLeaderThreadProxy.ts'
|
|
33
29
|
import { IntentionalShutdownCause } from '../errors.ts'
|
|
34
|
-
import
|
|
30
|
+
import * as EventlogSqliteDb from '../EventlogSqliteDb.ts'
|
|
35
31
|
import type { LiveStoreSchema } from '../schema/mod.ts'
|
|
36
|
-
import { EventSequenceNumber, LiveStoreEvent
|
|
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
|
|
39
|
-
import type { BackendIdMismatchError, IsOfflineError,
|
|
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
|
|
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
|
|
53
|
-
import type { InitialBlockingSyncContext
|
|
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
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
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.
|
|
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
|
|
237
|
-
const
|
|
238
|
-
const
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
const
|
|
248
|
-
const
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
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
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
const
|
|
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
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
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
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
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
|
-
|
|
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
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
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
|
-
|
|
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
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
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
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
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
|
-
|
|
336
|
-
|
|
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
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
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
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
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
|
-
|
|
445
|
-
|
|
446
|
-
|
|
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
|
-
|
|
450
|
-
|
|
451
|
-
|
|
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
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
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
|
-
|
|
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
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
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
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
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
|
-
|
|
499
|
-
|
|
500
|
-
|
|
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
|
-
|
|
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
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
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
|
-
|
|
512
|
-
|
|
513
|
-
|
|
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
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
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
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
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
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
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
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
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
|
-
|
|
612
|
-
|
|
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
|
-
|
|
617
|
-
const
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
yield*
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
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
|
-
|
|
654
|
-
|
|
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
|
-
|
|
658
|
-
if (syncBackend === undefined) return
|
|
761
|
+
export const layer = (options: Options) => Layer.effect(LeaderSyncProcessor, make(options))
|
|
659
762
|
|
|
660
|
-
|
|
661
|
-
|
|
763
|
+
type OperationId = number
|
|
764
|
+
type LocalRequestId = number
|
|
765
|
+
type PullBatchId = number
|
|
662
766
|
|
|
663
|
-
|
|
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
|
-
|
|
776
|
+
interface LocalItem {
|
|
777
|
+
readonly requestId: LocalRequestId
|
|
778
|
+
readonly index: number
|
|
779
|
+
readonly event: LiveStoreEvent.Client.Encoded
|
|
780
|
+
}
|
|
666
781
|
|
|
667
|
-
|
|
668
|
-
|
|
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
|
-
|
|
672
|
-
|
|
673
|
-
|
|
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
|
-
|
|
677
|
-
|
|
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
|
-
|
|
800
|
+
interface OutstandingPage {
|
|
801
|
+
readonly completion: Deferred.Deferred<void>
|
|
802
|
+
readonly processed: number
|
|
803
|
+
readonly pageInfo: SyncBackend.PullResPageInfo
|
|
804
|
+
}
|
|
685
805
|
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
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
|
-
|
|
692
|
-
|
|
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
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
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
|
-
}
|
|
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
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
893
|
+
interface LocalRequest {
|
|
894
|
+
readonly deferred: Deferred.Deferred<void, RejectedPushError>
|
|
895
|
+
readonly remaining: number
|
|
896
|
+
}
|
|
724
897
|
|
|
725
|
-
|
|
726
|
-
|
|
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
|
-
|
|
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
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
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
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
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
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
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
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
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
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
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
|
-
|
|
817
|
-
yield*
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
yield*
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
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
|
-
|
|
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
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
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
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
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
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
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
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
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
|
-
|
|
903
|
-
|
|
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
|
-
|
|
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
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
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
|
-
|
|
954
|
-
|
|
955
|
-
|
|
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
|
-
|
|
958
|
-
|
|
959
|
-
|
|
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
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
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
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
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
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
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<
|
|
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<
|
|
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
|
|
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
|
|
1025
|
-
.flatMap(([seqNumStr,
|
|
1026
|
-
|
|
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(({
|
|
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
|
|
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(
|
|
1052
|
-
// .flatMap(([seqNumStr,
|
|
1053
|
-
//
|
|
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
|
|
1064
|
-
// ...
|
|
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,
|
|
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
|
-
|
|
1084
|
-
|
|
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
|
-
|
|
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,
|
|
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.
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
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
|
|
1265
|
-
|
|
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))
|