@powersync/common 1.57.3 → 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
@@ -2750,6 +2750,37 @@ class EventQueue {
2750
2750
  };
2751
2751
  }
2752
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
+ }
2753
2784
 
2754
2785
  /**
2755
2786
  * @internal
@@ -10979,7 +11010,7 @@ function requireDist () {
10979
11010
 
10980
11011
  var distExports = requireDist();
10981
11012
 
10982
- var version = "1.57.3";
11013
+ var version = "1.58.0";
10983
11014
  var PACKAGE = {
10984
11015
  version: version};
10985
11016
 
@@ -11314,14 +11345,15 @@ class AbstractRemote {
11314
11345
  }
11315
11346
  return res.json();
11316
11347
  }
11317
- async get(path, headers) {
11348
+ async get(path, headers, signal) {
11318
11349
  const request = await this.buildRequest(path);
11319
11350
  const res = await this.fetch(request.url, {
11320
11351
  method: 'GET',
11321
11352
  headers: {
11322
11353
  ...headers,
11323
11354
  ...request.headers
11324
- }
11355
+ },
11356
+ signal
11325
11357
  });
11326
11358
  if (res.status === 401) {
11327
11359
  this.invalidateCredentials();
@@ -11374,9 +11406,11 @@ class AbstractRemote {
11374
11406
  }
11375
11407
  });
11376
11408
  let didClose = false;
11377
- let connectionEstablished = false;
11378
11409
  let pendingEventsCount = syncQueueRequestSize;
11379
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;
11380
11414
  const abortRequest = () => {
11381
11415
  if (didClose) {
11382
11416
  return;
@@ -11389,6 +11423,10 @@ class AbstractRemote {
11389
11423
  if (rsocket) {
11390
11424
  rsocket.close();
11391
11425
  }
11426
+ if (rejectPendingQueue) {
11427
+ rejectPendingQueue(new Error('Connection aborted'));
11428
+ rejectPendingQueue = null;
11429
+ }
11392
11430
  // Send a bogus event to the queue to ensure a pending listener gets woken up. We check for didClose and would
11393
11431
  // return a doneEvent.
11394
11432
  queue.notify(null);
@@ -11460,6 +11498,7 @@ class AbstractRemote {
11460
11498
  // Helps to prevent double close scenarios
11461
11499
  rsocket.onClose(() => (rsocket = null));
11462
11500
  return await new Promise((resolve, reject) => {
11501
+ rejectPendingQueue = reject;
11463
11502
  const queueAsIterator = {
11464
11503
  next: async () => {
11465
11504
  if (didClose)
@@ -11500,14 +11539,15 @@ class AbstractRemote {
11500
11539
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
11501
11540
  abortRequest();
11502
11541
  // Handles cases where the connection failed e.g. auth error or connection error
11503
- if (!connectionEstablished) {
11542
+ if (rejectPendingQueue) {
11504
11543
  reject(e);
11544
+ rejectPendingQueue = null;
11505
11545
  }
11506
11546
  },
11507
11547
  onNext: (payload) => {
11508
11548
  // The connection is active
11509
- if (!connectionEstablished) {
11510
- connectionEstablished = true;
11549
+ if (rejectPendingQueue) {
11550
+ rejectPendingQueue = null;
11511
11551
  resolve(queueAsIterator);
11512
11552
  }
11513
11553
  const { data } = payload;
@@ -11520,6 +11560,12 @@ class AbstractRemote {
11520
11560
  requestMore();
11521
11561
  },
11522
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
+ }
11523
11569
  abortRequest(); // this will also emit a done event
11524
11570
  },
11525
11571
  onExtension: () => { }
@@ -11542,7 +11588,7 @@ class AbstractRemote {
11542
11588
  * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
11543
11589
  */
