-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathAbstractStreamingSyncImplementation.ts
750 lines (671 loc) · 25.9 KB
/
AbstractStreamingSyncImplementation.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
import Logger, { ILogger } from 'js-logger';
import { SyncPriorityStatus, SyncStatus, SyncStatusOptions } from '../../../db/crud/SyncStatus.js';
import { AbortOperation } from '../../../utils/AbortOperation.js';
import { BaseListener, BaseObserver, Disposable } from '../../../utils/BaseObserver.js';
import { throttleLeadingTrailing } from '../../../utils/throttle.js';
import { BucketChecksum, BucketDescription, BucketStorageAdapter, Checkpoint } from '../bucket/BucketStorageAdapter.js';
import { CrudEntry } from '../bucket/CrudEntry.js';
import { SyncDataBucket } from '../bucket/SyncDataBucket.js';
import { AbstractRemote, SyncStreamOptions, FetchStrategy } from './AbstractRemote.js';
import {
BucketRequest,
StreamingSyncLine,
StreamingSyncRequestParameterType,
isStreamingKeepalive,
isStreamingSyncCheckpoint,
isStreamingSyncCheckpointComplete,
isStreamingSyncCheckpointDiff,
isStreamingSyncCheckpointPartiallyComplete,
isStreamingSyncData
} from './streaming-sync-types.js';
import { DataStream } from 'src/utils/DataStream.js';
export enum LockType {
CRUD = 'crud',
SYNC = 'sync'
}
export enum SyncStreamConnectionMethod {
HTTP = 'http',
WEB_SOCKET = 'web-socket'
}
/**
* Abstract Lock to be implemented by various JS environments
*/
export interface LockOptions<T> {
callback: () => Promise<T>;
type: LockType;
signal?: AbortSignal;
}
export interface AbstractStreamingSyncImplementationOptions extends AdditionalConnectionOptions {
adapter: BucketStorageAdapter;
uploadCrud: () => Promise<void>;
/**
* An identifier for which PowerSync DB this sync implementation is
* linked to. Most commonly DB name, but not restricted to DB name.
*/
identifier?: string;
logger?: ILogger;
remote: AbstractRemote;
}
export interface StreamingSyncImplementationListener extends BaseListener {
/**
* Triggered whenever a status update has been attempted to be made or
* refreshed.
*/
statusUpdated?: ((statusUpdate: SyncStatusOptions) => void) | undefined;
/**
* Triggers whenever the status' members have changed in value
*/
statusChanged?: ((status: SyncStatus) => void) | undefined;
}
/**
* Configurable options to be used when connecting to the PowerSync
* backend instance.
*/
export interface PowerSyncConnectionOptions extends BaseConnectionOptions, AdditionalConnectionOptions {}
/** @internal */
export interface BaseConnectionOptions {
/**
* The connection method to use when streaming updates from
* the PowerSync backend instance.
* Defaults to a HTTP streaming connection.
*/
connectionMethod?: SyncStreamConnectionMethod;
/**
* The fetch strategy to use when streaming updates from the PowerSync backend instance.
*/
fetchStrategy?: FetchStrategy;
/**
* These parameters are passed to the sync rules, and will be available under the`user_parameters` object.
*/
params?: Record<string, StreamingSyncRequestParameterType>;
}
/** @internal */
export interface AdditionalConnectionOptions {
/**
* Delay for retrying sync streaming operations
* from the PowerSync backend after an error occurs.
*/
retryDelayMs?: number;
/**
* Backend Connector CRUD operations are throttled
* to occur at most every `crudUploadThrottleMs`
* milliseconds.
*/
crudUploadThrottleMs?: number;
}
/** @internal */
export type RequiredAdditionalConnectionOptions = Required<AdditionalConnectionOptions>;
export interface StreamingSyncImplementation extends BaseObserver<StreamingSyncImplementationListener>, Disposable {
/**
* Connects to the sync service
*/
connect(options?: PowerSyncConnectionOptions): Promise<void>;
/**
* Disconnects from the sync services.
* @throws if not connected or if abort is not controlled internally
*/
disconnect(): Promise<void>;
getWriteCheckpoint: () => Promise<string>;
hasCompletedSync: () => Promise<boolean>;
isConnected: boolean;
lastSyncedAt?: Date;
syncStatus: SyncStatus;
triggerCrudUpload: () => void;
waitForReady(): Promise<void>;
waitForStatus(status: SyncStatusOptions): Promise<void>;
waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
}
export const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
export const DEFAULT_RETRY_DELAY_MS = 5000;
export const DEFAULT_STREAMING_SYNC_OPTIONS = {
retryDelayMs: DEFAULT_RETRY_DELAY_MS,
logger: Logger.get('PowerSyncStream'),
crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS
};
export type RequiredPowerSyncConnectionOptions = Required<BaseConnectionOptions>;
export const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptions = {
connectionMethod: SyncStreamConnectionMethod.WEB_SOCKET,
fetchStrategy: FetchStrategy.Buffered,
params: {}
};
// The priority we assume when we receive checkpoint lines where no priority is set.
// This is the default priority used by the sync service, but can be set to an arbitrary
// value since sync services without priorities also won't send partial sync completion
// messages.
const FALLBACK_PRIORITY = 3;
export abstract class AbstractStreamingSyncImplementation
extends BaseObserver<StreamingSyncImplementationListener>
implements StreamingSyncImplementation
{
protected _lastSyncedAt: Date | null;
protected options: AbstractStreamingSyncImplementationOptions;
protected abortController: AbortController | null;
protected crudUpdateListener?: () => void;
protected streamingSyncPromise?: Promise<void>;
syncStatus: SyncStatus;
triggerCrudUpload: () => void;
constructor(options: AbstractStreamingSyncImplementationOptions) {
super();
this.options = { ...DEFAULT_STREAMING_SYNC_OPTIONS, ...options };
this.syncStatus = new SyncStatus({
connected: false,
connecting: false,
lastSyncedAt: undefined,
dataFlow: {
uploading: false,
downloading: false
}
});
this.abortController = null;
this.triggerCrudUpload = throttleLeadingTrailing(() => {
if (!this.syncStatus.connected || this.syncStatus.dataFlowStatus.uploading) {
return;
}
this._uploadAllCrud();
}, this.options.crudUploadThrottleMs!);
}
async waitForReady() {}
waitForStatus(status: SyncStatusOptions): Promise<void> {
return this.waitUntilStatusMatches((currentStatus) => {
/**
* Match only the partial status options provided in the
* matching status
*/
const matchPartialObject = (compA: object, compB: object) => {
return Object.entries(compA).every(([key, value]) => {
const comparisonBValue = compB[key];
if (typeof value == 'object' && typeof comparisonBValue == 'object') {
return matchPartialObject(value, comparisonBValue);
}
return value == comparisonBValue;
});
};
return matchPartialObject(status, currentStatus);
});
}
waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void> {
return new Promise((resolve) => {
if (predicate(this.syncStatus)) {
resolve();
return;
}
const l = this.registerListener({
statusChanged: (updatedStatus) => {
if (predicate(updatedStatus)) {
resolve();
l?.();
}
}
});
});
}
get lastSyncedAt() {
const lastSynced = this.syncStatus.lastSyncedAt;
return lastSynced && new Date(lastSynced);
}
get isConnected() {
return this.syncStatus.connected;
}
protected get logger() {
return this.options.logger!;
}
async dispose() {
this.crudUpdateListener?.();
this.crudUpdateListener = undefined;
}
abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
async hasCompletedSync() {
return this.options.adapter.hasCompletedSync();
}
async getWriteCheckpoint(): Promise<string> {
const clientId = await this.options.adapter.getClientId();
let path = `/write-checkpoint2.json?client_id=${clientId}`;
const response = await this.options.remote.get(path);
return response['data']['write_checkpoint'] as string;
}
protected async _uploadAllCrud(): Promise<void> {
return this.obtainLock({
type: LockType.CRUD,
callback: async () => {
/**
* Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
*/
let checkedCrudItem: CrudEntry | undefined;
while (true) {
this.updateSyncStatus({
dataFlow: {
uploading: true
}
});
try {
/**
* This is the first item in the FIFO CRUD queue.
*/
const nextCrudItem = await this.options.adapter.nextCrudItem();
if (nextCrudItem) {
if (nextCrudItem.clientId == checkedCrudItem?.clientId) {
// This will force a higher log level than exceptions which are caught here.
this.logger.warn(`Potentially previously uploaded CRUD entries are still present in the upload queue.
Make sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.
The next upload iteration will be delayed.`);
throw new Error('Delaying due to previously encountered CRUD item.');
}
checkedCrudItem = nextCrudItem;
await this.options.uploadCrud();
} else {
// Uploading is completed
await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
break;
}
} catch (ex) {
// TODO: Handle 401s to invalidate cached credentials
checkedCrudItem = undefined;
this.updateSyncStatus({
dataFlow: {
uploading: false
}
});
await this.delayRetry();
if (!this.isConnected) {
// Exit the upload loop if the sync stream is no longer connected
break;
}
this.logger.debug(
`Caught exception when uploading. Upload will retry after a delay. Exception: ${ex.message}`
);
} finally {
this.updateSyncStatus({
dataFlow: {
uploading: false
}
});
}
}
}
});
}
async connect(options?: PowerSyncConnectionOptions) {
if (this.abortController) {
await this.disconnect();
}
this.abortController = new AbortController();
this.streamingSyncPromise = this.streamingSync(this.abortController.signal, options);
// Return a promise that resolves when the connection status is updated
return new Promise<void>((resolve) => {
const l = this.registerListener({
statusUpdated: (update) => {
// This is triggered as soon as a connection is read from
if (typeof update.connected == 'undefined') {
// only concern with connection updates
return;
}
if (update.connected == false) {
/**
* This function does not reject if initial connect attempt failed
*/
this.logger.warn('Initial connect attempt did not successfully connect to server');
}
resolve();
l();
}
});
});
}
async disconnect(): Promise<void> {
if (!this.abortController) {
return;
}
// This might be called multiple times
if (!this.abortController.signal.aborted) {
this.abortController.abort(new AbortOperation('Disconnect has been requested'));
}
// Await any pending operations before completing the disconnect operation
try {
await this.streamingSyncPromise;
} catch (ex) {
// The operation might have failed, all we care about is if it has completed
this.logger.warn(ex);
}
this.streamingSyncPromise = undefined;
this.abortController = null;
this.updateSyncStatus({ connected: false, connecting: false });
}
/**
* @deprecated use [connect instead]
*/
async streamingSync(signal?: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void> {
if (!signal) {
this.abortController = new AbortController();
signal = this.abortController.signal;
}
/**
* Listen for CRUD updates and trigger upstream uploads
*/
this.crudUpdateListener = this.options.adapter.registerListener({
crudUpdate: () => this.triggerCrudUpload()
});
/**
* Create a new abort controller which aborts items downstream.
* This is needed to close any previous connections on exception.
*/
let nestedAbortController = new AbortController();
signal.addEventListener('abort', () => {
/**
* A request for disconnect was received upstream. Relay the request
* to the nested abort controller.
*/
nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
this.crudUpdateListener?.();
this.crudUpdateListener = undefined;
this.updateSyncStatus({
connected: false,
connecting: false,
dataFlow: {
downloading: false
}
});
});
/**
* This loops runs until [retry] is false or the abort signal is set to aborted.
* Aborting the nestedAbortController will:
* - Abort any pending fetch requests
* - Close any sync stream ReadableStreams (which will also close any established network requests)
*/
while (true) {
this.updateSyncStatus({ connecting: true });
try {
if (signal?.aborted) {
break;
}
const { retry } = await this.streamingSyncIteration(nestedAbortController.signal, options);
if (!retry) {
/**
* A sync error ocurred that we cannot recover from here.
* This loop must terminate.
* The nestedAbortController will close any open network requests and streams below.
*/
break;
}
// Continue immediately
} catch (ex) {
/**
* Either:
* - A network request failed with a failed connection or not OKAY response code.
* - There was a sync processing error.
* This loop will retry.
* The nested abort controller will cleanup any open network requests and streams.
* The WebRemote should only abort pending fetch requests or close active Readable streams.
*/
if (ex instanceof AbortOperation) {
this.logger.warn(ex);
} else {
this.logger.error(ex);
}
// On error, wait a little before retrying
await this.delayRetry();
} finally {
if (!signal.aborted) {
nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));
nestedAbortController = new AbortController();
}
this.updateSyncStatus({
connected: false,
connecting: true // May be unnecessary
});
}
}
// Mark as disconnected if here
this.updateSyncStatus({ connected: false, connecting: false });
}
private async collectLocalBucketState(): Promise<[BucketRequest[], Map<string, BucketDescription | null>]> {
const bucketEntries = await this.options.adapter.getBucketStates();
const req: BucketRequest[] = bucketEntries.map((entry) => ({
name: entry.bucket,
after: entry.op_id
}));
const localDescriptions = new Map<string, BucketDescription | null>();
for (const entry of bucketEntries) {
localDescriptions.set(entry.bucket, null);
}
return [req, localDescriptions];
}
protected async streamingSyncIteration(
signal: AbortSignal,
options?: PowerSyncConnectionOptions
): Promise<{ retry?: boolean }> {
return await this.obtainLock({
type: LockType.SYNC,
signal,
callback: async () => {
const resolvedOptions: RequiredPowerSyncConnectionOptions = {
...DEFAULT_STREAM_CONNECTION_OPTIONS,
...(options ?? {})
};
this.logger.debug('Streaming sync iteration started');
this.options.adapter.startSession();
let [req, bucketMap] = await this.collectLocalBucketState();
// These are compared by reference
let targetCheckpoint: Checkpoint | null = null;
let validatedCheckpoint: Checkpoint | null = null;
let appliedCheckpoint: Checkpoint | null = null;
const clientId = await this.options.adapter.getClientId();
this.logger.debug('Requesting stream from server');
const syncOptions: SyncStreamOptions = {
path: '/sync/stream',
abortSignal: signal,
data: {
buckets: req,
include_checksum: true,
raw_data: true,
parameters: resolvedOptions.params,
client_id: clientId
}
};
let stream: DataStream<StreamingSyncLine>;
if (resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP) {
stream = await this.options.remote.postStream(syncOptions);
} else {
stream = await this.options.remote.socketStream({
...syncOptions,
...{ fetchStrategy: resolvedOptions.fetchStrategy }
});
}
this.logger.debug('Stream established. Processing events');
while (!stream.closed) {
const line = await stream.read();
if (!line) {
// The stream has closed while waiting
return { retry: true };
}
// A connection is active and messages are being received
if (!this.syncStatus.connected) {
// There is a connection now
Promise.resolve().then(() => this.triggerCrudUpload());
this.updateSyncStatus({
connected: true
});
}
if (isStreamingSyncCheckpoint(line)) {
targetCheckpoint = line.checkpoint;
const bucketsToDelete = new Set<string>(bucketMap.keys());
const newBuckets = new Map<string, BucketDescription>();
for (const checksum of line.checkpoint.buckets) {
newBuckets.set(checksum.bucket, {
name: checksum.bucket,
priority: checksum.priority ?? FALLBACK_PRIORITY
});
bucketsToDelete.delete(checksum.bucket);
}
if (bucketsToDelete.size > 0) {
this.logger.debug('Removing buckets', [...bucketsToDelete]);
}
bucketMap = newBuckets;
await this.options.adapter.removeBuckets([...bucketsToDelete]);
await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
} else if (isStreamingSyncCheckpointComplete(line)) {
this.logger.debug('Checkpoint complete', targetCheckpoint);
const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint!);
if (!result.checkpointValid) {
// This means checksums failed. Start again with a new checkpoint.
// TODO: better back-off
await new Promise((resolve) => setTimeout(resolve, 50));
return { retry: true };
} else if (!result.ready) {
// Checksums valid, but need more data for a consistent checkpoint.
// Continue waiting.
// landing here the whole time
} else {
appliedCheckpoint = targetCheckpoint;
this.logger.debug('validated checkpoint', appliedCheckpoint);
this.updateSyncStatus({
connected: true,
lastSyncedAt: new Date(),
dataFlow: {
downloading: false
}
});
}
validatedCheckpoint = targetCheckpoint;
} else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
const priority = line.partial_checkpoint_complete.priority;
this.logger.debug('Partial checkpoint complete', priority);
const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint!, priority);
if (!result.checkpointValid) {
// This means checksums failed. Start again with a new checkpoint.
// TODO: better back-off
await new Promise((resolve) => setTimeout(resolve, 50));
return { retry: true };
} else if (!result.ready) {
// Need more data for a consistent partial sync within a priority - continue waiting.
} else {
// We'll keep on downloading, but can report that this priority is synced now.
this.logger.debug('partial checkpoint validation succeeded');
// All states with a higher priority can be deleted since this partial sync includes them.
const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);
priorityStates.push({
priority,
lastSyncedAt: new Date(),
hasSynced: true
});
this.updateSyncStatus({
connected: true,
priorityStatusEntries: priorityStates
});
}
} else if (isStreamingSyncCheckpointDiff(line)) {
// TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint
if (targetCheckpoint == null) {
throw new Error('Checkpoint diff without previous checkpoint');
}
const diff = line.checkpoint_diff;
const newBuckets = new Map<string, BucketChecksum>();
for (const checksum of targetCheckpoint.buckets) {
newBuckets.set(checksum.bucket, checksum);
}
for (const checksum of diff.updated_buckets) {
newBuckets.set(checksum.bucket, checksum);
}
for (const bucket of diff.removed_buckets) {
newBuckets.delete(bucket);
}
const newCheckpoint: Checkpoint = {
last_op_id: diff.last_op_id,
buckets: [...newBuckets.values()],
write_checkpoint: diff.write_checkpoint
};
targetCheckpoint = newCheckpoint;
bucketMap = new Map();
newBuckets.forEach((checksum, name) =>
bucketMap.set(name, {
name: checksum.bucket,
priority: checksum.priority ?? FALLBACK_PRIORITY
})
);
const bucketsToDelete = diff.removed_buckets;
if (bucketsToDelete.length > 0) {
this.logger.debug('Remove buckets', bucketsToDelete);
}
await this.options.adapter.removeBuckets(bucketsToDelete);
await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
} else if (isStreamingSyncData(line)) {
const { data } = line;
this.updateSyncStatus({
dataFlow: {
downloading: true
}
});
await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] });
} else if (isStreamingKeepalive(line)) {
const remaining_seconds = line.token_expires_in;
if (remaining_seconds == 0) {
// Connection would be closed automatically right after this
this.logger.debug('Token expiring; reconnect');
/**
* For a rare case where the backend connector does not update the token
* (uses the same one), this should have some delay.
*/
await this.delayRetry();
return { retry: true };
}
this.triggerCrudUpload();
} else {
this.logger.debug('Sync complete');
if (targetCheckpoint === appliedCheckpoint) {
this.updateSyncStatus({
connected: true,
lastSyncedAt: new Date(),
priorityStatusEntries: []
});
} else if (validatedCheckpoint === targetCheckpoint) {
const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint!);
if (!result.checkpointValid) {
// This means checksums failed. Start again with a new checkpoint.
// TODO: better back-off
await new Promise((resolve) => setTimeout(resolve, 50));
return { retry: false };
} else if (!result.ready) {
// Checksums valid, but need more data for a consistent checkpoint.
// Continue waiting.
} else {
appliedCheckpoint = targetCheckpoint;
this.updateSyncStatus({
connected: true,
lastSyncedAt: new Date(),
priorityStatusEntries: [],
dataFlow: {
downloading: false
}
});
}
}
}
}
this.logger.debug('Stream input empty');
// Connection closed. Likely due to auth issue.
return { retry: true };
}
});
}
protected updateSyncStatus(options: SyncStatusOptions) {
const updatedStatus = new SyncStatus({
connected: options.connected ?? this.syncStatus.connected,
connecting: !options.connected && (options.connecting ?? this.syncStatus.connecting),
lastSyncedAt: options.lastSyncedAt ?? this.syncStatus.lastSyncedAt,
dataFlow: {
...this.syncStatus.dataFlowStatus,
...options.dataFlow
},
priorityStatusEntries: options.priorityStatusEntries ?? this.syncStatus.priorityStatusEntries
});
if (!this.syncStatus.isEqual(updatedStatus)) {
this.syncStatus = updatedStatus;
// Only trigger this is there was a change
this.iterateListeners((cb) => cb.statusChanged?.(updatedStatus));
}
// trigger this for all updates
this.iterateListeners((cb) => cb.statusUpdated?.(options));
}
private async delayRetry() {
return new Promise((resolve) => setTimeout(resolve, this.options.retryDelayMs));
}
}