@powersync/common 1.57.2 → 1.58.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.
@@ -2392,12 +2392,16 @@ class ControlledExecutor {
2392
2392
  }
2393
2393
  async execute(param) {
2394
2394
  this.runningTask = this.task(param);
2395
- await this.runningTask;
2396
- this.runningTask = undefined;
2397
- if (this.pendingTaskParam) {
2398
- const pendingParam = this.pendingTaskParam;
2399
- this.pendingTaskParam = undefined;
2400
- this.execute(pendingParam);
2395
+ try {
2396
+ await this.runningTask;
2397
+ }
2398
+ finally {
2399
+ this.runningTask = undefined;
2400
+ if (this.pendingTaskParam) {
2401
+ const pendingParam = this.pendingTaskParam;
2402
+ this.pendingTaskParam = undefined;
2403
+ this.execute(pendingParam);
2404
+ }
2401
2405
  }
2402
2406
  }
2403
2407
  }
@@ -2748,6 +2752,37 @@ class EventQueue {
2748
2752
  };
2749
2753
  }
2750
2754
  }
2755
+ /**
2756
+ * Runs `action` with a signal that aborts once `signal` aborts or after `timeoutMs`, whichever comes first.
2757
+ *
2758
+ * @param description Names the operation in the error thrown when it times out.
2759
+ */
2760
+ async function runWithTimeout(signal, timeoutMs, description, action) {
2761
+ const controller = new AbortController();
2762
+ const timeoutError = new Error(`${description} timed out after ${timeoutMs}ms`);
2763
+ const onAbort = () => controller.abort(signal?.reason);
2764
+ if (signal?.aborted) {
2765
+ onAbort();
2766
+ }
2767
+ else {
2768
+ signal?.addEventListener('abort', onAbort, { once: true });
2769
+ }
2770
+ const timeout = setTimeout(() => controller.abort(timeoutError), timeoutMs);
2771
+ try {
2772
+ return await action(controller.signal);
2773
+ }
2774
+ catch (error) {
2775
+ // Some fetch implementations reject with a generic abort error instead of the signal's reason.
2776
+ if (controller.signal.reason === timeoutError) {
2777
+ throw timeoutError;
2778
+ }
2779
+ throw error;
2780
+ }
2781
+ finally {
2782
+ clearTimeout(timeout);
2783
+ signal?.removeEventListener('abort', onAbort);
2784
+ }
2785
+ }
2751
2786
 
