-
Notifications
You must be signed in to change notification settings - Fork 120
/
process.ts
1669 lines (1452 loc) · 52.2 KB
/
process.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import throttle from 'lodash.throttle'
import uniqWith from 'lodash.uniqwith'
import {
SatOpMigrate_Type,
SatRelation_RelationType,
} from '../_generated/protocol/satellite'
import { AuthConfig, AuthState } from '../auth/index'
import { DatabaseAdapter } from '../electric/adapter'
import { Migrator } from '../migrators/index'
import {
AuthStateNotification,
Change,
ChangeOrigin,
Notifier,
UnsubscribeFunction,
} from '../notifiers/index'
import {
Waiter,
base64,
bytesToNumber,
emptyPromise,
getWaiter,
} from '../util/common'
import { QualifiedTablename } from '../util/tablename'
import {
AdditionalData,
ConnectivityState,
ConnectivityStatus,
DataChange,
DbName,
LSN,
MigrationTable,
Relation,
RelationsCache,
ReplicationStatus,
SatelliteError,
SatelliteErrorCode,
SchemaChange,
SqlValue,
Statement,
Transaction,
isDataChange,
Uuid,
Record as DataRecord,
ReplicatedRowTransformer,
} from '../util/types'
import { SatelliteOpts } from './config'
import { Client, Satellite } from './index'
import {
OPTYPES,
OplogEntry,
ShadowEntry,
ShadowEntryChanges,
encodeTags,
fromTransaction,
generateTag,
getShadowPrimaryKey,
primaryKeyToStr,
toTransactions,
} from './oplog'
import { Mutex } from 'async-mutex'
import Log from 'loglevel'
import { generateTableTriggers } from '../migrators/triggers'
import { prepareInsertBatchedStatements } from '../util/statements'
import { mergeEntries } from './merge'
import { SubscriptionsManager, getAllTablesForShape } from './shapes'
import { InMemorySubscriptionsManager } from './shapes/manager'
import {
Shape,
InitialDataChange,
ShapeDefinition,
ShapeRequest,
SubscribeResponse,
SubscriptionData,
} from './shapes/types'
import { backOff } from 'exponential-backoff'
import { chunkBy, genUUID } from '../util'
import { isFatal, isOutOfSyncError, isThrowable, wrapFatalError } from './error'
import { inferRelationsFromSQLite } from '../util/relations'
import { decodeUserIdFromToken } from '../auth/secure'
import { InvalidArgumentError } from '../client/validation/errors/invalidArgumentError'
import Long from 'long'
type ChangeAccumulator = {
[key: string]: Change
}
export type ShapeSubscription = {
synced: Promise<void>
}
type ThrottleFunction = {
cancel: () => void
(): Promise<Date> | undefined
}
type MetaEntries = {
clientId: Uuid | ''
compensations: number
lsn: string | null
subscriptions: string
seenAdditionalData: string
}
type ConnectRetryHandler = (error: Error, attempt: number) => boolean
const connectRetryHandler: ConnectRetryHandler = (error) => {
if (
!(error instanceof SatelliteError) ||
isThrowable(error) ||
isFatal(error)
) {
Log.debug(`connectAndStartRetryHandler was cancelled: ${error.message}`)
return false
}
return true
}
export class SatelliteProcess implements Satellite {
dbName: DbName
adapter: DatabaseAdapter
migrator: Migrator
notifier: Notifier
client: Client
opts: SatelliteOpts
_authState?: AuthState
_unsubscribeFromAuthState?: UnsubscribeFunction
connectivityState?: ConnectivityState
_unsubscribeFromConnectivityChanges?: UnsubscribeFunction
_pollingInterval?: any
_unsubscribeFromPotentialDataChanges?: UnsubscribeFunction
_throttledSnapshot: ThrottleFunction
_lsn?: LSN
relations: RelationsCache
previousShapeSubscriptions: Shape[]
subscriptions: SubscriptionsManager
subscriptionNotifiers: Record<string, ReturnType<typeof emptyPromise<void>>>
subscriptionIdGenerator: (...args: any) => string
shapeRequestIdGenerator: (...args: any) => string
/**
* To optimize inserting a lot of data when the subscription data comes, we need to do
* less `INSERT` queries, but SQLite supports only a limited amount of `?` positional
* arguments. Precisely, its either 999 for versions prior to 3.32.0 and 32766 for
* versions after.
*/
private maxSqlParameters: 999 | 32766 = 999
private snapshotMutex: Mutex = new Mutex()
private performingSnapshot = false
private _connectRetryHandler: ConnectRetryHandler
private initializing?: Waiter
constructor(
dbName: DbName,
adapter: DatabaseAdapter,
migrator: Migrator,
notifier: Notifier,
client: Client,
opts: SatelliteOpts
) {
this.dbName = dbName
this.adapter = adapter
this.migrator = migrator
this.notifier = notifier
this.client = client
this.opts = opts
this.relations = {}
this.previousShapeSubscriptions = []
this.subscriptions = new InMemorySubscriptionsManager(
this._garbageCollectShapeHandler.bind(this)
)
this._throttledSnapshot = throttle(
this._mutexSnapshot.bind(this),
opts.minSnapshotWindow,
{
leading: true,
trailing: true,
}
)
this.subscriptionNotifiers = {}
this.subscriptionIdGenerator = () => genUUID()
this.shapeRequestIdGenerator = this.subscriptionIdGenerator
this._connectRetryHandler = connectRetryHandler
this.setClientListeners()
}
/**
* Perform a snapshot while taking out a mutex to avoid concurrent calls.
*/
async _mutexSnapshot() {
const release = await this.snapshotMutex.acquire()
try {
return await this._performSnapshot()
} finally {
release()
}
}
async start(authConfig?: AuthConfig): Promise<void> {
if (this.opts.debug) {
await this.logSQLiteVersion()
}
await this.migrator.up()
const isVerified = await this._verifyTableStructure()
if (!isVerified) {
throw new Error('Invalid database schema.')
}
const clientId =
authConfig?.clientId && authConfig.clientId !== ''
? authConfig.clientId
: await this._getClientId()
this._setAuthState({ clientId: clientId })
const notifierSubscriptions = Object.entries({
_authStateSubscription: this._unsubscribeFromAuthState,
_connectivityChangeSubscription: this._unsubscribeFromConnectivityChanges,
_potentialDataChangeSubscription:
this._unsubscribeFromPotentialDataChanges,
})
notifierSubscriptions.forEach(([name, value]) => {
if (value !== undefined) {
throw new Error(
`Starting satellite process with an existing
\`${name}\`.
This means there is a notifier subscription leak.`
)
}
})
// Monitor auth state changes.
const authStateHandler = this._updateAuthState.bind(this)
this._unsubscribeFromAuthState =
this.notifier.subscribeToAuthStateChanges(authStateHandler)
// Request a snapshot whenever the data in our database potentially changes.
this._unsubscribeFromPotentialDataChanges =
this.notifier.subscribeToPotentialDataChanges(this._throttledSnapshot)
// Start polling to request a snapshot every `pollingInterval` ms.
this._pollingInterval = setInterval(
this._throttledSnapshot,
this.opts.pollingInterval
)
// Starting now!
await this._throttledSnapshot()
// Need to reload primary keys after schema migration
this.relations = await this._getLocalRelations()
this.checkMaxSqlParameters()
const lsnBase64 = await this._getMeta('lsn')
if (lsnBase64 && lsnBase64.length > 0) {
this._lsn = base64.toBytes(lsnBase64)
Log.info(`retrieved lsn ${this._lsn}`)
} else {
Log.info(`no lsn retrieved from store`)
}
const subscriptionsState = await this._getMeta('subscriptions')
if (subscriptionsState) {
this.subscriptions.setState(subscriptionsState)
}
}
private async logSQLiteVersion(): Promise<void> {
const sqliteVersionRow = await this.adapter.query({
sql: 'SELECT sqlite_version() AS version',
})
Log.info(`Using SQLite version: ${sqliteVersionRow[0]['version']}`)
}
_setAuthState(authState: AuthState): void {
this._authState = authState
}
async _garbageCollectShapeHandler(
shapeDefs: ShapeDefinition[]
): Promise<void> {
const allTables = shapeDefs
.map((def: ShapeDefinition) => def.definition)
.flatMap((x) => getAllTablesForShape(x))
const tables = uniqWith(allTables, (a, b) => a.isEqual(b))
// TODO: table and schema warrant escaping here too, but they aren't in the triggers table.
const tablenames = tables.map((x) => x.toString())
const deleteStmts = tables.map((x) => ({
sql: `DELETE FROM ${x.toString()}`,
}))
const stmtsWithTriggers = [
// reverts to off on commit/abort
{ sql: 'PRAGMA defer_foreign_keys = ON' },
...this._disableTriggers(tablenames),
...deleteStmts,
...this._enableTriggers(tablenames),
]
await this.adapter.runInTransaction(...stmtsWithTriggers)
}
setClientListeners(): void {
this.client.subscribeToError(this._handleClientError.bind(this))
this.client.subscribeToRelations(this._updateRelations.bind(this))
this.client.subscribeToTransactions(this._applyTransaction.bind(this))
this.client.subscribeToAdditionalData(this._applyAdditionalData.bind(this))
this.client.subscribeToOutboundStarted(this._throttledSnapshot.bind(this))
this.client.subscribeToSubscriptionEvents(
this._handleSubscriptionData.bind(this),
this._handleSubscriptionError.bind(this)
)
}
// Unsubscribe from data changes and stop polling
async stop(shutdown?: boolean): Promise<void> {
return this._stop(shutdown)
}
private async _stop(shutdown?: boolean): Promise<void> {
// Stop snapshotting and polling for changes.
this._throttledSnapshot.cancel()
// Ensure that no snapshot is left running in the background
// by acquiring the mutex and releasing it immediately.
const releaseMutex = await this.snapshotMutex.acquire()
releaseMutex()
if (this._pollingInterval !== undefined) {
clearInterval(this._pollingInterval)
this._pollingInterval = undefined
}
// Unsubscribe all listeners and remove them
const unsubscribers = [
'_unsubscribeFromAuthState',
'_unsubscribeFromConnectivityChanges',
'_unsubscribeFromPotentialDataChanges',
] as const
unsubscribers.forEach((unsubscriber) => {
const unsub = this[unsubscriber]
if (unsub !== undefined) {
unsub!()
this[unsubscriber] = undefined
}
})
this.disconnect()
if (shutdown) {
this.client.shutdown()
}
}
async subscribe(shapeDefinitions: Shape[]): Promise<ShapeSubscription> {
// Await for client to be ready before doing anything else
await this.initializing?.waitOn()
// First, we want to check if we already have either fulfilled or fulfilling subscriptions with exactly the same definitions
const existingSubscription =
this.subscriptions.getDuplicatingSubscription(shapeDefinitions)
if (existingSubscription !== null && 'inFlight' in existingSubscription) {
return {
synced:
this.subscriptionNotifiers[existingSubscription.inFlight].promise,
}
} else if (
existingSubscription !== null &&
'fulfilled' in existingSubscription
) {
return { synced: Promise.resolve() }
}
// If no exact match found, we try to establish the subscription
const shapeReqs: ShapeRequest[] = shapeDefinitions.map((definition) => ({
requestId: this.shapeRequestIdGenerator(),
definition,
}))
const subId = this.subscriptionIdGenerator()
this.subscriptions.subscriptionRequested(subId, shapeReqs)
// store the resolve and reject
// such that we can resolve/reject
// the promise later when the shape
// is fulfilled or when an error arrives
// we store it before making the actual request
// to avoid that the answer would arrive too fast
// and this resolver and rejecter would not yet be stored
// this could especially happen in unit tests
this.subscriptionNotifiers[subId] = emptyPromise()
// store the promise because by the time the
// `await this.client.subscribe(subId, shapeReqs)` call resolves
// the `subId` entry in the `subscriptionNotifiers` may have been deleted
// so we can no longer access it
const subProm = this.subscriptionNotifiers[subId].promise
// `clearSubAndThrow` deletes the listeners and cancels the subscription
const clearSubAndThrow = (error: any): never => {
delete this.subscriptionNotifiers[subId]
this.subscriptions.subscriptionCancelled(subId)
throw error
}
try {
const { subscriptionId, error }: SubscribeResponse =
await this.client.subscribe(subId, shapeReqs)
if (subId !== subscriptionId) {
clearSubAndThrow(
new Error(
`Expected SubscripeResponse for subscription id: ${subId} but got it for another id: ${subscriptionId}`
)
)
}
if (error) {
clearSubAndThrow(error)
}
return {
synced: subProm,
}
} catch (error: any) {
return clearSubAndThrow(error)
}
}
async unsubscribe(_subscriptionId: string): Promise<void> {
throw new SatelliteError(
SatelliteErrorCode.INTERNAL,
'unsubscribe shape not supported'
)
// return this.subscriptions.unsubscribe(subscriptionId)
}
async _handleSubscriptionData(subsData: SubscriptionData): Promise<void> {
this.subscriptions.subscriptionDelivered(subsData)
// When data is empty, we will simply store the subscription and lsn state
// Not storing this state means that a second open of the app will try to
// re-insert rows which will possible trigger a UNIQUE constraint violation
await this._applySubscriptionData(subsData.data, subsData.lsn)
// Call the `onSuccess` callback for this subscription
const { resolve: onSuccess } =
this.subscriptionNotifiers[subsData.subscriptionId]
delete this.subscriptionNotifiers[subsData.subscriptionId] // GC the notifiers for this subscription ID
onSuccess()
}
// Applies initial data for a shape subscription. Current implementation
// assumes there are no conflicts INSERTing new rows and only expects
// subscriptions for entire tables.
async _applySubscriptionData(
changes: InitialDataChange[],
lsn: LSN,
additionalStmts: Statement[] = []
) {
const stmts: Statement[] = []
stmts.push({ sql: 'PRAGMA defer_foreign_keys = ON' })
// It's much faster[1] to do less statements to insert the data instead of doing an insert statement for each row
// so we're going to do just that, but with a caveat: SQLite has a max number of parameters in prepared statements,
// so this is less of "insert all at once" and more of "insert in batches". This should be even more noticeable with
// WASM builds, since we'll be crossing the JS-WASM boundary less.
//
// [1]: https://medium.com/@JasonWyatt/squeezing-performance-from-sqlite-insertions-971aff98eef2
const groupedChanges = new Map<
string,
{
relation: Relation
dataChanges: InitialDataChange[]
tableName: QualifiedTablename
}
>()
const allArgsForShadowInsert: Record<
'namespace' | 'tablename' | 'primaryKey' | 'tags',
SqlValue
>[] = []
// Group all changes by table name to be able to insert them all together
for (const op of changes) {
const tableName = new QualifiedTablename('main', op.relation.table)
const tableNameString = tableName.toString()
if (groupedChanges.has(tableNameString)) {
const changeGroup = groupedChanges.get(tableNameString)!
changeGroup.dataChanges.push(op)
} else {
groupedChanges.set(tableNameString, {
relation: op.relation,
dataChanges: [op],
tableName: tableName,
})
}
// Since we're already iterating changes, we can also prepare data for shadow table
const primaryKeyCols = op.relation.columns.reduce((agg, col) => {
if (col.primaryKey)
agg[col.name] = op.record[col.name] as string | number
return agg
}, {} as Record<string, string | number>)
allArgsForShadowInsert.push({
namespace: 'main',
tablename: op.relation.table,
primaryKey: primaryKeyToStr(primaryKeyCols),
tags: encodeTags(op.tags),
})
}
// Disable trigger for all affected tables
stmts.push(...this._disableTriggers([...groupedChanges.keys()]))
// For each table, do a batched insert
for (const [table, { relation, dataChanges }] of groupedChanges) {
const records = dataChanges.map((change) => change.record)
const columnNames = relation.columns.map((col) => col.name)
const sqlBase = `INSERT OR IGNORE INTO ${table} (${columnNames.join(
', '
)}) VALUES `
stmts.push(
...prepareInsertBatchedStatements(
sqlBase,
columnNames,
records as Record<string, SqlValue>[],
this.maxSqlParameters
)
)
}
// And re-enable the triggers for all of them
stmts.push(...this._enableTriggers([...groupedChanges.keys()]))
// Then do a batched insert for the shadow table
const upsertShadowStmt = `INSERT or REPLACE INTO ${this.opts.shadowTable.toString()} (namespace, tablename, primaryKey, tags) VALUES `
stmts.push(
...prepareInsertBatchedStatements(
upsertShadowStmt,
['namespace', 'tablename', 'primaryKey', 'tags'],
allArgsForShadowInsert,
this.maxSqlParameters
)
)
// Then update subscription state and LSN
stmts.push(
this._setMetaStatement('subscriptions', this.subscriptions.serialize()),
this.updateLsnStmt(lsn),
...additionalStmts
)
try {
await this.adapter.runInTransaction(...stmts)
// We're explicitly not specifying rowids in these changes for now,
// because nobody uses them and we don't have the machinery to to a
// `RETURNING` clause in the middle of `runInTransaction`.
const notificationChanges: Change[] = []
groupedChanges.forEach(({ dataChanges, tableName, relation }) => {
const primaryKeyColNames = relation.columns
.filter((col) => col.primaryKey)
.map((col) => col.name)
notificationChanges.push({
qualifiedTablename: tableName,
rowids: [],
recordChanges: dataChanges.map((change) => {
return {
primaryKey: Object.fromEntries(
primaryKeyColNames.map((col_name) => {
return [col_name, change.record[col_name]]
})
),
type: 'INITIAL',
}
}),
})
})
this.notifier.actuallyChanged(this.dbName, notificationChanges, 'initial')
} catch (e) {
this._handleSubscriptionError(
new SatelliteError(
SatelliteErrorCode.INTERNAL,
`Error applying subscription data: ${(e as any).message}`
)
)
}
}
async _resetClientState(opts?: {
keepSubscribedShapes: boolean
}): Promise<void> {
Log.warn(`resetting client state`)
this.disconnect()
const subscriptionIds = this.subscriptions.getFulfilledSubscriptions()
if (opts?.keepSubscribedShapes) {
const shapeDefs: Shape[] = subscriptionIds
.map((subId) => this.subscriptions.shapesForActiveSubscription(subId))
.filter((s): s is ShapeDefinition[] => s !== undefined)
.flatMap((s: ShapeDefinition[]) => s.map((i) => i.definition))
this.previousShapeSubscriptions.push(...shapeDefs)
}
this._lsn = undefined
// TODO: this is obviously too conservative
// we should also work on updating subscriptions
// atomically on unsubscribe()
await this.subscriptions.unsubscribeAll()
await this.adapter.runInTransaction(
this._setMetaStatement('lsn', null),
this._setMetaStatement('subscriptions', this.subscriptions.serialize())
)
}
async _handleSubscriptionError(
satelliteError: SatelliteError,
subscriptionId?: string
): Promise<void> {
Log.error('encountered a subscription error: ' + satelliteError.message)
let resettingError: any
try {
await this._resetClientState()
} catch (error) {
// If we encounter an error here, we want to float it to the client so that the bug is visible
// instead of just a broken state.
resettingError = error
resettingError.stack +=
'\n Encountered when handling a subscription error: \n ' +
satelliteError.stack
}
// Call the `onFailure` callback for this subscription
if (subscriptionId) {
const { reject: onFailure } = this.subscriptionNotifiers[subscriptionId]
delete this.subscriptionNotifiers[subscriptionId] // GC the notifiers for this subscription ID
onFailure(resettingError ?? satelliteError)
}
}
// handles async client errors: can be a socket error or a server error message
_handleClientError(satelliteError: SatelliteError) {
if (this.initializing && !this.initializing.finished()) {
if (satelliteError.code === SatelliteErrorCode.SOCKET_ERROR) {
Log.warn(
`a socket error occurred while connecting to server: ${satelliteError.message}`
)
return
}
if (satelliteError.code === SatelliteErrorCode.AUTH_REQUIRED) {
// TODO: should stop retrying
Log.warn(
`an authentication error occurred while connecting to server: ${satelliteError.message}`
)
return
}
// throw unhandled error
throw satelliteError
}
Log.warn(`an error occurred in satellite: ${satelliteError.message}`)
this._handleOrThrowClientError(satelliteError)
}
async _handleOrThrowClientError(error: SatelliteError): Promise<void> {
if (error.code === SatelliteErrorCode.AUTH_EXPIRED) {
Log.warn('Connection closed by Electric because the JWT expired.')
return this.disconnect(
new SatelliteError(
error.code,
'Connection closed by Electric because the JWT expired.'
)
)
}
this.disconnect(error)
if (isThrowable(error)) {
throw error
}
if (isFatal(error)) {
throw wrapFatalError(error)
}
Log.warn('Client disconnected with a non fatal error, reconnecting')
return this.connectWithBackoff()
}
/**
* Sets the JWT token.
* @param token The JWT token.
*/
setToken(token: string): void {
const newUserId = decodeUserIdFromToken(token)
const userId: string | undefined = this._authState?.userId
if (typeof userId !== 'undefined' && newUserId !== userId) {
// We must check that the new token is still using the same user ID.
// We can't accept a re-connection that changes the user ID because the Satellite process is statefull.
// To change user ID the user must re-electrify the database.
throw new InvalidArgumentError(
`Can't change user ID when reconnecting. Previously connected with user ID '${userId}' but trying to reconnect with user ID '${newUserId}'`
)
}
this._setAuthState({
...this._authState!,
userId: newUserId,
token,
})
}
/**
* @returns True if a JWT token has been set previously. False otherwise.
*/
hasToken(): boolean {
return this._authState?.token !== undefined
}
async connectWithBackoff(): Promise<void> {
if (this.client.isConnected()) {
// we're already connected
return
}
if (this.initializing && !this.initializing.finished()) {
// we're already trying to connect to Electric
// return the promise that resolves when the connection is established
return this.initializing.waitOn()
}
if (!this.initializing || this.initializing?.finished()) {
this.initializing = getWaiter()
}
const opts = {
...this.opts.connectionBackOffOptions,
retry: this._connectRetryHandler,
}
const prom = this.initializing.waitOn()
await backOff(async () => {
if (this.initializing?.finished()) {
return prom
}
await this._connect()
await this._startReplication()
this._subscribePreviousShapeRequests()
this._notifyConnectivityState('connected')
this.initializing?.resolve()
}, opts).catch((e) => {
// We're very sure that no calls are going to modify `this.initializing` before this promise resolves
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const error = !connectRetryHandler(e, 0)
? e
: new SatelliteError(
SatelliteErrorCode.CONNECTION_FAILED_AFTER_RETRY,
`Failed to connect to server after exhausting retry policy. Last error thrown by server: ${e.message}`
)
this.disconnect(error)
this.initializing?.reject(error)
})
return prom
}
_subscribePreviousShapeRequests(): void {
try {
if (this.previousShapeSubscriptions.length > 0) {
Log.warn(`Subscribing previous shape definitions`)
this.subscribe(
this.previousShapeSubscriptions.splice(
0,
this.previousShapeSubscriptions.length
)
)
}
} catch (error: any) {
const message = `Client was unable to subscribe previously subscribed shapes: ${error.message}`
throw new SatelliteError(SatelliteErrorCode.INTERNAL, message)
}
}
// NO DIRECT CALLS TO CONNECT
private async _connect(): Promise<void> {
Log.info(`connecting to electric server`)
if (!this._authState || !this._authState.token) {
throw new Error(`trying to connect before authentication`)
}
try {
await this.client.connect()
await this.authenticate(this._authState!.token!)
} catch (error: any) {
Log.debug(
`server returned an error while establishing connection: ${error.message}`
)
throw error
}
}
/**
* Authenticates with the Electric sync service using the provided token.
* @returns A promise that resolves to void if authentication succeeded. Otherwise, rejects with the reason for the error.
*/
async authenticate(token: string): Promise<void> {
const authState = {
clientId: this._authState!.clientId,
token,
}
const authResp = await this.client.authenticate(authState)
if (authResp.error) {
throw authResp.error
}
this._setAuthState(authState)
}
cancelConnectionWaiter(error: SatelliteError): void {
if (this.initializing && !this.initializing.finished()) {
this.initializing?.reject(error)
}
}
disconnect(error?: SatelliteError): void {
this.client.disconnect()
this._notifyConnectivityState('disconnected', error)
}
/**
* A disconnection issued by the client.
*/
clientDisconnect(): void {
const error = new SatelliteError(
SatelliteErrorCode.CONNECTION_CANCELLED_BY_DISCONNECT,
`Connection cancelled by 'disconnect'`
)
this.disconnect(error)
this.cancelConnectionWaiter(error)
}
async _startReplication(): Promise<void> {
try {
const schemaVersion = await this.migrator.querySchemaVersion()
// Fetch the subscription IDs that were fulfilled
// such that we can resume and inform Electric
// about fulfilled subscriptions
const subscriptionIds = this.subscriptions.getFulfilledSubscriptions()
const observedTransactionData = await this._getMeta('seenAdditionalData')
const { error } = await this.client.startReplication(
this._lsn,
schemaVersion,
subscriptionIds.length > 0 ? subscriptionIds : undefined,
observedTransactionData
.split(',')
.filter((x) => x !== '')
.map((x) => Long.fromString(x))
)
if (error) {
throw error
}
} catch (error: any) {
Log.warn(`Couldn't start replication: ${error.message}`)
if (!(error instanceof SatelliteError)) {
throw new SatelliteError(SatelliteErrorCode.INTERNAL, error.message)
}
if (isOutOfSyncError(error) && this.opts?.clearOnBehindWindow) {
await this._resetClientState({ keepSubscribedShapes: true })
throw error
}
// Some errors could be fixed by dropping local database entirely
// We propagate throwable and fatal errors for the app to decide
if (isThrowable(error)) {
throw error
}
if (isFatal(error)) {
throw wrapFatalError(error)
}
}
}
private _notifyConnectivityState(
connectivityStatus: ConnectivityStatus,
error?: SatelliteError
): void {
this.connectivityState = {
status: connectivityStatus,
reason: error,
}
this.notifier.connectivityStateChanged(this.dbName, this.connectivityState)
}
async _verifyTableStructure(): Promise<boolean> {
const meta = this.opts.metaTable.tablename
const oplog = this.opts.oplogTable.tablename
const shadow = this.opts.shadowTable.tablename
const tablesExist = `
SELECT count(name) as numTables FROM sqlite_master
WHERE type='table'
AND name IN (?, ?, ?)
`
const [{ numTables }] = await this.adapter.query({
sql: tablesExist,
args: [meta, oplog, shadow],
})
return numTables === 3
}
// Handle auth state changes.
async _updateAuthState({ authState }: AuthStateNotification): Promise<void> {
// XXX do whatever we need to stop/start or reconnect the replication
// connection with the new auth state.
// XXX Maybe we need to auto-start processing and/or replication
// when we get the right authState?
this._authState = authState
}
// Perform a snapshot and notify which data actually changed.
// It is not safe to call concurrently. Use mutexSnapshot.
async _performSnapshot(): Promise<Date> {
// assert a single call at a time
if (this.performingSnapshot) {
throw new SatelliteError(
SatelliteErrorCode.INTERNAL,
'already performing snapshot'
)
} else {
this.performingSnapshot = true
}
try {
const oplog = this.opts.oplogTable
const shadow = this.opts.shadowTable
const timestamp = new Date()
const newTag = this._generateTag(timestamp)
/*
* IMPORTANT!
*
* The following queries make use of a documented but rare SQLite behaviour that allows selecting bare column
* on aggregate queries: https://sqlite.org/lang_select.html#bare_columns_in_an_aggregate_query
*
* In short, when a query has a `GROUP BY` clause with a single `min()` or `max()` present in SELECT/HAVING,
* then the "bare" columns (i.e. those not mentioned in a `GROUP BY` clause) are definitely the ones from the
* row that satisfied that `min`/`max` function. We make use of it here to find first/last operations in the
* oplog that touch a particular row.
*/
// Update the timestamps on all "new" entries - they have been added but timestamp is still `NULL`
const q1: Statement = {
sql: `
UPDATE ${oplog} SET timestamp = ?
WHERE rowid in (
SELECT rowid FROM ${oplog}
WHERE timestamp is NULL
ORDER BY rowid ASC
)
RETURNING *
`,
args: [timestamp.toISOString()],
}