@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.
Files changed (76) hide show
  1. package/dist/bundle.cjs +161 -766
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +162 -755
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +161 -766
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +162 -755
  8. package/dist/bundle.node.mjs.map +1 -1
  9. package/dist/index.d.cts +39 -370
  10. package/legacy/sync_protocol.d.ts +103 -0
  11. package/lib/client/ConnectionManager.js +1 -1
  12. package/lib/client/ConnectionManager.js.map +1 -1
  13. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +6 -64
  14. package/lib/client/sync/bucket/BucketStorageAdapter.js +4 -0
  15. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -1
  16. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +1 -28
  17. package/lib/client/sync/bucket/SqliteBucketStorage.js +0 -162
  18. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -1
  19. package/lib/client/sync/stream/AbstractRemote.d.ts +2 -12
  20. package/lib/client/sync/stream/AbstractRemote.js +3 -13
  21. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  22. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +12 -35
  23. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +145 -424
  24. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  25. package/lib/client/sync/stream/JsonValue.d.ts +7 -0
  26. package/lib/client/sync/stream/JsonValue.js +2 -0
  27. package/lib/client/sync/stream/JsonValue.js.map +1 -0
  28. package/lib/client/sync/stream/core-instruction.d.ts +14 -9
  29. package/lib/client/sync/stream/core-instruction.js +3 -0
  30. package/lib/client/sync/stream/core-instruction.js.map +1 -1
  31. package/lib/db/DBAdapter.d.ts +9 -0
  32. package/lib/db/DBAdapter.js +8 -1
  33. package/lib/db/DBAdapter.js.map +1 -1
  34. package/lib/db/crud/SyncStatus.d.ts +3 -4
  35. package/lib/db/crud/SyncStatus.js +0 -4
  36. package/lib/db/crud/SyncStatus.js.map +1 -1
  37. package/lib/db/schema/RawTable.d.ts +0 -5
  38. package/lib/db/schema/Schema.d.ts +0 -2
  39. package/lib/db/schema/Schema.js +0 -2
  40. package/lib/db/schema/Schema.js.map +1 -1
  41. package/lib/index.d.ts +1 -5
  42. package/lib/index.js +1 -5
  43. package/lib/index.js.map +1 -1
  44. package/package.json +9 -6
  45. package/src/client/ConnectionManager.ts +1 -1
  46. package/src/client/sync/bucket/BucketStorageAdapter.ts +6 -71
  47. package/src/client/sync/bucket/SqliteBucketStorage.ts +1 -197
  48. package/src/client/sync/stream/AbstractRemote.ts +5 -27
  49. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +168 -496
  50. package/src/client/sync/stream/JsonValue.ts +8 -0
  51. package/src/client/sync/stream/core-instruction.ts +15 -5
  52. package/src/db/DBAdapter.ts +20 -2
  53. package/src/db/crud/SyncStatus.ts +4 -5
  54. package/src/db/schema/RawTable.ts +0 -5
  55. package/src/db/schema/Schema.ts +0 -2
  56. package/src/index.ts +1 -5
  57. package/lib/client/sync/bucket/OpType.d.ts +0 -16
  58. package/lib/client/sync/bucket/OpType.js +0 -23
  59. package/lib/client/sync/bucket/OpType.js.map +0 -1
  60. package/lib/client/sync/bucket/OplogEntry.d.ts +0 -23
  61. package/lib/client/sync/bucket/OplogEntry.js +0 -36
  62. package/lib/client/sync/bucket/OplogEntry.js.map +0 -1
  63. package/lib/client/sync/bucket/SyncDataBatch.d.ts +0 -6
  64. package/lib/client/sync/bucket/SyncDataBatch.js +0 -12
  65. package/lib/client/sync/bucket/SyncDataBatch.js.map +0 -1
  66. package/lib/client/sync/bucket/SyncDataBucket.d.ts +0 -40
  67. package/lib/client/sync/bucket/SyncDataBucket.js +0 -40
  68. package/lib/client/sync/bucket/SyncDataBucket.js.map +0 -1
  69. package/lib/client/sync/stream/streaming-sync-types.d.ts +0 -143
  70. package/lib/client/sync/stream/streaming-sync-types.js +0 -26
  71. package/lib/client/sync/stream/streaming-sync-types.js.map +0 -1
  72. package/src/client/sync/bucket/OpType.ts +0 -23
  73. package/src/client/sync/bucket/OplogEntry.ts +0 -50
  74. package/src/client/sync/bucket/SyncDataBatch.ts +0 -11
  75. package/src/client/sync/bucket/SyncDataBucket.ts +0 -49
  76. package/src/client/sync/stream/streaming-sync-types.ts +0 -210
