@powersync/common 1.52.0 → 1.53.1

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 (79) hide show
  1. package/dist/bundle.cjs +167 -767
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +168 -756
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +167 -767
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +168 -756
  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/lib/utils/stream_transform.js +6 -1
  45. package/lib/utils/stream_transform.js.map +1 -1
  46. package/package.json +9 -6
  47. package/src/client/ConnectionManager.ts +1 -1
  48. package/src/client/sync/bucket/BucketStorageAdapter.ts +6 -71
  49. package/src/client/sync/bucket/SqliteBucketStorage.ts +1 -197
  50. package/src/client/sync/stream/AbstractRemote.ts +5 -27
  51. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +168 -496
  52. package/src/client/sync/stream/JsonValue.ts +8 -0
  53. package/src/client/sync/stream/core-instruction.ts +15 -5
  54. package/src/db/DBAdapter.ts +20 -2
  55. package/src/db/crud/SyncStatus.ts +4 -5
  56. package/src/db/schema/RawTable.ts +0 -5
  57. package/src/db/schema/Schema.ts +0 -2
  58. package/src/index.ts +1 -5
  59. package/src/utils/stream_transform.ts +7 -1
  60. package/lib/client/sync/bucket/OpType.d.ts +0 -16
  61. package/lib/client/sync/bucket/OpType.js +0 -23
  62. package/lib/client/sync/bucket/OpType.js.map +0 -1
  63. package/lib/client/sync/bucket/OplogEntry.d.ts +0 -23
  64. package/lib/client/sync/bucket/OplogEntry.js +0 -36
  65. package/lib/client/sync/bucket/OplogEntry.js.map +0 -1
  66. package/lib/client/sync/bucket/SyncDataBatch.d.ts +0 -6
  67. package/lib/client/sync/bucket/SyncDataBatch.js +0 -12
  68. package/lib/client/sync/bucket/SyncDataBatch.js.map +0 -1
  69. package/lib/client/sync/bucket/SyncDataBucket.d.ts +0 -40
  70. package/lib/client/sync/bucket/SyncDataBucket.js +0 -40
  71. package/lib/client/sync/bucket/SyncDataBucket.js.map +0 -1
  72. package/lib/client/sync/stream/streaming-sync-types.d.ts +0 -143
  73. package/lib/client/sync/stream/streaming-sync-types.js +0 -26
  74. package/lib/client/sync/stream/streaming-sync-types.js.map +0 -1
  75. package/src/client/sync/bucket/OpType.ts +0 -23
  76. package/src/client/sync/bucket/OplogEntry.ts +0 -50
  77. package/src/client/sync/bucket/SyncDataBatch.ts +0 -11
  78. package/src/client/sync/bucket/SyncDataBucket.ts +0 -49
  79. package/src/client/sync/stream/streaming-sync-types.ts +0 -210
