@powersync/common 1.52.0 → 1.53.0
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/bundle.cjs +161 -766
- package/dist/bundle.cjs.map +1 -1
- package/dist/bundle.mjs +162 -755
- package/dist/bundle.mjs.map +1 -1
- package/dist/bundle.node.cjs +161 -766
- package/dist/bundle.node.cjs.map +1 -1
- package/dist/bundle.node.mjs +162 -755
- package/dist/bundle.node.mjs.map +1 -1
- package/dist/index.d.cts +39 -370
- package/legacy/sync_protocol.d.ts +103 -0
- package/lib/client/ConnectionManager.js +1 -1
- package/lib/client/ConnectionManager.js.map +1 -1
- package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +6 -64
- package/lib/client/sync/bucket/BucketStorageAdapter.js +4 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -1
- package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +1 -28
- package/lib/client/sync/bucket/SqliteBucketStorage.js +0 -162
- package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -1
- package/lib/client/sync/stream/AbstractRemote.d.ts +2 -12
- package/lib/client/sync/stream/AbstractRemote.js +3 -13
- package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +12 -35
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +145 -424
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
- package/lib/client/sync/stream/JsonValue.d.ts +7 -0
- package/lib/client/sync/stream/JsonValue.js +2 -0
- package/lib/client/sync/stream/JsonValue.js.map +1 -0
- package/lib/client/sync/stream/core-instruction.d.ts +14 -9
- package/lib/client/sync/stream/core-instruction.js +3 -0
- package/lib/client/sync/stream/core-instruction.js.map +1 -1
- package/lib/db/DBAdapter.d.ts +9 -0
- package/lib/db/DBAdapter.js +8 -1
- package/lib/db/DBAdapter.js.map +1 -1
- package/lib/db/crud/SyncStatus.d.ts +3 -4
- package/lib/db/crud/SyncStatus.js +0 -4
- package/lib/db/crud/SyncStatus.js.map +1 -1
- package/lib/db/schema/RawTable.d.ts +0 -5
- package/lib/db/schema/Schema.d.ts +0 -2
- package/lib/db/schema/Schema.js +0 -2
- package/lib/db/schema/Schema.js.map +1 -1
- package/lib/index.d.ts +1 -5
- package/lib/index.js +1 -5
- package/lib/index.js.map +1 -1
- package/package.json +9 -6
- package/src/client/ConnectionManager.ts +1 -1
- package/src/client/sync/bucket/BucketStorageAdapter.ts +6 -71
- package/src/client/sync/bucket/SqliteBucketStorage.ts +1 -197
- package/src/client/sync/stream/AbstractRemote.ts +5 -27
- package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +168 -496
- package/src/client/sync/stream/JsonValue.ts +8 -0
- package/src/client/sync/stream/core-instruction.ts +15 -5
- package/src/db/DBAdapter.ts +20 -2
- package/src/db/crud/SyncStatus.ts +4 -5
- package/src/db/schema/RawTable.ts +0 -5
- package/src/db/schema/Schema.ts +0 -2
- package/src/index.ts +1 -5
- package/lib/client/sync/bucket/OpType.d.ts +0 -16
- package/lib/client/sync/bucket/OpType.js +0 -23
- package/lib/client/sync/bucket/OpType.js.map +0 -1
- package/lib/client/sync/bucket/OplogEntry.d.ts +0 -23
- package/lib/client/sync/bucket/OplogEntry.js +0 -36
- package/lib/client/sync/bucket/OplogEntry.js.map +0 -1
- package/lib/client/sync/bucket/SyncDataBatch.d.ts +0 -6
- package/lib/client/sync/bucket/SyncDataBatch.js +0 -12
- package/lib/client/sync/bucket/SyncDataBatch.js.map +0 -1
- package/lib/client/sync/bucket/SyncDataBucket.d.ts +0 -40
- package/lib/client/sync/bucket/SyncDataBucket.js +0 -40
- package/lib/client/sync/bucket/SyncDataBucket.js.map +0 -1
- package/lib/client/sync/stream/streaming-sync-types.d.ts +0 -143
- package/lib/client/sync/stream/streaming-sync-types.js +0 -26
- package/lib/client/sync/stream/streaming-sync-types.js.map +0 -1
- package/src/client/sync/bucket/OpType.ts +0 -23
- package/src/client/sync/bucket/OplogEntry.ts +0 -50
- package/src/client/sync/bucket/SyncDataBatch.ts +0 -11
- package/src/client/sync/bucket/SyncDataBucket.ts +0 -49
- package/src/client/sync/stream/streaming-sync-types.ts +0 -210
|
@@ -1,42 +1,27 @@
|
|
|
1
1
|
import Logger, { ILogger } from 'js-logger';
|
|
2
2
|
|
|
3
|
-
import { InternalProgressInformation } from '../../../db/crud/SyncProgress.js';
|
|
4
3
|
import { SyncStatus, SyncStatusOptions } from '../../../db/crud/SyncStatus.js';
|
|
5
4
|
import { AbortOperation } from '../../../utils/AbortOperation.js';
|
|
6
5
|
import { BaseListener, BaseObserver, BaseObserverInterface, Disposable } from '../../../utils/BaseObserver.js';
|
|
7
6
|
import { throttleLeadingTrailing } from '../../../utils/async.js';
|
|
8
|
-
import {
|
|
9
|
-
BucketChecksum,
|
|
10
|
-
BucketDescription,
|
|
11
|
-
BucketStorageAdapter,
|
|
12
|
-
Checkpoint,
|
|
13
|
-
PowerSyncControlCommand
|
|
14
|
-
} from '../bucket/BucketStorageAdapter.js';
|
|
7
|
+
import { BucketStorageAdapter, PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';
|
|
15
8
|
import { CrudEntry } from '../bucket/CrudEntry.js';
|
|
16
|
-
import { SyncDataBucket } from '../bucket/SyncDataBucket.js';
|
|
17
9
|
import { AbstractRemote, FetchStrategy, SyncStreamOptions } from './AbstractRemote.js';
|
|
18
|
-
import { EstablishSyncStream, Instruction, coreStatusToJs } from './core-instruction.js';
|
|
19
10
|
import {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
isStreamingSyncCheckpoint,
|
|
26
|
-
isStreamingSyncCheckpointComplete,
|
|
27
|
-
isStreamingSyncCheckpointDiff,
|
|
28
|
-
isStreamingSyncCheckpointPartiallyComplete,
|
|
29
|
-
isStreamingSyncData
|
|
30
|
-
} from './streaming-sync-types.js';
|
|
11
|
+
Instruction,
|
|
12
|
+
NonInterruptingInstruction,
|
|
13
|
+
coreStatusToJs,
|
|
14
|
+
isInterruptingInstruction
|
|
15
|
+
} from './core-instruction.js';
|
|
31
16
|
import {
|
|
32
|
-
|
|
33
|
-
extractJsonLines,
|
|
17
|
+
doneResult,
|
|
34
18
|
injectable,
|
|
35
19
|
InjectableIterator,
|
|
36
20
|
map,
|
|
37
|
-
SimpleAsyncIterator
|
|
21
|
+
SimpleAsyncIterator,
|
|
22
|
+
valueResult
|
|
38
23
|
} from '../../../utils/stream_transform.js';
|
|
39
|
-
import
|
|
24
|
+
import { StreamingSyncRequestParameterType } from './JsonValue.js';
|
|
40
25
|
|
|
41
26
|
export enum LockType {
|
|
42
27
|
CRUD = 'crud',
|
|
@@ -49,35 +34,21 @@ export enum SyncStreamConnectionMethod {
|
|
|
49
34
|
}
|
|
50
35
|
|
|
51
36
|
export enum SyncClientImplementation {
|
|
52
|
-
/**
|
|
53
|
-
* Decodes and handles sync lines received from the sync service in JavaScript.
|
|
54
|
-
*
|
|
55
|
-
* This is the default option.
|
|
56
|
-
*
|
|
57
|
-
* @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
|
|
58
|
-
* the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
|
|
59
|
-
* version of the PowerSync SDK.
|
|
60
|
-
*/
|
|
61
|
-
JAVASCRIPT = 'js',
|
|
62
37
|
/**
|
|
63
38
|
* This implementation offloads the sync line decoding and handling into the PowerSync
|
|
64
39
|
* core extension.
|
|
65
40
|
*
|
|
66
|
-
* This
|
|
67
|
-
* recommended client implementation for all apps.
|
|
41
|
+
* This is the only option, as an older JavaScript client implementation has been removed from the SDK.
|
|
68
42
|
*
|
|
69
43
|
* ## Compatibility warning
|
|
70
44
|
*
|
|
71
45
|
* The Rust sync client stores sync data in a format that is slightly different than the one used
|
|
72
|
-
* by the old
|
|
73
|
-
*
|
|
74
|
-
* Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
|
|
75
|
-
* the version introducing {@link RUST} as an option) also supports the new format, so you can switch
|
|
76
|
-
* back to {@link JAVASCRIPT} later.
|
|
46
|
+
* by the old JavaScript client. When adopting the {@link RUST} client on existing databases, the PowerSync SDK will
|
|
47
|
+
* migrate the format automatically.
|
|
77
48
|
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
49
|
+
* SDK versions supporting both the JavaScript and the Rust client support both formats with the JavaScript client
|
|
50
|
+
* implementaiton. However, downgrading to an SDK version that only supports the JavaScript client would not be
|
|
51
|
+
* possible anymore. Problematic SDK versions have been released before 2025-06-09.
|
|
81
52
|
*/
|
|
82
53
|
RUST = 'rust'
|
|
83
54
|
}
|
|
@@ -137,11 +108,7 @@ export interface BaseConnectionOptions {
|
|
|
137
108
|
appMetadata?: Record<string, string>;
|
|
138
109
|
|
|
139
110
|
/**
|
|
140
|
-
*
|
|
141
|
-
* service, or whether this work should be offloaded to the PowerSync core extension.
|
|
142
|
-
*
|
|
143
|
-
* This defaults to the JavaScript implementation ({@link SyncClientImplementation.JAVASCRIPT})
|
|
144
|
-
* since the ({@link SyncClientImplementation.RUST}) implementation is experimental at the moment.
|
|
111
|
+
* @deprecated The Rust sync client is used unconditionally, so this option can't be configured.
|
|
145
112
|
*/
|
|
146
113
|
clientImplementation?: SyncClientImplementation;
|
|
147
114
|
|
|
@@ -207,15 +174,14 @@ export interface StreamingSyncImplementation
|
|
|
207
174
|
*/
|
|
208
175
|
disconnect(): Promise<void>;
|
|
209
176
|
getWriteCheckpoint: () => Promise<string>;
|
|
210
|
-
hasCompletedSync: () => Promise<boolean>;
|
|
211
177
|
isConnected: boolean;
|
|
212
|
-
lastSyncedAt?: Date;
|
|
213
178
|
syncStatus: SyncStatus;
|
|
214
179
|
triggerCrudUpload: () => void;
|
|
215
180
|
waitForReady(): Promise<void>;
|
|
216
181
|
waitForStatus(status: SyncStatusOptions): Promise<void>;
|
|
217
182
|
waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
|
|
218
183
|
updateSubscriptions(subscriptions: SubscribedStream[]): void;
|
|
184
|
+
markConnectionMayHaveChanged(): void;
|
|
219
185
|
}
|
|
220
186
|
|
|
221
187
|
export const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
|
|
@@ -253,16 +219,16 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
253
219
|
extends BaseObserver<StreamingSyncImplementationListener>
|
|
254
220
|
implements StreamingSyncImplementation
|
|
255
221
|
{
|
|
256
|
-
protected _lastSyncedAt: Date | null;
|
|
257
222
|
protected options: AbstractStreamingSyncImplementationOptions;
|
|
258
223
|
protected abortController: AbortController | null;
|
|
259
224
|
// In rare cases, mostly for tests, uploads can be triggered without being properly connected.
|
|
260
225
|
// This allows ensuring that all upload processes can be aborted.
|
|
261
|
-
protected uploadAbortController: AbortController |
|
|
226
|
+
protected uploadAbortController: AbortController | undefined;
|
|
262
227
|
protected crudUpdateListener?: () => void;
|
|
263
228
|
protected streamingSyncPromise?: Promise<void>;
|
|
264
229
|
protected logger: ILogger;
|
|
265
230
|
private activeStreams: SubscribedStream[];
|
|
231
|
+
private connectionMayHaveChanged = false;
|
|
266
232
|
|
|
267
233
|
private isUploadingCrud: boolean = false;
|
|
268
234
|
private notifyCompletedUploads?: () => void;
|
|
@@ -309,7 +275,7 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
309
275
|
* Match only the partial status options provided in the
|
|
310
276
|
* matching status
|
|
311
277
|
*/
|
|
312
|
-
const matchPartialObject = (compA: object, compB:
|
|
278
|
+
const matchPartialObject = (compA: object, compB: any): any => {
|
|
313
279
|
return Object.entries(compA).every(([key, value]) => {
|
|
314
280
|
const comparisonBValue = compB[key];
|
|
315
281
|
if (typeof value == 'object' && typeof comparisonBValue == 'object') {
|
|
@@ -359,10 +325,6 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
359
325
|
|
|
360
326
|
abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
|
|
361
327
|
|
|
362
|
-
async hasCompletedSync() {
|
|
363
|
-
return this.options.adapter.hasCompletedSync();
|
|
364
|
-
}
|
|
365
|
-
|
|
366
328
|
async getWriteCheckpoint(): Promise<string> {
|
|
367
329
|
const clientId = await this.options.adapter.getClientId();
|
|
368
330
|
let path = `/write-checkpoint2.json?client_id=${clientId}`;
|
|
@@ -433,7 +395,7 @@ The next upload iteration will be delayed.`);
|
|
|
433
395
|
this.updateSyncStatus({
|
|
434
396
|
dataFlow: {
|
|
435
397
|
uploading: false,
|
|
436
|
-
uploadError: ex
|
|
398
|
+
uploadError: ex as Error
|
|
437
399
|
}
|
|
438
400
|
});
|
|
439
401
|
await this.delayRetry(controller.signal);
|
|
@@ -442,7 +404,7 @@ The next upload iteration will be delayed.`);
|
|
|
442
404
|
break;
|
|
443
405
|
}
|
|
444
406
|
this.logger.debug(
|
|
445
|
-
`Caught exception when uploading. Upload will retry after a delay. Exception: ${ex.message}`
|
|
407
|
+
`Caught exception when uploading. Upload will retry after a delay. Exception: ${(ex as Error).message}`
|
|
446
408
|
);
|
|
447
409
|
} finally {
|
|
448
410
|
this.updateSyncStatus({
|
|
@@ -452,7 +414,7 @@ The next upload iteration will be delayed.`);
|
|
|
452
414
|
});
|
|
453
415
|
}
|
|
454
416
|
}
|
|
455
|
-
this.uploadAbortController =
|
|
417
|
+
this.uploadAbortController = undefined;
|
|
456
418
|
}
|
|
457
419
|
});
|
|
458
420
|
}
|
|
@@ -579,13 +541,17 @@ The next upload iteration will be delayed.`);
|
|
|
579
541
|
this.logger.warn(ex);
|
|
580
542
|
shouldDelayRetry = false;
|
|
581
543
|
// A disconnect was requested, we should not delay since there is no explicit retry
|
|
544
|
+
} else if (this.connectionMayHaveChanged && (ex as Error).message?.indexOf('No iteration is active') >= 0) {
|
|
545
|
+
this.connectionMayHaveChanged = false;
|
|
546
|
+
this.logger.info('Sync error after changed connection, retrying immediately');
|
|
547
|
+
shouldDelayRetry = false;
|
|
582
548
|
} else {
|
|
583
549
|
this.logger.error(ex);
|
|
584
550
|
}
|
|
585
551
|
|
|
586
552
|
this.updateSyncStatus({
|
|
587
553
|
dataFlow: {
|
|
588
|
-
downloadError: ex
|
|
554
|
+
downloadError: ex as Error
|
|
589
555
|
}
|
|
590
556
|
});
|
|
591
557
|
} finally {
|
|
@@ -614,18 +580,15 @@ The next upload iteration will be delayed.`);
|
|
|
614
580
|
this.updateSyncStatus({ connected: false, connecting: false });
|
|
615
581
|
}
|
|
616
582
|
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
after: entry.op_id
|
|
622
|
-
}));
|
|
623
|
-
const localDescriptions = new Map<string, BucketDescription | null>();
|
|
624
|
-
for (const entry of bucketEntries) {
|
|
625
|
-
localDescriptions.set(entry.bucket, null);
|
|
626
|
-
}
|
|
583
|
+
markConnectionMayHaveChanged() {
|
|
584
|
+
// By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
|
|
585
|
+
// an active sync iteration on the connection in use.
|
|
586
|
+
this.connectionMayHaveChanged = true;
|
|
627
587
|
|
|
628
|
-
|
|
588
|
+
// This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
|
|
589
|
+
// make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
|
|
590
|
+
// iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
|
|
591
|
+
this.handleActiveStreamsChange?.();
|
|
629
592
|
}
|
|
630
593
|
|
|
631
594
|
/**
|
|
@@ -675,277 +638,62 @@ The next upload iteration will be delayed.`);
|
|
|
675
638
|
`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`
|
|
676
639
|
);
|
|
677
640
|
}
|
|
678
|
-
const clientImplementation = resolvedOptions.clientImplementation;
|
|
679
|
-
this.updateSyncStatus({ clientImplementation });
|
|
680
641
|
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
return null;
|
|
684
|
-
} else {
|
|
685
|
-
await this.requireKeyFormat(true);
|
|
686
|
-
return await this.rustSyncIteration(signal, resolvedOptions);
|
|
687
|
-
}
|
|
642
|
+
await this.requireKeyFormat(true);
|
|
643
|
+
return await this.rustSyncIteration(signal, resolvedOptions);
|
|
688
644
|
}
|
|
689
645
|
});
|
|
690
646
|
}
|
|
691
647
|
|
|
692
|
-
private
|
|
648
|
+
private receiveSyncLines(data: {
|
|
693
649
|
options: SyncStreamOptions;
|
|
694
650
|
connection: RequiredPowerSyncConnectionOptions;
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
const { options, connection, bson } = data;
|
|
651
|
+
}): SimpleAsyncIterator<EnqueuedCommand> {
|
|
652
|
+
const { options, connection } = data;
|
|
698
653
|
const remote = this.options.remote;
|
|
699
654
|
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
{
|
|
655
|
+
const openInner = async () => {
|
|
656
|
+
if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
|
|
657
|
+
return await remote.fetchStream(options);
|
|
658
|
+
} else {
|
|
659
|
+
return await this.options.remote.socketStreamRaw({
|
|
705
660
|
...options,
|
|
706
661
|
...{ fetchStrategy: connection.fetchStrategy }
|
|
707
|
-
},
|
|
708
|
-
bson
|
|
709
|
-
);
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
private async legacyStreamingSyncIteration(signal: AbortSignal, resolvedOptions: RequiredPowerSyncConnectionOptions) {
|
|
714
|
-
const rawTables = resolvedOptions.serializedSchema?.raw_tables;
|
|
715
|
-
if (rawTables != null && rawTables.length) {
|
|
716
|
-
this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
|
|
717
|
-
}
|
|
718
|
-
if (this.activeStreams.length) {
|
|
719
|
-
this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
this.logger.debug('Streaming sync iteration started');
|
|
723
|
-
this.options.adapter.startSession();
|
|
724
|
-
let [req, bucketMap] = await this.collectLocalBucketState();
|
|
725
|
-
|
|
726
|
-
let targetCheckpoint: Checkpoint | null = null;
|
|
727
|
-
// A checkpoint that has been validated but not applied (e.g. due to pending local writes)
|
|
728
|
-
let pendingValidatedCheckpoint: Checkpoint | null = null;
|
|
729
|
-
|
|
730
|
-
const clientId = await this.options.adapter.getClientId();
|
|
731
|
-
const usingFixedKeyFormat = await this.requireKeyFormat(false);
|
|
732
|
-
|
|
733
|
-
this.logger.debug('Requesting stream from server');
|
|
734
|
-
|
|
735
|
-
const syncOptions: SyncStreamOptions = {
|
|
736
|
-
path: '/sync/stream',
|
|
737
|
-
abortSignal: signal,
|
|
738
|
-
data: {
|
|
739
|
-
buckets: req,
|
|
740
|
-
include_checksum: true,
|
|
741
|
-
raw_data: true,
|
|
742
|
-
parameters: resolvedOptions.params,
|
|
743
|
-
app_metadata: resolvedOptions.appMetadata,
|
|
744
|
-
client_id: clientId
|
|
745
|
-
}
|
|
746
|
-
};
|
|
747
|
-
|
|
748
|
-
const bson = await this.options.remote.getBSON();
|
|
749
|
-
const source = await this.receiveSyncLines({
|
|
750
|
-
options: syncOptions,
|
|
751
|
-
connection: resolvedOptions,
|
|
752
|
-
bson
|
|
753
|
-
});
|
|
754
|
-
const stream: InjectableIterator<StreamingSyncLineOrCrudUploadComplete> = injectable(
|
|
755
|
-
map(source, (line) => {
|
|
756
|
-
if (typeof line == 'string') {
|
|
757
|
-
return JSON.parse(line) as StreamingSyncLine;
|
|
758
|
-
} else {
|
|
759
|
-
return bson.deserialize(line) as StreamingSyncLine;
|
|
760
|
-
}
|
|
761
|
-
})
|
|
762
|
-
);
|
|
763
|
-
|
|
764
|
-
this.logger.debug('Stream established. Processing events');
|
|
765
|
-
|
|
766
|
-
this.notifyCompletedUploads = () => {
|
|
767
|
-
stream.inject({ crud_upload_completed: null });
|
|
768
|
-
};
|
|
769
|
-
|
|
770
|
-
while (true) {
|
|
771
|
-
const { value: line, done } = await stream.next();
|
|
772
|
-
if (done) {
|
|
773
|
-
// The stream has closed while waiting
|
|
774
|
-
return;
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
if ('crud_upload_completed' in line) {
|
|
778
|
-
if (pendingValidatedCheckpoint != null) {
|
|
779
|
-
const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);
|
|
780
|
-
if (applied) {
|
|
781
|
-
pendingValidatedCheckpoint = null;
|
|
782
|
-
} else if (endIteration) {
|
|
783
|
-
break;
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
|
|
787
|
-
continue;
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
// A connection is active and messages are being received
|
|
791
|
-
if (!this.syncStatus.connected) {
|
|
792
|
-
// There is a connection now
|
|
793
|
-
Promise.resolve().then(() => this.triggerCrudUpload());
|
|
794
|
-
this.updateSyncStatus({
|
|
795
|
-
connected: true
|
|
796
662
|
});
|
|
797
663
|
}
|
|
664
|
+
};
|
|
798
665
|
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
666
|
+
let inner: SimpleAsyncIterator<string | Uint8Array> | undefined;
|
|
667
|
+
let done = false;
|
|
668
|
+
|
|
669
|
+
return {
|
|
670
|
+
async next(): Promise<IteratorResult<EnqueuedCommand>> {
|
|
671
|
+
if (done) {
|
|
672
|
+
return doneResult;
|
|
673
|
+
} else if (inner == null) {
|
|
674
|
+
inner = await openInner();
|
|
675
|
+
// We're connected here, so we can tell the core extension about it.
|
|
676
|
+
return valueResult<EnqueuedCommand>({
|
|
677
|
+
command: PowerSyncControlCommand.CONNECTION_STATE,
|
|
678
|
+
payload: 'established'
|
|
809
679
|
});
|
|
810
|
-
bucketsToDelete.delete(checksum.bucket);
|
|
811
|
-
}
|
|
812
|
-
if (bucketsToDelete.size > 0) {
|
|
813
|
-
this.logger.debug('Removing buckets', [...bucketsToDelete]);
|
|
814
|
-
}
|
|
815
|
-
bucketMap = newBuckets;
|
|
816
|
-
await this.options.adapter.removeBuckets([...bucketsToDelete]);
|
|
817
|
-
await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
|
|
818
|
-
await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
|
|
819
|
-
} else if (isStreamingSyncCheckpointComplete(line)) {
|
|
820
|
-
const result = await this.applyCheckpoint(targetCheckpoint!);
|
|
821
|
-
if (result.endIteration) {
|
|
822
|
-
return;
|
|
823
|
-
} else if (!result.applied) {
|
|
824
|
-
// "Could not apply checkpoint due to local data". We need to retry after
|
|
825
|
-
// finishing uploads.
|
|
826
|
-
pendingValidatedCheckpoint = targetCheckpoint;
|
|
827
|
-
} else {
|
|
828
|
-
// Nothing to retry later. This would likely already be null from the last
|
|
829
|
-
// checksum or checksum_diff operation, but we make sure.
|
|
830
|
-
pendingValidatedCheckpoint = null;
|
|
831
|
-
}
|
|
832
|
-
} else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
|
|
833
|
-
const priority = line.partial_checkpoint_complete.priority;
|
|
834
|
-
this.logger.debug('Partial checkpoint complete', priority);
|
|
835
|
-
const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint!, priority);
|
|
836
|
-
if (!result.checkpointValid) {
|
|
837
|
-
// This means checksums failed. Start again with a new checkpoint.
|
|
838
|
-
// TODO: better back-off
|
|
839
|
-
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
840
|
-
return;
|
|
841
|
-
} else if (!result.ready) {
|
|
842
|
-
// If we have pending uploads, we can't complete new checkpoints outside of priority 0.
|
|
843
|
-
// We'll resolve this for a complete checkpoint.
|
|
844
680
|
} else {
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
connected: true,
|
|
858
|
-
priorityStatusEntries: priorityStates
|
|
859
|
-
});
|
|
860
|
-
}
|
|
861
|
-
} else if (isStreamingSyncCheckpointDiff(line)) {
|
|
862
|
-
// TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint
|
|
863
|
-
if (targetCheckpoint == null) {
|
|
864
|
-
throw new Error('Checkpoint diff without previous checkpoint');
|
|
865
|
-
}
|
|
866
|
-
// New checkpoint - existing validated checkpoint is no longer valid
|
|
867
|
-
pendingValidatedCheckpoint = null;
|
|
868
|
-
const diff = line.checkpoint_diff;
|
|
869
|
-
const newBuckets = new Map<string, BucketChecksum>();
|
|
870
|
-
for (const checksum of targetCheckpoint.buckets) {
|
|
871
|
-
newBuckets.set(checksum.bucket, checksum);
|
|
872
|
-
}
|
|
873
|
-
for (const checksum of diff.updated_buckets) {
|
|
874
|
-
newBuckets.set(checksum.bucket, checksum);
|
|
875
|
-
}
|
|
876
|
-
for (const bucket of diff.removed_buckets) {
|
|
877
|
-
newBuckets.delete(bucket);
|
|
878
|
-
}
|
|
879
|
-
|
|
880
|
-
const newCheckpoint: Checkpoint = {
|
|
881
|
-
last_op_id: diff.last_op_id,
|
|
882
|
-
buckets: [...newBuckets.values()],
|
|
883
|
-
write_checkpoint: diff.write_checkpoint
|
|
884
|
-
};
|
|
885
|
-
targetCheckpoint = newCheckpoint;
|
|
886
|
-
await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
|
|
887
|
-
|
|
888
|
-
bucketMap = new Map();
|
|
889
|
-
newBuckets.forEach((checksum, name) =>
|
|
890
|
-
bucketMap.set(name, {
|
|
891
|
-
name: checksum.bucket,
|
|
892
|
-
priority: checksum.priority ?? FALLBACK_PRIORITY
|
|
893
|
-
})
|
|
894
|
-
);
|
|
895
|
-
|
|
896
|
-
const bucketsToDelete = diff.removed_buckets;
|
|
897
|
-
if (bucketsToDelete.length > 0) {
|
|
898
|
-
this.logger.debug('Remove buckets', bucketsToDelete);
|
|
899
|
-
}
|
|
900
|
-
await this.options.adapter.removeBuckets(bucketsToDelete);
|
|
901
|
-
await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
|
|
902
|
-
} else if (isStreamingSyncData(line)) {
|
|
903
|
-
const { data } = line;
|
|
904
|
-
const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;
|
|
905
|
-
let updatedProgress: InternalProgressInformation | null = null;
|
|
906
|
-
if (previousProgress) {
|
|
907
|
-
updatedProgress = { ...previousProgress };
|
|
908
|
-
const progressForBucket = updatedProgress[data.bucket];
|
|
909
|
-
if (progressForBucket) {
|
|
910
|
-
updatedProgress[data.bucket] = {
|
|
911
|
-
...progressForBucket,
|
|
912
|
-
since_last: progressForBucket.since_last + data.data.length
|
|
913
|
-
};
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
this.updateSyncStatus({
|
|
918
|
-
dataFlow: {
|
|
919
|
-
downloading: true,
|
|
920
|
-
downloadProgress: updatedProgress
|
|
681
|
+
const event = await inner.next();
|
|
682
|
+
if (event.done) {
|
|
683
|
+
done = true;
|
|
684
|
+
return valueResult<EnqueuedCommand>({ command: PowerSyncControlCommand.CONNECTION_STATE, payload: 'end' });
|
|
685
|
+
} else {
|
|
686
|
+
return valueResult<EnqueuedCommand>({
|
|
687
|
+
command:
|
|
688
|
+
typeof event.value == 'string'
|
|
689
|
+
? PowerSyncControlCommand.PROCESS_TEXT_LINE
|
|
690
|
+
: PowerSyncControlCommand.PROCESS_BSON_LINE,
|
|
691
|
+
payload: event.value
|
|
692
|
+
});
|
|
921
693
|
}
|
|
922
|
-
});
|
|
923
|
-
await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);
|
|
924
|
-
} else if (isStreamingKeepalive(line)) {
|
|
925
|
-
const remaining_seconds = line.token_expires_in;
|
|
926
|
-
if (remaining_seconds == 0) {
|
|
927
|
-
// Connection would be closed automatically right after this
|
|
928
|
-
this.logger.debug('Token expiring; reconnect');
|
|
929
|
-
/**
|
|
930
|
-
* For a rare case where the backend connector does not update the token
|
|
931
|
-
* (uses the same one), this should have some delay.
|
|
932
|
-
*/
|
|
933
|
-
await this.delayRetry();
|
|
934
|
-
return;
|
|
935
|
-
} else if (remaining_seconds < 30) {
|
|
936
|
-
this.logger.debug('Token will expire soon; reconnect');
|
|
937
|
-
// Pre-emptively refresh the token
|
|
938
|
-
this.options.remote.invalidateCredentials();
|
|
939
|
-
return;
|
|
940
694
|
}
|
|
941
|
-
this.triggerCrudUpload();
|
|
942
|
-
} else {
|
|
943
|
-
this.logger.debug('Received unknown sync line', line);
|
|
944
695
|
}
|
|
945
|
-
}
|
|
946
|
-
this.logger.debug('Stream input empty');
|
|
947
|
-
// Connection closed. Likely due to auth issue.
|
|
948
|
-
return;
|
|
696
|
+
};
|
|
949
697
|
}
|
|
950
698
|
|
|
951
699
|
private async rustSyncIteration(
|
|
@@ -955,83 +703,41 @@ The next upload iteration will be delayed.`);
|
|
|
955
703
|
const syncImplementation = this;
|
|
956
704
|
const adapter = this.options.adapter;
|
|
957
705
|
const remote = this.options.remote;
|
|
958
|
-
const controller = new AbortController();
|
|
959
|
-
const abort = () => {
|
|
960
|
-
return controller.abort(signal.reason);
|
|
961
|
-
};
|
|
962
|
-
signal.addEventListener('abort', abort);
|
|
963
|
-
let receivingLines: Promise<void> | null = null;
|
|
964
|
-
let hadSyncLine = false;
|
|
965
706
|
let hideDisconnectOnRestart = false;
|
|
707
|
+
let notifyTokenRefreshed: (() => void) | undefined;
|
|
966
708
|
|
|
967
709
|
if (signal.aborted) {
|
|
968
710
|
throw new AbortOperation('Connection request has been aborted');
|
|
969
711
|
}
|
|
970
712
|
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
const syncOptions: SyncStreamOptions = {
|
|
978
|
-
path: '/sync/stream',
|
|
979
|
-
abortSignal: controller.signal,
|
|
980
|
-
data: instr.request
|
|
713
|
+
function startCommand() {
|
|
714
|
+
const options: any = {
|
|
715
|
+
parameters: resolvedOptions.params,
|
|
716
|
+
app_metadata: resolvedOptions.appMetadata,
|
|
717
|
+
active_streams: syncImplementation.activeStreams,
|
|
718
|
+
include_defaults: resolvedOptions.includeDefaultStreams
|
|
981
719
|
};
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
map(
|
|
985
|
-
await syncImplementation.receiveSyncLines({
|
|
986
|
-
options: syncOptions,
|
|
987
|
-
connection: resolvedOptions
|
|
988
|
-
}),
|
|
989
|
-
(line) => {
|
|
990
|
-
if (typeof line == 'string') {
|
|
991
|
-
return {
|
|
992
|
-
command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
|
|
993
|
-
payload: line
|
|
994
|
-
};
|
|
995
|
-
} else {
|
|
996
|
-
return {
|
|
997
|
-
command: PowerSyncControlCommand.PROCESS_BSON_LINE,
|
|
998
|
-
payload: line
|
|
999
|
-
};
|
|
1000
|
-
}
|
|
1001
|
-
}
|
|
1002
|
-
)
|
|
1003
|
-
);
|
|
1004
|
-
|
|
1005
|
-
// The rust client will set connected: true after the first sync line because that's when it gets invoked, but
|
|
1006
|
-
// we're already connected here and can report that.
|
|
1007
|
-
syncImplementation.updateSyncStatus({ connected: true });
|
|
1008
|
-
|
|
1009
|
-
try {
|
|
1010
|
-
while (true) {
|
|
1011
|
-
let event = await controlInvocations.next();
|
|
1012
|
-
if (event.done) {
|
|
1013
|
-
break;
|
|
1014
|
-
}
|
|
1015
|
-
|
|
1016
|
-
const line = event.value;
|
|
1017
|
-
await control(line.command, line.payload);
|
|
1018
|
-
|
|
1019
|
-
if (!hadSyncLine) {
|
|
1020
|
-
syncImplementation.triggerCrudUpload();
|
|
1021
|
-
hadSyncLine = true;
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
} finally {
|
|
1025
|
-
abort();
|
|
1026
|
-
signal.removeEventListener('abort', abort);
|
|
720
|
+
if (resolvedOptions.serializedSchema) {
|
|
721
|
+
options.schema = resolvedOptions.serializedSchema;
|
|
1027
722
|
}
|
|
723
|
+
|
|
724
|
+
return invokePowerSyncControl(PowerSyncControlCommand.START, JSON.stringify(options));
|
|
1028
725
|
}
|
|
1029
726
|
|
|
1030
727
|
async function stop() {
|
|
1031
|
-
await
|
|
728
|
+
const instructions = await invokePowerSyncControl(PowerSyncControlCommand.STOP);
|
|
729
|
+
for (const instruction of instructions) {
|
|
730
|
+
// We don't need to handle interrupting instructions since we're unconditionally ending the sync iteration at
|
|
731
|
+
// this point.
|
|
732
|
+
if (isInterruptingInstruction(instruction)) continue;
|
|
733
|
+
await handleInstruction(instruction);
|
|
734
|
+
}
|
|
1032
735
|
}
|
|
1033
736
|
|
|
1034
|
-
async function
|
|
737
|
+
async function invokePowerSyncControl(
|
|
738
|
+
op: PowerSyncControlCommand,
|
|
739
|
+
payload?: Uint8Array | string
|
|
740
|
+
): Promise<Instruction[]> {
|
|
1035
741
|
const rawResponse = await adapter.control(op, payload ?? null);
|
|
1036
742
|
const logger = syncImplementation.logger;
|
|
1037
743
|
logger.trace(
|
|
@@ -1041,10 +747,15 @@ The next upload iteration will be delayed.`);
|
|
|
1041
747
|
rawResponse
|
|
1042
748
|
);
|
|
1043
749
|
|
|
1044
|
-
|
|
750
|
+
if (op != PowerSyncControlCommand.STOP) {
|
|
751
|
+
// Evidently we have a working connection here, otherwise powersync_control would have failed.
|
|
752
|
+
syncImplementation.connectionMayHaveChanged = false;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
return JSON.parse(rawResponse);
|
|
1045
756
|
}
|
|
1046
757
|
|
|
1047
|
-
async function handleInstruction(instruction:
|
|
758
|
+
async function handleInstruction(instruction: NonInterruptingInstruction) {
|
|
1048
759
|
if ('LogLine' in instruction) {
|
|
1049
760
|
switch (instruction.LogLine.severity) {
|
|
1050
761
|
case 'DEBUG':
|
|
@@ -1059,13 +770,6 @@ The next upload iteration will be delayed.`);
|
|
|
1059
770
|
}
|
|
1060
771
|
} else if ('UpdateSyncStatus' in instruction) {
|
|
1061
772
|
syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));
|
|
1062
|
-
} else if ('EstablishSyncStream' in instruction) {
|
|
1063
|
-
if (receivingLines != null) {
|
|
1064
|
-
// Already connected, this shouldn't happen during a single iteration.
|
|
1065
|
-
throw 'Unexpected request to establish sync stream, already connected';
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
receivingLines = connect(instruction.EstablishSyncStream);
|
|
1069
773
|
} else if ('FetchCredentials' in instruction) {
|
|
1070
774
|
if (instruction.FetchCredentials.did_expire) {
|
|
1071
775
|
remote.invalidateCredentials();
|
|
@@ -1075,16 +779,13 @@ The next upload iteration will be delayed.`);
|
|
|
1075
779
|
// Restart iteration after the credentials have been refreshed.
|
|
1076
780
|
remote.fetchCredentials().then(
|
|
1077
781
|
(_) => {
|
|
1078
|
-
|
|
782
|
+
notifyTokenRefreshed?.();
|
|
1079
783
|
},
|
|
1080
784
|
(err) => {
|
|
1081
785
|
syncImplementation.logger.warn('Could not prefetch credentials', err);
|
|
1082
786
|
}
|
|
1083
787
|
);
|
|
1084
788
|
}
|
|
1085
|
-
} else if ('CloseSyncStream' in instruction) {
|
|
1086
|
-
controller.abort();
|
|
1087
|
-
hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
|
|
1088
789
|
} else if ('FlushFileSystem' in instruction) {
|
|
1089
790
|
// Not necessary on JS platforms.
|
|
1090
791
|
} else if ('DidCompleteSync' in instruction) {
|
|
@@ -1096,115 +797,86 @@ The next upload iteration will be delayed.`);
|
|
|
1096
797
|
}
|
|
1097
798
|
}
|
|
1098
799
|
|
|
1099
|
-
async function handleInstructions(instructions: Instruction[]) {
|
|
1100
|
-
for (const instr of instructions) {
|
|
1101
|
-
await handleInstruction(instr);
|
|
1102
|
-
}
|
|
1103
|
-
}
|
|
1104
|
-
|
|
1105
800
|
try {
|
|
1106
|
-
const
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
801
|
+
const defaultResult = { immediateRestart: false };
|
|
802
|
+
// Pending sync lines received from the service, as well as local events that trigger a powersync_control
|
|
803
|
+
// invocation (local events include refreshed tokens and completed uploads).
|
|
804
|
+
// This is a single data stream so that we can handle all control calls from a single place.
|
|
805
|
+
let controlInvocations: InjectableIterator<EnqueuedCommand> | null = null;
|
|
806
|
+
|
|
807
|
+
for (const startInstruction of await startCommand()) {
|
|
808
|
+
if ('EstablishSyncStream' in startInstruction) {
|
|
809
|
+
const syncOptions: SyncStreamOptions = {
|
|
810
|
+
path: '/sync/stream',
|
|
811
|
+
abortSignal: signal,
|
|
812
|
+
data: startInstruction.EstablishSyncStream.request
|
|
813
|
+
};
|
|
814
|
+
|
|
815
|
+
controlInvocations = injectable(
|
|
816
|
+
syncImplementation.receiveSyncLines({
|
|
817
|
+
options: syncOptions,
|
|
818
|
+
connection: resolvedOptions
|
|
819
|
+
})
|
|
820
|
+
);
|
|
821
|
+
} else if ('CloseSyncStream' in startInstruction) {
|
|
822
|
+
return defaultResult;
|
|
823
|
+
} else {
|
|
824
|
+
await handleInstruction(startInstruction);
|
|
825
|
+
}
|
|
1114
826
|
}
|
|
1115
|
-
|
|
1116
|
-
await control(PowerSyncControlCommand.START, JSON.stringify(options));
|
|
827
|
+
if (controlInvocations == null) return defaultResult;
|
|
1117
828
|
|
|
1118
829
|
this.notifyCompletedUploads = () => {
|
|
1119
|
-
controlInvocations
|
|
830
|
+
controlInvocations.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
|
|
1120
831
|
};
|
|
1121
832
|
this.handleActiveStreamsChange = () => {
|
|
1122
|
-
controlInvocations
|
|
833
|
+
controlInvocations.inject({
|
|
1123
834
|
command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
|
|
1124
835
|
payload: JSON.stringify(this.activeStreams)
|
|
1125
836
|
});
|
|
1126
837
|
};
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
return { immediateRestart: hideDisconnectOnRestart };
|
|
1134
|
-
}
|
|
1135
|
-
|
|
1136
|
-
private async updateSyncStatusForStartingCheckpoint(checkpoint: Checkpoint) {
|
|
1137
|
-
const localProgress = await this.options.adapter.getBucketOperationProgress();
|
|
1138
|
-
const progress: InternalProgressInformation = {};
|
|
1139
|
-
let invalidated = false;
|
|
1140
|
-
|
|
1141
|
-
for (const bucket of checkpoint.buckets) {
|
|
1142
|
-
const savedProgress = localProgress[bucket.bucket];
|
|
1143
|
-
const atLast = savedProgress?.atLast ?? 0;
|
|
1144
|
-
const sinceLast = savedProgress?.sinceLast ?? 0;
|
|
1145
|
-
|
|
1146
|
-
progress[bucket.bucket] = {
|
|
1147
|
-
// The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service
|
|
1148
|
-
// will use by default.
|
|
1149
|
-
priority: bucket.priority ?? 3,
|
|
1150
|
-
at_last: atLast,
|
|
1151
|
-
since_last: sinceLast,
|
|
1152
|
-
target_count: bucket.count ?? 0
|
|
838
|
+
notifyTokenRefreshed = () => {
|
|
839
|
+
controlInvocations.inject({
|
|
840
|
+
command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED
|
|
841
|
+
});
|
|
1153
842
|
};
|
|
1154
843
|
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
844
|
+
let hadSyncLine = false;
|
|
845
|
+
loop: while (true) {
|
|
846
|
+
const { done, value } = await controlInvocations.next();
|
|
847
|
+
if (done) break;
|
|
848
|
+
|
|
849
|
+
if (!hadSyncLine) {
|
|
850
|
+
// Trigger a local CRUD upload when the first sync line has been received, this allows uploading local changes
|
|
851
|
+
// that have been made while offline or disconnected.
|
|
852
|
+
if (
|
|
853
|
+
value.command == PowerSyncControlCommand.PROCESS_TEXT_LINE ||
|
|
854
|
+
value.command == PowerSyncControlCommand.PROCESS_BSON_LINE
|
|
855
|
+
) {
|
|
856
|
+
hadSyncLine = true;
|
|
857
|
+
this.triggerCrudUpload?.();
|
|
858
|
+
}
|
|
859
|
+
}
|
|
1170
860
|
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
861
|
+
const instructions = await invokePowerSyncControl(value.command, value.payload);
|
|
862
|
+
for (const instruction of instructions) {
|
|
863
|
+
if ('EstablishSyncStream' in instruction) {
|
|
864
|
+
throw new Error('Received EstablishSyncStream while already connected.');
|
|
865
|
+
} else if ('CloseSyncStream' in instruction) {
|
|
866
|
+
hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
|
|
867
|
+
break loop;
|
|
868
|
+
} else {
|
|
869
|
+
await handleInstruction(instruction);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
1175
872
|
}
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
let result = await this.options.adapter.syncLocalDatabase(checkpoint);
|
|
1181
|
-
|
|
1182
|
-
if (!result.checkpointValid) {
|
|
1183
|
-
this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);
|
|
1184
|
-
// This means checksums failed. Start again with a new checkpoint.
|
|
1185
|
-
// TODO: better back-off
|
|
1186
|
-
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
1187
|
-
return { applied: false, endIteration: true };
|
|
1188
|
-
} else if (!result.ready) {
|
|
1189
|
-
this.logger.debug(
|
|
1190
|
-
`Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`
|
|
1191
|
-
);
|
|
1192
|
-
|
|
1193
|
-
return { applied: false, endIteration: false };
|
|
873
|
+
} finally {
|
|
874
|
+
this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
|
|
875
|
+
notifyTokenRefreshed = undefined;
|
|
876
|
+
await stop();
|
|
1194
877
|
}
|
|
1195
878
|
|
|
1196
|
-
|
|
1197
|
-
this.updateSyncStatus({
|
|
1198
|
-
connected: true,
|
|
1199
|
-
lastSyncedAt: new Date(),
|
|
1200
|
-
dataFlow: {
|
|
1201
|
-
downloading: false,
|
|
1202
|
-
downloadProgress: null,
|
|
1203
|
-
downloadError: undefined
|
|
1204
|
-
}
|
|
1205
|
-
});
|
|
1206
|
-
|
|
1207
|
-
return { applied: true, endIteration: false };
|
|
879
|
+
return { immediateRestart: hideDisconnectOnRestart };
|
|
1208
880
|
}
|
|
1209
881
|
|
|
1210
882
|
protected updateSyncStatus(options: SyncStatusOptions) {
|