@@ -4,11 +4,9 @@ import { AbortOperation } from '../../../utils/AbortOperation.js';
4
4
  import { BaseObserver } from '../../../utils/BaseObserver.js';
5
5
  import { throttleLeadingTrailing } from '../../../utils/async.js';
6
6
  import { PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';
7
- import { SyncDataBucket } from '../bucket/SyncDataBucket.js';
8
7
  import { FetchStrategy } from './AbstractRemote.js';
9
- import { coreStatusToJs } from './core-instruction.js';
10
- import { isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData } from './streaming-sync-types.js';
11
- import { injectable, map } from '../../../utils/stream_transform.js';
8
+ import { coreStatusToJs, isInterruptingInstruction } from './core-instruction.js';
9
+ import { doneResult, injectable, valueResult } from '../../../utils/stream_transform.js';
12
10
  export var LockType;
13
11
  (function (LockType) {
14
12
  LockType["CRUD"] = "crud";
@@ -21,35 +19,21 @@ export var SyncStreamConnectionMethod;
21
19
  })(SyncStreamConnectionMethod || (SyncStreamConnectionMethod = {}));
22
20
  export var SyncClientImplementation;
23
21
  (function (SyncClientImplementation) {
24
- /**
25
- * Decodes and handles sync lines received from the sync service in JavaScript.
26
- *
27
- * This is the default option.
28
- *
29
- * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
30
- * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
31
- * version of the PowerSync SDK.
32
- */
33
- SyncClientImplementation["JAVASCRIPT"] = "js";
34
22
  /**
35
23
  * This implementation offloads the sync line decoding and handling into the PowerSync
36
24
  * core extension.
37
25
  *
38
- * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
39
- * recommended client implementation for all apps.
26
+ * This is the only option, as an older JavaScript client implementation has been removed from the SDK.
40
27
  *
41
28
  * ## Compatibility warning
42
29
  *
43
30
  * The Rust sync client stores sync data in a format that is slightly different than the one used
44
- * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing
45
- * databases, the PowerSync SDK will migrate the format automatically.
46
- * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
47
- * the version introducing {@link RUST} as an option) also supports the new format, so you can switch
48
- * back to {@link JAVASCRIPT} later.
31
+ * by the old JavaScript client. When adopting the {@link RUST} client on existing databases, the PowerSync SDK will
32
+ * migrate the format automatically.
49
33
  *
50
- * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later
51
- * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)
52
- * can lead to sync issues.
34
+ * SDK versions supporting both the JavaScript and the Rust client support both formats with the JavaScript client
35
+ * implementaiton. However, downgrading to an SDK version that only supports the JavaScript client would not be
36
+ * possible anymore. Problematic SDK versions have been released before 2025-06-09.
53
37
  */
54
38
  SyncClientImplementation["RUST"] = "rust";
55
39
  })(SyncClientImplementation || (SyncClientImplementation = {}));
@@ -78,7 +62,6 @@ export const DEFAULT_STREAM_CONNECTION_OPTIONS = {
78
62
  // messages.
79
63
  const FALLBACK_PRIORITY = 3;
80
64
  export class AbstractStreamingSyncImplementation extends BaseObserver {
81
- _lastSyncedAt;
82
65
  options;
83
66
  abortController;
84
67
  // In rare cases, mostly for tests, uploads can be triggered without being properly connected.
@@ -88,6 +71,7 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
88
71
  streamingSyncPromise;
89
72
  logger;
90
73
  activeStreams;
74
+ connectionMayHaveChanged = false;
91
75
  isUploadingCrud = false;
92
76
  notifyCompletedUploads;
93
77
  handleActiveStreamsChange;
@@ -167,9 +151,6 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
167
151
  this.crudUpdateListener = undefined;
168
152
  this.uploadAbortController?.abort();
169
153
  }
170
- async hasCompletedSync() {
171
- return this.options.adapter.hasCompletedSync();
172
- }
173
154
  async getWriteCheckpoint() {
174
155
  const clientId = await this.options.adapter.getClientId();
175
156
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
@@ -251,7 +232,7 @@ The next upload iteration will be delayed.`);
251
232
  });
252
233
  }
253
234
  }
254
- this.uploadAbortController = null;
235
+ this.uploadAbortController = undefined;
255
236
  }
256
237
  });
257
238
  }
@@ -367,6 +348,11 @@ The next upload iteration will be delayed.`);
367
348
  shouldDelayRetry = false;
368
349
  // A disconnect was requested, we should not delay since there is no explicit retry
369
350
  }
351
+ else if (this.connectionMayHaveChanged && ex.message?.indexOf('No iteration is active') >= 0) {
352
+ this.connectionMayHaveChanged = false;
353
+ this.logger.info('Sync error after changed connection, retrying immediately');
354
+ shouldDelayRetry = false;
355
+ }
370
356
  else {
371
357
  this.logger.error(ex);
372
358
  }
@@ -397,17 +383,14 @@ The next upload iteration will be delayed.`);
397
383
  // Mark as disconnected if here
398
384
  this.updateSyncStatus({ connected: false, connecting: false });
399
385
  }
400
- async collectLocalBucketState() {
401
- const bucketEntries = await this.options.adapter.getBucketStates();
402
- const req = bucketEntries.map((entry) => ({
403
- name: entry.bucket,
404
- after: entry.op_id
405
- }));
406
- const localDescriptions = new Map();
407
- for (const entry of bucketEntries) {
408
- localDescriptions.set(entry.bucket, null);
409
- }
410
- return [req, localDescriptions];
386
+ markConnectionMayHaveChanged() {
387
+ // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
388
+ // an active sync iteration on the connection in use.
389
+ this.connectionMayHaveChanged = true;
390
+ // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
391
+ // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
392
+ // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
393
+ this.handleActiveStreamsChange?.();
411
394
  }
412
395
  /**
413
396
  * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
@@ -448,331 +431,98 @@ The next upload iteration will be delayed.`);
448
431
  if (invalidMetadata.length > 0) {
449
432
  throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);