@@ -1819,8 +1819,15 @@ class BaseTransaction {
1819
1819
  class TransactionImplementation extends DBGetUtilsDefaultMixin(BaseTransaction) {
1820
1820
  static async runWith(ctx, fn) {
1821
1821
  let tx = new TransactionImplementation(ctx);
1822
+ // For write transactions, use BEGIN IMMEDIATE to immediately obtain a write lock on the database (instead of doing
1823
+ // that on the first statement). If we have a genuine read-only connection, we also use BEGIN IMMEDIATE there: In
1824
+ // WAL mode, that ensures we pin the current state of the database (instead of the state at the first statement in
1825
+ // the transaction). But if we have a "fake" read-only connection implemented through `pragma query_only = true`, we
1826
+ // can't use this trick because it would attempt to lock the connection. So there, we use a regular `BEGIN`
1827
+ // statement.
1828
+ const useBeginImmediate = ctx.connectionType != 'queryOnly';
1822
1829
  try {
1823
- await ctx.execute('BEGIN IMMEDIATE');
1830
+ await ctx.execute(useBeginImmediate ? 'BEGIN IMMEDIATE' : 'BEGIN');
1824
1831
  const result = await fn(tx);
1825
1832
  await tx.commit();
1826
1833
  return result;
@@ -1979,16 +1986,12 @@ class SyncStatus {
1979
1986
  *
1980
1987
  * This returns null when the database is currently being opened and we don't have reliable information about all
1981
1988
  * included streams yet.
1982
- *
1983
- * @experimental Sync streams are currently in alpha.
1984
1989
  */
1985
1990
  get syncStreams() {
1986
1991
  return this.options.dataFlow?.internalStreamSubscriptions?.map((core) => new SyncStreamStatusView(this, core));
1987
1992
  }
1988
1993
  /**
1989
1994
  * If the `stream` appears in {@link syncStreams}, returns the current status for that stream.
1990
- *
1991
- * @experimental Sync streams are currently in alpha.
1992
1995
  */
1993
1996
  forStream(stream) {
1994
1997
  const asJson = JSON.stringify(stream.parameters);
@@ -2571,7 +2574,7 @@ class SyncStreamSubscriptionHandle {
2571
2574
  constructor(subscription) {
2572
2575
  this.subscription = subscription;
2573
2576
  subscription.refcount++;
2574
- _finalizer?.register(this, subscription);
2577
+ _finalizer?.register(this, subscription, this);
2575
2578
  }
2576
2579
  get name() {
2577
2580
  return this.subscription.name;
@@ -3160,6 +3163,10 @@ exports.PowerSyncControlCommand = void 0;
3160
3163
  PowerSyncControlCommand["NOTIFY_TOKEN_REFRESHED"] = "refreshed_token";
3161
3164
  PowerSyncControlCommand["NOTIFY_CRUD_UPLOAD_COMPLETED"] = "completed_upload";
3162
3165
  PowerSyncControlCommand["UPDATE_SUBSCRIPTIONS"] = "update_subscriptions";
3166
+ /**
3167
+ * An `established` or `end` event for response streams.
3168
+ */
3169
+ PowerSyncControlCommand["CONNECTION_STATE"] = "connection";
3163
3170
  })(exports.PowerSyncControlCommand || (exports.PowerSyncControlCommand = {}));
3164
3171
 
3165
3172
  /**
@@ -3341,103 +3348,6 @@ class AbortOperation extends Error {
3341
3348
  }
3342
3349
  }
3343
3350
 
3344
- exports.OpTypeEnum = void 0;
3345
- (function (OpTypeEnum) {
3346
- OpTypeEnum[OpTypeEnum["CLEAR"] = 1] = "CLEAR";
3347
- OpTypeEnum[OpTypeEnum["MOVE"] = 2] = "MOVE";
3348
- OpTypeEnum[OpTypeEnum["PUT"] = 3] = "PUT";
3349
- OpTypeEnum[OpTypeEnum["REMOVE"] = 4] = "REMOVE";
3350
- })(exports.OpTypeEnum || (exports.OpTypeEnum = {}));
3351
- /**
3352
- * Used internally for sync buckets.
3353
- */
3354
- class OpType {
3355
- value;
3356
- static fromJSON(jsonValue) {
3357
- return new OpType(exports.OpTypeEnum[jsonValue]);
3358
- }
3359
- constructor(value) {
3360
- this.value = value;
3361
- }
3362
- toJSON() {
3363
- return Object.entries(exports.OpTypeEnum).find(([, value]) => value === this.value)[0];
3364
- }
3365
- }
3366
-
3367
- class OplogEntry {
3368
- op_id;
3369
- op;
3370
- checksum;
3371
- subkey;
3372
- object_type;
3373
- object_id;
3374
- data;
3375
- static fromRow(row) {
3376
- return new OplogEntry(row.op_id, OpType.fromJSON(row.op), row.checksum, row.subkey, row.object_type, row.object_id, row.data);
3377
- }
3378
- constructor(op_id, op, checksum, subkey, object_type, object_id, data) {
3379
- this.op_id = op_id;
3380
- this.op = op;
3381
- this.checksum = checksum;
3382
- this.subkey = subkey;
3383
- this.object_type = object_type;
3384
- this.object_id = object_id;
3385
- this.data = data;
3386
- }
3387
- toJSON(fixedKeyEncoding = false) {
3388
- return {
3389
- op_id: this.op_id,
3390
- op: this.op.toJSON(),
3391
- object_type: this.object_type,
3392
- object_id: this.object_id,
3393
- checksum: this.checksum,
3394
- data: this.data,
3395
- // Older versions of the JS SDK used to always JSON.stringify here. That has always been wrong,
3396
- // but we need to migrate gradually to not break existing databases.
3397
- subkey: fixedKeyEncoding ? this.subkey : JSON.stringify(this.subkey)
3398
- };
3399
- }
3400
- }
3401
-
3402
- class SyncDataBucket {
3403
- bucket;
3404
- data;
3405
- has_more;
3406
- after;
3407
- next_after;
3408
- static fromRow(row) {
3409
- return new SyncDataBucket(row.bucket, row.data.map((entry) => OplogEntry.fromRow(entry)), row.has_more ?? false, row.after, row.next_after);
3410
- }
3411
- constructor(bucket, data,
3412
- /**
3413
- * True if the response does not contain all the data for this bucket, and another request must be made.
3414
- */
3415
- has_more,
3416
- /**
3417
- * The `after` specified in the request.
3418
- */
3419
- after,
3420
- /**
3421
- * Use this for the next request.
3422
- */
3423
- next_after) {
3424
- this.bucket = bucket;
3425
- this.data = data;
3426
- this.has_more = has_more;
3427
- this.after = after;
3428
- this.next_after = next_after;
3429
- }
3430
- toJSON(fixedKeyEncoding = false) {
3431
- return {
3432
- bucket: this.bucket,
3433
- has_more: this.has_more,
3434
- after: this.after,
3435
- next_after: this.next_after,
3436
- data: this.data.map((entry) => entry.toJSON(fixedKeyEncoding))
3437
- };
3438
- }
3439
- }
3440
-
3441
3351
  var dist = {};
3442
3352
 
3443
3353
  var Codecs = {};
@@ -8222,7 +8132,7 @@ function requireDist () {
8222
8132
 
8223
8133
  var distExports = requireDist();
8224
8134
 
8225
- var version = "1.52.0";
8135
+ var version = "1.53.1";
8226
8136
  var PACKAGE = {
8227
8137
  version: version};
8228
8138
 
@@ -8392,22 +8302,6 @@ const doneResult = { done: true, value: undefined };
8392
8302
  function valueResult(value) {
8393
8303
  return { done: false, value };
8394
8304
  }
8395
- /**
8396
- * A variant of {@link Array.map} for async iterators.
8397
- */
8398
- function map(source, map) {
8399
- return {
8400
- next: async () => {
8401
- const value = await source.next();
8402
- if (value.done) {
8403
- return value;
8404
- }
8405
- else {
8406
- return { value: map(value.value) };
8407
- }
8408
- }
8409
- };
8410
- }
8411
8305
  /**
8412
8306
  * Expands a source async iterator by allowing to inject events asynchronously.
8413
8307
  *
@@ -8422,6 +8316,7 @@ function injectable(source) {
8422
8316
  let waiter = undefined; // An active, waiting next() call.
8423
8317
  // A pending upstream event that couldn't be dispatched because inject() has been called before it was resolved.
8424
8318
  let pendingSourceEvent = null;
8319
+ let sourceFetchInFlight = false;
8425
8320
  let pendingInjectedEvents = [];
8426
8321
  const consumeWaiter = () => {
8427
8322
  const pending = waiter;
@@ -8430,6 +8325,7 @@ function injectable(source) {
8430
8325
  };
8431
8326
  const fetchFromSource = () => {
8432
8327
  const resolveWaiter = (propagate) => {
8328
+ sourceFetchInFlight = false;
8433
8329
  const active = consumeWaiter();
8434
8330
  if (active) {
8435
8331
  propagate(active);
@@ -8438,6 +8334,7 @@ function injectable(source) {
8438
8334
  pendingSourceEvent = propagate;
8439
8335
  }
8440
8336
  };
8337
+ sourceFetchInFlight = true;
8441
8338
  const nextFromSource = source.next();
8442
8339
  nextFromSource.then((value) => {
8443
8340
  sourceIsDone = value.done == true;
@@ -8464,7 +8361,9 @@ function injectable(source) {
8464
8361
  }
8465
8362
  // Nothing pending? Fetch from source
8466
8363
  waiter = { resolve, reject };
8467
- return fetchFromSource();
8364
+ if (!sourceFetchInFlight) {
8365
+ fetchFromSource();
8366
+ }
8468
8367
  });
8469
8368
  },
8470
8369
  inject: (event) => {
@@ -8779,22 +8678,12 @@ class AbstractRemote {
8779
8678
  * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
8780
8679
  *
8781
8680
  * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
8782
- *
8783
- * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
8784
- * (required for compatibility with older sync services).
8785
8681
  */
8786
- async socketStreamRaw(options, bson) {
8682
+ async socketStreamRaw(options) {
8787
8683
  const { path, fetchStrategy = exports.FetchStrategy.Buffered } = options;
8788
- const mimeType = bson == null ? 'application/json' : 'application/bson';
8684
+ const mimeType = 'application/json';
8789
8685
  function toBuffer(js) {
8790
- let contents;
8791
- if (bson != null) {
8792
- contents = bson.serialize(js);
8793
- }
8794
- else {
8795
- contents = JSON.stringify(js);
8796
- }
8797
- return node_buffer.Buffer.from(contents);
8686
+ return node_buffer.Buffer.from(JSON.stringify(js));
8798
8687
  }
8799
8688
  const syncQueueRequestSize = fetchStrategy == exports.FetchStrategy.Buffered ? 10 : 1;
8800
8689
  const request = await this.buildRequest(path);
@@ -9095,31 +8984,8 @@ function coreStatusToJs(status) {
9095
8984
  priorityStatusEntries: status.priority_status.map(priorityToJs)
9096
8985
  };
9097
8986
  }
9098
-
9099
- function isStreamingSyncData(line) {
9100
- return line.data != null;
9101
- }
9102
- function isStreamingKeepalive(line) {
9103
- return line.token_expires_in != null;
9104
- }
9105
- function isStreamingSyncCheckpoint(line) {
9106
- return line.checkpoint != null;
9107
- }
9108
- function isStreamingSyncCheckpointComplete(line) {
9109
- return line.checkpoint_complete != null;
9110
- }
9111
- function isStreamingSyncCheckpointPartiallyComplete(line) {
9112
- return line.partial_checkpoint_complete != null;
9113
- }
9114
- function isStreamingSyncCheckpointDiff(line) {
9115
- return line.checkpoint_diff != null;
9116
- }
9117
- function isContinueCheckpointRequest(request) {
9118
- return (Array.isArray(request.buckets) &&
9119
- typeof request.checkpoint_token == 'string');
9120
- }
9121
- function isSyncNewCheckpointRequest(request) {
9122
- return typeof request.request_checkpoint == 'object';
8987
+ function isInterruptingInstruction(instruction) {
8988
+ return 'EstablishSyncStream' in instruction || 'CloseSyncStream' in instruction;
9123
8989
  }
9124
8990
 
9125
8991
  exports.LockType = void 0;
@@ -9134,35 +9000,21 @@ exports.SyncStreamConnectionMethod = void 0;
9134
9000
  })(exports.SyncStreamConnectionMethod || (exports.SyncStreamConnectionMethod = {}));
9135
9001
  exports.SyncClientImplementation = void 0;
9136
9002
  (function (SyncClientImplementation) {
9137
- /**
9138
- * Decodes and handles sync lines received from the sync service in JavaScript.
9139
- *
9140
- * This is the default option.
9141
- *
9142
- * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
9143
- * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
9144
- * version of the PowerSync SDK.
9145
- */
9146
- SyncClientImplementation["JAVASCRIPT"] = "js";
9147
9003
  /**
9148
9004
  * This implementation offloads the sync line decoding and handling into the PowerSync
9149
9005
  * core extension.
9150
9006
  *
9151
- * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
9152
- * recommended client implementation for all apps.
9007
+ * This is the only option, as an older JavaScript client implementation has been removed from the SDK.
9153
9008
  *
9154
9009
  * ## Compatibility warning
9155
9010
  *
9156
9011
  * The Rust sync client stores sync data in a format that is slightly different than the one used
9157
- * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing
9158
- * databases, the PowerSync SDK will migrate the format automatically.
9159
- * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
9160
- * the version introducing {@link RUST} as an option) also supports the new format, so you can switch
9161
- * back to {@link JAVASCRIPT} later.
9012
+ * by the old JavaScript client. When adopting the {@link RUST} client on existing databases, the PowerSync SDK will
9013
+ * migrate the format automatically.
9162
9014
  *
9163
- * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later
9164
- * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)
9165
- * can lead to sync issues.
9015
+ * SDK versions supporting both the JavaScript and the Rust client support both formats with the JavaScript client
9016
+ * implementaiton. However, downgrading to an SDK version that only supports the JavaScript client would not be
9017
+ * possible anymore. Problematic SDK versions have been released before 2025-06-09.
9166
9018
  */
9167
9019
  SyncClientImplementation["RUST"] = "rust";
9168
9020
  })(exports.SyncClientImplementation || (exports.SyncClientImplementation = {}));
@@ -9185,13 +9037,7 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
9185
9037
  serializedSchema: undefined,
9186
9038
  includeDefaultStreams: true
9187
9039
  };
9188
- // The priority we assume when we receive checkpoint lines where no priority is set.
9189
- // This is the default priority used by the sync service, but can be set to an arbitrary
9190
- // value since sync services without priorities also won't send partial sync completion
9191
- // messages.
9192
- const FALLBACK_PRIORITY = 3;
9193
9040
  class AbstractStreamingSyncImplementation extends BaseObserver {
9194
- _lastSyncedAt;
9195
9041
  options;
9196
9042
  abortController;
9197
9043
  // In rare cases, mostly for tests, uploads can be triggered without being properly connected.
@@ -9201,6 +9047,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
9201
9047
  streamingSyncPromise;
9202
9048
  logger;
9203
9049
  activeStreams;
9050
+ connectionMayHaveChanged = false;
9204
9051
  isUploadingCrud = false;
9205
9052
  notifyCompletedUploads;
9206
9053
  handleActiveStreamsChange;
@@ -9280,9 +9127,6 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
9280
9127
  this.crudUpdateListener = undefined;
9281
9128
  this.uploadAbortController?.abort();
9282
9129
  }
9283
- async hasCompletedSync() {
9284
- return this.options.adapter.hasCompletedSync();
9285
- }
9286
9130
  async getWriteCheckpoint() {
9287
9131
  const clientId = await this.options.adapter.getClientId();
9288
9132
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
@@ -9364,7 +9208,7 @@ The next upload iteration will be delayed.`);
9364
9208
  });
9365
9209
  }
9366
9210
  }
9367
- this.uploadAbortController = null;
9211
+ this.uploadAbortController = undefined;
9368
9212
  }
9369
9213
  });
9370
9214
  }
@@ -9480,6 +9324,11 @@ The next upload iteration will be delayed.`);
9480
9324
  shouldDelayRetry = false;
9481
9325
  // A disconnect was requested, we should not delay since there is no explicit retry
9482
9326
  }
9327
+ else if (this.connectionMayHaveChanged && ex.message?.indexOf('No iteration is active') >= 0) {
9328
+ this.connectionMayHaveChanged = false;
9329
+ this.logger.info('Sync error after changed connection, retrying immediately');
9330
+ shouldDelayRetry = false;
9331
+ }
9483
9332
  else {
9484
9333
  this.logger.error(ex);
9485
9334
  }
@@ -9510,17 +9359,14 @@ The next upload iteration will be delayed.`);
9510
9359
  // Mark as disconnected if here
9511
9360
  this.updateSyncStatus({ connected: false, connecting: false });
9512
9361
  }
9513
- async collectLocalBucketState() {
9514
- const bucketEntries = await this.options.adapter.getBucketStates();
9515
- const req = bucketEntries.map((entry) => ({
9516
- name: entry.bucket,
9517
- after: entry.op_id
9518
- }));
9519
- const localDescriptions = new Map();
9520
- for (const entry of bucketEntries) {
9521
- localDescriptions.set(entry.bucket, null);
9522
- }
9523
- return [req, localDescriptions];
9362
+ markConnectionMayHaveChanged() {
9363
+ // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
9364
+ // an active sync iteration on the connection in use.
9365
+ this.connectionMayHaveChanged = true;
9366
+ // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
9367
+ // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
9368
+ // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
9369
+ this.handleActiveStreamsChange?.();
9524
9370
  }
9525
9371
  /**
9526
9372
  * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
@@ -9561,328 +9407,98 @@ The next upload iteration will be delayed.`);
9561
9407
  if (invalidMetadata.length > 0) {
9562
9408
  throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);
9563
9409
  }
9564
- const clientImplementation = resolvedOptions.clientImplementation;
9565
- this.updateSyncStatus({ clientImplementation });
9566
- if (clientImplementation == exports.SyncClientImplementation.JAVASCRIPT) {
9567
- await this.legacyStreamingSyncIteration(signal, resolvedOptions);
9568
- return null;
9569
- }
9570
- else {
9571
- await this.requireKeyFormat(true);
9572
- return await this.rustSyncIteration(signal, resolvedOptions);
9573
- }
9410
+ await this.requireKeyFormat(true);
9411
+ return await this.rustSyncIteration(signal, resolvedOptions);
9574
9412
  }
9575
9413
  });