2752
2787
  /**
2753
2788
  * @internal
@@ -8606,7 +8641,7 @@ function requireDist () {
8606
8641
 
8607
8642
  var distExports = requireDist();
8608
8643
 
8609
- var version = "1.57.2";
8644
+ var version = "1.58.0";
8610
8645
  var PACKAGE = {
8611
8646
  version: version};
8612
8647
 
@@ -8941,14 +8976,15 @@ class AbstractRemote {
8941
8976
  }
8942
8977
  return res.json();
8943
8978
  }
8944
- async get(path, headers) {
8979
+ async get(path, headers, signal) {
8945
8980
  const request = await this.buildRequest(path);
8946
8981
  const res = await this.fetch(request.url, {
8947
8982
  method: 'GET',
8948
8983
  headers: {
8949
8984
  ...headers,
8950
8985
  ...request.headers
8951
- }
8986
+ },
8987
+ signal
8952
8988
  });
8953
8989
  if (res.status === 401) {
8954
8990
  this.invalidateCredentials();
@@ -9001,9 +9037,11 @@ class AbstractRemote {
9001
9037
  }
9002
9038
  });
9003
9039
  let didClose = false;
9004
- let connectionEstablished = false;
9005
9040
  let pendingEventsCount = syncQueueRequestSize;
9006
9041
  let res = null;
9042
+ // Function to reject the promise returned by this method. Set to null while initializing the socket, and after the
9043
+ // promise was resolved.
9044
+ let rejectPendingQueue = null;
9007
9045
  const abortRequest = () => {
9008
9046
  if (didClose) {
9009
9047
  return;
@@ -9016,6 +9054,10 @@ class AbstractRemote {
9016
9054
  if (rsocket) {
9017
9055
  rsocket.close();
9018
9056
  }
9057
+ if (rejectPendingQueue) {
9058
+ rejectPendingQueue(new Error('Connection aborted'));
9059
+ rejectPendingQueue = null;
9060
+ }
9019
9061
  // Send a bogus event to the queue to ensure a pending listener gets woken up. We check for didClose and would
9020
9062
  // return a doneEvent.
9021
9063
  queue.notify(null);
@@ -9087,6 +9129,7 @@ class AbstractRemote {
9087
9129
  // Helps to prevent double close scenarios
9088
9130
  rsocket.onClose(() => (rsocket = null));
9089
9131
  return await new Promise((resolve, reject) => {
9132
+ rejectPendingQueue = reject;
9090
9133
  const queueAsIterator = {
9091
9134
  next: async () => {
9092
9135
  if (didClose)
@@ -9127,14 +9170,15 @@ class AbstractRemote {
9127
9170
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
9128
9171
  abortRequest();
9129
9172
  // Handles cases where the connection failed e.g. auth error or connection error
9130
- if (!connectionEstablished) {
9173
+ if (rejectPendingQueue) {
9131
9174
  reject(e);
9175
+ rejectPendingQueue = null;
9132
9176
  }
9133
9177
  },
9134
9178
  onNext: (payload) => {
9135
9179
  // The connection is active
9136
- if (!connectionEstablished) {
9137
- connectionEstablished = true;
9180
+ if (rejectPendingQueue) {
9181
+ rejectPendingQueue = null;
9138
9182
  resolve(queueAsIterator);
9139
9183
  }
9140
9184
  const { data } = payload;
@@ -9147,6 +9191,12 @@ class AbstractRemote {
9147
9191
  requestMore();
9148
9192
  },
9149
9193
  onComplete: () => {
9194
+ console.log('onComplete', rejectPendingQueue);
9195
+ if (rejectPendingQueue) {
9196
+ // Closed without ever emitting an event? Still emit an empty queue.
9197
+ rejectPendingQueue = null;
9198
+ resolve(queueAsIterator);
9199
+ }
9150
9200
  abortRequest(); // this will also emit a done event
9151
9201
  },
9152
9202
  onExtension: () => { }
@@ -9169,7 +9219,7 @@ class AbstractRemote {
9169
9219
  * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
9170
9220
  */
