@livestore/common 0.5.0 → 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,661 +1,697 @@
|
|
|
1
|
-
import { casesHandled,
|
|
2
|
-
import { Cause, Context, Deferred, Duration, Effect, Exit, FiberHandle,
|
|
3
|
-
import {
|
|
1
|
+
import { casesHandled, TRACE_VERBOSE } from '@livestore/utils';
|
|
2
|
+
import { Cause, Context, Deferred, Duration, Effect, Exit, FiberHandle, FiberSet, Layer, Queue, Random, ReadonlyArray, Ref, Result, Schema, Stream, Subscribable, SubscriptionRef, } from '@livestore/utils/effect';
|
|
3
|
+
import { UnknownError } from '../adapter-types.js';
|
|
4
|
+
import { PullItem } from '../ClientSessionLeaderThreadProxy.js';
|
|
4
5
|
import { IntentionalShutdownCause } from '../errors.js';
|
|
5
|
-
import
|
|
6
|
-
import { EventSequenceNumber, LiveStoreEvent
|
|
6
|
+
import * as EventlogSqliteDb from '../EventlogSqliteDb.js';
|
|
7
|
+
import { EventSequenceNumber, LiveStoreEvent } from '../schema/mod.js';
|
|
7
8
|
import { EVENTLOG_META_TABLE, SYNC_STATUS_TABLE } from '../schema/state/sqlite/system-tables/eventlog-tables.js';
|
|
8
|
-
import * as
|
|
9
|
+
import * as StateSqliteDb from '../StateSqliteDb.js';
|
|
9
10
|
import * as SyncState from '../sync/syncstate.js';
|
|
10
11
|
import { sql } from '../util.js';
|
|
11
12
|
import * as Eventlog from './eventlog.js';
|
|
12
|
-
import
|
|
13
|
-
import {
|
|
13
|
+
import * as LeaderPersistence from './LeaderPersistence.js';
|
|
14
|
+
import { LeaderAheadError, NonContiguousBatchError, NonMonotonicBatchError, StaleRebaseGenerationError, } from './RejectedPushError.js';
|
|
15
|
+
import * as Shutdown from './shutdown-channel.js';
|
|
14
16
|
export const TypeId = '~@livestore/common/LeaderSyncProcessor';
|
|
15
17
|
/**
|
|
16
|
-
*
|
|
17
|
-
* the local state and the sync backend, ensuring efficient and orderly processing.
|
|
18
|
+
* Public entry point and orchestration owner for leader synchronization.
|
|
18
19
|
*
|
|
19
|
-
*
|
|
20
|
+
* Local pushes, backend batches, retries, failures, and shutdown all enter one mailbox and are handled one at a time.
|
|
21
|
+
* This makes the in-memory model easier to reason about because the mailbox loop is the only place that changes it.
|
|
20
22
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* - Pushing events to the sync backend.
|
|
25
|
-
*
|
|
26
|
-
* Notes:
|
|
27
|
-
*
|
|
28
|
-
* local push processing:
|
|
29
|
-
* - localPushesQueue:
|
|
30
|
-
* - Maintains events in ascending order.
|
|
31
|
-
* - Uses `Deferred` objects to resolve/reject events based on application success.
|
|
32
|
-
* - Processes events from the queue, applying events in batches.
|
|
33
|
-
* - Controlled by a mutex (`Semaphore(1)`) to ensure mutual exclusion between local push and backend pull processing.
|
|
34
|
-
* - The backend pull side acquires the mutex before processing and releases it on post-pull completion.
|
|
35
|
-
* - Processes up to `maxBatchSize` events per cycle.
|
|
36
|
-
*
|
|
37
|
-
* Currently, we're advancing the state db and eventlog in lockstep, but we could also decouple this in the future
|
|
38
|
-
*
|
|
39
|
-
* Tricky concurrency scenarios:
|
|
40
|
-
* - Queued local push batches becoming invalid due to a prior local push item being rejected.
|
|
41
|
-
* Solution: Introduce a generation number for local push batches which is used to filter out old batches items in case of rejection.
|
|
42
|
-
*
|
|
43
|
-
* See ClientSessionSyncProcessor for how the leader and session sync processors are similar/different.
|
|
23
|
+
* The processor owns lifecycle, queues, provider work, publication, and acknowledgements. Durable work is delegated to
|
|
24
|
+
* `LeaderPersistence`, and only a successful receipt may update observable state, publish events, schedule a backend
|
|
25
|
+
* push, or resolve a push acknowledgement.
|
|
44
26
|
*/
|
|
45
27
|
export class LeaderSyncProcessor extends Context.Service()('@livestore/common/LeaderSyncProcessor') {
|
|
46
28
|
}
|
|
47
29
|
export const make = Effect.fnUntraced(function* ({ schema, runtime, initialBlockingSyncContext, initialSyncState, onError, onBackendIdMismatch, livePull, params, testing, }) {
|
|
48
|
-
const
|
|
49
|
-
const
|
|
50
|
-
const
|
|
51
|
-
const
|
|
52
|
-
const
|
|
53
|
-
const
|
|
54
|
-
const
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
// It's important that we filter after acquiring the localPushBackendPullMutex, otherwise we might filter with the old generation
|
|
105
|
-
const [filteredItems, droppedItems] = ReadonlyArray.partition(batchItems, (batchItem) => batchItem[0].seqNum.rebaseGeneration >= currentRebaseGeneration
|
|
106
|
-
? Result.succeed(batchItem)
|
|
107
|
-
: Result.fail(batchItem));
|
|
108
|
-
if (droppedItems.length > 0) {
|
|
109
|
-
yield* Effect.spanEvent(`push:drop-old-generation`, {
|
|
110
|
-
droppedCount: droppedItems.length,
|
|
111
|
-
currentRebaseGeneration,
|
|
112
|
-
});
|
|
113
|
-
yield* Effect.forEach(droppedItems, ([eventEncoded, deferred]) => Deferred.fail(deferred, StaleRebaseGenerationError.make({
|
|
114
|
-
currentRebaseGeneration,
|
|
115
|
-
providedRebaseGeneration: eventEncoded.seqNum.rebaseGeneration,
|
|
116
|
-
sessionId: eventEncoded.sessionId,
|
|
117
|
-
})));
|
|
118
|
-
yield* releasePushReservations(droppedItems, syncState.localHead);
|
|
119
|
-
}
|
|
120
|
-
if (filteredItems.length === 0) {
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
const [newEvents, deferreds] = ReadonlyArray.unzip(filteredItems);
|
|
124
|
-
yield* Effect.annotateCurrentSpan({
|
|
125
|
-
batchSize: newEvents.length,
|
|
126
|
-
...(TRACE_VERBOSE === true ? { newEvents: jsonStringify(newEvents) } : {}),
|
|
127
|
-
});
|
|
128
|
-
const mergeResult = yield* SyncState.merge({
|
|
129
|
-
syncState,
|
|
130
|
-
payload: { _tag: 'local-push', newEvents },
|
|
131
|
-
isClientOnlyEvent,
|
|
132
|
-
isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
|
|
133
|
-
});
|
|
134
|
-
switch (mergeResult._tag) {
|
|
135
|
-
case 'rebase': {
|
|
136
|
-
return yield* Effect.dieDebugger('The leader thread should never have to rebase due to a local push');
|
|
137
|
-
}
|
|
138
|
-
case 'reject': {
|
|
139
|
-
yield* Effect.spanEvent(`push:reject`, {
|
|
140
|
-
batchSize: newEvents.length,
|
|
141
|
-
...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
|
|
142
|
-
});
|
|
143
|
-
// TODO: how to test this?
|
|
144
|
-
const nextRebaseGeneration = currentRebaseGeneration + 1;
|
|
145
|
-
const providedNum = newEvents.at(0).seqNum;
|
|
146
|
-
// All subsequent pushes with same generation should be rejected as well
|
|
147
|
-
// We're also handling the case where the localPushQueue already contains events
|
|
148
|
-
// from the next generation which we preserve in the queue
|
|
149
|
-
const remainingEventsMatchingGeneration = yield* takePrefixUntil(localPushesQueue, ([eventEncoded]) => eventEncoded.seqNum.rebaseGeneration >= nextRebaseGeneration);
|
|
150
|
-
// TODO we still need to better understand and handle this scenario
|
|
151
|
-
const remainingLocalPushes = yield* snapshotTxQueue(localPushesQueue);
|
|
152
|
-
if (LS_DEV === true && remainingLocalPushes.length > 0) {
|
|
153
|
-
console.log('localPushesQueue is not empty', remainingLocalPushes.length);
|
|
154
|
-
// oxlint-disable-next-line no-debugger -- intentional breakpoint for unexpected queue state
|
|
155
|
-
debugger;
|
|
156
|
-
}
|
|
157
|
-
const allDeferredsToReject = [
|
|
158
|
-
...deferreds,
|
|
159
|
-
...remainingEventsMatchingGeneration.map(([_, deferred]) => deferred),
|
|
160
|
-
];
|
|
161
|
-
// The rejected batch and its drained same-generation suffix will never advance leader state,
|
|
162
|
-
// so release their sequence-number reservations before clients retry from the authoritative head.
|
|
163
|
-
yield* releasePushReservations([...filteredItems, ...remainingEventsMatchingGeneration], syncState.localHead);
|
|
164
|
-
yield* Effect.forEach(allDeferredsToReject, (deferred) => Deferred.fail(deferred, LeaderAheadError.make({
|
|
165
|
-
minimumExpectedNum: mergeResult.expectedMinimumId,
|
|
166
|
-
providedNum,
|
|
167
|
-
sessionId: newEvents.at(0).sessionId,
|
|
168
|
-
})));
|
|
169
|
-
// In this case we're skipping state update and down/upstream processing
|
|
170
|
-
// We've cleared the local push queue and are now waiting for new local pushes / backend pulls
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
case 'advance': {
|
|
174
|
-
break;
|
|
175
|
-
}
|
|
176
|
-
default: {
|
|
177
|
-
casesHandled(mergeResult);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
// For a local-push advance, `newEvents` and the appended pending suffix describe the same logical
|
|
181
|
-
// events but serve different roles and may be distinct instances. Materialize the retained pending
|
|
182
|
-
// instances so their rollback metadata remains available if a later backend event causes a rebase.
|
|
183
|
-
const acceptedPendingEvents = mergeResult.newSyncState.pending.slice(syncState.pending.length);
|
|
184
|
-
if (acceptedPendingEvents.length !== mergeResult.newEvents.length) {
|
|
185
|
-
return yield* Effect.dieDebugger('Local push events must be retained in pending state');
|
|
186
|
-
}
|
|
187
|
-
yield* materializeEventsBatch({ batchItems: acceptedPendingEvents });
|
|
188
|
-
yield* SubscriptionRef.set(syncStateSref, mergeResult.newSyncState);
|
|
189
|
-
yield* connectedClientSessionPullQueues.offer({
|
|
190
|
-
payload: SyncState.PayloadUpstreamAdvance.make({ newEvents: acceptedPendingEvents }),
|
|
191
|
-
leaderHead: mergeResult.newSyncState.localHead,
|
|
192
|
-
});
|
|
193
|
-
yield* Effect.spanEvent(`push:advance`, {
|
|
194
|
-
batchSize: newEvents.length,
|
|
195
|
-
...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
|
|
196
|
-
});
|
|
197
|
-
// Don't sync client-only events
|
|
198
|
-
const globalOrUnknownEvents = acceptedPendingEvents.filter((e) => !isClientOnlyEvent(e));
|
|
199
|
-
yield* TxQueue.offerAll(syncBackendPushQueue, globalOrUnknownEvents);
|
|
200
|
-
yield* releasePushReservations(filteredItems, mergeResult.newSyncState.localHead);
|
|
201
|
-
// A push is acknowledged only after the complete batch is materialized, published in
|
|
202
|
-
// leader sync state, exposed to sessions, and queued for backend propagation.
|
|
203
|
-
yield* Effect.forEach(deferreds, (deferred) => Deferred.succeed(deferred, void 0));
|
|
204
|
-
}).pipe(localPushBackendPullMutex.withPermits(1));
|
|
30
|
+
const dbEventlog = yield* EventlogSqliteDb.EventlogSqliteDb;
|
|
31
|
+
const dbState = yield* StateSqliteDb.StateSqliteDb;
|
|
32
|
+
const persistence = yield* LeaderPersistence.LeaderPersistence;
|
|
33
|
+
const { devtoolsLatch, shutdownChannel, span, syncBackend } = runtime;
|
|
34
|
+
const mailbox = yield* Queue.unbounded();
|
|
35
|
+
const syncStateRef = yield* SubscriptionRef.make(initialSyncState);
|
|
36
|
+
const connectedSessions = yield* makePullQueueSet;
|
|
37
|
+
const bootDeferred = yield* Deferred.make();
|
|
38
|
+
const startedDeferred = yield* Deferred.make();
|
|
39
|
+
const stoppedDeferred = yield* Deferred.make();
|
|
40
|
+
const nextLocalRequestId = yield* Ref.make(1);
|
|
41
|
+
const nextPullBatchId = yield* Ref.make(1);
|
|
42
|
+
const localRequests = yield* Ref.make({ _tag: 'open', requests: new Map() });
|
|
43
|
+
const pullBatches = yield* Ref.make(new Map());
|
|
44
|
+
const bootStarted = yield* Ref.make(false);
|
|
45
|
+
const pushHandle = yield* FiberHandle.make();
|
|
46
|
+
const pullHandle = yield* FiberHandle.make();
|
|
47
|
+
const backgroundFibers = yield* FiberSet.make();
|
|
48
|
+
const config = {
|
|
49
|
+
livePull,
|
|
50
|
+
localCommitBatchSize: params.localPushBatchSize ?? 10,
|
|
51
|
+
backendPushBatchSize: params.backendPushBatchSize ?? 50,
|
|
52
|
+
onError,
|
|
53
|
+
onBackendIdMismatch,
|
|
54
|
+
localWorkInitiallyBlocked: testing.delays?.localPushProcessing !== undefined,
|
|
55
|
+
};
|
|
56
|
+
const isClientOnlyEvent = (event) => schema.eventsDefsMap.get(event.name)?.options.clientOnly ?? false;
|
|
57
|
+
// `model` is intentionally local rather than a Ref. Only the mailbox loop changes it, apart from boot and
|
|
58
|
+
// operation startup which also run in this scope before their asynchronous work reports back through the mailbox.
|
|
59
|
+
let model = initialModel(config, syncBackend !== undefined, initialSyncState, isClientOnlyEvent);
|
|
60
|
+
const send = (message) => Queue.offer(mailbox, message).pipe(Effect.asVoid);
|
|
61
|
+
const fork = (effect) => FiberSet.run(backgroundFibers, effect).pipe(Effect.asVoid);
|
|
62
|
+
const allocateOperationId = () => {
|
|
63
|
+
// Completion messages carry this id so a late result from an interrupted provider call cannot affect newer work.
|
|
64
|
+
const operationId = model.nextOperationId;
|
|
65
|
+
model = { ...model, nextOperationId: operationId + 1 };
|
|
66
|
+
return operationId;
|
|
67
|
+
};
|
|
68
|
+
const interruptAllWork = Effect.all([
|
|
69
|
+
FiberHandle.clear(pushHandle),
|
|
70
|
+
FiberHandle.clear(pullHandle),
|
|
71
|
+
FiberSet.clear(backgroundFibers),
|
|
72
|
+
interruptAllLocalRequests(localRequests),
|
|
73
|
+
interruptAllPullBatches(pullBatches),
|
|
74
|
+
]);
|
|
75
|
+
const stop = (args) => Effect.gen(function* () {
|
|
76
|
+
if ((yield* Deferred.isDone(stoppedDeferred)) === true)
|
|
77
|
+
return false;
|
|
78
|
+
model = { ...model, lifecycle: args.lifecycle };
|
|
79
|
+
if (args.notify === true && args.error !== undefined) {
|
|
80
|
+
// A broken shutdown channel must not prevent resource cleanup or leave admitted pushes unresolved.
|
|
81
|
+
yield* shutdownChannel
|
|
82
|
+
.send(Schema.is(Shutdown.All)(args.error) === true
|
|
83
|
+
? args.error
|
|
84
|
+
: UnknownError.make({ cause: args.error, note: 'Leader sync loop failed' }))
|
|
85
|
+
.pipe(Effect.exit);
|
|
205
86
|
}
|
|
87
|
+
yield* interruptAllWork;
|
|
88
|
+
yield* Deferred.succeed(stoppedDeferred, void 0);
|
|
89
|
+
return false;
|
|
90
|
+
});
|
|
91
|
+
const stopForSyncFailure = (cause) => stop({ lifecycle: 'failed', error: cause, notify: config.onError === 'shutdown' });
|
|
92
|
+
const startProviderPush = () => Effect.gen(function* () {
|
|
93
|
+
if (model.lifecycle !== 'running' || model.push._tag !== 'idle')
|
|
94
|
+
return;
|
|
95
|
+
if (model.push.queued.length === 0)
|
|
96
|
+
return;
|
|
97
|
+
const batch = model.push.queued.slice(0, config.backendPushBatchSize);
|
|
98
|
+
yield* runPushOperation({ attempt: 0, batch, queued: model.push.queued.slice(batch.length) });
|
|
206
99
|
});
|
|
207
|
-
|
|
100
|
+
/** Starts a provider push for `batch`. A retry reuses it with the attempt count of the failed operation. */
|
|
101
|
+
const runPushOperation = (push) => Effect.gen(function* () {
|
|
102
|
+
if (syncBackend === undefined)
|
|
103
|
+
return;
|
|
104
|
+
const operationId = allocateOperationId();
|
|
105
|
+
model = {
|
|
106
|
+
...model,
|
|
107
|
+
push: { _tag: 'in-flight', operationId, attempt: push.attempt, batch: push.batch, queued: push.queued },
|
|
108
|
+
};
|
|
109
|
+
yield* FiberHandle.run(pushHandle, runProviderPush({ operationId, attempt: push.attempt, batch: push.batch }, syncBackend, devtoolsLatch, send)).pipe(Effect.asVoid);
|
|
110
|
+
});
|
|
111
|
+
/**
|
|
112
|
+
* Waits before retrying an offline pull. A false→true connectivity transition wakes the retry immediately; a jittered,
|
|
113
|
+
* capped fallback timer covers connectivity that stays stale-true. Resolves `true` when woken by a reconnect.
|
|
114
|
+
*/
|
|
115
|
+
const awaitPullRetry = (attempt) => Effect.gen(function* () {
|
|
116
|
+
const jitteredMs = retryDelay(attempt) * (yield* Random.nextBetween(0.8, 1.2));
|
|
117
|
+
const fallbackMs = testing.delays?.backendPullReconnect?.(jitteredMs) ?? jitteredMs;
|
|
208
118
|
if (syncBackend === undefined)
|
|
119
|
+
return yield* Effect.sleep(Duration.millis(fallbackMs)).pipe(Effect.as(false));
|
|
120
|
+
const waitHook = testing.hooks?.backendPullReconnectWait;
|
|
121
|
+
const changes = SubscriptionRef.changes(syncBackend.isConnected);
|
|
122
|
+
const observed = waitHook === undefined
|
|
123
|
+
? changes
|
|
124
|
+
: changes.pipe(Stream.tap((isConnected) => waitHook({ isConnected, fallbackMs })));
|
|
125
|
+
// A stale initial `true` is not a reconnect: wait for false→true, even while the fallback timer is pending.
|
|
126
|
+
return yield* observed.pipe(Stream.dropWhile((isConnected) => isConnected === true), Stream.filter((isConnected) => isConnected === true), Stream.runHead, Effect.as(true), Effect.timeoutOrElse({ duration: Duration.millis(fallbackMs), orElse: () => Effect.succeed(false) }));
|
|
127
|
+
});
|
|
128
|
+
const startProviderPull = (attempt) => Effect.gen(function* () {
|
|
129
|
+
if (syncBackend === undefined || model.lifecycle !== 'running')
|
|
209
130
|
return;
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
131
|
+
const pullId = allocateOperationId();
|
|
132
|
+
model = { ...model, pull: { _tag: 'streaming', pullId, pagination: 'between-pages', attempt } };
|
|
133
|
+
yield* FiberHandle.run(pullHandle, runProviderPull({
|
|
134
|
+
pullId,
|
|
135
|
+
cursor: model.syncState.upstreamHead,
|
|
136
|
+
live: config.livePull,
|
|
137
|
+
syncBackend,
|
|
138
|
+
devtoolsLatch,
|
|
139
|
+
dbEventlog,
|
|
140
|
+
pullBatches,
|
|
141
|
+
nextPullBatchId,
|
|
142
|
+
initialBlockingSyncContext,
|
|
143
|
+
send,
|
|
144
|
+
})).pipe(Effect.asVoid);
|
|
145
|
+
});
|
|
146
|
+
const replacePushPlan = (replacement) => Effect.gen(function* () {
|
|
147
|
+
if (model.push._tag === 'disabled')
|
|
148
|
+
return;
|
|
149
|
+
const inFlight = model.push._tag === 'in-flight';
|
|
150
|
+
// An upstream rebase may have changed every pending sequence number. Rebuild the provider queue from the
|
|
151
|
+
// committed sync state instead of trying to patch the old plan.
|
|
152
|
+
model = { ...model, push: { _tag: 'idle', queued: replacement } };
|
|
153
|
+
if (inFlight === true)
|
|
154
|
+
yield* FiberHandle.clear(pushHandle);
|
|
155
|
+
yield* startProviderPush();
|
|
156
|
+
});
|
|
157
|
+
const publish = (args) => Effect.gen(function* () {
|
|
158
|
+
model = { ...model, syncState: args.syncState };
|
|
159
|
+
yield* SubscriptionRef.set(syncStateRef, args.syncState);
|
|
160
|
+
yield* connectedSessions.offer({
|
|
161
|
+
payload: args.payload,
|
|
162
|
+
globalHead: args.syncState.upstreamHead,
|
|
163
|
+
leaderHead: args.syncState.localHead,
|
|
164
|
+
materializerHashes: args.materializerHashes,
|
|
216
165
|
});
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
166
|
+
});
|
|
167
|
+
const processLocalBatch = (items) => Effect.gen(function* () {
|
|
168
|
+
const mergeExit = yield* SyncState.merge({
|
|
169
|
+
syncState: model.syncState,
|
|
170
|
+
payload: { _tag: 'local-push', newEvents: items.map((item) => item.event) },
|
|
171
|
+
isClientOnlyEvent,
|
|
172
|
+
isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
|
|
173
|
+
}).pipe(Effect.exit);
|
|
174
|
+
if (Exit.isFailure(mergeExit) === true)
|
|
175
|
+
return yield* stopForSyncFailure(Cause.squash(mergeExit.cause));
|
|
176
|
+
const merge = mergeExit.value;
|
|
177
|
+
if (merge._tag === 'reject') {
|
|
178
|
+
// Later events in the same generation were numbered on top of this rejected batch, so they cannot remain
|
|
179
|
+
// valid on their own. Reject them together and let the session produce a fresh sequence.
|
|
180
|
+
const generation = items[0]?.event.seqNum.rebaseGeneration;
|
|
181
|
+
const queuedSameGeneration = model.localQueue.filter((item) => item.event.seqNum.rebaseGeneration === generation);
|
|
182
|
+
const rejectedItems = [...items, ...queuedSameGeneration];
|
|
183
|
+
const rejectedKeys = new Set(rejectedItems.map(localItemKey));
|
|
184
|
+
const firstEvent = items[0]?.event;
|
|
185
|
+
model = {
|
|
186
|
+
...model,
|
|
187
|
+
localQueue: model.localQueue.filter((item) => !rejectedKeys.has(localItemKey(item))),
|
|
188
|
+
};
|
|
189
|
+
if (firstEvent !== undefined) {
|
|
190
|
+
const error = new LeaderAheadError({
|
|
191
|
+
minimumExpectedNum: merge.expectedMinimumId,
|
|
192
|
+
providedNum: firstEvent.seqNum,
|
|
193
|
+
sessionId: firstEvent.sessionId,
|
|
194
|
+
});
|
|
195
|
+
yield* rejectLocalItems(localRequests, rejectedItems.map((item) => ({ item, error })));
|
|
221
196
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
197
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
if (merge._tag === 'rebase')
|
|
201
|
+
return yield* stopForSyncFailure(new Error('Local push required rebase'));
|
|
202
|
+
// Commit the events retained by the merge, not the input objects. This is the proposed state transition that
|
|
203
|
+
// LeaderPersistence must either make durable as a whole or reject.
|
|
204
|
+
const events = merge.newSyncState.pending.slice(model.syncState.pending.length);
|
|
205
|
+
if (events.length !== merge.newEvents.length) {
|
|
206
|
+
return yield* stopForSyncFailure(new Error('Local push was not retained as pending'));
|
|
207
|
+
}
|
|
208
|
+
const persistExit = yield* persistence.persistLocal({ events }).pipe(Effect.exit);
|
|
209
|
+
if (Exit.isFailure(persistExit) === true)
|
|
210
|
+
return yield* stopForSyncFailure(Cause.squash(persistExit.cause));
|
|
211
|
+
const receipt = persistExit.value;
|
|
212
|
+
if (EventSequenceNumber.Client.isEqual(receipt.stateHead, merge.newSyncState.localHead) === false) {
|
|
213
|
+
return yield* stopForSyncFailure({
|
|
214
|
+
_tag: 'PersistReceiptMismatch',
|
|
215
|
+
expectedStateHead: merge.newSyncState.localHead,
|
|
216
|
+
receipt,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
yield* publish({
|
|
220
|
+
syncState: merge.newSyncState,
|
|
221
|
+
payload: SyncState.PayloadUpstreamAdvance.make({ newEvents: receipt.persistedEvents }),
|
|
222
|
+
materializerHashes: receipt.materializerHashes,
|
|
223
|
+
});
|
|
224
|
+
model = enqueuePushEvents(model, receipt.persistedEvents.filter((event) => !isClientOnlyEvent(event)));
|
|
225
|
+
yield* startProviderPush();
|
|
226
|
+
yield* completeLocalItems(localRequests, items);
|
|
227
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
228
|
+
return true;
|
|
229
|
+
});
|
|
230
|
+
const processUpstreamBatch = (batch) => Effect.gen(function* () {
|
|
231
|
+
const mergeExit = yield* SyncState.merge({
|
|
232
|
+
syncState: model.syncState,
|
|
233
|
+
payload: SyncState.PayloadUpstreamAdvance.make({ newEvents: batch.events }),
|
|
234
|
+
isClientOnlyEvent,
|
|
235
|
+
isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
|
|
236
|
+
ignoreClientOnlyEvents: true,
|
|
237
|
+
}).pipe(Effect.exit);
|
|
238
|
+
if (Exit.isFailure(mergeExit) === true)
|
|
239
|
+
return yield* stopForSyncFailure(Cause.squash(mergeExit.cause));
|
|
240
|
+
const merge = mergeExit.value;
|
|
241
|
+
if (merge._tag === 'reject')
|
|
242
|
+
return yield* stopForSyncFailure(new Error('Upstream batch rejected'));
|
|
243
|
+
const rollbackEvents = merge._tag === 'rebase' ? merge.rollbackEvents : [];
|
|
244
|
+
const confirmedEvents = merge._tag === 'advance' ? merge.confirmedEvents : [];
|
|
245
|
+
const backendHead = batch.events.at(-1)?.seqNum;
|
|
246
|
+
if (backendHead === undefined)
|
|
247
|
+
return yield* stopForSyncFailure(new Error('Upstream batch has no head'));
|
|
248
|
+
const persistExit = yield* persistence
|
|
249
|
+
.persistUpstream({
|
|
250
|
+
pulledEvents: batch.pulledEvents,
|
|
251
|
+
events: merge.newEvents,
|
|
252
|
+
rollbackEvents,
|
|
253
|
+
confirmedEvents,
|
|
254
|
+
backendHead,
|
|
255
|
+
})
|
|
256
|
+
.pipe(Effect.exit);
|
|
257
|
+
if (Exit.isFailure(persistExit) === true)
|
|
258
|
+
return yield* stopForSyncFailure(Cause.squash(persistExit.cause));
|
|
259
|
+
const receipt = persistExit.value;
|
|
260
|
+
// The backend reports confirmed events without their local rebase generation, so confirming a pending event
|
|
261
|
+
// that was rebased locally leaves the persisted state head at the same DAG position with a higher generation.
|
|
262
|
+
if (LeaderPersistence.isSameSequencePosition(receipt.stateHead, merge.newSyncState.localHead) === false ||
|
|
263
|
+
EventSequenceNumber.Client.isEqual(receipt.backendHead, backendHead) === false) {
|
|
264
|
+
return yield* stopForSyncFailure({
|
|
265
|
+
_tag: 'PersistReceiptMismatch',
|
|
266
|
+
expectedStateHead: merge.newSyncState.localHead,
|
|
267
|
+
expectedBackendHead: backendHead,
|
|
268
|
+
receipt,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
const payload = merge._tag === 'rebase'
|
|
272
|
+
? SyncState.PayloadUpstreamRebase.make({ rollbackEvents, newEvents: receipt.persistedEvents })
|
|
273
|
+
: SyncState.PayloadUpstreamAdvance.make({ newEvents: receipt.persistedEvents });
|
|
274
|
+
yield* publish({ syncState: merge.newSyncState, payload, materializerHashes: receipt.materializerHashes });
|
|
275
|
+
yield* Effect.forEach(batch.batchIds, (batchId) => completePullBatch(pullBatches, batchId), { discard: true });
|
|
276
|
+
yield* replacePushPlan(merge.newSyncState.pending.filter((event) => !isClientOnlyEvent(event)));
|
|
277
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
278
|
+
return true;
|
|
279
|
+
});
|
|
280
|
+
const processNextWork = () => Effect.gen(function* () {
|
|
281
|
+
if (model.lifecycle !== 'running')
|
|
282
|
+
return true;
|
|
283
|
+
// Apply backend truth before more local work. This avoids assigning local events on top of a head that is
|
|
284
|
+
// already known to need an upstream advance or rebase.
|
|
285
|
+
const upstream = coalesceUpstreamBatches(model.upstreamQueue);
|
|
286
|
+
if (upstream !== undefined) {
|
|
287
|
+
model = { ...model, upstreamQueue: model.upstreamQueue.slice(upstream.batchIds.length) };
|
|
288
|
+
return yield* processUpstreamBatch(upstream);
|
|
289
|
+
}
|
|
290
|
+
// When a backend page says another page follows, keep local work paused until that page arrives. Together the
|
|
291
|
+
// pages describe one uninterrupted upstream advance.
|
|
292
|
+
if (model.pull._tag === 'streaming' && model.pull.pagination === 'more-expected')
|
|
293
|
+
return true;
|
|
294
|
+
if (model.localWorkEnabled === false || model.localQueue.length === 0)
|
|
295
|
+
return true;
|
|
296
|
+
const selected = model.localQueue.slice(0, config.localCommitBatchSize);
|
|
297
|
+
const selectedKeys = new Set(selected.map(localItemKey));
|
|
298
|
+
const remaining = model.localQueue.filter((item) => !selectedKeys.has(localItemKey(item)));
|
|
299
|
+
const currentGeneration = model.syncState.localHead.rebaseGeneration;
|
|
300
|
+
const staleItems = selected.filter((item) => item.event.seqNum.rebaseGeneration < currentGeneration);
|
|
301
|
+
const activeItems = selected.filter((item) => item.event.seqNum.rebaseGeneration >= currentGeneration);
|
|
302
|
+
model = { ...model, localQueue: remaining };
|
|
303
|
+
if (staleItems.length > 0) {
|
|
304
|
+
model = { ...model, localQueue: [...activeItems, ...remaining] };
|
|
305
|
+
yield* rejectLocalItems(localRequests, staleItems.map((item) => ({
|
|
306
|
+
item,
|
|
307
|
+
error: new StaleRebaseGenerationError({
|
|
308
|
+
currentRebaseGeneration: currentGeneration,
|
|
309
|
+
providedRebaseGeneration: item.event.seqNum.rebaseGeneration,
|
|
310
|
+
sessionId: item.event.sessionId,
|
|
311
|
+
}),
|
|
312
|
+
})));
|
|
313
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
314
|
+
return true;
|
|
315
|
+
}
|
|
316
|
+
return yield* processLocalBatch(activeItems);
|
|
317
|
+
});
|
|
318
|
+
const handleBackendMismatch = Effect.fn('@livestore/common:LeaderSyncProcessor:handleBackendIdMismatch')(function* (error, direction) {
|
|
319
|
+
switch (config.onBackendIdMismatch) {
|
|
320
|
+
case 'ignore':
|
|
321
|
+
model = {
|
|
322
|
+
...model,
|
|
323
|
+
...(direction === 'pull'
|
|
324
|
+
? { pull: { _tag: 'completed' } }
|
|
325
|
+
: { push: { _tag: 'disabled' } }),
|
|
326
|
+
};
|
|
327
|
+
if (direction === 'pull')
|
|
328
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
329
|
+
return true;
|
|
330
|
+
case 'shutdown':
|
|
331
|
+
yield* Effect.logWarning('Sync backend identity changed (backend was reset). Shutting down without clearing local storage.', error);
|
|
332
|
+
return yield* stop({ lifecycle: 'failed', error, notify: true });
|
|
333
|
+
case 'reset': {
|
|
334
|
+
yield* Effect.logWarning('Sync backend identity changed (backend was reset). Clearing local storage and shutting down.', error);
|
|
335
|
+
// Stop all work that could still touch the databases before clearing them.
|
|
336
|
+
model = { ...model, lifecycle: 'stopping' };
|
|
337
|
+
yield* interruptAllWork;
|
|
338
|
+
const resetExit = yield* clearLocalDatabases({ dbEventlog, dbState }).pipe(Effect.exit);
|
|
339
|
+
const cause = Exit.isFailure(resetExit) === true
|
|
340
|
+
? Cause.squash(resetExit.cause)
|
|
341
|
+
: IntentionalShutdownCause.make({ reason: 'backend-id-mismatch' });
|
|
342
|
+
return yield* stop({ lifecycle: 'failed', error: cause, notify: true });
|
|
227
343
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
344
|
+
default:
|
|
345
|
+
return casesHandled(config.onBackendIdMismatch);
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
const handleMessage = (message) => Effect.gen(function* () {
|
|
349
|
+
if (message._tag === 'ShutdownRequested') {
|
|
350
|
+
return yield* stop({ lifecycle: 'stopping', notify: false });
|
|
351
|
+
}
|
|
352
|
+
if (message._tag === 'Started') {
|
|
353
|
+
if (model.lifecycle !== 'starting')
|
|
354
|
+
return true;
|
|
355
|
+
// Provider work starts inside a turn, so it cannot interleave with pushes or pages that change the model.
|
|
356
|
+
model = { ...model, lifecycle: 'running' };
|
|
357
|
+
if (syncBackend !== undefined) {
|
|
358
|
+
yield* startProviderPull(0);
|
|
359
|
+
yield* startProviderPush();
|
|
232
360
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
if (model.lifecycle !== 'running') {
|
|
364
|
+
if (message._tag === 'LocalPushRequested')
|
|
365
|
+
yield* interruptLocalRequests(localRequests, [message.requestId]);
|
|
366
|
+
return true;
|
|
367
|
+
}
|
|
368
|
+
switch (message._tag) {
|
|
369
|
+
case 'LocalPushRequested': {
|
|
370
|
+
// The local queue holds admitted but not-yet-committed events. Validating against its tail prevents two
|
|
371
|
+
// callers from being admitted with the same sequence number while they wait in the queue.
|
|
372
|
+
const pushHead = model.localQueue.at(-1)?.event.seqNum ?? model.syncState.localHead;
|
|
373
|
+
const validation = yield* validatePushBatch(message.events, pushHead, isClientOnlyEvent).pipe(Effect.result);
|
|
374
|
+
const items = message.events.map((pushedEvent, index) => ({
|
|
375
|
+
requestId: message.requestId,
|
|
376
|
+
index,
|
|
377
|
+
event: pushedEvent,
|
|
378
|
+
}));
|
|
379
|
+
if (Result.isFailure(validation) === true) {
|
|
380
|
+
yield* rejectLocalItems(localRequests, items.map((item) => ({ item, error: validation.failure })));
|
|
381
|
+
return true;
|
|
248
382
|
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
.set(mergeResult.rollbackEvents[0].parentSeqNum)
|
|
268
|
-
.pipe(Effect.mapError((cause) => MaterializeError.make({ cause })));
|
|
269
|
-
}
|
|
270
|
-
yield* connectedClientSessionPullQueues.offer({
|
|
271
|
-
payload: SyncState.payloadFromMergeResult(mergeResult),
|
|
272
|
-
leaderHead: mergeResult.newSyncState.localHead,
|
|
273
|
-
});
|
|
383
|
+
model = { ...model, localQueue: [...model.localQueue, ...items] };
|
|
384
|
+
yield* testing.hooks?.localPushAdmitted?.(message.events) ?? Effect.void;
|
|
385
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
386
|
+
return true;
|
|
387
|
+
}
|
|
388
|
+
case 'LocalWorkEnabled':
|
|
389
|
+
model = { ...model, localWorkEnabled: true };
|
|
390
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
391
|
+
return true;
|
|
392
|
+
case 'ContinueWork':
|
|
393
|
+
return yield* processNextWork();
|
|
394
|
+
case 'UpstreamBatchReceived': {
|
|
395
|
+
yield* testing.hooks?.upstreamBatchReceived?.(message.batch.events) ?? Effect.void;
|
|
396
|
+
if (model.pull._tag !== 'streaming' || model.pull.pullId !== message.batch.pullId) {
|
|
397
|
+
// The provider fiber waits for every page to be released. Even a late page from an old pull must be
|
|
398
|
+
// released, although it must not change the current model.
|
|
399
|
+
yield* completePullBatch(pullBatches, message.batch.batchId);
|
|
400
|
+
return true;
|
|
274
401
|
}
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
const globalOrUnknownPendingEvents = mergeResult.newSyncState.pending.filter((e) => !isClientOnlyEvent(e));
|
|
282
|
-
yield* restartBackendPushing(globalOrUnknownPendingEvents);
|
|
283
|
-
yield* connectedClientSessionPullQueues.offer({
|
|
284
|
-
payload: SyncState.payloadFromMergeResult(mergeResult),
|
|
285
|
-
leaderHead: mergeResult.newSyncState.localHead,
|
|
286
|
-
});
|
|
287
|
-
if (mergeResult.confirmedEvents.length > 0) {
|
|
288
|
-
// `mergeResult.confirmedEvents` don't contain the correct sync metadata, so we need to use
|
|
289
|
-
// `newEvents` instead which we filter via `mergeResult.confirmedEvents`
|
|
290
|
-
const confirmedNewEvents = newEvents.filter((event) => mergeResult.confirmedEvents.some((confirmedEvent) => EventSequenceNumber.Client.isEqual(event.seqNum, confirmedEvent.seqNum)));
|
|
291
|
-
yield* Eventlog.updateSyncMetadataForDb(dbEventlog, confirmedNewEvents).pipe(Effect.orDieDebugger);
|
|
402
|
+
// Any response, including an empty page, proves backend contact even when connectivity is reported stale.
|
|
403
|
+
const pull = { ...model.pull, attempt: 0 };
|
|
404
|
+
model = { ...model, pull };
|
|
405
|
+
if (message.batch.events.length === 0) {
|
|
406
|
+
if (message.batch.pageInfo._tag === 'NoMore') {
|
|
407
|
+
model = { ...model, pull: { ...pull, pagination: 'between-pages' } };
|
|
292
408
|
}
|
|
409
|
+
yield* completePullBatch(pullBatches, message.batch.batchId);
|
|
410
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
411
|
+
return true;
|
|
293
412
|
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
yield*
|
|
303
|
-
|
|
304
|
-
if (Exit.isFailure(chunkExit) === true) {
|
|
305
|
-
yield* releasePullMutexIfHeld;
|
|
306
|
-
return yield* Effect.failCause(chunkExit.cause);
|
|
307
|
-
}
|
|
308
|
-
if (isPullPaginationComplete(pageInfo) === true) {
|
|
309
|
-
yield* releasePullMutexIfHeld;
|
|
310
|
-
}
|
|
311
|
-
});
|
|
312
|
-
const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(Effect.orDieDebugger);
|
|
313
|
-
const cursorInfo = yield* Eventlog.getSyncBackendCursorInfoForDb(dbEventlog, {
|
|
314
|
-
remoteHead: syncState.upstreamHead.global,
|
|
315
|
-
});
|
|
316
|
-
const hashMaterializerResult = makeMaterializerHash({ schema, dbState });
|
|
317
|
-
yield* syncBackend.pull(cursorInfo, { live: livePull }).pipe(
|
|
318
|
-
// TODO only take from queue while connected
|
|
319
|
-
Stream.tap(({ batch, pageInfo }) => Effect.gen(function* () {
|
|
320
|
-
// Any response (including an empty batch) proves backend contact, even with stale connectivity.
|
|
321
|
-
onPullSuccess();
|
|
322
|
-
// NOTE we only want to take process events when the sync backend is connected
|
|
323
|
-
// (e.g. needed for simulating being offline)
|
|
324
|
-
// TODO remove when there's a better way to handle this in stream above
|
|
325
|
-
yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true);
|
|
326
|
-
yield* onNewPullChunk(batch.map((_) => LiveStoreEvent.Client.EncodedWithMeta.fromGlobal(_.eventEncoded, {
|
|
327
|
-
syncMetadata: _.metadata,
|
|
328
|
-
// 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
|
|
329
|
-
// This is a bug and needs to be fixed https://github.com/livestorejs/livestore/issues/503#issuecomment-3114533165
|
|
330
|
-
materializerHashLeader: hashMaterializerResult(LiveStoreEvent.Global.toClientEncoded(_.eventEncoded)),
|
|
331
|
-
materializerHashSession: Option.none(),
|
|
332
|
-
})), pageInfo);
|
|
333
|
-
yield* initialBlockingSyncContext.update({ processed: batch.length, pageInfo });
|
|
334
|
-
})), Stream.runDrain, Effect.interruptible, Effect.ensuring(releasePullMutexIfHeld));
|
|
335
|
-
// Should only ever happen when livePull is false
|
|
336
|
-
yield* Effect.logDebug('backend-pulling finished', { livePull });
|
|
337
|
-
});
|
|
338
|
-
const backgroundBackendPushing = Effect.gen(function* () {
|
|
339
|
-
if (syncBackend === undefined)
|
|
340
|
-
return;
|
|
341
|
-
while (true) {
|
|
342
|
-
yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true);
|
|
343
|
-
const queueItems = yield* TxQueue.takeBetween(syncBackendPushQueue, 1, backendPushBatchSize);
|
|
344
|
-
yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true);
|
|
345
|
-
if (devtoolsLatch !== undefined) {
|
|
346
|
-
yield* devtoolsLatch.await;
|
|
413
|
+
model = {
|
|
414
|
+
...model,
|
|
415
|
+
pull: {
|
|
416
|
+
...pull,
|
|
417
|
+
pagination: message.batch.pageInfo._tag === 'NoMore' ? 'between-pages' : 'more-expected',
|
|
418
|
+
},
|
|
419
|
+
upstreamQueue: [...model.upstreamQueue, message.batch],
|
|
420
|
+
};
|
|
421
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
422
|
+
return true;
|
|
347
423
|
}
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
// Push with declarative retry/backoff using Effect schedules
|
|
353
|
-
// - Exponential backoff starting at 1s and doubling (1s, 2s, 4s, 8s, 16s, 30s ...)
|
|
354
|
-
// - Delay clamped at 30s (continues retrying at 30s)
|
|
355
|
-
// - Resets automatically after successful push
|
|
356
|
-
// TODO(metrics): expose counters/gauges for retry attempts and queue health via devtools/metrics
|
|
357
|
-
yield* Effect.gen(function* () {
|
|
358
|
-
const iteration = yield* Schedule.CurrentMetadata;
|
|
359
|
-
const pushResult = yield* syncBackend.push(queueItems.map((_) => _.toGlobal())).pipe(Effect.result);
|
|
360
|
-
const retries = iteration.attempt;
|
|
361
|
-
if (retries > 0 && Result.isSuccess(pushResult) === true) {
|
|
362
|
-
yield* Effect.spanEvent('backend-push-retry-success', { retries, batchSize: queueItems.length });
|
|
424
|
+
case 'PullCompleted':
|
|
425
|
+
if (model.pull._tag === 'streaming' && model.pull.pullId === message.pullId) {
|
|
426
|
+
model = { ...model, pull: { _tag: 'completed' } };
|
|
427
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
363
428
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
const
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
return yield* error;
|
|
429
|
+
return true;
|
|
430
|
+
case 'PullFailed':
|
|
431
|
+
if (model.pull._tag !== 'streaming' || model.pull.pullId !== message.pullId)
|
|
432
|
+
return true;
|
|
433
|
+
if (message.error._tag === 'IsOfflineError') {
|
|
434
|
+
const retryId = allocateOperationId();
|
|
435
|
+
const attempt = model.pull.attempt + 1;
|
|
436
|
+
model = { ...model, pull: { _tag: 'retry-wait', retryId, attempt } };
|
|
437
|
+
yield* fork(awaitPullRetry(attempt).pipe(Effect.flatMap((reconnected) => send({ _tag: 'PullRetryElapsed', retryId, reconnected }))));
|
|
438
|
+
return true;
|
|
439
|
+
}
|
|
440
|
+
if (message.error._tag === 'BackendIdMismatchError')
|
|
441
|
+
return yield* handleBackendMismatch(message.error, 'pull');
|
|
442
|
+
if (config.onError === 'shutdown')
|
|
443
|
+
return yield* stop({ lifecycle: 'failed', error: message.error, notify: true });
|
|
444
|
+
model = { ...model, pull: { _tag: 'completed' } };
|
|
445
|
+
yield* send({ _tag: 'ContinueWork' });
|
|
446
|
+
return true;
|
|
447
|
+
case 'PullRetryElapsed':
|
|
448
|
+
if (model.pull._tag === 'retry-wait' && model.pull.retryId === message.retryId) {
|
|
449
|
+
// A reconnect proves the backend is reachable again, so the next outage starts from the shortest delay.
|
|
450
|
+
yield* startProviderPull(message.reconnected === true ? 0 : model.pull.attempt);
|
|
451
|
+
}
|
|
452
|
+
return true;
|
|
453
|
+
case 'PushSucceeded':
|
|
454
|
+
if (model.push._tag === 'in-flight' && model.push.operationId === message.operationId) {
|
|
455
|
+
model = {
|
|
456
|
+
...model,
|
|
457
|
+
push: { _tag: 'idle', queued: model.push.queued },
|
|
458
|
+
};
|
|
459
|
+
yield* startProviderPush();
|
|
460
|
+
}
|
|
461
|
+
return true;
|
|
462
|
+
case 'PushFailed':
|
|
463
|
+
if (model.push._tag !== 'in-flight' || model.push.operationId !== message.operationId)
|
|
464
|
+
return true;
|
|
465
|
+
if (message.error._tag === 'ServerAheadError') {
|
|
466
|
+
// Pulling first will either confirm or rebase these events. Keep them queued, but do not retry the same
|
|
467
|
+
// stale batch until the pull has established the new durable plan.
|
|
468
|
+
model = {
|
|
469
|
+
...model,
|
|
470
|
+
push: {
|
|
471
|
+
_tag: 'awaiting-pull',
|
|
472
|
+
queued: [...model.push.batch, ...model.push.queued],
|
|
473
|
+
},
|
|
474
|
+
};
|
|
475
|
+
return true;
|
|
476
|
+
}
|
|
477
|
+
if (message.error._tag === 'BackendIdMismatchError')
|
|
478
|
+
return yield* handleBackendMismatch(message.error, 'push');
|
|
479
|
+
// Provider errors are retried indefinitely. A defect is not a provider error: like a failed pull, it follows
|
|
480
|
+
// `onError`, so a deterministic defect stops the leader instead of retrying forever.
|
|
481
|
+
if (message.defect === true && config.onError === 'shutdown')
|
|
482
|
+
return yield* stop({ lifecycle: 'failed', error: message.error, notify: true });
|
|
483
|
+
const retryId = allocateOperationId();
|
|
484
|
+
const attempt = model.push.attempt + 1;
|
|
485
|
+
model = {
|
|
486
|
+
...model,
|
|
487
|
+
push: {
|
|
488
|
+
_tag: 'retry-wait',
|
|
489
|
+
retryId,
|
|
490
|
+
attempt,
|
|
491
|
+
batch: model.push.batch,
|
|
492
|
+
queued: model.push.queued,
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
yield* fork(Effect.sleep(Duration.millis(retryDelay(attempt))).pipe(Effect.andThen(send({ _tag: 'PushRetryElapsed', retryId }))));
|
|
496
|
+
return true;
|
|
497
|
+
case 'PushRetryElapsed':
|
|
498
|
+
if (model.push._tag === 'retry-wait' && model.push.retryId === message.retryId) {
|
|
499
|
+
const { attempt, batch, queued } = model.push;
|
|
500
|
+
yield* runPushOperation({ attempt, batch, queued });
|
|
377
501
|
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
schedule: Schedule.exponential(Duration.seconds(1)).pipe(Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.min(duration, Duration.seconds(30))))),
|
|
382
|
-
while: (error) => error._tag === 'IsOfflineError' || error._tag === 'UnknownError',
|
|
383
|
-
}),
|
|
384
|
-
// This is needed to narrow the Error type. Our retry policy runs indefinitely, but Effect.retry does not narrow the Error type.
|
|
385
|
-
Effect.catchIf((error) => error._tag === 'IsOfflineError' || error._tag === 'UnknownError', Effect.die));
|
|
502
|
+
return true;
|
|
503
|
+
default:
|
|
504
|
+
return casesHandled(message);
|
|
386
505
|
}
|
|
387
|
-
})
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
// prevents backend reconciliation from changing the fence midway through admission.
|
|
397
|
-
yield* pushAdmissionSemaphore.withPermits(1)(
|
|
398
|
-
// Cancellation must not leave reservations, queue contents, and the admission fence disagreeing.
|
|
399
|
-
Effect.gen(function* () {
|
|
400
|
-
yield* validatePushBatch(newEvents, pushHeadRef.current, isClientOnlyEvent);
|
|
401
|
-
for (const item of items)
|
|
402
|
-
reservedLocalPushItems.add(item);
|
|
403
|
-
yield* TxQueue.offerAll(localPushesQueue, items);
|
|
404
|
-
pushHeadRef.current = newEvents.at(-1).seqNum;
|
|
405
|
-
if (testing.hooks?.localPushAdmitted !== undefined) {
|
|
406
|
-
yield* testing.hooks.localPushAdmitted(newEvents);
|
|
506
|
+
});
|
|
507
|
+
const run = Effect.gen(function* () {
|
|
508
|
+
// This is the only general message consumer and therefore the single owner of transition ordering.
|
|
509
|
+
let running = true;
|
|
510
|
+
while (running === true) {
|
|
511
|
+
const message = yield* Queue.take(mailbox);
|
|
512
|
+
const exit = yield* handleMessage(message).pipe(Effect.exit);
|
|
513
|
+
if (Exit.isFailure(exit) === true) {
|
|
514
|
+
running = yield* stop({ lifecycle: 'failed', error: Cause.squash(exit.cause), notify: true });
|
|
407
515
|
}
|
|
408
|
-
|
|
409
|
-
|
|
516
|
+
else {
|
|
517
|
+
running = exit.value;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
yield* Queue.shutdown(mailbox);
|
|
521
|
+
});
|
|
522
|
+
const push = (events) => Effect.gen(function* () {
|
|
523
|
+
if (events.length === 0)
|
|
524
|
+
return;
|
|
525
|
+
const requestId = yield* Ref.modify(nextLocalRequestId, (id) => [id, id + 1]);
|
|
526
|
+
const deferred = yield* Deferred.make();
|
|
527
|
+
// Register the acknowledgement before waiting for boot. Shutdown can then interrupt every admitted caller,
|
|
528
|
+
// including one that has not reached the mailbox yet.
|
|
529
|
+
const admitted = yield* Ref.modify(localRequests, (registry) => {
|
|
530
|
+
if (registry._tag === 'closed')
|
|
531
|
+
return [false, registry];
|
|
532
|
+
return [
|
|
533
|
+
true,
|
|
534
|
+
{
|
|
535
|
+
_tag: 'open',
|
|
536
|
+
requests: new Map(registry.requests).set(requestId, { deferred, remaining: events.length }),
|
|
537
|
+
},
|
|
538
|
+
];
|
|
539
|
+
});
|
|
540
|
+
if (admitted === false)
|
|
541
|
+
return yield* Effect.interrupt;
|
|
542
|
+
yield* Deferred.await(startedDeferred);
|
|
543
|
+
yield* send({ _tag: 'LocalPushRequested', requestId, events });
|
|
544
|
+
yield* Deferred.await(deferred);
|
|
410
545
|
}).pipe(Effect.withSpan('@livestore/common:LeaderSyncProcessor:push', {
|
|
411
|
-
attributes: {
|
|
412
|
-
batchSize: newEvents.length,
|
|
413
|
-
batch: TRACE_VERBOSE === true ? newEvents : undefined,
|
|
414
|
-
},
|
|
546
|
+
attributes: { batchSize: events.length, batch: TRACE_VERBOSE === true ? events : undefined },
|
|
415
547
|
links: span !== undefined ? [{ span, attributes: {} }] : undefined,
|
|
416
548
|
}));
|
|
549
|
+
const boot = Effect.gen(function* () {
|
|
550
|
+
const shouldStart = yield* Ref.modify(bootStarted, (started) => [started === false, true]);
|
|
551
|
+
if (shouldStart === false)
|
|
552
|
+
return { initialLeaderHead: yield* Deferred.await(bootDeferred) };
|
|
553
|
+
yield* run.pipe(Effect.forkScoped);
|
|
554
|
+
yield* SubscriptionRef.set(syncStateRef, initialSyncState);
|
|
555
|
+
// The mailbox is FIFO: `Started` is handled before any push released below, and only the mailbox changes the model.
|
|
556
|
+
yield* send({ _tag: 'Started' });
|
|
557
|
+
yield* Deferred.succeed(startedDeferred, void 0);
|
|
558
|
+
if (testing.delays?.localPushProcessing !== undefined) {
|
|
559
|
+
yield* fork(testing.delays.localPushProcessing.pipe(Effect.withSpan('localPushProcessingDelay'), Effect.andThen(send({ _tag: 'LocalWorkEnabled' }))));
|
|
560
|
+
}
|
|
561
|
+
yield* Deferred.succeed(bootDeferred, initialSyncState.localHead);
|
|
562
|
+
yield* Effect.addFinalizer(() => send({ _tag: 'ShutdownRequested', reason: 'scope-closed' }).pipe(Effect.ignore, Effect.andThen(Deferred.await(stoppedDeferred))));
|
|
563
|
+
return { initialLeaderHead: initialSyncState.localHead };
|
|
564
|
+
}).pipe(Effect.withSpanScoped('@livestore/common:LeaderSyncProcessor:boot'), Effect.uninterruptible);
|
|
417
565
|
return LeaderSyncProcessor.of({
|
|
418
566
|
[TypeId]: TypeId,
|
|
419
|
-
|
|
420
|
-
boot: Effect.gen(function* () {
|
|
421
|
-
/** State transitions need to happen atomically, so we use a Ref to track the state */
|
|
422
|
-
yield* SubscriptionRef.set(syncStateSref, initialSyncState);
|
|
423
|
-
// Rehydrate sync queue
|
|
424
|
-
if (initialSyncState.pending.length > 0) {
|
|
425
|
-
const globalOrUnknownPendingEvents = initialSyncState.pending
|
|
426
|
-
// Don't sync client-only events
|
|
427
|
-
.filter((eventEncoded) => !isClientOnlyEvent(eventEncoded));
|
|
428
|
-
if (globalOrUnknownPendingEvents.length > 0) {
|
|
429
|
-
yield* TxQueue.offerAll(syncBackendPushQueue, globalOrUnknownPendingEvents);
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
const handleBackendIdMismatchError = (error) => handleBackendIdMismatch({ error, onBackendIdMismatch, shutdownChannel, dbEventlog, dbState });
|
|
433
|
-
const maybeShutdownOnError = (cause) => Effect.gen(function* () {
|
|
434
|
-
if (onError === 'ignore') {
|
|
435
|
-
if (LS_DEV === true) {
|
|
436
|
-
yield* Effect.logDebug(`Ignoring sync error (${Option.getOrUndefined(Cause.findErrorOption(cause))?._tag ?? cause.toString()})`, Cause.pretty(cause));
|
|
437
|
-
}
|
|
438
|
-
return;
|
|
439
|
-
}
|
|
440
|
-
const error = Option.getOrUndefined(Cause.findErrorOption(cause));
|
|
441
|
-
const errorToSend = error === undefined ? UnknownError.make({ cause }) : error;
|
|
442
|
-
yield* shutdownChannel.send(errorToSend).pipe(Effect.orDie);
|
|
443
|
-
return yield* Effect.failCause(cause).pipe(Effect.orDie);
|
|
444
|
-
});
|
|
445
|
-
yield* backgroundApplyLocalPushes.pipe(Effect.catchCause(maybeShutdownOnError), Effect.forkScoped);
|
|
446
|
-
const backendPushingFiberHandle = yield* FiberHandle.make();
|
|
447
|
-
const backendPushingEffect = backgroundBackendPushing.pipe(Effect.catchTag('BackendIdMismatchError', handleBackendIdMismatchError), Effect.catchCause(maybeShutdownOnError));
|
|
448
|
-
yield* FiberHandle.run(backendPushingFiberHandle, backendPushingEffect);
|
|
449
|
-
let offlinePullFallbackMs = 1_000;
|
|
450
|
-
yield* backgroundBackendPulling({
|
|
451
|
-
onPullSuccess: () => {
|
|
452
|
-
offlinePullFallbackMs = 1_000;
|
|
453
|
-
},
|
|
454
|
-
restartBackendPushing: (filteredRebasedPending) => Effect.gen(function* () {
|
|
455
|
-
// Stop current pushing fiber
|
|
456
|
-
yield* FiberHandle.clear(backendPushingFiberHandle);
|
|
457
|
-
// Reset the sync backend push queue
|
|
458
|
-
yield* TxQueue.clear(syncBackendPushQueue);
|
|
459
|
-
yield* TxQueue.offerAll(syncBackendPushQueue, filteredRebasedPending);
|
|
460
|
-
// Restart pushing fiber
|
|
461
|
-
yield* FiberHandle.run(backendPushingFiberHandle, backendPushingEffect);
|
|
462
|
-
}),
|
|
463
|
-
}).pipe(Effect.tapError((error) => {
|
|
464
|
-
if (error._tag !== 'IsOfflineError' || syncBackend === undefined)
|
|
465
|
-
return Effect.void;
|
|
466
|
-
const isConnected = syncBackend.isConnected;
|
|
467
|
-
return Effect.gen(function* () {
|
|
468
|
-
// Wake immediately on reconnection. Probe on a capped fallback timer if connectivity is stale.
|
|
469
|
-
const jitter = yield* Random.nextBetween(0.8, 1.2);
|
|
470
|
-
const fallbackMs = testing.delays?.backendPullReconnect?.(offlinePullFallbackMs * jitter) ?? offlinePullFallbackMs * jitter;
|
|
471
|
-
offlinePullFallbackMs = Math.min(offlinePullFallbackMs * 2, 30_000);
|
|
472
|
-
// A stale initial true is not a reconnect. Watch false→true even while the fallback timer is pending.
|
|
473
|
-
const waitHook = testing.hooks?.backendPullReconnectWait;
|
|
474
|
-
const changes = SubscriptionRef.changes(isConnected);
|
|
475
|
-
const observedChanges = waitHook === undefined
|
|
476
|
-
? changes
|
|
477
|
-
: changes.pipe(Stream.tap((value) => waitHook({ isConnected: value, fallbackMs })));
|
|
478
|
-
const reconnected = yield* observedChanges.pipe(Stream.dropWhile((value) => value === true), Stream.filter((value) => value === true), Stream.runHead, Effect.as(true), Effect.timeoutOrElse({ duration: fallbackMs, orElse: () => Effect.succeed(false) }));
|
|
479
|
-
if (reconnected === true)
|
|
480
|
-
offlinePullFallbackMs = 1_000;
|
|
481
|
-
});
|
|
482
|
-
}), Effect.retry({
|
|
483
|
-
// The unbounded offline-only retry keeps IsOfflineError out of the terminal error channel.
|
|
484
|
-
until: (error) => error._tag !== 'IsOfflineError',
|
|
485
|
-
}), Effect.catchTag('BackendIdMismatchError', handleBackendIdMismatchError), Effect.catchCause(maybeShutdownOnError),
|
|
486
|
-
// Needed to avoid `Fiber terminated with an unhandled error` logs which seem to happen because of the `Effect.retry` above.
|
|
487
|
-
// This might be a bug in Effect. Only seems to happen in the browser.
|
|
488
|
-
Effect.provideService(References.UnhandledLogLevel, undefined), Effect.forkScoped);
|
|
489
|
-
return { initialLeaderHead: initialSyncState.localHead };
|
|
490
|
-
}).pipe(Effect.withSpanScoped('@livestore/common:LeaderSyncProcessor:boot')),
|
|
567
|
+
boot,
|
|
491
568
|
push,
|
|
492
|
-
pushPartial: ({ event: { name, args }, clientId, sessionId }) => Effect.gen(function* () {
|
|
493
|
-
const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(Effect.orDieDebugger);
|
|
494
|
-
const resolution = yield* resolveEventDef(schema, {
|
|
495
|
-
operation: '@livestore/common:LeaderSyncProcessor:pushPartial',
|
|
496
|
-
event: {
|
|
497
|
-
name,
|
|
498
|
-
args,
|
|
499
|
-
clientId,
|
|
500
|
-
sessionId,
|
|
501
|
-
seqNum: syncState.localHead,
|
|
502
|
-
},
|
|
503
|
-
});
|
|
504
|
-
if (resolution._tag === 'unknown') {
|
|
505
|
-
// Ignore partial pushes for unrecognised events – they are still
|
|
506
|
-
// persisted server-side once a schema update ships.
|
|
507
|
-
return;
|
|
508
|
-
}
|
|
509
|
-
const eventEncoded = new LiveStoreEvent.Client.EncodedWithMeta({
|
|
510
|
-
name,
|
|
511
|
-
args,
|
|
512
|
-
clientId,
|
|
513
|
-
sessionId,
|
|
514
|
-
...EventSequenceNumber.Client.nextPair({
|
|
515
|
-
seqNum: syncState.localHead,
|
|
516
|
-
isClientOnly: resolution.eventDef.options.clientOnly,
|
|
517
|
-
}),
|
|
518
|
-
});
|
|
519
|
-
yield* push([eventEncoded]);
|
|
520
|
-
}).pipe(
|
|
521
|
-
// pushPartial constructs the event sequence number internally, so these errors should never happen.
|
|
522
|
-
Effect.catchIf(isRejectedPushError, Effect.die)),
|
|
523
569
|
pull: ({ cursor }) => Effect.gen(function* () {
|
|
524
|
-
const queue = yield*
|
|
570
|
+
const queue = yield* connectedSessions.makeQueue(cursor);
|
|
525
571
|
return Stream.fromQueue(queue);
|
|
526
572
|
}).pipe(Stream.unwrap),
|
|
527
|
-
|
|
528
|
-
Notes for a potential new `LeaderSyncProcessor.pull` implementation:
|
|
529
|
-
|
|
530
|
-
- Doesn't take cursor but is "atomically called" in the leader during the snapshot phase
|
|
531
|
-
- TODO: how is this done "atomically" in the web adapter where the snapshot is read optimistically?
|
|
532
|
-
- Would require a new kind of "boot-phase" API which is stream based:
|
|
533
|
-
- initial message: state snapshot + seq num head
|
|
534
|
-
- subsequent messages: sync state payloads
|
|
535
|
-
|
|
536
|
-
- alternative: instead of session pulling sync state payloads from leader, we could send
|
|
537
|
-
- events in the "advance" case
|
|
538
|
-
- full new state db snapshot in the "rebase" case
|
|
539
|
-
- downside: importing the snapshot is expensive
|
|
540
|
-
*/
|
|
541
|
-
pullQueue: ({ cursor }) => connectedClientSessionPullQueues.makeQueue(cursor),
|
|
573
|
+
pullQueue: ({ cursor }) => connectedSessions.makeQueue(cursor),
|
|
542
574
|
syncState: Subscribable.make({
|
|
543
|
-
get: SubscriptionRef.get(
|
|
544
|
-
changes: SubscriptionRef.changes(
|
|
575
|
+
get: SubscriptionRef.get(syncStateRef),
|
|
576
|
+
changes: SubscriptionRef.changes(syncStateRef),
|
|
545
577
|
}),
|
|
546
578
|
});
|
|
547
579
|
});
|
|
548
580
|
export const layer = (options) => Layer.effect(LeaderSyncProcessor, make(options));
|
|
549
|
-
|
|
550
|
-
const
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
dbEventlog.execute('COMMIT', undefined); // Commit the transaction
|
|
568
|
-
}).pipe(Effect.uninterruptible, Effect.scoped, Effect.withSpan('@livestore/common:LeaderSyncProcessor:materializeEventItems', {
|
|
569
|
-
attributes: { batchSize: batchItems.length },
|
|
570
|
-
}), Effect.tapCauseLogPretty);
|
|
571
|
-
const trimChangesetRows = (db, newHead) => {
|
|
572
|
-
// Since we're using the session changeset rows to query for the current head,
|
|
573
|
-
// we're keeping at least one row for the current head, and thus are using `<` instead of `<=`
|
|
574
|
-
db.execute(sql `DELETE FROM ${SystemTables.SESSION_CHANGESET_META_TABLE} WHERE seqNumGlobal < ${newHead.global}`);
|
|
581
|
+
/** Pages a pull may read ahead of the page currently being made durable. */
|
|
582
|
+
const MAX_PAGES_AHEAD = 16;
|
|
583
|
+
/**
|
|
584
|
+
* Combines the queued pages at the front of the upstream queue that belong to the same pull. Consecutive pages
|
|
585
|
+
* describe one contiguous stretch of backend history, so merging them is the same upstream advance as applying them
|
|
586
|
+
* one after another, without rebasing pending events and publishing to sessions in between.
|
|
587
|
+
*/
|
|
588
|
+
const coalesceUpstreamBatches = (queue) => {
|
|
589
|
+
const first = queue[0];
|
|
590
|
+
if (first === undefined)
|
|
591
|
+
return undefined;
|
|
592
|
+
const otherPull = queue.findIndex((page) => page.pullId !== first.pullId);
|
|
593
|
+
const pages = otherPull === -1 ? queue : queue.slice(0, otherPull);
|
|
594
|
+
return {
|
|
595
|
+
batchIds: pages.map((page) => page.batchId),
|
|
596
|
+
events: pages.flatMap((page) => page.events),
|
|
597
|
+
pulledEvents: pages.flatMap((page) => page.pulledEvents),
|
|
598
|
+
};
|
|
575
599
|
};
|
|
576
|
-
const
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
};
|
|
601
|
-
}
|
|
602
|
-
else {
|
|
603
|
-
return { payload };
|
|
604
|
-
}
|
|
605
|
-
});
|
|
606
|
-
// console.debug(
|
|
607
|
-
// 'seeding new queue',
|
|
608
|
-
// {
|
|
609
|
-
// cursor,
|
|
610
|
-
// },
|
|
611
|
-
// '\n mergePayloads',
|
|
612
|
-
// ...Array.from(cachedPayloads.entries())
|
|
613
|
-
// .flatMap(([seqNumStr, payloads]) =>
|
|
614
|
-
// payloads.map((payload) => ({ payload, seqNum: EventSequenceNumber.fromString(seqNumStr) })),
|
|
615
|
-
// )
|
|
616
|
-
// .map(({ payload, seqNum }) => [
|
|
617
|
-
// seqNum,
|
|
618
|
-
// payload._tag,
|
|
619
|
-
// 'newEvents',
|
|
620
|
-
// ...payload.newEvents.map((_) => _.toJSON()),
|
|
621
|
-
// 'rollbackEvents',
|
|
622
|
-
// ...(payload._tag === 'upstream-rebase' ? payload.rollbackEvents.map((_) => _.toJSON()) : []),
|
|
623
|
-
// ]),
|
|
624
|
-
// '\n payloadsSinceCursor',
|
|
625
|
-
// ...payloadsSinceCursor.map(({ payload }) => [
|
|
626
|
-
// payload._tag,
|
|
627
|
-
// 'newEvents',
|
|
628
|
-
// ...payload.newEvents.map((_) => _.toJSON()),
|
|
629
|
-
// 'rollbackEvents',
|
|
630
|
-
// ...(payload._tag === 'upstream-rebase' ? payload.rollbackEvents.map((_) => _.toJSON()) : []),
|
|
631
|
-
// ]),
|
|
632
|
-
// )
|
|
633
|
-
yield* Queue.offerAll(queue, payloadsSinceCursor);
|
|
634
|
-
set.add(queue);
|
|
635
|
-
return queue;
|
|
600
|
+
const initialModel = (config, backendEnabled, initialSyncState, isClientOnlyEvent) => ({
|
|
601
|
+
lifecycle: 'starting',
|
|
602
|
+
syncState: initialSyncState,
|
|
603
|
+
pull: backendEnabled === true ? { _tag: 'completed' } : { _tag: 'disabled' },
|
|
604
|
+
push: backendEnabled === true
|
|
605
|
+
? { _tag: 'idle', queued: initialSyncState.pending.filter((event) => !isClientOnlyEvent(event)) }
|
|
606
|
+
: { _tag: 'disabled' },
|
|
607
|
+
localQueue: [],
|
|
608
|
+
upstreamQueue: [],
|
|
609
|
+
localWorkEnabled: config.localWorkInitiallyBlocked === false,
|
|
610
|
+
nextOperationId: 1,
|
|
611
|
+
});
|
|
612
|
+
const enqueuePushEvents = (model, events) => {
|
|
613
|
+
if (model.push._tag === 'disabled' || events.length === 0)
|
|
614
|
+
return model;
|
|
615
|
+
return { ...model, push: { ...model.push, queued: [...model.push.queued, ...events] } };
|
|
616
|
+
};
|
|
617
|
+
const runProviderPush = (operation, syncBackend, devtoolsLatch, send) => Effect.gen(function* () {
|
|
618
|
+
yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (connected) => connected === true);
|
|
619
|
+
if (devtoolsLatch !== undefined)
|
|
620
|
+
yield* devtoolsLatch.await;
|
|
621
|
+
yield* Effect.spanEvent('backend-push', {
|
|
622
|
+
batchSize: operation.batch.length,
|
|
623
|
+
...(TRACE_VERBOSE === true ? { batch: jsonStringify(operation.batch) } : {}),
|
|
636
624
|
});
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
625
|
+
yield* syncBackend.push(operation.batch.map(LiveStoreEvent.Client.toGlobal));
|
|
626
|
+
}).pipe(Effect.matchEffect({
|
|
627
|
+
onFailure: (error) => Effect.spanEvent('backend-push-error', {
|
|
628
|
+
error: error.toString(),
|
|
629
|
+
retries: operation.attempt,
|
|
630
|
+
batchSize: operation.batch.length,
|
|
631
|
+
}).pipe(Effect.andThen(send({ _tag: 'PushFailed', operationId: operation.operationId, error, defect: false }))),
|
|
632
|
+
onSuccess: () => Effect.gen(function* () {
|
|
633
|
+
if (operation.attempt > 0) {
|
|
634
|
+
yield* Effect.spanEvent('backend-push-retry-success', {
|
|
635
|
+
retries: operation.attempt,
|
|
636
|
+
batchSize: operation.batch.length,
|
|
637
|
+
});
|
|
649
638
|
}
|
|
650
|
-
|
|
651
|
-
|
|
639
|
+
yield* send({ _tag: 'PushSucceeded', operationId: operation.operationId });
|
|
640
|
+
}),
|
|
641
|
+
}), Effect.catchCause((cause) => send({
|
|
642
|
+
_tag: 'PushFailed',
|
|
643
|
+
operationId: operation.operationId,
|
|
644
|
+
error: UnknownError.make({ cause, note: 'Sync backend push defected' }),
|
|
645
|
+
defect: Cause.hasInterruptsOnly(cause) === false,
|
|
646
|
+
})), Effect.interruptible);
|
|
647
|
+
const runProviderPull = ({ pullId, cursor, live, syncBackend, devtoolsLatch, dbEventlog, pullBatches, nextPullBatchId, initialBlockingSyncContext, send, }) => Effect.gen(function* () {
|
|
648
|
+
// Pages handed to the mailbox but not yet durable. Offering blocks while MAX_PAGES_AHEAD are waiting, which is
|
|
649
|
+
// the provider stream's backpressure. A child fiber awaits them in order and reports initial-sync progress.
|
|
650
|
+
const outstanding = yield* Queue.bounded(MAX_PAGES_AHEAD);
|
|
651
|
+
const allDurable = yield* Deferred.make();
|
|
652
|
+
yield* Effect.forkChild(Effect.gen(function* () {
|
|
653
|
+
while (true) {
|
|
654
|
+
const page = yield* Queue.take(outstanding);
|
|
655
|
+
if (page === 'end')
|
|
656
|
+
return yield* Deferred.succeed(allDurable, undefined);
|
|
657
|
+
yield* Deferred.await(page.completion);
|
|
658
|
+
yield* initialBlockingSyncContext.update({ processed: page.processed, pageInfo: page.pageInfo });
|
|
652
659
|
}
|
|
653
|
-
});
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
660
|
+
}));
|
|
661
|
+
yield* Effect.gen(function* () {
|
|
662
|
+
const cursorInfo = yield* Eventlog.getSyncBackendCursorInfoForDb(dbEventlog, { remoteHead: cursor.global });
|
|
663
|
+
yield* syncBackend.pull(cursorInfo, { live }).pipe(Stream.runForEach(({ batch, pageInfo }) => Effect.gen(function* () {
|
|
664
|
+
yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (connected) => connected === true);
|
|
665
|
+
if (devtoolsLatch !== undefined)
|
|
666
|
+
yield* devtoolsLatch.await;
|
|
667
|
+
const batchId = yield* Ref.modify(nextPullBatchId, (id) => [id, id + 1]);
|
|
668
|
+
const completion = yield* Deferred.make();
|
|
669
|
+
yield* Ref.update(pullBatches, (batches) => new Map(batches).set(batchId, completion));
|
|
670
|
+
const pulledEvents = batch.map((item) => ({
|
|
671
|
+
event: LiveStoreEvent.Client.fromGlobal(item.eventEncoded),
|
|
672
|
+
syncMetadata: item.metadata,
|
|
673
|
+
}));
|
|
674
|
+
yield* send({
|
|
675
|
+
_tag: 'UpstreamBatchReceived',
|
|
676
|
+
batch: { pullId, batchId, events: pulledEvents.map(({ event }) => event), pulledEvents, pageInfo },
|
|
677
|
+
});
|
|
678
|
+
// Read on without waiting for this page to become durable (up to MAX_PAGES_AHEAD). Pages that are already
|
|
679
|
+
// available, such as a backlog released on reconnect, then queue up while the mailbox applies one page, and
|
|
680
|
+
// it applies the queued ones as one upstream batch: a leader with pending events rebases them once instead
|
|
681
|
+
// of once per page, and every session applies one rebase instead of many. Pages are still applied in order,
|
|
682
|
+
// and the persisted backend cursor is the head of the last page applied.
|
|
683
|
+
yield* Queue.offer(outstanding, { completion, processed: batch.length, pageInfo });
|
|
684
|
+
yield* Effect.yieldNow;
|
|
685
|
+
})));
|
|
686
|
+
}).pipe(Effect.matchEffect({
|
|
687
|
+
onFailure: (error) => send({ _tag: 'PullFailed', pullId, error }),
|
|
688
|
+
onSuccess: () => Effect.void,
|
|
689
|
+
}), Effect.catchCauseIf((cause) => Cause.hasInterruptsOnly(cause) === false, (cause) => send({ _tag: 'PullFailed', pullId, error: UnknownError.make({ cause, note: 'Sync backend pull defected' }) })));
|
|
690
|
+
// Pages sent before a failure are still applied, so keep reporting their progress: one of them may be the `NoMore`
|
|
691
|
+
// page that ends a blocking initial sync. A retry replaces this fiber, which ends the wait.
|
|
692
|
+
yield* Queue.offer(outstanding, 'end');
|
|
693
|
+
yield* Deferred.await(allDurable);
|
|
694
|
+
}).pipe(Effect.withSpan('@livestore/common:LeaderSyncProcessor:backend-pulling'), Effect.ensuring(send({ _tag: 'PullCompleted', pullId })), Effect.interruptible);
|
|
659
695
|
/**
|
|
660
696
|
* Validate a client-provided batch before it is admitted to the leader queue.
|
|
661
697
|
* Ensures the numbers form a strictly increasing chain and that the first
|
|
@@ -706,7 +742,7 @@ const validatePushBatch = (batch, pushHead, isClientOnlyEvent) => Effect.gen(fun
|
|
|
706
742
|
rebaseGeneration: event.seqNum.rebaseGeneration,
|
|
707
743
|
});
|
|
708
744
|
if (EventSequenceNumber.Client.isEqual(event.seqNum, expectedPair.seqNum) === false ||
|
|
709
|
-
isSameSequencePosition(event.parentSeqNum, expectedPair.parentSeqNum) === false) {
|
|
745
|
+
LeaderPersistence.isSameSequencePosition(event.parentSeqNum, expectedPair.parentSeqNum) === false) {
|
|
710
746
|
return yield* NonContiguousBatchError.make({
|
|
711
747
|
expectedSeqNum: expectedPair.seqNum,
|
|
712
748
|
providedSeqNum: event.seqNum,
|
|
@@ -719,59 +755,195 @@ const validatePushBatch = (batch, pushHead, isClientOnlyEvent) => Effect.gen(fun
|
|
|
719
755
|
precedingSeqNum = event.seqNum;
|
|
720
756
|
}
|
|
721
757
|
});
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
758
|
+
const completeLocalItems = (requestsRef, items) => Effect.gen(function* () {
|
|
759
|
+
const counts = countRequestItems(items);
|
|
760
|
+
const completions = [];
|
|
761
|
+
yield* Ref.update(requestsRef, (registry) => {
|
|
762
|
+
if (registry._tag === 'closed')
|
|
763
|
+
return registry;
|
|
764
|
+
const next = new Map(registry.requests);
|
|
765
|
+
for (const [requestId, count] of counts) {
|
|
766
|
+
const request = next.get(requestId);
|
|
767
|
+
if (request === undefined)
|
|
768
|
+
continue;
|
|
769
|
+
const remaining = request.remaining - count;
|
|
770
|
+
if (remaining === 0) {
|
|
771
|
+
next.delete(requestId);
|
|
772
|
+
completions.push(request.deferred);
|
|
773
|
+
}
|
|
774
|
+
else {
|
|
775
|
+
next.set(requestId, { ...request, remaining });
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
return { _tag: 'open', requests: next };
|
|
779
|
+
});
|
|
780
|
+
yield* Effect.forEach(completions, (deferred) => Deferred.succeed(deferred, void 0), { discard: true });
|
|
781
|
+
});
|
|
782
|
+
const rejectLocalItems = (requestsRef, items) => Effect.gen(function* () {
|
|
783
|
+
const failures = [];
|
|
784
|
+
yield* Ref.update(requestsRef, (registry) => {
|
|
785
|
+
if (registry._tag === 'closed')
|
|
786
|
+
return registry;
|
|
787
|
+
const next = new Map(registry.requests);
|
|
788
|
+
for (const { item, error } of items) {
|
|
789
|
+
const request = next.get(item.requestId);
|
|
790
|
+
if (request === undefined)
|
|
791
|
+
continue;
|
|
792
|
+
next.delete(item.requestId);
|
|
793
|
+
failures.push({ deferred: request.deferred, error });
|
|
794
|
+
}
|
|
795
|
+
return { _tag: 'open', requests: next };
|
|
796
|
+
});
|
|
797
|
+
yield* Effect.forEach(failures, ({ deferred, error }) => Deferred.fail(deferred, error), { discard: true });
|
|
798
|
+
});
|
|
799
|
+
const interruptLocalRequests = (requestsRef, requestIds) => Effect.gen(function* () {
|
|
800
|
+
const deferreds = [];
|
|
801
|
+
yield* Ref.update(requestsRef, (registry) => {
|
|
802
|
+
if (registry._tag === 'closed')
|
|
803
|
+
return registry;
|
|
804
|
+
const next = new Map(registry.requests);
|
|
805
|
+
for (const requestId of new Set(requestIds)) {
|
|
806
|
+
const request = next.get(requestId);
|
|
807
|
+
if (request !== undefined)
|
|
808
|
+
deferreds.push(request.deferred);
|
|
809
|
+
next.delete(requestId);
|
|
810
|
+
}
|
|
811
|
+
return { _tag: 'open', requests: next };
|
|
812
|
+
});
|
|
813
|
+
yield* Effect.forEach(deferreds, Deferred.interrupt, { discard: true });
|
|
814
|
+
});
|
|
815
|
+
const interruptAllLocalRequests = (requestsRef) => Effect.gen(function* () {
|
|
816
|
+
const registry = yield* Ref.getAndSet(requestsRef, { _tag: 'closed' });
|
|
817
|
+
if (registry._tag === 'closed')
|
|
818
|
+
return;
|
|
819
|
+
yield* Effect.forEach(registry.requests.values(), ({ deferred }) => Deferred.interrupt(deferred), { discard: true });
|
|
820
|
+
});
|
|
821
|
+
const interruptAllPullBatches = (batchesRef) => Effect.gen(function* () {
|
|
822
|
+
const batches = yield* Ref.getAndSet(batchesRef, new Map());
|
|
823
|
+
yield* Effect.forEach(batches.values(), Deferred.interrupt, { discard: true });
|
|
824
|
+
});
|
|
825
|
+
const completePullBatch = (batchesRef, batchId) => Effect.gen(function* () {
|
|
826
|
+
let completion;
|
|
827
|
+
yield* Ref.update(batchesRef, (current) => {
|
|
828
|
+
const next = new Map(current);
|
|
829
|
+
completion = next.get(batchId);
|
|
830
|
+
next.delete(batchId);
|
|
831
|
+
return next;
|
|
832
|
+
});
|
|
833
|
+
if (completion !== undefined)
|
|
834
|
+
yield* Deferred.succeed(completion, void 0);
|
|
835
|
+
});
|
|
836
|
+
const countRequestItems = (items) => {
|
|
837
|
+
const counts = new Map();
|
|
838
|
+
for (const item of items)
|
|
839
|
+
counts.set(item.requestId, (counts.get(item.requestId) ?? 0) + 1);
|
|
840
|
+
return counts;
|
|
841
|
+
};
|
|
842
|
+
const makePullQueueSet = Effect.gen(function* () {
|
|
843
|
+
const set = new Set();
|
|
844
|
+
// NOTE this could grow unbounded for long running sessions
|
|
845
|
+
const cachedPullItems = new Map();
|
|
846
|
+
yield* Effect.addFinalizer(() => Effect.gen(function* () {
|
|
847
|
+
for (const queue of set) {
|
|
848
|
+
yield* Queue.shutdown(queue);
|
|
849
|
+
}
|
|
850
|
+
set.clear();
|
|
851
|
+
}));
|
|
852
|
+
const makeQueue = (cursor) => Effect.gen(function* () {
|
|
853
|
+
const queue = yield* Effect.acquireRelease(Queue.unbounded(), Queue.shutdown);
|
|
854
|
+
yield* Effect.addFinalizer(() => Effect.sync(() => set.delete(queue)));
|
|
855
|
+
const pullItemsSinceCursor = Array.from(cachedPullItems.entries())
|
|
856
|
+
.flatMap(([seqNumStr, items]) => items.map((item) => ({ item, seqNum: EventSequenceNumber.Client.fromString(seqNumStr) })))
|
|
857
|
+
.filter(({ seqNum }) => EventSequenceNumber.Client.isGreaterThan(seqNum, cursor))
|
|
858
|
+
.toSorted((a, b) => EventSequenceNumber.Client.compare(a.seqNum, b.seqNum))
|
|
859
|
+
.map(({ item }) => {
|
|
860
|
+
if (item.payload._tag === 'upstream-advance') {
|
|
861
|
+
return PullItem.make({
|
|
862
|
+
globalHead: item.globalHead,
|
|
863
|
+
materializerHashes: item.materializerHashes.filter(({ eventNum }) => EventSequenceNumber.Client.isGreaterThan(eventNum, cursor)),
|
|
864
|
+
payload: {
|
|
865
|
+
_tag: 'upstream-advance',
|
|
866
|
+
newEvents: ReadonlyArray.dropWhile(item.payload.newEvents, (eventEncoded) => EventSequenceNumber.Client.isGreaterThanOrEqual(cursor, eventEncoded.seqNum)),
|
|
867
|
+
},
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
else {
|
|
871
|
+
return item;
|
|
872
|
+
}
|
|
873
|
+
});
|
|
874
|
+
// console.debug(
|
|
875
|
+
// 'seeding new queue',
|
|
876
|
+
// {
|
|
877
|
+
// cursor,
|
|
878
|
+
// },
|
|
879
|
+
// '\n mergePayloads',
|
|
880
|
+
// ...Array.from(cachedPullItems.entries())
|
|
881
|
+
// .flatMap(([seqNumStr, items]) =>
|
|
882
|
+
// items.map(({ payload }) => ({ payload, seqNum: EventSequenceNumber.fromString(seqNumStr) })),
|
|
883
|
+
// )
|
|
884
|
+
// .map(({ payload, seqNum }) => [
|
|
885
|
+
// seqNum,
|
|
886
|
+
// payload._tag,
|
|
887
|
+
// 'newEvents',
|
|
888
|
+
// ...payload.newEvents.map((_) => _.toJSON()),
|
|
889
|
+
// 'rollbackEvents',
|
|
890
|
+
// ...(payload._tag === 'upstream-rebase' ? payload.rollbackEvents.map((_) => _.toJSON()) : []),
|
|
891
|
+
// ]),
|
|
892
|
+
// '\n pullItemsSinceCursor',
|
|
893
|
+
// ...pullItemsSinceCursor.map(({ payload }) => [
|
|
894
|
+
// payload._tag,
|
|
895
|
+
// 'newEvents',
|
|
896
|
+
// ...payload.newEvents.map((_) => _.toJSON()),
|
|
897
|
+
// 'rollbackEvents',
|
|
898
|
+
// ...(payload._tag === 'upstream-rebase' ? payload.rollbackEvents.map((_) => _.toJSON()) : []),
|
|
899
|
+
// ]),
|
|
900
|
+
// )
|
|
901
|
+
yield* Queue.offerAll(queue, pullItemsSinceCursor);
|
|
902
|
+
set.add(queue);
|
|
903
|
+
return queue;
|
|
904
|
+
});
|
|
905
|
+
const offer = (item) => Effect.gen(function* () {
|
|
906
|
+
const seqNumStr = EventSequenceNumber.Client.toString(item.leaderHead);
|
|
907
|
+
const pullItem = PullItem.make({
|
|
908
|
+
payload: item.payload,
|
|
909
|
+
globalHead: item.globalHead,
|
|
910
|
+
materializerHashes: item.materializerHashes,
|
|
911
|
+
});
|
|
912
|
+
if (cachedPullItems.has(seqNumStr) === true) {
|
|
913
|
+
cachedPullItems.get(seqNumStr).push(pullItem);
|
|
914
|
+
}
|
|
915
|
+
else {
|
|
916
|
+
cachedPullItems.set(seqNumStr, [pullItem]);
|
|
917
|
+
}
|
|
918
|
+
// console.debug(`offering to ${set.size} queues`, item.leaderHead, JSON.stringify(item.payload, null, 2))
|
|
919
|
+
for (const queue of set) {
|
|
920
|
+
yield* Queue.offer(queue, pullItem);
|
|
921
|
+
}
|
|
922
|
+
});
|
|
923
|
+
return {
|
|
924
|
+
makeQueue,
|
|
925
|
+
offer,
|
|
926
|
+
};
|
|
749
927
|
});
|
|
750
928
|
/**
|
|
751
929
|
* Clears local databases (eventlog and state) so the client can start fresh on next boot.
|
|
752
930
|
* This is used when the sync backend identity has changed (i.e. backend was reset).
|
|
753
931
|
*/
|
|
754
|
-
const clearLocalDatabases = ({ dbEventlog, dbState }) => Effect.
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
932
|
+
const clearLocalDatabases = ({ dbEventlog, dbState }) => Effect.try({
|
|
933
|
+
try: () => {
|
|
934
|
+
// Clear eventlog tables
|
|
935
|
+
dbEventlog.execute(sql `DELETE FROM ${EVENTLOG_META_TABLE}`);
|
|
936
|
+
dbEventlog.execute(sql `DELETE FROM ${SYNC_STATUS_TABLE}`);
|
|
937
|
+
// Drop all state tables - they'll be recreated on next boot
|
|
938
|
+
const tables = dbState.select(sql `SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`);
|
|
939
|
+
for (const { name } of tables) {
|
|
940
|
+
dbState.execute(`DROP TABLE IF EXISTS "${name}"`);
|
|
941
|
+
}
|
|
942
|
+
},
|
|
943
|
+
catch: (cause) => UnknownError.make({ cause, note: 'Failed to reset local databases after backend mismatch' }),
|
|
763
944
|
});
|
|
764
|
-
const
|
|
765
|
-
|
|
766
|
-
yield* TxQueue.offerAll(queue, items);
|
|
767
|
-
return items;
|
|
768
|
-
}));
|
|
769
|
-
const takePrefixUntil = (queue, predicate) => Effect.tx(Effect.gen(function* () {
|
|
770
|
-
const items = yield* TxQueue.clear(queue);
|
|
771
|
-
const [prefix, rest] = ReadonlyArray.splitWhere(items, predicate);
|
|
772
|
-
yield* TxQueue.offerAll(queue, rest);
|
|
773
|
-
return prefix;
|
|
774
|
-
}));
|
|
945
|
+
const localItemKey = (item) => `${item.requestId}:${item.index}`;
|
|
946
|
+
const retryDelay = (attempt) => Math.min(30_000, 1_000 * 2 ** Math.max(0, attempt - 1));
|
|
775
947
|
/** Serialize value to JSON string for trace attributes */
|
|
776
948
|
const jsonStringify = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
|
|
777
949
|
//# sourceMappingURL=LeaderSyncProcessor.js.map
|