11544
11590
  async fetchStreamRaw(options) {
11545
- const { data, path, headers, abortSignal } = options;
11591
+ const { data, path, headers, abortSignal, connectTimeoutMs } = options;
11546
11592
  const request = await this.buildRequest(path);
11547
11593
  /**
11548
11594
  * This abort controller will abort pending fetch requests.
@@ -11577,7 +11623,7 @@ class AbstractRemote {
11577
11623
  try {
11578
11624
  const ndJson = 'application/x-ndjson';
11579
11625
  const bson = 'application/vnd.powersync.bson-stream';
11580
- res = await this.fetch(request.url, {
11626
+ const postStream = (signal) => this.fetch(request.url, {
11581
11627
  method: 'POST',
11582
11628
  headers: {
11583
11629
  ...headers,
@@ -11585,11 +11631,15 @@ class AbstractRemote {
11585
11631
  accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
11586
11632
  },
11587
11633
  body: JSON.stringify(data),
11588
- signal: controller.signal,
11634
+ signal,
11589
11635
  cache: 'no-store',
11590
11636
  ...(this.options.fetchOptions ?? {}),
11591
11637
  ...options.fetchOptions
11592
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));
11593
11643
  if (!res.ok || !res.body) {
11594
11644
  const text = await res.text();
11595
11645
  this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
@@ -11748,7 +11798,8 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
11748
11798
  fetchStrategy: exports.FetchStrategy.Buffered,
11749
11799
  params: {},
11750
11800
  serializedSchema: undefined,
11751
- includeDefaultStreams: true
11801
+ includeDefaultStreams: true,
11802
+ connectTimeoutMs: 30_000
11752
11803
  };
11753
11804
  /**
11754
11805
  * @internal
@@ -11762,6 +11813,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
11762
11813
  activeStreams;
11763
11814
  connectionMayHaveChanged = false;
11764
11815
  crudUploadNotifier = asyncNotifier();
11816
+ connectTimeoutMs = DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
11765
11817
  notifyCompletedUploads;
11766
11818
  handleActiveStreamsChange;
11767
11819
  syncStatus;
@@ -11831,10 +11883,10 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
11831
11883
  this.crudUpdateListener?.();
11832
11884
  this.crudUpdateListener = undefined;
11833
11885
  }
11834
- async getWriteCheckpoint() {
11886
+ async getWriteCheckpoint(abort) {
11835
11887
  const clientId = await this.options.adapter.getClientId();
11836
11888
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
11837
- 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));
11838
11890
  const checkpoint = response['data']['write_checkpoint'];
11839
11891
  this.logger.debug(`Created write checkpoint: ${checkpoint}`);
11840
11892
  return checkpoint;
@@ -11887,7 +11939,7 @@ The next upload iteration will be delayed.`);
11887
11939
  }
11888
11940
  else {
11889
11941
  // Uploading is completed
11890
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
11942
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint(signal));
11891
11943
  if (neededUpdate) {
11892
11944
  this.notifyCompletedUploads?.();
11893
11945
  }
@@ -11930,6 +11982,7 @@ The next upload iteration will be delayed.`);
11930
11982
  }
11931
11983
  const controller = new AbortController();
11932
11984
  this.abortController = controller;
11985
+ this.connectTimeoutMs = options?.connectTimeoutMs ?? DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
11933
11986
  this.streamingSyncPromise = Promise.all([
11934
11987
  this.crudUploadLoop(controller.signal).catch((ex) => this.logger.error('Error in crud upload loop', ex)),
11935
11988
  this.streamingSync(controller.signal, options)
@@ -12259,7 +12312,8 @@ The next upload iteration will be delayed.`);
12259
12312
  const syncOptions = {
12260
12313
  path: '/sync/stream',
12261
12314
  abortSignal: signal,
12262
- data: startInstruction.EstablishSyncStream.request
12315
+ data: startInstruction.EstablishSyncStream.request,
12316
+ connectTimeoutMs: resolvedOptions.connectTimeoutMs
12263
12317
  };
12264
12318
  controlInvocations = injectable(syncImplementation.receiveSyncLines({
12265
12319
  options: syncOptions,