-
Notifications
You must be signed in to change notification settings - Fork 322
Expand file tree
/
Copy pathclient.ts
More file actions
2216 lines (1987 loc) · 73.8 KB
/
client.ts
File metadata and controls
2216 lines (1987 loc) · 73.8 KB
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 {
Message,
Offset,
Schema,
Row,
MaybePromise,
GetExtensions,
ChangeMessage,
SnapshotMetadata,
SubsetParams,
} from './types'
import { MessageParser, Parser, TransformFunction } from './parser'
import {
ColumnMapper,
encodeWhereClause,
quoteIdentifier,
} from './column-mapper'
import {
getOffset,
isUpToDateMessage,
isChangeMessage,
bigintSafeStringify,
} from './helpers'
import {
FetchError,
FetchBackoffAbortError,
MissingShapeUrlError,
InvalidSignalError,
MissingShapeHandleError,
ReservedParamError,
MissingHeadersError,
StaleCacheError,
} from './error'
import {
BackoffDefaults,
BackoffOptions,
createFetchWithBackoff,
createFetchWithChunkBuffer,
createFetchWithConsumedMessages,
createFetchWithResponseHeadersCheck,
} from './fetch'
import {
CHUNK_LAST_OFFSET_HEADER,
LIVE_CACHE_BUSTER_HEADER,
LIVE_CACHE_BUSTER_QUERY_PARAM,
EXPIRED_HANDLE_QUERY_PARAM,
COLUMNS_QUERY_PARAM,
LIVE_QUERY_PARAM,
OFFSET_QUERY_PARAM,
SHAPE_HANDLE_HEADER,
SHAPE_HANDLE_QUERY_PARAM,
SHAPE_SCHEMA_HEADER,
WHERE_QUERY_PARAM,
WHERE_PARAMS_PARAM,
TABLE_QUERY_PARAM,
REPLICA_PARAM,
FORCE_DISCONNECT_AND_REFRESH,
PAUSE_STREAM,
SYSTEM_WAKE,
EXPERIMENTAL_LIVE_SSE_QUERY_PARAM,
LIVE_SSE_QUERY_PARAM,
ELECTRIC_PROTOCOL_QUERY_PARAMS,
LOG_MODE_QUERY_PARAM,
SUBSET_PARAM_WHERE,
SUBSET_PARAM_WHERE_PARAMS,
SUBSET_PARAM_LIMIT,
SUBSET_PARAM_OFFSET,
SUBSET_PARAM_ORDER_BY,
SUBSET_PARAM_WHERE_EXPR,
SUBSET_PARAM_ORDER_BY_EXPR,
CACHE_BUSTER_QUERY_PARAM,
} from './constants'
import { compileExpression, compileOrderBy } from './expression-compiler'
import {
EventSourceMessage,
fetchEventSource,
} from '@microsoft/fetch-event-source'
import { expiredShapesCache } from './expired-shapes-cache'
import { upToDateTracker } from './up-to-date-tracker'
import { SnapshotTracker } from './snapshot-tracker'
import {
createInitialState,
ErrorState,
PausedState,
ShapeStreamState,
} from './shape-stream-state'
import { PauseLock } from './pause-lock'
const RESERVED_PARAMS: Set<ReservedParamKeys> = new Set([
LIVE_CACHE_BUSTER_QUERY_PARAM,
SHAPE_HANDLE_QUERY_PARAM,
LIVE_QUERY_PARAM,
OFFSET_QUERY_PARAM,
CACHE_BUSTER_QUERY_PARAM,
])
const TROUBLESHOOTING_URL = `https://electric-sql.com/docs/guides/troubleshooting`
function createCacheBuster(): string {
return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`
}
type Replica = `full` | `default`
export type LogMode = `changes_only` | `full`
/**
* PostgreSQL-specific shape parameters that can be provided externally
*/
export interface PostgresParams<T extends Row<unknown> = Row> {
/** The root table for the shape. Not required if you set the table in your proxy. */
table?: string
/**
* The columns to include in the shape.
* Must include primary keys, and can only include valid columns.
* Defaults to all columns of the type `T`. If provided, must include primary keys, and can only include valid columns.
*/
columns?: (keyof T)[]
/** The where clauses for the shape */
where?: string
/**
* Positional where clause paramater values. These will be passed to the server
* and will substitute `$i` parameters in the where clause.
*
* It can be an array (note that positional arguments start at 1, the array will be mapped
* accordingly), or an object with keys matching the used positional parameters in the where clause.
*
* If where clause is `id = $1 or id = $2`, params must have keys `"1"` and `"2"`, or be an array with length 2.
*/
params?: Record<`${number}`, string> | string[]
/**
* If `replica` is `default` (the default) then Electric will only send the
* changed columns in an update.
*
* If it's `full` Electric will send the entire row with both changed and
* unchanged values. `old_value` will also be present on update messages,
* containing the previous value for changed columns.
*
* Setting `replica` to `full` will result in higher bandwidth
* usage and so is not generally recommended.
*/
replica?: Replica
}
type SerializableParamValue = string | string[] | Record<string, string>
type ParamValue =
| SerializableParamValue
| (() => SerializableParamValue | Promise<SerializableParamValue>)
/**
* External params type - what users provide.
* Excludes reserved parameters to prevent dynamic variations that could cause stream shape changes.
*/
export type ExternalParamsRecord<T extends Row<unknown> = Row> = {
[K in string]: ParamValue | undefined
} & Partial<PostgresParams<T>> & { [K in ReservedParamKeys]?: never }
type ReservedParamKeys =
| typeof LIVE_CACHE_BUSTER_QUERY_PARAM
| typeof SHAPE_HANDLE_QUERY_PARAM
| typeof LIVE_QUERY_PARAM
| typeof OFFSET_QUERY_PARAM
| typeof CACHE_BUSTER_QUERY_PARAM
| `subset__${string}`
/**
* External headers type - what users provide.
* Allows string or function values for any header.
*/
export type ExternalHeadersRecord = {
[key: string]: string | (() => string | Promise<string>)
}
/**
* Internal params type - used within the library.
* All values are converted to strings.
*/
type InternalParamsRecord = {
[K in string as K extends ReservedParamKeys ? never : K]:
| string
| Record<string, string>
}
/**
* Helper function to resolve a function or value to its final value
*/
export async function resolveValue<T>(
value: T | (() => T | Promise<T>)
): Promise<T> {
if (typeof value === `function`) {
return (value as () => T | Promise<T>)()
}
return value
}
/**
* Helper function to convert external params to internal format
*/
async function toInternalParams(
params: ExternalParamsRecord<Row>
): Promise<InternalParamsRecord> {
const entries = Object.entries(params)
const resolvedEntries = await Promise.all(
entries.map(async ([key, value]) => {
if (value === undefined) return [key, undefined]
const resolvedValue = await resolveValue(value)
return [
key,
Array.isArray(resolvedValue) ? resolvedValue.join(`,`) : resolvedValue,
]
})
)
return Object.fromEntries(
resolvedEntries.filter(([_, value]) => value !== undefined)
)
}
/**
* Helper function to resolve headers
*/
async function resolveHeaders(
headers?: ExternalHeadersRecord
): Promise<Record<string, string>> {
if (!headers) return {}
const entries = Object.entries(headers)
const resolvedEntries = await Promise.all(
entries.map(async ([key, value]) => [key, await resolveValue(value)])
)
return Object.fromEntries(resolvedEntries)
}
type RetryOpts = {
params?: ExternalParamsRecord
headers?: ExternalHeadersRecord
}
type ShapeStreamErrorHandler = (
error: Error
) => void | RetryOpts | Promise<void | RetryOpts>
/**
* Options for constructing a ShapeStream.
*/
export interface ShapeStreamOptions<T = never> {
/**
* The full URL to where the Shape is served. This can either be the Electric server
* directly or a proxy. E.g. for a local Electric instance, you might set `http://localhost:3000/v1/shape`
*/
url: string
/**
* The "offset" on the shape log. This is typically not set as the ShapeStream
* will handle this automatically. A common scenario where you might pass an offset
* is if you're maintaining a local cache of the log. If you've gone offline
* and are re-starting a ShapeStream to catch-up to the latest state of the Shape,
* you'd pass in the last offset and shapeHandle you'd seen from the Electric server
* so it knows at what point in the shape to catch you up from.
*/
offset?: Offset
/**
* Similar to `offset`, this isn't typically used unless you're maintaining
* a cache of the shape log.
*/
handle?: string
/**
* HTTP headers to attach to requests made by the client.
* Values can be strings or functions (sync or async) that return strings.
* Function values are resolved in parallel when needed, making this useful
* for authentication tokens or other dynamic headers.
*/
headers?: ExternalHeadersRecord
/**
* Additional request parameters to attach to the URL.
* Values can be strings, string arrays, or functions (sync or async) that return these types.
* Function values are resolved in parallel when needed, making this useful
* for user-specific parameters or dynamic filters.
*
* These will be merged with Electric's standard parameters.
* Note: You cannot use Electric's reserved parameter names
* (offset, handle, live, cursor).
*
* PostgreSQL-specific options like table, where, columns, and replica
* should be specified here.
*/
params?: ExternalParamsRecord
/**
* Automatically fetch updates to the Shape. If you just want to sync the current
* shape and stop, pass false.
*/
subscribe?: boolean
/**
* @deprecated No longer experimental, use {@link liveSse} instead.
*/
experimentalLiveSse?: boolean
/**
* Use Server-Sent Events (SSE) for live updates.
*/
liveSse?: boolean
/**
* Initial data loading mode
*/
log?: LogMode
signal?: AbortSignal
fetchClient?: typeof fetch
backoffOptions?: BackoffOptions
parser?: Parser<T>
/**
* Function to transform rows after parsing (e.g., for encryption, type coercion).
* Applied to data received from Electric.
*
* **Note**: If you're using `transformer` solely for column name transformation
* (e.g., snake_case → camelCase), consider using `columnMapper` instead, which
* provides bidirectional transformation and automatically encodes WHERE clauses.
*
* **Execution order** when both are provided:
* 1. `columnMapper.decode` runs first (renames columns)
* 2. `transformer` runs second (transforms values)
*
* @example
* ```typescript
* // For column renaming only - use columnMapper
* import { snakeCamelMapper } from '@electric-sql/client'
* const stream = new ShapeStream({ columnMapper: snakeCamelMapper() })
* ```
*
* @example
* ```typescript
* // For value transformation (encryption, etc.) - use transformer
* const stream = new ShapeStream({
* transformer: (row) => ({
* ...row,
* encrypted_field: decrypt(row.encrypted_field)
* })
* })
* ```
*
* @example
* ```typescript
* // Use both together
* const stream = new ShapeStream({
* columnMapper: snakeCamelMapper(), // Runs first: renames columns
* transformer: (row) => ({ // Runs second: transforms values
* ...row,
* encryptedData: decrypt(row.encryptedData)
* })
* })
* ```
*/
transformer?: TransformFunction<T>
/**
* Bidirectional column name mapper for transforming between database column names
* (e.g., snake_case) and application column names (e.g., camelCase).
*
* The mapper handles both:
* - **Decoding**: Database → Application (applied to query results)
* - **Encoding**: Application → Database (applied to WHERE clauses)
*
* @example
* ```typescript
* // Most common case: snake_case ↔ camelCase
* import { snakeCamelMapper } from '@electric-sql/client'
*
* const stream = new ShapeStream({
* url: 'http://localhost:3000/v1/shape',
* params: { table: 'todos' },
* columnMapper: snakeCamelMapper()
* })
* ```
*
* @example
* ```typescript
* // Custom mapping
* import { createColumnMapper } from '@electric-sql/client'
*
* const stream = new ShapeStream({
* columnMapper: createColumnMapper({
* user_id: 'userId',
* project_id: 'projectId',
* created_at: 'createdAt'
* })
* })
* ```
*/
columnMapper?: ColumnMapper
/**
* A function for handling shapestream errors.
*
* **Automatic retries**: The client automatically retries 5xx server errors, network
* errors, and 429 rate limits with exponential backoff. The `onError` callback is
* only invoked after these automatic retries are exhausted, or for non-retryable
* errors like 4xx client errors.
*
* When not provided, non-retryable errors will be thrown and syncing will stop.
*
* **Return value behavior**:
* - Return an **object** (RetryOpts or empty `{}`) to retry syncing:
* - `{}` - Retry with the same params and headers
* - `{ params }` - Retry with modified params
* - `{ headers }` - Retry with modified headers (e.g., refreshed auth token)
* - `{ params, headers }` - Retry with both modified
* - Return **void** or **undefined** to stop the stream permanently
*
* **Important**: If you want syncing to continue after an error (e.g., to retry
* on network failures), you MUST return at least an empty object `{}`. Simply
* logging the error and returning nothing will stop syncing.
*
* Supports async functions that return `Promise<void | RetryOpts>`.
*
* @example
* ```typescript
* // Retry on network errors, stop on others
* onError: (error) => {
* console.error('Stream error:', error)
* if (error instanceof FetchError && error.status >= 500) {
* return {} // Retry with same params
* }
* // Return void to stop on other errors
* }
* ```
*
* @example
* ```typescript
* // Refresh auth token on 401
* onError: async (error) => {
* if (error instanceof FetchError && error.status === 401) {
* const newToken = await refreshAuthToken()
* return { headers: { Authorization: `Bearer ${newToken}` } }
* }
* return {} // Retry other errors
* }
* ```
*/
onError?: ShapeStreamErrorHandler
/**
* HTTP method to use for subset snapshot requests (`requestSnapshot`/`fetchSnapshot`).
*
* - `'GET'` (default): Sends subset params as URL query parameters. May fail with
* HTTP 414 errors for large queries with many parameters.
* - `'POST'`: Sends subset params in request body as JSON. Recommended for queries
* with large parameter lists (e.g., `WHERE id = ANY($1)` with hundreds of IDs).
*
* This can be overridden per-request by passing `method` in the subset params.
*
* @example
* ```typescript
* const stream = new ShapeStream({
* url: 'http://localhost:3000/v1/shape',
* params: { table: 'items' },
* subsetMethod: 'POST', // Use POST for all subset requests
* })
* ```
*/
subsetMethod?: `GET` | `POST`
}
export interface ShapeStreamInterface<T extends Row<unknown> = Row> {
subscribe(
callback: (
messages: Message<T>[]
) => MaybePromise<void> | { columns?: (keyof T)[] },
onError?: (error: FetchError | Error) => void
): () => void
unsubscribeAll(): void
isLoading(): boolean
lastSyncedAt(): number | undefined
lastSynced(): number
isConnected(): boolean
hasStarted(): boolean
isUpToDate: boolean
lastOffset: Offset
shapeHandle?: string
error?: unknown
mode: LogMode
forceDisconnectAndRefresh(): Promise<void>
requestSnapshot(params: SubsetParams): Promise<{
metadata: SnapshotMetadata
data: Array<Message<T>>
}>
fetchSnapshot(opts: SubsetParams): Promise<{
metadata: SnapshotMetadata
data: Array<ChangeMessage<T>>
}>
}
/**
* Creates a canonical shape key from a URL excluding only Electric protocol parameters
*/
function canonicalShapeKey(url: URL): string {
const cleanUrl = new URL(url.origin + url.pathname)
// Copy all params except Electric protocol ones that vary between requests
for (const [key, value] of url.searchParams) {
if (!ELECTRIC_PROTOCOL_QUERY_PARAMS.includes(key)) {
cleanUrl.searchParams.set(key, value)
}
}
cleanUrl.searchParams.sort()
return cleanUrl.toString()
}
/**
* Reads updates to a shape from Electric using HTTP requests and long polling or
* Server-Sent Events (SSE).
* Notifies subscribers when new messages come in. Doesn't maintain any history of the
* log but does keep track of the offset position and is the best way
* to consume the HTTP `GET /v1/shape` api.
*
* @constructor
* @param {ShapeStreamOptions} options - configure the shape stream
* @example
* Register a callback function to subscribe to the messages.
* ```
* const stream = new ShapeStream(options)
* stream.subscribe(messages => {
* // messages is 1 or more row updates
* })
* ```
*
* To use Server-Sent Events (SSE) for real-time updates:
* ```
* const stream = new ShapeStream({
* url: `http://localhost:3000/v1/shape`,
* liveSse: true
* })
* ```
*
* To abort the stream, abort the `signal`
* passed in via the `ShapeStreamOptions`.
* ```
* const aborter = new AbortController()
* const issueStream = new ShapeStream({
* url: `${BASE_URL}/${table}`
* subscribe: true,
* signal: aborter.signal,
* })
* // Later...
* aborter.abort()
* ```
*/
export class ShapeStream<T extends Row<unknown> = Row>
implements ShapeStreamInterface<T>
{
static readonly Replica = {
FULL: `full` as Replica,
DEFAULT: `default` as Replica,
}
readonly options: ShapeStreamOptions<GetExtensions<T>>
#error: unknown = null
readonly #fetchClient: typeof fetch
readonly #sseFetchClient: typeof fetch
readonly #messageParser: MessageParser<T>
readonly #subscribers = new Map<
object,
[
(messages: Message<T>[]) => MaybePromise<void>,
((error: Error) => void) | undefined,
]
>()
#started = false
#syncState: ShapeStreamState
#connected: boolean = false
#mode: LogMode
#onError?: ShapeStreamErrorHandler
#requestAbortController?: AbortController
#refreshCount = 0
#snapshotCounter = 0
get #isRefreshing(): boolean {
return this.#refreshCount > 0
}
#tickPromise?: Promise<void>
#tickPromiseResolver?: () => void
#tickPromiseRejecter?: (reason?: unknown) => void
#messageChain = Promise.resolve<void[]>([]) // promise chain for incoming messages
#snapshotTracker = new SnapshotTracker()
#pauseLock: PauseLock
#currentFetchUrl?: URL // Current fetch URL for computing shape key
#lastSseConnectionStartTime?: number
#minSseConnectionDuration = 1000 // Minimum expected SSE connection duration (1 second)
#maxShortSseConnections = 3 // Fall back to long polling after this many short connections
#sseBackoffBaseDelay = 100 // Base delay for exponential backoff (ms)
#sseBackoffMaxDelay = 5000 // Maximum delay cap (ms)
#unsubscribeFromVisibilityChanges?: () => void
#unsubscribeFromWakeDetection?: () => void
#maxStaleCacheRetries = 3
// Fast-loop detection: track recent non-live requests to detect tight retry
// loops caused by proxy/CDN misconfiguration or stale client-side caches
#recentRequestEntries: Array<{ timestamp: number; offset: string }> = []
#fastLoopWindowMs = 500
#fastLoopThreshold = 5
#fastLoopBackoffBaseMs = 100
#fastLoopBackoffMaxMs = 5_000
#fastLoopConsecutiveCount = 0
#fastLoopMaxCount = 5
#pendingRequestShapeCacheBuster?: string
#maxSnapshotRetries = 5
#expiredShapeRecoveryKey: string | null = null
#pendingSelfHealCheck: { shapeKey: string; staleHandle: string } | null = null
#consecutiveErrorRetries = 0
#maxConsecutiveErrorRetries = 50
constructor(options: ShapeStreamOptions<GetExtensions<T>>) {
this.options = { subscribe: true, ...options }
validateOptions(this.options)
this.#syncState = createInitialState({
offset: this.options.offset ?? `-1`,
handle: this.options.handle,
})
this.#pauseLock = new PauseLock({
onAcquired: () => {
this.#syncState = this.#syncState.pause()
if (this.#started) {
this.#requestAbortController?.abort(PAUSE_STREAM)
}
},
onReleased: () => {
if (!this.#started) return
if (this.options.signal?.aborted) return
// Don't transition syncState here — let #requestShape handle
// the PausedState→previous transition so it can detect
// resumingFromPause and avoid live long-polling.
this.#start().catch(() => {
// Errors from #start are handled internally via onError.
// This catch prevents unhandled promise rejection in Node/Bun.
})
},
})
// Build transformer chain: columnMapper.decode -> transformer
// columnMapper transforms column names, transformer transforms values
let transformer: TransformFunction<GetExtensions<T>> | undefined
if (options.columnMapper) {
const applyColumnMapper = (
row: Row<GetExtensions<T>>
): Row<GetExtensions<T>> => {
const result: Record<string, unknown> = {}
for (const [dbKey, value] of Object.entries(row)) {
const appKey = options.columnMapper!.decode(dbKey)
result[appKey] = value
}
return result as Row<GetExtensions<T>>
}
transformer = options.transformer
? (row: Row<GetExtensions<T>>) =>
options.transformer!(applyColumnMapper(row))
: applyColumnMapper
} else {
transformer = options.transformer
}
this.#messageParser = new MessageParser<T>(options.parser, transformer)
this.#onError = this.options.onError
this.#mode = this.options.log ?? `full`
const baseFetchClient =
options.fetchClient ??
((...args: Parameters<typeof fetch>) => fetch(...args))
const backOffOpts = {
...(options.backoffOptions ?? BackoffDefaults),
onFailedAttempt: () => {
this.#connected = false
options.backoffOptions?.onFailedAttempt?.()
},
}
const fetchWithBackoffClient = createFetchWithBackoff(
baseFetchClient,
backOffOpts
)
this.#sseFetchClient = createFetchWithResponseHeadersCheck(
createFetchWithChunkBuffer(fetchWithBackoffClient)
)
this.#fetchClient = createFetchWithConsumedMessages(this.#sseFetchClient)
this.#subscribeToVisibilityChanges()
}
get shapeHandle() {
return this.#syncState.handle
}
get error() {
return this.#error
}
get isUpToDate() {
return this.#syncState.isUpToDate
}
get lastOffset() {
return this.#syncState.offset
}
get mode() {
return this.#mode
}
async #start(): Promise<void> {
this.#started = true
this.#subscribeToWakeDetection()
try {
await this.#requestShape()
} catch (err) {
this.#error = err
if (err instanceof Error) {
this.#syncState = this.#syncState.toErrorState(err)
}
// Check if onError handler wants to retry
if (this.#onError) {
const retryOpts = await this.#onError(err as Error)
// Guard against null (typeof null === "object" in JavaScript)
const isRetryable = !(err instanceof MissingHeadersError)
if (retryOpts && typeof retryOpts === `object` && isRetryable) {
// Update params/headers but don't reset offset
// We want to continue from where we left off, not refetch everything
if (retryOpts.params) {
// Merge new params with existing params to preserve other parameters
this.options.params = {
...(this.options.params ?? {}),
...retryOpts.params,
}
}
if (retryOpts.headers) {
// Merge new headers with existing headers to preserve other headers
this.options.headers = {
...(this.options.headers ?? {}),
...retryOpts.headers,
}
}
// Bound the onError retry loop to prevent unbounded retries
this.#consecutiveErrorRetries++
if (
this.#consecutiveErrorRetries > this.#maxConsecutiveErrorRetries
) {
console.warn(
`[Electric] onError retry loop exhausted after ${this.#maxConsecutiveErrorRetries} consecutive retries. ` +
`The error was never resolved by the onError handler. ` +
`Error: ${err instanceof Error ? err.message : String(err)}`,
new Error(`stack trace`)
)
if (err instanceof Error) {
this.#sendErrorToSubscribers(err)
}
this.#teardown()
return
}
// Clear the error since we're retrying
this.#error = null
if (this.#syncState instanceof ErrorState) {
this.#syncState = this.#syncState.retry()
}
this.#fastLoopConsecutiveCount = 0
this.#recentRequestEntries = []
// Restart from current offset
this.#started = false
return this.#start()
}
// onError returned void, meaning it doesn't want to retry
// This is an unrecoverable error, notify subscribers
if (err instanceof Error) {
this.#sendErrorToSubscribers(err)
}
this.#teardown()
return
}
// No onError handler provided, this is an unrecoverable error
// Notify subscribers and throw
if (err instanceof Error) {
this.#sendErrorToSubscribers(err)
}
this.#teardown()
throw err
}
this.#teardown()
}
#teardown() {
this.#connected = false
this.#tickPromiseRejecter?.()
this.#unsubscribeFromWakeDetection?.()
}
async #requestShape(requestShapeCacheBuster?: string): Promise<void> {
// ErrorState should never reach the request loop — re-throw so
// #start's catch block can route it through onError properly.
if (this.#syncState instanceof ErrorState) {
throw this.#syncState.error
}
const activeCacheBuster =
requestShapeCacheBuster ?? this.#pendingRequestShapeCacheBuster
if (this.#pauseLock.isPaused) {
if (activeCacheBuster) {
this.#pendingRequestShapeCacheBuster = activeCacheBuster
}
return
}
if (
!this.options.subscribe &&
(this.options.signal?.aborted || this.#syncState.isUpToDate)
) {
return
}
// Only check for fast loops on non-live requests; live polling is expected to be rapid
if (!this.#syncState.isUpToDate) {
await this.#checkFastLoop()
} else {
this.#fastLoopConsecutiveCount = 0
this.#recentRequestEntries = []
}
let resumingFromPause = false
if (this.#syncState instanceof PausedState) {
resumingFromPause = true
this.#syncState = this.#syncState.resume()
}
const { url, signal } = this.options
const { fetchUrl, requestHeaders } = await this.#constructUrl(
url,
resumingFromPause
)
if (activeCacheBuster) {
fetchUrl.searchParams.set(CACHE_BUSTER_QUERY_PARAM, activeCacheBuster)
fetchUrl.searchParams.sort()
}
const abortListener = await this.#createAbortListener(signal)
const requestAbortController = this.#requestAbortController! // we know that it is not undefined because it is set by `this.#createAbortListener`
// Re-check after async setup — the lock may have been acquired
// during URL construction or abort controller creation (e.g., by
// requestSnapshot), when the abort controller didn't exist yet.
if (this.#pauseLock.isPaused) {
if (abortListener && signal) {
signal.removeEventListener(`abort`, abortListener)
}
if (activeCacheBuster) {
this.#pendingRequestShapeCacheBuster = activeCacheBuster
}
this.#requestAbortController = undefined
return
}
this.#pendingRequestShapeCacheBuster = undefined
try {
await this.#fetchShape({
fetchUrl,
requestAbortController,
headers: requestHeaders,
resumingFromPause,
})
} catch (e) {
const abortReason = requestAbortController.signal.reason
const isRestartAbort =
requestAbortController.signal.aborted &&
(abortReason === FORCE_DISCONNECT_AND_REFRESH ||
abortReason === SYSTEM_WAKE)
if (
(e instanceof FetchError || e instanceof FetchBackoffAbortError) &&
isRestartAbort
) {
return this.#requestShape()
}
if (e instanceof FetchBackoffAbortError) {
return // interrupted
}
if (e instanceof StaleCacheError) {
// Two paths throw StaleCacheError:
// 1. Normal stale-retry: response handle matched expired handle,
// #staleCacheBuster set to bypass CDN cache on next request.
// 2. Self-healing: stale retries exhausted, expired entry cleared,
// stream reset — retry without expired_handle param.
return this.#requestShape()
}
if (!(e instanceof FetchError)) throw e // should never happen
if (e.status == 409) {
// Upon receiving a 409, start from scratch with the newly
// provided shape handle. If the header is missing (e.g. proxy
// stripped it), reset without a handle and use a random
// cache-buster query param to ensure the retry URL is unique.
// Store the current shape URL as expired to avoid future 409s
if (this.#syncState.handle) {
const shapeKey = canonicalShapeKey(fetchUrl)
expiredShapesCache.markExpired(shapeKey, this.#syncState.handle)
}
const newShapeHandle = e.headers[SHAPE_HANDLE_HEADER]
let nextRequestShapeCacheBuster: string | undefined
if (!newShapeHandle) {
console.warn(
`[Electric] Received 409 response without a shape handle header. ` +
`This likely indicates a proxy or CDN stripping required headers.`,
new Error(`stack trace`)
)
nextRequestShapeCacheBuster = createCacheBuster()
}
this.#reset(newShapeHandle)
// must refetch control message might be in a list or not depending
// on whether it came from an SSE request or long poll. The body may
// also be null/undefined if a proxy returned an unexpected response.
// Handle all cases defensively here.
const messages409 = Array.isArray(e.json)
? e.json
: e.json != null
? [e.json]
: []
await this.#publish(messages409 as Message<T>[])
return this.#requestShape(nextRequestShapeCacheBuster)
} else {
// errors that have reached this point are not actionable without
// additional user input, such as 400s or failures to read the
// body of a response, so we exit the loop and let #start handle it
// Note: We don't notify subscribers here because onError might recover
throw e
}
} finally {
if (abortListener && signal) {
signal.removeEventListener(`abort`, abortListener)
}
this.#requestAbortController = undefined
}
this.#tickPromiseResolver?.()
return this.#requestShape()
}
/**
* Detects tight retry loops (e.g., from stale client-side caches or
* proxy/CDN misconfiguration) and attempts recovery. On first detection,
* clears client-side caches (in-memory and localStorage) and resets the
* stream to fetch from scratch.
* If the loop persists, applies exponential backoff and eventually throws.
*/
async #checkFastLoop(): Promise<void> {
const now = Date.now()
const currentOffset = this.#syncState.offset
this.#recentRequestEntries = this.#recentRequestEntries.filter(
(e) => now - e.timestamp < this.#fastLoopWindowMs
)
this.#recentRequestEntries.push({ timestamp: now, offset: currentOffset })
// Only flag as a fast loop if requests are stuck at the same offset.
// Normal rapid syncing advances the offset with each response.
const sameOffsetCount = this.#recentRequestEntries.filter(