450
433
  }
451
- const clientImplementation = resolvedOptions.clientImplementation;
452
- this.updateSyncStatus({ clientImplementation });
453
- if (clientImplementation == SyncClientImplementation.JAVASCRIPT) {
454
- await this.legacyStreamingSyncIteration(signal, resolvedOptions);
455
- return null;
456
- }
457
- else {
458
- await this.requireKeyFormat(true);
459
- return await this.rustSyncIteration(signal, resolvedOptions);
460
- }
434
+ await this.requireKeyFormat(true);
435
+ return await this.rustSyncIteration(signal, resolvedOptions);
461
436
  }
462
437
  });
463
438
  }
464
- async receiveSyncLines(data) {
465
- const { options, connection, bson } = data;
439
+ receiveSyncLines(data) {
440
+ const { options, connection } = data;
466
441
  const remote = this.options.remote;
467
- if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
468
- return await remote.fetchStream(options);
469
- }
470
- else {
471
- return await this.options.remote.socketStreamRaw({
472
- ...options,
473
- ...{ fetchStrategy: connection.fetchStrategy }
474
- }, bson);
475
- }
476
- }
477
- async legacyStreamingSyncIteration(signal, resolvedOptions) {
478
- const rawTables = resolvedOptions.serializedSchema?.raw_tables;
479
- if (rawTables != null && rawTables.length) {
480
- this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
481
- }
482
- if (this.activeStreams.length) {
483
- this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
484
- }
485
- this.logger.debug('Streaming sync iteration started');
486
- this.options.adapter.startSession();
487
- let [req, bucketMap] = await this.collectLocalBucketState();
488
- let targetCheckpoint = null;
489
- // A checkpoint that has been validated but not applied (e.g. due to pending local writes)
490
- let pendingValidatedCheckpoint = null;
491
- const clientId = await this.options.adapter.getClientId();
492
- const usingFixedKeyFormat = await this.requireKeyFormat(false);
493
- this.logger.debug('Requesting stream from server');
494
- const syncOptions = {
495
- path: '/sync/stream',
496
- abortSignal: signal,
497
- data: {
498
- buckets: req,
499
- include_checksum: true,
500
- raw_data: true,
501
- parameters: resolvedOptions.params,
502
- app_metadata: resolvedOptions.appMetadata,
503
- client_id: clientId
504
- }
505
- };
506
- const bson = await this.options.remote.getBSON();
507
- const source = await this.receiveSyncLines({
508
- options: syncOptions,
509
- connection: resolvedOptions,
510
- bson
511
- });
512
- const stream = injectable(map(source, (line) => {
513
- if (typeof line == 'string') {
514
- return JSON.parse(line);
442
+ const openInner = async () => {
443
+ if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
444
+ return await remote.fetchStream(options);
515
445
  }
516
446
  else {
517
- return bson.deserialize(line);
518
- }
519
- }));
520
- this.logger.debug('Stream established. Processing events');
521
- this.notifyCompletedUploads = () => {
522
- stream.inject({ crud_upload_completed: null });
523
- };
524
- while (true) {
525
- const { value: line, done } = await stream.next();
526
- if (done) {
527
- // The stream has closed while waiting
528
- return;
529
- }
530
- if ('crud_upload_completed' in line) {
531
- if (pendingValidatedCheckpoint != null) {
532
- const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);
533
- if (applied) {
534
- pendingValidatedCheckpoint = null;
535
- }
536
- else if (endIteration) {
537
- break;
538
- }
539
- }
540
- continue;
541
- }
542
- // A connection is active and messages are being received
543
- if (!this.syncStatus.connected) {
544
- // There is a connection now
545
- Promise.resolve().then(() => this.triggerCrudUpload());
546
- this.updateSyncStatus({
547
- connected: true
447
+ return await this.options.remote.socketStreamRaw({
448
+ ...options,
449
+ ...{ fetchStrategy: connection.fetchStrategy }
548
450
  });
549
451
  }
550
- if (isStreamingSyncCheckpoint(line)) {
551
- targetCheckpoint = line.checkpoint;
552
- // New checkpoint - existing validated checkpoint is no longer valid
553
- pendingValidatedCheckpoint = null;
554
- const bucketsToDelete = new Set(bucketMap.keys());
555
- const newBuckets = new Map();
556
- for (const checksum of line.checkpoint.buckets) {
557
- newBuckets.set(checksum.bucket, {
558
- name: checksum.bucket,
559
- priority: checksum.priority ?? FALLBACK_PRIORITY
452
+ };
453
+ let inner;
454
+ let done = false;
455
+ return {
456
+ async next() {
457
+ if (done) {
458
+ return doneResult;
459
+ }
460
+ else if (inner == null) {
461
+ inner = await openInner();
462
+ // We're connected here, so we can tell the core extension about it.
463
+ return valueResult({
464
+ command: PowerSyncControlCommand.CONNECTION_STATE,
465
+ payload: 'established'
560
466
  });
561
- bucketsToDelete.delete(checksum.bucket);
562
- }
563
- if (bucketsToDelete.size > 0) {
564
- this.logger.debug('Removing buckets', [...bucketsToDelete]);
565
- }
566
- bucketMap = newBuckets;
567
- await this.options.adapter.removeBuckets([...bucketsToDelete]);
568
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
569
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
570
- }
571
- else if (isStreamingSyncCheckpointComplete(line)) {
572
- const result = await this.applyCheckpoint(targetCheckpoint);
573
- if (result.endIteration) {
574
- return;
575
- }
576
- else if (!result.applied) {
577
- // "Could not apply checkpoint due to local data". We need to retry after
578
- // finishing uploads.
579
- pendingValidatedCheckpoint = targetCheckpoint;
580
467
  }
581
468
  else {
582
- // Nothing to retry later. This would likely already be null from the last
583
- // checksum or checksum_diff operation, but we make sure.
584
- pendingValidatedCheckpoint = null;
585
- }
586
- }
587
- else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
588
- const priority = line.partial_checkpoint_complete.priority;
589
- this.logger.debug('Partial checkpoint complete', priority);
590
- const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint, priority);
591
- if (!result.checkpointValid) {
592
- // This means checksums failed. Start again with a new checkpoint.
593
- // TODO: better back-off
594
- await new Promise((resolve) => setTimeout(resolve, 50));
595
- return;
596
- }
597
- else if (!result.ready) {
598
- // If we have pending uploads, we can't complete new checkpoints outside of priority 0.
599
- // We'll resolve this for a complete checkpoint.
600
- }
601
- else {
602
- // We'll keep on downloading, but can report that this priority is synced now.
603
- this.logger.debug('partial checkpoint validation succeeded');
604
- // All states with a higher priority can be deleted since this partial sync includes them.
605
- const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);
606
- priorityStates.push({
607
- priority,
608
- lastSyncedAt: new Date(),
609
- hasSynced: true
610
- });
611
- this.updateSyncStatus({
612
- connected: true,
613
- priorityStatusEntries: priorityStates
614
- });
615
- }
616
- }
617
- else if (isStreamingSyncCheckpointDiff(line)) {
618
- // TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint
619
- if (targetCheckpoint == null) {
620
- throw new Error('Checkpoint diff without previous checkpoint');
621
- }
622
- // New checkpoint - existing validated checkpoint is no longer valid
623
- pendingValidatedCheckpoint = null;
624
- const diff = line.checkpoint_diff;
625
- const newBuckets = new Map();
626
- for (const checksum of targetCheckpoint.buckets) {
627
- newBuckets.set(checksum.bucket, checksum);
628
- }
629
- for (const checksum of diff.updated_buckets) {
630
- newBuckets.set(checksum.bucket, checksum);
631
- }
632
- for (const bucket of diff.removed_buckets) {
633
- newBuckets.delete(bucket);
634
- }
635
- const newCheckpoint = {
636
- last_op_id: diff.last_op_id,
637
- buckets: [...newBuckets.values()],
638
- write_checkpoint: diff.write_checkpoint
639
- };
640
- targetCheckpoint = newCheckpoint;
641
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
642
- bucketMap = new Map();
643
- newBuckets.forEach((checksum, name) => bucketMap.set(name, {
644
- name: checksum.bucket,
645
- priority: checksum.priority ?? FALLBACK_PRIORITY
646
- }));
647
- const bucketsToDelete = diff.removed_buckets;
648
- if (bucketsToDelete.length > 0) {
649
- this.logger.debug('Remove buckets', bucketsToDelete);
650
- }
651
- await this.options.adapter.removeBuckets(bucketsToDelete);
652
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
653
- }
654
- else if (isStreamingSyncData(line)) {
655
- const { data } = line;
656
- const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;
657
- let updatedProgress = null;
658
- if (previousProgress) {
659
- updatedProgress = { ...previousProgress };
660
- const progressForBucket = updatedProgress[data.bucket];
661
- if (progressForBucket) {
662
- updatedProgress[data.bucket] = {
663
- ...progressForBucket,
664
- since_last: progressForBucket.since_last + data.data.length
665
- };
469
+ const event = await inner.next();
470
+ if (event.done) {
471
+ done = true;
472
+ return valueResult({ command: PowerSyncControlCommand.CONNECTION_STATE, payload: 'end' });
666
473
  }
667
- }
668
- this.updateSyncStatus({
669
- dataFlow: {
670
- downloading: true,
671
- downloadProgress: updatedProgress
474
+ else {
475
+ return valueResult({
476
+ command: typeof event.value == 'string'
477
+ ? PowerSyncControlCommand.PROCESS_TEXT_LINE
478
+ : PowerSyncControlCommand.PROCESS_BSON_LINE,
479
+ payload: event.value
480
+ });
672
481
  }
673
- });
674
- await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);
675
- }
676
- else if (isStreamingKeepalive(line)) {
677
- const remaining_seconds = line.token_expires_in;
678
- if (remaining_seconds == 0) {
679
- // Connection would be closed automatically right after this
680
- this.logger.debug('Token expiring; reconnect');
681
- /**
682
- * For a rare case where the backend connector does not update the token
683
- * (uses the same one), this should have some delay.
684
- */
685
- await this.delayRetry();
686
- return;
687
482
  }
688
- else if (remaining_seconds < 30) {
689
- this.logger.debug('Token will expire soon; reconnect');
690
- // Pre-emptively refresh the token
691
- this.options.remote.invalidateCredentials();
692
- return;
693
- }
694
- this.triggerCrudUpload();
695
- }
696
- else {
697
- this.logger.debug('Received unknown sync line', line);
698
483
  }
699
- }
700
- this.logger.debug('Stream input empty');
701
- // Connection closed. Likely due to auth issue.
702
- return;
484
+ };
703
485
  }
704
486
  async rustSyncIteration(signal, resolvedOptions) {
705
487
  const syncImplementation = this;
706
488
  const adapter = this.options.adapter;
707
489
  const remote = this.options.remote;
708
- const controller = new AbortController();
709
- const abort = () => {
710
- return controller.abort(signal.reason);
711
- };
712
- signal.addEventListener('abort', abort);
713
- let receivingLines = null;
714
- let hadSyncLine = false;
715
490
  let hideDisconnectOnRestart = false;
491
+ let notifyTokenRefreshed;
716
492
  if (signal.aborted) {
717
493
  throw new AbortOperation('Connection request has been aborted');
718
494
  }
719
- // Pending sync lines received from the service, as well as local events that trigger a powersync_control
720
- // invocation (local events include refreshed tokens and completed uploads).
721
- // This is a single data stream so that we can handle all control calls from a single place.
722
- let controlInvocations = null;
723
- async function connect(instr) {
724
- const syncOptions = {
725
- path: '/sync/stream',
726
- abortSignal: controller.signal,
727
- data: instr.request
495
+ function startCommand() {
496
+ const options = {
497
+ parameters: resolvedOptions.params,
498
+ app_metadata: resolvedOptions.appMetadata,
499
+ active_streams: syncImplementation.activeStreams,
500
+ include_defaults: resolvedOptions.includeDefaultStreams
728
501
  };
729
- controlInvocations = injectable(map(await syncImplementation.receiveSyncLines({
730
- options: syncOptions,
731
- connection: resolvedOptions
732
- }), (line) => {
733
- if (typeof line == 'string') {
734
- return {
735
- command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
736
- payload: line
737
- };
738
- }
739
- else {
740
- return {
741
- command: PowerSyncControlCommand.PROCESS_BSON_LINE,
742
- payload: line
743
- };
744
- }
745
- }));
746
- // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
747
- // we're already connected here and can report that.
748
- syncImplementation.updateSyncStatus({ connected: true });
749
- try {
750
- while (true) {
751
- let event = await controlInvocations.next();
752
- if (event.done) {
753
- break;
754
- }
755
- const line = event.value;
756
- await control(line.command, line.payload);
757
- if (!hadSyncLine) {
758
- syncImplementation.triggerCrudUpload();
759
- hadSyncLine = true;
760
- }
761
- }
762
- }
763
- finally {
764
- abort();
765
- signal.removeEventListener('abort', abort);
502
+ if (resolvedOptions.serializedSchema) {
503
+ options.schema = resolvedOptions.serializedSchema;
766
504
  }
505
+ return invokePowerSyncControl(PowerSyncControlCommand.START, JSON.stringify(options));
767
506
  }
768
507
  async function stop() {
769
- await control(PowerSyncControlCommand.STOP);
508
+ const instructions = await invokePowerSyncControl(PowerSyncControlCommand.STOP);
509
+ for (const instruction of instructions) {
510
+ // We don't need to handle interrupting instructions since we're unconditionally ending the sync iteration at
511
+ // this point.
512
+ if (isInterruptingInstruction(instruction))
513
+ continue;
514
+ await handleInstruction(instruction);
515
+ }
770
516
  }
771
- async function control(op, payload) {
517
+ async function invokePowerSyncControl(op, payload) {
772
518
  const rawResponse = await adapter.control(op, payload ?? null);
773
519
  const logger = syncImplementation.logger;
774
520
  logger.trace('powersync_control', op, payload == null || typeof payload == 'string' ? payload : '<bytes>', rawResponse);
775
- await handleInstructions(JSON.parse(rawResponse));
521
+ if (op != PowerSyncControlCommand.STOP) {
522
+ // Evidently we have a working connection here, otherwise powersync_control would have failed.
523
+ syncImplementation.connectionMayHaveChanged = false;
524
+ }
525
+ return JSON.parse(rawResponse);
776
526
  }
777
527
  async function handleInstruction(instruction) {
778
528
  if ('LogLine' in instruction) {
@@ -791,13 +541,6 @@ The next upload iteration will be delayed.`);
791
541
  else if ('UpdateSyncStatus' in instruction) {
792
542
  syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));
793
543
  }
794
- else if ('EstablishSyncStream' in instruction) {
795
- if (receivingLines != null) {
796
- // Already connected, this shouldn't happen during a single iteration.
797
- throw 'Unexpected request to establish sync stream, already connected';
798
- }
799
- receivingLines = connect(instruction.EstablishSyncStream);
800
- }
801
544
  else if ('FetchCredentials' in instruction) {
802
545
  if (instruction.FetchCredentials.did_expire) {
803
546
  remote.invalidateCredentials();
@@ -806,16 +549,12 @@ The next upload iteration will be delayed.`);
806
549
  remote.invalidateCredentials();
807
550
  // Restart iteration after the credentials have been refreshed.
808
551
  remote.fetchCredentials().then((_) => {
809
- controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
552
+ notifyTokenRefreshed?.();
810
553
  }, (err) => {
811
554
  syncImplementation.logger.warn('Could not prefetch credentials', err);
812
555
  });
813
556
  }
814
557
  }
815
- else if ('CloseSyncStream' in instruction) {
816
- controller.abort();
817
- hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
818
- }
819
558
  else if ('FlushFileSystem' in instruction) {
820
559
  // Not necessary on JS platforms.
821
560
  }
@@ -827,101 +566,83 @@ The next upload iteration will be delayed.`);
827
566
  });
828
567
  }
829
568
  }
830
- async function handleInstructions(instructions) {
831
- for (const instr of instructions) {
832
- await handleInstruction(instr);
833
- }
834
- }
835
569
  try {
836
- const options = {
837
- parameters: resolvedOptions.params,
838
- app_metadata: resolvedOptions.appMetadata,
839
- active_streams: this.activeStreams,
840
- include_defaults: resolvedOptions.includeDefaultStreams
841
- };
842
- if (resolvedOptions.serializedSchema) {
843
- options.schema = resolvedOptions.serializedSchema;
570
+ const defaultResult = { immediateRestart: false };
571
+ // Pending sync lines received from the service, as well as local events that trigger a powersync_control
572
+ // invocation (local events include refreshed tokens and completed uploads).
573
+ // This is a single data stream so that we can handle all control calls from a single place.
574
+ let controlInvocations = null;
575
+ for (const startInstruction of await startCommand()) {
576
+ if ('EstablishSyncStream' in startInstruction) {
577
+ const syncOptions = {
578
+ path: '/sync/stream',
579
+ abortSignal: signal,
580
+ data: startInstruction.EstablishSyncStream.request
581
+ };
582
+ controlInvocations = injectable(syncImplementation.receiveSyncLines({
583
+ options: syncOptions,
584
+ connection: resolvedOptions
585
+ }));
586
+ }
587
+ else if ('CloseSyncStream' in startInstruction) {
588
+ return defaultResult;
589
+ }
590
+ else {
591
+ await handleInstruction(startInstruction);
592
+ }
844
593
  }
845
- await control(PowerSyncControlCommand.START, JSON.stringify(options));
594
+ if (controlInvocations == null)
595
+ return defaultResult;
846
596
  this.notifyCompletedUploads = () => {
847
- controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
597
+ controlInvocations.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
848
598
  };
849
599
  this.handleActiveStreamsChange = () => {
850
- controlInvocations?.inject({
600
+ controlInvocations.inject({
851
601
  command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
852
602
  payload: JSON.stringify(this.activeStreams)
853
603
  });
854
604
  };
855
- await receivingLines;
605
+ notifyTokenRefreshed = () => {
606
+ controlInvocations.inject({
607
+ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED
608
+ });
609
+ };
610
+ let hadSyncLine = false;
611
+ loop: while (true) {
612
+ const { done, value } = await controlInvocations.next();
613
+ if (done)
614
+ break;
615
+ if (!hadSyncLine) {
616
+ // Trigger a local CRUD upload when the first sync line has been received, this allows uploading local changes
617
+ // that have been made while offline or disconnected.
618
+ if (value.command == PowerSyncControlCommand.PROCESS_TEXT_LINE ||
619
+ value.command == PowerSyncControlCommand.PROCESS_BSON_LINE) {
620
+ hadSyncLine = true;
621
+ this.triggerCrudUpload?.();
622
+ }
623
+ }
624
+ const instructions = await invokePowerSyncControl(value.command, value.payload);
625
+ for (const instruction of instructions) {
626
+ if ('EstablishSyncStream' in instruction) {
627
+ throw new Error('Received EstablishSyncStream while already connected.');
628
+ }
629
+ else if ('CloseSyncStream' in instruction) {
630
+ hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
631
+ break loop;
632
+ }
633
+ else {
634
+ await handleInstruction(instruction);
635
+ }
636
+ }
637
+ }
856
638
  }
857
639
  finally {
858
640
  this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
641
+ notifyTokenRefreshed = undefined;
859
642
  await stop();
860
643
  }
861
644
  return { immediateRestart: hideDisconnectOnRestart };
862
645
  }
863
- async updateSyncStatusForStartingCheckpoint(checkpoint) {
864
- const localProgress = await this.options.adapter.getBucketOperationProgress();
865
- const progress = {};
866
- let invalidated = false;
867
- for (const bucket of checkpoint.buckets) {
868
- const savedProgress = localProgress[bucket.bucket];
869
- const atLast = savedProgress?.atLast ?? 0;
870
- const sinceLast = savedProgress?.sinceLast ?? 0;
871
- progress[bucket.bucket] = {
872
- // The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service
873
- // will use by default.
874
- priority: bucket.priority ?? 3,
875
- at_last: atLast,
876
- since_last: sinceLast,
877
- target_count: bucket.count ?? 0
878
- };
879
- if (bucket.count != null && bucket.count < atLast + sinceLast) {
880
- // Either due to a defrag / sync rule deploy or a compaction operation, the size
881
- // of the bucket shrank so much that the local ops exceed the ops in the updated
882
- // bucket. We can't prossibly report progress in this case (it would overshoot 100%).
883
- invalidated = true;
884
- }
885
- }
886
- if (invalidated) {
887
- for (const bucket in progress) {
888
- const bucketProgress = progress[bucket];
889
- bucketProgress.at_last = 0;
890
- bucketProgress.since_last = 0;
891
- }
892
- }
893
- this.updateSyncStatus({
894
- dataFlow: {
895
- downloading: true,
896
- downloadProgress: progress
897
- }
898
- });
899
- }
900
- async applyCheckpoint(checkpoint) {
901
- let result = await this.options.adapter.syncLocalDatabase(checkpoint);
902
- if (!result.checkpointValid) {
903
- this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);
904
- // This means checksums failed. Start again with a new checkpoint.
905
- // TODO: better back-off
906
- await new Promise((resolve) => setTimeout(resolve, 50));
907
- return { applied: false, endIteration: true };
908
- }
909
- else if (!result.ready) {
910
- this.logger.debug(`Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`);
911
- return { applied: false, endIteration: false };
912
- }
913
- this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);
914
- this.updateSyncStatus({
915
- connected: true,
916
- lastSyncedAt: new Date(),
917
- dataFlow: {
918
- downloading: false,
919
- downloadProgress: null,
920
- downloadError: undefined
921
- }
922
- });
923
- return { applied: true, endIteration: false };
924
- }
925
646
  updateSyncStatus(options) {
926
647
  const updatedStatus = new SyncStatus({
927
648
  connected: options.connected ?? this.syncStatus.connected,