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