@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.
package/dist/bundle.cjs CHANGED
@@ -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
@@ -10975,7 +11010,7 @@ function requireDist () {
10975
11010
 
10976
11011
  var distExports = requireDist();
10977
11012
 
10978
- var version = "1.57.2";
11013
+ var version = "1.58.0";
10979
11014
  var PACKAGE = {
10980
11015
  version: version};
10981
11016
 
@@ -11310,14 +11345,15 @@ class AbstractRemote {
11310
11345
  }
11311
11346
  return res.json();
11312
11347
  }
11313
- async get(path, headers) {
11348
+ async get(path, headers, signal) {
11314
11349
  const request = await this.buildRequest(path);
11315
11350
  const res = await this.fetch(request.url, {
11316
11351
  method: 'GET',
11317
11352
  headers: {
11318
11353
  ...headers,
11319
11354
  ...request.headers
11320
- }
11355
+ },
11356
+ signal
11321
11357
  });
11322
11358
  if (res.status === 401) {
11323
11359
  this.invalidateCredentials();
@@ -11370,9 +11406,11 @@ class AbstractRemote {
11370
11406
  }
11371
11407
  });
11372
11408
  let didClose = false;
11373
- let connectionEstablished = false;
11374
11409
  let pendingEventsCount = syncQueueRequestSize;
11375
11410
  let res = null;
