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