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