11411
+ // Function to reject the promise returned by this method. Set to null while initializing the socket, and after the
11412
+ // promise was resolved.
11413
+ let rejectPendingQueue = null;
11376
11414
  const abortRequest = () => {
11377
11415
  if (didClose) {
11378
11416
  return;
@@ -11385,6 +11423,10 @@ class AbstractRemote {
11385
11423
  if (rsocket) {
11386
11424
  rsocket.close();
11387
11425
  }
11426
+ if (rejectPendingQueue) {
11427
+ rejectPendingQueue(new Error('Connection aborted'));
11428
+ rejectPendingQueue = null;
11429
+ }
11388
11430
  // Send a bogus event to the queue to ensure a pending listener gets woken up. We check for didClose and would
11389
11431
  // return a doneEvent.
11390
11432
  queue.notify(null);
@@ -11456,6 +11498,7 @@ class AbstractRemote {
11456
11498
  // Helps to prevent double close scenarios
11457
11499
  rsocket.onClose(() => (rsocket = null));
11458
11500
  return await new Promise((resolve, reject) => {
11501
+ rejectPendingQueue = reject;
11459
11502
  const queueAsIterator = {
11460
11503
  next: async () => {
11461
11504
  if (didClose)
@@ -11496,14 +11539,15 @@ class AbstractRemote {
11496
11539
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
11497
11540
  abortRequest();
11498
11541
  // Handles cases where the connection failed e.g. auth error or connection error
11499
- if (!connectionEstablished) {
11542
+ if (rejectPendingQueue) {
11500
11543
  reject(e);
11544
+ rejectPendingQueue = null;
11501
11545
  }
11502
11546
  },
11503
11547
  onNext: (payload) => {
11504
11548
  // The connection is active
11505
- if (!connectionEstablished) {
11506
- connectionEstablished = true;
11549
+ if (rejectPendingQueue) {
11550
+ rejectPendingQueue = null;
11507
11551
  resolve(queueAsIterator);
11508
11552
  }
11509
11553
  const { data } = payload;
@@ -11516,6 +11560,12 @@ class AbstractRemote {
11516
11560
  requestMore();
11517
11561
  },
11518
11562
  onComplete: () => {
11563
+ console.log('onComplete', rejectPendingQueue);
11564
+ if (rejectPendingQueue) {
11565
+ // Closed without ever emitting an event? Still emit an empty queue.
11566
+ rejectPendingQueue = null;
11567
+ resolve(queueAsIterator);
11568
+ }
11519
11569
  abortRequest(); // this will also emit a done event
11520
11570
  },
11521
11571
  onExtension: () => { }
@@ -11538,7 +11588,7 @@ class AbstractRemote {
11538
11588
  * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
11539
11589
  */
11540
11590
  async fetchStreamRaw(options) {
11541
- const { data, path, headers, abortSignal } = options;
11591
+ const { data, path, headers, abortSignal, connectTimeoutMs } = options;
11542
11592
  const request = await this.buildRequest(path);
11543
11593
  /**
11544
11594
  * This abort controller will abort pending fetch requests.
@@ -11573,7 +11623,7 @@ class AbstractRemote {
11573
11623
  try {
11574
11624
  const ndJson = 'application/x-ndjson';
11575
11625
  const bson = 'application/vnd.powersync.bson-stream';
11576
- res = await this.fetch(request.url, {
11626
+ const postStream = (signal) => this.fetch(request.url, {
11577
11627
  method: 'POST',
11578
11628
  headers: {
11579
11629
  ...headers,
@@ -11581,11 +11631,15 @@ class AbstractRemote {
11581
11631
  accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
11582
11632
  },
11583
11633
  body: JSON.stringify(data),
11584
- signal: controller.signal,
11634
+ signal,
11585
11635
  cache: 'no-store',
11586
11636
  ...(this.options.fetchOptions ?? {}),
11587
11637
  ...options.fetchOptions
11588
11638
  });
11639
+ // The timeout ends once the response starts, so it never aborts the response body.
11640
+ res = await (connectTimeoutMs == null
11641
+ ? postStream(controller.signal)
11642
+ : runWithTimeout(controller.signal, connectTimeoutMs, 'Sync stream connection', postStream));
11589
11643
  if (!res.ok || !res.body) {
11590
11644
  const text = await res.text();
11591
11645
  this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
@@ -11744,7 +11798,8 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
11744
11798
  fetchStrategy: exports.FetchStrategy.Buffered,
11745
11799
  params: {},
11746
11800
  serializedSchema: undefined,
11747
- includeDefaultStreams: true
11801
+ includeDefaultStreams: true,
11802
+ connectTimeoutMs: 30_000
11748
11803
  };
11749
11804
  /**
11750
11805
  * @internal
@@ -11758,6 +11813,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
11758
11813
  activeStreams;
11759
11814
  connectionMayHaveChanged = false;
11760
11815
  crudUploadNotifier = asyncNotifier();
11816
+ connectTimeoutMs = DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
11761
11817
  notifyCompletedUploads;
11762
11818
  handleActiveStreamsChange;
11763
11819
  syncStatus;
@@ -11827,10 +11883,10 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
11827
11883
  this.crudUpdateListener?.();
11828
11884
  this.crudUpdateListener = undefined;
11829
11885
  }
11830
- async getWriteCheckpoint() {
11886
+ async getWriteCheckpoint(abort) {
11831
11887
  const clientId = await this.options.adapter.getClientId();
11832
11888
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
11833
- const response = await this.options.remote.get(path);
11889
+ const response = await runWithTimeout(abort, this.connectTimeoutMs, 'Write checkpoint request', (signal) => this.options.remote.get(path, undefined, signal));
11834
11890
  const checkpoint = response['data']['write_checkpoint'];
11835
11891
  this.logger.debug(`Created write checkpoint: ${checkpoint}`);
11836
11892
  return checkpoint;
@@ -11848,6 +11904,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
11848
11904
  async _uploadAllCrud(signal) {
11849
11905
  return this.obtainLock({
11850
11906
  type: exports.LockType.CRUD,
11907
+ signal,
11851
11908
  callback: async () => {
11852
11909
  /**
11853
11910
  * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
@@ -11882,7 +11939,7 @@ The next upload iteration will be delayed.`);
11882
11939
  }
11883
11940
  else {
11884
11941
  // Uploading is completed
11885
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
11942
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint(signal));
11886
11943
  if (neededUpdate) {
11887
11944
  this.notifyCompletedUploads?.();
11888
11945
  }
@@ -11925,6 +11982,7 @@ The next upload iteration will be delayed.`);
11925
11982
  }
11926
11983
  const controller = new AbortController();
11927
11984
  this.abortController = controller;
11985
+ this.connectTimeoutMs = options?.connectTimeoutMs ?? DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
11928
11986
  this.streamingSyncPromise = Promise.all([
11929
11987
  this.crudUploadLoop(controller.signal).catch((ex) => this.logger.error('Error in crud upload loop', ex)),
11930
11988
  this.streamingSync(controller.signal, options)
@@ -12254,7 +12312,8 @@ The next upload iteration will be delayed.`);
12254
12312
  const syncOptions = {
12255
12313
  path: '/sync/stream',
12256
12314
  abortSignal: signal,
12257
- data: startInstruction.EstablishSyncStream.request
12315
+ data: startInstruction.EstablishSyncStream.request,
12316
+ connectTimeoutMs: resolvedOptions.connectTimeoutMs
12258
12317
  };
12259
12318
  controlInvocations = injectable(syncImplementation.receiveSyncLines({
12260
12319
  options: syncOptions,
@@ -13472,7 +13531,7 @@ SELECT * FROM crud_entries;
13472
13531
  }
13473
13532
  /**
13474
13533
  * Open a read-only transaction.
13475
- * Read transactions can run concurrently to a write transaction.
13534
+ * When multiple connections are available, read transactions can run concurrently to a write transaction.
13476
13535
  * Changes from any write transaction are not visible to read transactions started before it.
13477
13536
  *
13478
13537
  * @param callback - Function to execute within the transaction