9171
9221
  async fetchStreamRaw(options) {
9172
- const { data, path, headers, abortSignal } = options;
9222
+ const { data, path, headers, abortSignal, connectTimeoutMs } = options;
9173
9223
  const request = await this.buildRequest(path);
9174
9224
  /**
9175
9225
  * This abort controller will abort pending fetch requests.
@@ -9204,7 +9254,7 @@ class AbstractRemote {
9204
9254
  try {
9205
9255
  const ndJson = 'application/x-ndjson';
9206
9256
  const bson = 'application/vnd.powersync.bson-stream';
9207
- res = await this.fetch(request.url, {
9257
+ const postStream = (signal) => this.fetch(request.url, {
9208
9258
  method: 'POST',
9209
9259
  headers: {
9210
9260
  ...headers,
@@ -9212,11 +9262,15 @@ class AbstractRemote {
9212
9262
  accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
9213
9263
  },
9214
9264
  body: JSON.stringify(data),
9215
- signal: controller.signal,
9265
+ signal,
9216
9266
  cache: 'no-store',
9217
9267
  ...(this.options.fetchOptions ?? {}),
9218
9268
  ...options.fetchOptions
9219
9269
  });
9270
+ // The timeout ends once the response starts, so it never aborts the response body.
9271
+ res = await (connectTimeoutMs == null
9272
+ ? postStream(controller.signal)
9273
+ : runWithTimeout(controller.signal, connectTimeoutMs, 'Sync stream connection', postStream));
9220
9274
  if (!res.ok || !res.body) {
9221
9275
  const text = await res.text();
9222
9276
  this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
@@ -9375,7 +9429,8 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
9375
9429
  fetchStrategy: exports.FetchStrategy.Buffered,
9376
9430
  params: {},
9377
9431
  serializedSchema: undefined,
9378
- includeDefaultStreams: true
9432
+ includeDefaultStreams: true,
9433
+ connectTimeoutMs: 30_000
9379
9434
  };
9380
9435
  /**
9381
9436
  * @internal
@@ -9389,6 +9444,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
9389
9444
  activeStreams;
9390
9445
  connectionMayHaveChanged = false;
9391
9446
  crudUploadNotifier = asyncNotifier();
9447
+ connectTimeoutMs = DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
9392
9448
  notifyCompletedUploads;
9393
9449
  handleActiveStreamsChange;
9394
9450
  syncStatus;
@@ -9458,10 +9514,10 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
9458
9514
  this.crudUpdateListener?.();
9459
9515
  this.crudUpdateListener = undefined;
9460
9516
  }
9461
- async getWriteCheckpoint() {
9517
+ async getWriteCheckpoint(abort) {
9462
9518
  const clientId = await this.options.adapter.getClientId();
9463
9519
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
9464
- const response = await this.options.remote.get(path);
9520
+ const response = await runWithTimeout(abort, this.connectTimeoutMs, 'Write checkpoint request', (signal) => this.options.remote.get(path, undefined, signal));
9465
9521
  const checkpoint = response['data']['write_checkpoint'];
9466
9522
  this.logger.debug(`Created write checkpoint: ${checkpoint}`);
9467
9523
  return checkpoint;
@@ -9479,6 +9535,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
9479
9535
  async _uploadAllCrud(signal) {
9480
9536
  return this.obtainLock({
9481
9537
  type: exports.LockType.CRUD,
9538
+ signal,
9482
9539
  callback: async () => {
9483
9540
  /**
9484
9541
  * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
@@ -9513,7 +9570,7 @@ The next upload iteration will be delayed.`);
9513
9570
  }
9514
9571
  else {
9515
9572
  // Uploading is completed
9516
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
9573
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint(signal));
9517
9574
  if (neededUpdate) {
9518
9575
  this.notifyCompletedUploads?.();
9519
9576
  }
@@ -9556,6 +9613,7 @@ The next upload iteration will be delayed.`);
9556
9613
  }
9557
9614
  const controller = new AbortController();
9558
9615
  this.abortController = controller;
9616
+ this.connectTimeoutMs = options?.connectTimeoutMs ?? DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
9559
9617
  this.streamingSyncPromise = Promise.all([
9560
9618
  this.crudUploadLoop(controller.signal).catch((ex) => this.logger.error('Error in crud upload loop', ex)),
9561
9619
  this.streamingSync(controller.signal, options)
@@ -9885,7 +9943,8 @@ The next upload iteration will be delayed.`);
9885
9943
  const syncOptions = {
9886
9944
  path: '/sync/stream',
9887
9945
  abortSignal: signal,
9888
- data: startInstruction.EstablishSyncStream.request
9946
+ data: startInstruction.EstablishSyncStream.request,
9947
+ connectTimeoutMs: resolvedOptions.connectTimeoutMs
9889
9948
  };
9890
9949
  controlInvocations = injectable(syncImplementation.receiveSyncLines({
9891
9950
  options: syncOptions,
@@ -11103,7 +11162,7 @@ SELECT * FROM crud_entries;
11103
11162
  }
11104
11163
  /**
11105
11164
  * Open a read-only transaction.
11106
- * Read transactions can run concurrently to a write transaction.
11165
+ * When multiple connections are available, read transactions can run concurrently to a write transaction.
11107
11166
  * Changes from any write transaction are not visible to read transactions started before it.
11108
11167
  *
11109
11168
  * @param callback - Function to execute within the transaction