9576
9414
  }
9577
- async receiveSyncLines(data) {
9578
- const { options, connection, bson } = data;
9415
+ receiveSyncLines(data) {
9416
+ const { options, connection } = data;
9579
9417
  const remote = this.options.remote;
9580
- if (connection.connectionMethod == exports.SyncStreamConnectionMethod.HTTP) {
9581
- return await remote.fetchStream(options);
9582
- }
9583
- else {
9584
- return await this.options.remote.socketStreamRaw({
9585
- ...options,
9586
- ...{ fetchStrategy: connection.fetchStrategy }
9587
- }, bson);
9588
- }
9589
- }
9590
- async legacyStreamingSyncIteration(signal, resolvedOptions) {
9591
- const rawTables = resolvedOptions.serializedSchema?.raw_tables;
9592
- if (rawTables != null && rawTables.length) {
9593
- this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
9594
- }
9595
- if (this.activeStreams.length) {
9596
- this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
9597
- }
9598
- this.logger.debug('Streaming sync iteration started');
9599
- this.options.adapter.startSession();
9600
- let [req, bucketMap] = await this.collectLocalBucketState();
9601
- let targetCheckpoint = null;
9602
- // A checkpoint that has been validated but not applied (e.g. due to pending local writes)
9603
- let pendingValidatedCheckpoint = null;
9604
- const clientId = await this.options.adapter.getClientId();
9605
- const usingFixedKeyFormat = await this.requireKeyFormat(false);
9606
- this.logger.debug('Requesting stream from server');
9607
- const syncOptions = {
9608
- path: '/sync/stream',
9609
- abortSignal: signal,
9610
- data: {
9611
- buckets: req,
9612
- include_checksum: true,
9613
- raw_data: true,
9614
- parameters: resolvedOptions.params,
9615
- app_metadata: resolvedOptions.appMetadata,
9616
- client_id: clientId
9617
- }
9618
- };
9619
- const bson = await this.options.remote.getBSON();
9620
- const source = await this.receiveSyncLines({
9621
- options: syncOptions,
9622
- connection: resolvedOptions,
9623
- bson
9624
- });
9625
- const stream = injectable(map(source, (line) => {
9626
- if (typeof line == 'string') {
9627
- return JSON.parse(line);
9418
+ const openInner = async () => {
9419
+ if (connection.connectionMethod == exports.SyncStreamConnectionMethod.HTTP) {
9420
+ return await remote.fetchStream(options);
9628
9421
  }
9629
9422
  else {
9630
- return bson.deserialize(line);
9423
+ return await this.options.remote.socketStreamRaw({
9424
+ ...options,
9425
+ ...{ fetchStrategy: connection.fetchStrategy }
9426
+ });
9631
9427
  }
9632
- }));
9633
- this.logger.debug('Stream established. Processing events');
9634
- this.notifyCompletedUploads = () => {
9635
- stream.inject({ crud_upload_completed: null });
9636
9428
  };
9637
- while (true) {
9638
- const { value: line, done } = await stream.next();
9639
- if (done) {
9640
- // The stream has closed while waiting
9641
- return;
9642
- }
9643
- if ('crud_upload_completed' in line) {
9644
- if (pendingValidatedCheckpoint != null) {
9645
- const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);
9646
- if (applied) {
9647
- pendingValidatedCheckpoint = null;
9648
- }
9649
- else if (endIteration) {
9650
- break;
9651
- }
9429
+ let inner;
9430
+ let done = false;
9431
+ return {
9432
+ async next() {
9433
+ if (done) {
9434
+ return doneResult;
9652
9435
  }
9653
- continue;
9654
- }
9655
- // A connection is active and messages are being received
9656
- if (!this.syncStatus.connected) {
9657
- // There is a connection now
9658
- Promise.resolve().then(() => this.triggerCrudUpload());
9659
- this.updateSyncStatus({
9660
- connected: true
9661
- });
9662
- }
9663
- if (isStreamingSyncCheckpoint(line)) {
9664
- targetCheckpoint = line.checkpoint;
9665
- // New checkpoint - existing validated checkpoint is no longer valid
9666
- pendingValidatedCheckpoint = null;
9667
- const bucketsToDelete = new Set(bucketMap.keys());
9668
- const newBuckets = new Map();
9669
- for (const checksum of line.checkpoint.buckets) {
9670
- newBuckets.set(checksum.bucket, {
9671
- name: checksum.bucket,
9672
- priority: checksum.priority ?? FALLBACK_PRIORITY
9436
+ else if (inner == null) {
9437
+ inner = await openInner();
9438
+ // We're connected here, so we can tell the core extension about it.
9439
+ return valueResult({
9440
+ command: exports.PowerSyncControlCommand.CONNECTION_STATE,
9441
+ payload: 'established'
9673
9442
  });
9674
- bucketsToDelete.delete(checksum.bucket);
9675
- }
9676
- if (bucketsToDelete.size > 0) {
9677
- this.logger.debug('Removing buckets', [...bucketsToDelete]);
9678
- }
9679
- bucketMap = newBuckets;
9680
- await this.options.adapter.removeBuckets([...bucketsToDelete]);
9681
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
9682
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
9683
- }
9684
- else if (isStreamingSyncCheckpointComplete(line)) {
9685
- const result = await this.applyCheckpoint(targetCheckpoint);
9686
- if (result.endIteration) {
9687
- return;
9688
- }
9689
- else if (!result.applied) {
9690
- // "Could not apply checkpoint due to local data". We need to retry after
9691
- // finishing uploads.
9692
- pendingValidatedCheckpoint = targetCheckpoint;
9693
9443
  }
9694
9444
  else {
9695
- // Nothing to retry later. This would likely already be null from the last
9696
- // checksum or checksum_diff operation, but we make sure.
9697
- pendingValidatedCheckpoint = null;
9698
- }
9699
- }
9700
- else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
9701
- const priority = line.partial_checkpoint_complete.priority;
9702
- this.logger.debug('Partial checkpoint complete', priority);
9703
- const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint, priority);
9704
- if (!result.checkpointValid) {
9705
- // This means checksums failed. Start again with a new checkpoint.
9706
- // TODO: better back-off
9707
- await new Promise((resolve) => setTimeout(resolve, 50));
9708
- return;
9709
- }
9710
- else if (!result.ready) ;
9711
- else {
9712
- // We'll keep on downloading, but can report that this priority is synced now.
9713
- this.logger.debug('partial checkpoint validation succeeded');
9714
- // All states with a higher priority can be deleted since this partial sync includes them.
9715
- const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);
9716
- priorityStates.push({
9717
- priority,
9718
- lastSyncedAt: new Date(),
9719
- hasSynced: true
9720
- });
9721
- this.updateSyncStatus({
9722
- connected: true,
9723
- priorityStatusEntries: priorityStates
9724
- });
9725
- }
9726
- }
9727
- else if (isStreamingSyncCheckpointDiff(line)) {
9728
- // TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint
9729
- if (targetCheckpoint == null) {
9730
- throw new Error('Checkpoint diff without previous checkpoint');
9731
- }
9732
- // New checkpoint - existing validated checkpoint is no longer valid
9733
- pendingValidatedCheckpoint = null;
9734
- const diff = line.checkpoint_diff;
9735
- const newBuckets = new Map();
9736
- for (const checksum of targetCheckpoint.buckets) {
9737
- newBuckets.set(checksum.bucket, checksum);
9738
- }
9739
- for (const checksum of diff.updated_buckets) {
9740
- newBuckets.set(checksum.bucket, checksum);
9741
- }
9742
- for (const bucket of diff.removed_buckets) {
9743
- newBuckets.delete(bucket);
9744
- }
9745
- const newCheckpoint = {
9746
- last_op_id: diff.last_op_id,
9747
- buckets: [...newBuckets.values()],
9748
- write_checkpoint: diff.write_checkpoint
9749
- };
9750
- targetCheckpoint = newCheckpoint;
9751
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
9752
- bucketMap = new Map();
9753
- newBuckets.forEach((checksum, name) => bucketMap.set(name, {
9754
- name: checksum.bucket,
9755
- priority: checksum.priority ?? FALLBACK_PRIORITY
9756
- }));
9757
- const bucketsToDelete = diff.removed_buckets;
9758
- if (bucketsToDelete.length > 0) {
9759
- this.logger.debug('Remove buckets', bucketsToDelete);
9760
- }
9761
- await this.options.adapter.removeBuckets(bucketsToDelete);
9762
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
9763
- }
9764
- else if (isStreamingSyncData(line)) {
9765
- const { data } = line;
9766
- const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;
9767
- let updatedProgress = null;
9768
- if (previousProgress) {
9769
- updatedProgress = { ...previousProgress };
9770
- const progressForBucket = updatedProgress[data.bucket];
9771
- if (progressForBucket) {
9772
- updatedProgress[data.bucket] = {
9773
- ...progressForBucket,
9774
- since_last: progressForBucket.since_last + data.data.length
9775
- };
9445
+ const event = await inner.next();
9446
+ if (event.done) {
9447
+ done = true;
9448
+ return valueResult({ command: exports.PowerSyncControlCommand.CONNECTION_STATE, payload: 'end' });
9776
9449
  }
9777
- }
9778
- this.updateSyncStatus({
9779
- dataFlow: {
9780
- downloading: true,
9781
- downloadProgress: updatedProgress
9450
+ else {
9451
+ return valueResult({
9452
+ command: typeof event.value == 'string'
9453
+ ? exports.PowerSyncControlCommand.PROCESS_TEXT_LINE
9454
+ : exports.PowerSyncControlCommand.PROCESS_BSON_LINE,
9455
+ payload: event.value
9456
+ });
9782
9457
  }
9783
- });
9784
- await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);
9785
- }
9786
- else if (isStreamingKeepalive(line)) {
9787
- const remaining_seconds = line.token_expires_in;
9788
- if (remaining_seconds == 0) {
9789
- // Connection would be closed automatically right after this
9790
- this.logger.debug('Token expiring; reconnect');
9791
- /**
9792
- * For a rare case where the backend connector does not update the token
9793
- * (uses the same one), this should have some delay.
9794
- */
9795
- await this.delayRetry();
9796
- return;
9797
- }
9798
- else if (remaining_seconds < 30) {
9799
- this.logger.debug('Token will expire soon; reconnect');
9800
- // Pre-emptively refresh the token
9801
- this.options.remote.invalidateCredentials();
9802
- return;
9803
9458
  }
9804
- this.triggerCrudUpload();
9805
- }
9806
- else {
9807
- this.logger.debug('Received unknown sync line', line);
9808
9459
  }
9809
- }
9810
- this.logger.debug('Stream input empty');
9811
- // Connection closed. Likely due to auth issue.
9812
- return;
9460
+ };
9813
9461
  }
9814
9462
  async rustSyncIteration(signal, resolvedOptions) {
9815
9463
  const syncImplementation = this;
9816
9464
  const adapter = this.options.adapter;
9817
9465
  const remote = this.options.remote;
9818
- const controller = new AbortController();
9819
- const abort = () => {
9820
- return controller.abort(signal.reason);
9821
- };
9822
- signal.addEventListener('abort', abort);
9823
- let receivingLines = null;
9824
- let hadSyncLine = false;
9825
9466
  let hideDisconnectOnRestart = false;
9467
+ let notifyTokenRefreshed;
9826
9468
  if (signal.aborted) {
9827
9469
  throw new AbortOperation('Connection request has been aborted');
9828
9470
  }
9829
- // Pending sync lines received from the service, as well as local events that trigger a powersync_control
9830
- // invocation (local events include refreshed tokens and completed uploads).
9831
- // This is a single data stream so that we can handle all control calls from a single place.
9832
- let controlInvocations = null;
9833
- async function connect(instr) {
9834
- const syncOptions = {
9835
- path: '/sync/stream',
9836
- abortSignal: controller.signal,
9837
- data: instr.request
9471
+ function startCommand() {
9472
+ const options = {
9473
+ parameters: resolvedOptions.params,
9474
+ app_metadata: resolvedOptions.appMetadata,
9475
+ active_streams: syncImplementation.activeStreams,
9476
+ include_defaults: resolvedOptions.includeDefaultStreams
9838
9477
  };
9839
- controlInvocations = injectable(map(await syncImplementation.receiveSyncLines({
9840
- options: syncOptions,
9841
- connection: resolvedOptions
9842
- }), (line) => {
9843
- if (typeof line == 'string') {
9844
- return {
9845
- command: exports.PowerSyncControlCommand.PROCESS_TEXT_LINE,
9846
- payload: line
9847
- };
9848
- }
9849
- else {
9850
- return {
9851
- command: exports.PowerSyncControlCommand.PROCESS_BSON_LINE,
9852
- payload: line
9853
- };
9854
- }
9855
- }));
9856
- // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
9857
- // we're already connected here and can report that.
9858
- syncImplementation.updateSyncStatus({ connected: true });
9859
- try {
9860
- while (true) {
9861
- let event = await controlInvocations.next();
9862
- if (event.done) {
9863
- break;
9864
- }
9865
- const line = event.value;
9866
- await control(line.command, line.payload);
9867
- if (!hadSyncLine) {
9868
- syncImplementation.triggerCrudUpload();
9869
- hadSyncLine = true;
9870
- }
9871
- }
9872
- }
9873
- finally {
9874
- abort();
9875
- signal.removeEventListener('abort', abort);
9478
+ if (resolvedOptions.serializedSchema) {
9479
+ options.schema = resolvedOptions.serializedSchema;
9876
9480
  }
9481
+ return invokePowerSyncControl(exports.PowerSyncControlCommand.START, JSON.stringify(options));
9877
9482
  }
9878
9483
  async function stop() {
9879
- await control(exports.PowerSyncControlCommand.STOP);
9484
+ const instructions = await invokePowerSyncControl(exports.PowerSyncControlCommand.STOP);
9485
+ for (const instruction of instructions) {
9486
+ // We don't need to handle interrupting instructions since we're unconditionally ending the sync iteration at
9487
+ // this point.
9488
+ if (isInterruptingInstruction(instruction))
9489
+ continue;
9490
+ await handleInstruction(instruction);
9491
+ }
9880
9492
  }
9881
- async function control(op, payload) {
9493
+ async function invokePowerSyncControl(op, payload) {
9882
9494
  const rawResponse = await adapter.control(op, payload ?? null);
9883
9495
  const logger = syncImplementation.logger;
9884
9496
  logger.trace('powersync_control', op, payload == null || typeof payload == 'string' ? payload : '<bytes>', rawResponse);
9885
- await handleInstructions(JSON.parse(rawResponse));
9497
+ if (op != exports.PowerSyncControlCommand.STOP) {
9498
+ // Evidently we have a working connection here, otherwise powersync_control would have failed.
9499
+ syncImplementation.connectionMayHaveChanged = false;
9500
+ }
9501
+ return JSON.parse(rawResponse);
9886
9502
  }
9887
9503
  async function handleInstruction(instruction) {
9888
9504
  if ('LogLine' in instruction) {
@@ -9901,13 +9517,6 @@ The next upload iteration will be delayed.`);
9901
9517
  else if ('UpdateSyncStatus' in instruction) {
9902
9518
  syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));
9903
9519
  }
9904
- else if ('EstablishSyncStream' in instruction) {
9905
- if (receivingLines != null) {
9906
- // Already connected, this shouldn't happen during a single iteration.
9907
- throw 'Unexpected request to establish sync stream, already connected';
9908
- }
9909
- receivingLines = connect(instruction.EstablishSyncStream);
9910
- }
9911
9520
  else if ('FetchCredentials' in instruction) {
9912
9521
  if (instruction.FetchCredentials.did_expire) {
9913
9522
  remote.invalidateCredentials();
@@ -9916,16 +9525,12 @@ The next upload iteration will be delayed.`);
9916
9525
  remote.invalidateCredentials();
9917
9526
  // Restart iteration after the credentials have been refreshed.
9918
9527
  remote.fetchCredentials().then((_) => {
9919
- controlInvocations?.inject({ command: exports.PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
9528
+ notifyTokenRefreshed?.();
9920
9529
  }, (err) => {
9921
9530
  syncImplementation.logger.warn('Could not prefetch credentials', err);
9922
9531
  });
9923
9532
  }
9924
9533
  }
9925
- else if ('CloseSyncStream' in instruction) {
9926
- controller.abort();
9927
- hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
9928
- }
9929
9534
  else if ('FlushFileSystem' in instruction) ;
9930
9535
  else if ('DidCompleteSync' in instruction) {
9931
9536
  syncImplementation.updateSyncStatus({
@@ -9935,101 +9540,83 @@ The next upload iteration will be delayed.`);
9935
9540
  });
9936
9541
  }
9937
9542
  }
9938
- async function handleInstructions(instructions) {
9939
- for (const instr of instructions) {
9940
- await handleInstruction(instr);
9941
- }
9942
- }
9943
9543
  try {
9944
- const options = {
9945
- parameters: resolvedOptions.params,
9946
- app_metadata: resolvedOptions.appMetadata,
9947
- active_streams: this.activeStreams,
9948
- include_defaults: resolvedOptions.includeDefaultStreams
9949
- };
9950
- if (resolvedOptions.serializedSchema) {
9951
- options.schema = resolvedOptions.serializedSchema;
9544
+ const defaultResult = { immediateRestart: false };
9545
+ // Pending sync lines received from the service, as well as local events that trigger a powersync_control
9546
+ // invocation (local events include refreshed tokens and completed uploads).
9547
+ // This is a single data stream so that we can handle all control calls from a single place.
9548
+ let controlInvocations = null;
9549
+ for (const startInstruction of await startCommand()) {
9550
+ if ('EstablishSyncStream' in startInstruction) {
9551
+ const syncOptions = {
9552
+ path: '/sync/stream',
9553
+ abortSignal: signal,
9554
+ data: startInstruction.EstablishSyncStream.request
9555
+ };
9556
+ controlInvocations = injectable(syncImplementation.receiveSyncLines({
9557
+ options: syncOptions,
9558
+ connection: resolvedOptions
9559
+ }));
9560
+ }
9561
+ else if ('CloseSyncStream' in startInstruction) {
9562
+ return defaultResult;
9563
+ }
9564
+ else {
9565
+ await handleInstruction(startInstruction);
9566
+ }
9952
9567
  }
9953
- await control(exports.PowerSyncControlCommand.START, JSON.stringify(options));
9568
+ if (controlInvocations == null)
9569
+ return defaultResult;
9954
9570
  this.notifyCompletedUploads = () => {
9955
- controlInvocations?.inject({ command: exports.PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
9571
+ controlInvocations.inject({ command: exports.PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
9956
9572
  };
9957
9573
  this.handleActiveStreamsChange = () => {
9958
- controlInvocations?.inject({
9574
+ controlInvocations.inject({
9959
9575
  command: exports.PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
9960
9576
  payload: JSON.stringify(this.activeStreams)
9961
9577
  });
9962
9578
  };
9963
- await receivingLines;
9579
+ notifyTokenRefreshed = () => {
9580
+ controlInvocations.inject({
9581
+ command: exports.PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED
9582
+ });
9583
+ };
9584
+ let hadSyncLine = false;
9585
+ loop: while (true) {
9586
+ const { done, value } = await controlInvocations.next();
9587
+ if (done)
9588
+ break;
9589
+ if (!hadSyncLine) {
9590
+ // Trigger a local CRUD upload when the first sync line has been received, this allows uploading local changes
9591
+ // that have been made while offline or disconnected.
9592
+ if (value.command == exports.PowerSyncControlCommand.PROCESS_TEXT_LINE ||
9593
+ value.command == exports.PowerSyncControlCommand.PROCESS_BSON_LINE) {
9594
+ hadSyncLine = true;
9595
+ this.triggerCrudUpload?.();
9596
+ }
9597
+ }
9598
+ const instructions = await invokePowerSyncControl(value.command, value.payload);
9599
+ for (const instruction of instructions) {
9600
+ if ('EstablishSyncStream' in instruction) {
9601
+ throw new Error('Received EstablishSyncStream while already connected.');
9602
+ }
9603
+ else if ('CloseSyncStream' in instruction) {
9604
+ hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
9605
+ break loop;
9606
+ }
9607
+ else {
9608
+ await handleInstruction(instruction);
9609
+ }
9610
+ }
9611
+ }
9964
9612
  }
9965
9613
  finally {
9966
9614
  this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
9615
+ notifyTokenRefreshed = undefined;
9967
9616
  await stop();
9968
9617
  }
9969
9618
  return { immediateRestart: hideDisconnectOnRestart };
9970
9619
  }
9971
- async updateSyncStatusForStartingCheckpoint(checkpoint) {
9972
- const localProgress = await this.options.adapter.getBucketOperationProgress();
9973
- const progress = {};
9974
- let invalidated = false;
9975
- for (const bucket of checkpoint.buckets) {
9976
- const savedProgress = localProgress[bucket.bucket];
9977
- const atLast = savedProgress?.atLast ?? 0;
9978
- const sinceLast = savedProgress?.sinceLast ?? 0;
9979
- progress[bucket.bucket] = {
9980
- // The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service
9981
- // will use by default.
9982
- priority: bucket.priority ?? 3,
9983
- at_last: atLast,
9984
- since_last: sinceLast,
9985
- target_count: bucket.count ?? 0
9986
- };
9987
- if (bucket.count != null && bucket.count < atLast + sinceLast) {
9988
- // Either due to a defrag / sync rule deploy or a compaction operation, the size
9989
- // of the bucket shrank so much that the local ops exceed the ops in the updated
9990
- // bucket. We can't prossibly report progress in this case (it would overshoot 100%).
9991
- invalidated = true;
9992
- }
9993
- }
9994
- if (invalidated) {
9995
- for (const bucket in progress) {
9996
- const bucketProgress = progress[bucket];
9997
- bucketProgress.at_last = 0;
9998
- bucketProgress.since_last = 0;
9999
- }
10000
- }
10001
- this.updateSyncStatus({
10002
- dataFlow: {
10003
- downloading: true,
10004
- downloadProgress: progress
10005
- }
10006
- });
10007
- }
10008
- async applyCheckpoint(checkpoint) {
10009
- let result = await this.options.adapter.syncLocalDatabase(checkpoint);
10010
- if (!result.checkpointValid) {
10011
- this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);
10012
- // This means checksums failed. Start again with a new checkpoint.
10013
- // TODO: better back-off
10014
- await new Promise((resolve) => setTimeout(resolve, 50));
10015
- return { applied: false, endIteration: true };
10016
- }
10017
- else if (!result.ready) {
10018
- 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.`);
10019
- return { applied: false, endIteration: false };
10020
- }
10021
- this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);
10022
- this.updateSyncStatus({
10023
- connected: true,
10024
- lastSyncedAt: new Date(),
10025
- dataFlow: {
10026
- downloading: false,
10027
- downloadProgress: null,
10028
- downloadError: undefined
10029
- }
10030
- });
10031
- return { applied: true, endIteration: false };
10032
- }
10033
9620
  updateSyncStatus(options) {
10034
9621
  const updatedStatus = new SyncStatus({
10035
9622
  connected: options.connected ?? this.syncStatus.connected,
@@ -11568,14 +11155,12 @@ class SqliteBucketStorage extends BaseObserver {
11568
11155
  db;
11569
11156
  logger;
11570
11157
  tableNames;
11571
- _hasCompletedSync;
11572
11158
  updateListener;
11573
11159
  _clientId;
11574
11160
  constructor(db, logger = Logger.get('SqliteBucketStorage')) {
11575
11161
  super();
11576
11162
  this.db = db;
11577
11163
  this.logger = logger;
11578
- this._hasCompletedSync = false;
11579
11164
  this.tableNames = new Set();
11580
11165
  this.updateListener = db.registerListener({
11581
11166
  tablesUpdated: (update) => {
@@ -11587,7 +11172,6 @@ class SqliteBucketStorage extends BaseObserver {
11587
11172
  });
11588
11173
  }
11589
11174
  async init() {
11590
- this._hasCompletedSync = false;
11591
11175
  const existingTableRows = await this.db.getAll(`SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'`);
11592
11176
  for (const row of existingTableRows ?? []) {
11593
11177
  this.tableNames.add(row.name);
@@ -11609,156 +11193,6 @@ class SqliteBucketStorage extends BaseObserver {
11609
11193
  getMaxOpId() {
11610
11194
  return MAX_OP_ID;
11611
11195
  }
11612
- /**
11613
- * Reset any caches.
11614
- */
11615
- startSession() { }
11616
- async getBucketStates() {
11617
- const result = await this.db.getAll("SELECT name as bucket, cast(last_op as TEXT) as op_id FROM ps_buckets WHERE pending_delete = 0 AND name != '$local'");
11618
- return result;
11619
- }
11620
- async getBucketOperationProgress() {
11621
- const rows = await this.db.getAll('SELECT name, count_at_last, count_since_last FROM ps_buckets');
11622
- return Object.fromEntries(rows.map((r) => [r.name, { atLast: r.count_at_last, sinceLast: r.count_since_last }]));
11623
- }
11624
- async saveSyncData(batch, fixedKeyFormat = false) {
11625
- await this.writeTransaction(async (tx) => {
11626
- for (const b of batch.buckets) {
11627
- await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [
11628
- 'save',
11629
- JSON.stringify({ buckets: [b.toJSON(fixedKeyFormat)] })
11630
- ]);
11631
- this.logger.debug(`Saved batch of data for bucket: ${b.bucket}, operations: ${b.data.length}`);
11632
- }
11633
- });
11634
- }
11635
- async removeBuckets(buckets) {
11636
- for (const bucket of buckets) {
11637
- await this.deleteBucket(bucket);
11638
- }
11639
- }
11640
- /**
11641
- * Mark a bucket for deletion.
11642
- */
11643
- async deleteBucket(bucket) {
11644
- await this.writeTransaction(async (tx) => {
11645
- await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', ['delete_bucket', bucket]);
11646
- });
11647
- this.logger.debug(`Done deleting bucket ${bucket}`);
11648
- }
11649
- async hasCompletedSync() {
11650
- if (this._hasCompletedSync) {
11651
- return true;
11652
- }
11653
- const r = await this.db.get(`SELECT powersync_last_synced_at() as synced_at`);
11654
- const completed = r.synced_at != null;
11655
- if (completed) {
11656
- this._hasCompletedSync = true;
11657
- }
11658
- return completed;
11659
- }
11660
- async syncLocalDatabase(checkpoint, priority) {
11661
- const r = await this.validateChecksums(checkpoint, priority);
11662
- if (!r.checkpointValid) {
11663
- this.logger.error('Checksums failed for', r.checkpointFailures);
11664
- for (const b of r.checkpointFailures ?? []) {
11665
- await this.deleteBucket(b);
11666
- }
11667
- return { ready: false, checkpointValid: false, checkpointFailures: r.checkpointFailures };
11668
- }
11669
- if (priority == null) {
11670
- this.logger.debug(`Validated checksums checkpoint ${checkpoint.last_op_id}`);
11671
- }
11672
- else {
11673
- this.logger.debug(`Validated checksums for partial checkpoint ${checkpoint.last_op_id}, priority ${priority}`);
11674
- }
11675
- let buckets = checkpoint.buckets;
11676
- if (priority !== undefined) {
11677
- buckets = buckets.filter((b) => hasMatchingPriority(priority, b));
11678
- }
11679
- const bucketNames = buckets.map((b) => b.bucket);
11680
- await this.writeTransaction(async (tx) => {
11681
- await tx.execute(`UPDATE ps_buckets SET last_op = ? WHERE name IN (SELECT json_each.value FROM json_each(?))`, [
11682
- checkpoint.last_op_id,
11683
- JSON.stringify(bucketNames)
11684
- ]);
11685
- if (priority == null && checkpoint.write_checkpoint) {
11686
- await tx.execute("UPDATE ps_buckets SET last_op = ? WHERE name = '$local'", [checkpoint.write_checkpoint]);
11687
- }
11688
- });
11689
- const valid = await this.updateObjectsFromBuckets(checkpoint, priority);
11690
- if (!valid) {
11691
- return { ready: false, checkpointValid: true };
11692
- }
11693
- return {
11694
- ready: true,
11695
- checkpointValid: true
11696
- };
11697
- }
11698
- /**
11699
- * Atomically update the local state to the current checkpoint.
11700
- *
11701
- * This includes creating new tables, dropping old tables, and copying data over from the oplog.
11702
- */
11703
- async updateObjectsFromBuckets(checkpoint, priority) {
11704
- let arg = '';
11705
- if (priority !== undefined) {
11706
- const affectedBuckets = [];
11707
- for (const desc of checkpoint.buckets) {
11708
- if (hasMatchingPriority(priority, desc)) {
11709
- affectedBuckets.push(desc.bucket);
11710
- }
11711
- }
11712
- arg = JSON.stringify({ priority, buckets: affectedBuckets });
11713
- }
11714
- return this.writeTransaction(async (tx) => {
11715
- const { insertId: result } = await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [
11716
- 'sync_local',
11717
- arg
11718
- ]);
11719
- if (result == 1) {
11720
- if (priority == null) {
11721
- const bucketToCount = Object.fromEntries(checkpoint.buckets.map((b) => [b.bucket, b.count]));
11722
- // The two parameters could be replaced with one, but: https://github.com/powersync-ja/better-sqlite3/pull/6
11723
- const jsonBucketCount = JSON.stringify(bucketToCount);
11724
- await tx.execute("UPDATE ps_buckets SET count_since_last = 0, count_at_last = ?->name WHERE name != '$local' AND ?->name IS NOT NULL", [jsonBucketCount, jsonBucketCount]);
11725
- }
11726
- return true;
11727
- }
11728
- else {
11729
- return false;
11730
- }
11731
- });
11732
- }
11733
- async validateChecksums(checkpoint, priority) {
11734
- if (priority !== undefined) {
11735
- // Only validate the buckets within the priority we care about
11736
- const newBuckets = checkpoint.buckets.filter((cs) => hasMatchingPriority(priority, cs));
11737
- checkpoint = { ...checkpoint, buckets: newBuckets };
11738
- }
11739
- const rs = await this.db.execute('SELECT powersync_validate_checkpoint(?) as result', [
11740
- JSON.stringify({ ...checkpoint })
11741
- ]);
11742
- const resultItem = rs.rows?.item(0);
11743
- if (!resultItem) {
11744
- return {
11745
- checkpointValid: false,
11746
- ready: false,
11747
- checkpointFailures: []
11748
- };
11749
- }
11750
- const result = JSON.parse(resultItem['result']);
11751
- if (result['valid']) {
11752
- return { ready: true, checkpointValid: true };
11753
- }
11754
- else {
11755
- return {
11756
- checkpointValid: false,
11757
- ready: false,
11758
- checkpointFailures: result['failed_buckets']
11759
- };
11760
- }
11761
- }
11762
11196
  async updateLocalTarget(cb) {
11763
11197
  const rs1 = await this.db.getAll("SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)", [MAX_OP_ID]);
11764
11198
  if (!rs1.length) {
@@ -11849,12 +11283,6 @@ class SqliteBucketStorage extends BaseObserver {
11849
11283
  async writeTransaction(callback, options) {
11850
11284
  return this.db.writeTransaction(callback, options);
11851
11285
  }
11852
- /**
11853
- * Set a target checkpoint.
11854
- */
11855
- async setTargetCheckpoint(checkpoint) {
11856
- // No-op for now
11857
- }
11858
11286
  async control(op, payload) {
11859
11287
  return await this.writeTransaction(async (tx) => {
11860
11288
  const [[raw]] = await tx.executeRaw('SELECT powersync_control(?, ?)', [op, payload]);
@@ -11878,20 +11306,6 @@ class SqliteBucketStorage extends BaseObserver {
11878
11306
  }
11879
11307
  static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
11880
11308
  }
11881
- function hasMatchingPriority(priority, bucket) {
11882
- return bucket.priority != null && bucket.priority <= priority;
11883
- }
11884
-
11885
- // TODO JSON
11886
- class SyncDataBatch {
11887
- buckets;
11888
- static fromJSON(json) {
11889
- return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));
11890
- }
11891
- constructor(buckets) {
11892
- this.buckets = buckets;
11893
- }
11894
- }
11895
11309
 
11896
11310
  /**
11897
11311
  * Thrown when an underlying database connection is closed.
@@ -11951,10 +11365,8 @@ class Schema {
11951
11365
  * developer instead of automatically by PowerSync.
11952
11366
  * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
11953
11367
  * using client-side table and column constraints.
11954
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
11955
11368
  *
11956
11369
  * @param tables An object of (table name, raw table definition) entries.
11957
- * @experimental Note that the raw tables API is still experimental and may change in the future.
11958
11370
  */
11959
11371
  withRawTables(tables) {
11960
11372
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
@@ -12204,13 +11616,9 @@ exports.MAX_OP_ID = MAX_OP_ID;
12204
11616
  exports.MEMORY_TRIGGER_CLAIM_MANAGER = MEMORY_TRIGGER_CLAIM_MANAGER;
12205
11617
  exports.Mutex = Mutex;
12206
11618
  exports.OnChangeQueryProcessor = OnChangeQueryProcessor;
12207
- exports.OpType = OpType;
12208
- exports.OplogEntry = OplogEntry;
12209
11619
  exports.Schema = Schema;
12210
11620
  exports.Semaphore = Semaphore;
12211
11621
  exports.SqliteBucketStorage = SqliteBucketStorage;
12212
- exports.SyncDataBatch = SyncDataBatch;
12213
- exports.SyncDataBucket = SyncDataBucket;
12214
11622
  exports.SyncProgress = SyncProgress;
12215
11623
  exports.SyncStatus = SyncStatus;
12216
11624
  exports.SyncingService = SyncingService;
@@ -12225,18 +11633,10 @@ exports.createBaseLogger = createBaseLogger;
12225
11633
  exports.createLogger = createLogger;
12226
11634
  exports.extractTableUpdates = extractTableUpdates;
12227
11635
  exports.isBatchedUpdateNotification = isBatchedUpdateNotification;
12228
- exports.isContinueCheckpointRequest = isContinueCheckpointRequest;
12229
11636
  exports.isDBAdapter = isDBAdapter;
12230
11637
  exports.isPowerSyncDatabaseOptionsWithSettings = isPowerSyncDatabaseOptionsWithSettings;
12231
11638
  exports.isSQLOpenFactory = isSQLOpenFactory;
12232
11639
  exports.isSQLOpenOptions = isSQLOpenOptions;
12233
- exports.isStreamingKeepalive = isStreamingKeepalive;
12234
- exports.isStreamingSyncCheckpoint = isStreamingSyncCheckpoint;
12235
- exports.isStreamingSyncCheckpointComplete = isStreamingSyncCheckpointComplete;
12236
- exports.isStreamingSyncCheckpointDiff = isStreamingSyncCheckpointDiff;
12237
- exports.isStreamingSyncCheckpointPartiallyComplete = isStreamingSyncCheckpointPartiallyComplete;
12238
- exports.isStreamingSyncData = isStreamingSyncData;
12239
- exports.isSyncNewCheckpointRequest = isSyncNewCheckpointRequest;
12240
11640
  exports.parseQuery = parseQuery;
12241
11641
  exports.runOnSchemaChange = runOnSchemaChange;
12242
11642
  exports.sanitizeSQL = sanitizeSQL;