@powersync/web 1.39.1 → 1.39.2

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.
@@ -5668,6 +5668,37 @@ class EventQueue {
5668
5668
  };
5669
5669
  }
5670
5670
  }
5671
+ /**
5672
+ * Runs `action` with a signal that aborts once `signal` aborts or after `timeoutMs`, whichever comes first.
5673
+ *
5674
+ * @param description Names the operation in the error thrown when it times out.
5675
+ */
5676
+ async function runWithTimeout(signal, timeoutMs, description, action) {
5677
+ const controller = new AbortController();
5678
+ const timeoutError = new Error(`${description} timed out after ${timeoutMs}ms`);
5679
+ const onAbort = () => controller.abort(signal?.reason);
5680
+ if (signal?.aborted) {
5681
+ onAbort();
5682
+ }
5683
+ else {
5684
+ signal?.addEventListener('abort', onAbort, { once: true });
5685
+ }
5686
+ const timeout = setTimeout(() => controller.abort(timeoutError), timeoutMs);
5687
+ try {
5688
+ return await action(controller.signal);
5689
+ }
5690
+ catch (error) {
5691
+ // Some fetch implementations reject with a generic abort error instead of the signal's reason.
5692
+ if (controller.signal.reason === timeoutError) {
5693
+ throw timeoutError;
5694
+ }
5695
+ throw error;
5696
+ }
5697
+ finally {
5698
+ clearTimeout(timeout);
5699
+ signal?.removeEventListener('abort', onAbort);
5700
+ }
5701
+ }
5671
5702
 
5672
5703
  /**
5673
5704
  * @internal
@@ -13897,7 +13928,7 @@ function requireDist () {
13897
13928
 
13898
13929
  var distExports = requireDist();
13899
13930
 
13900
- var version = "1.57.3";
13931
+ var version = "1.58.0";
13901
13932
  var PACKAGE = {
13902
13933
  version: version};
13903
13934
 
@@ -14232,14 +14263,15 @@ class AbstractRemote {
14232
14263
  }
14233
14264
  return res.json();
14234
14265
  }
14235
- async get(path, headers) {
14266
+ async get(path, headers, signal) {
14236
14267
  const request = await this.buildRequest(path);
14237
14268
  const res = await this.fetch(request.url, {
14238
14269
  method: 'GET',
14239
14270
  headers: {
14240
14271
  ...headers,
14241
14272
  ...request.headers
14242
- }
14273
+ },
14274
+ signal
14243
14275
  });
14244
14276
  if (res.status === 401) {
14245
14277
  this.invalidateCredentials();
@@ -14292,9 +14324,11 @@ class AbstractRemote {
14292
14324
  }
14293
14325
  });
14294
14326
  let didClose = false;
14295
- let connectionEstablished = false;
14296
14327
  let pendingEventsCount = syncQueueRequestSize;
14297
14328
  let res = null;
14329
+ // Function to reject the promise returned by this method. Set to null while initializing the socket, and after the
14330
+ // promise was resolved.
14331
+ let rejectPendingQueue = null;
14298
14332
  const abortRequest = () => {
14299
14333
  if (didClose) {
14300
14334
  return;
@@ -14307,6 +14341,10 @@ class AbstractRemote {
14307
14341
  if (rsocket) {
14308
14342
  rsocket.close();
14309
14343
  }
14344
+ if (rejectPendingQueue) {
14345
+ rejectPendingQueue(new Error('Connection aborted'));
14346
+ rejectPendingQueue = null;
14347
+ }
14310
14348
  // Send a bogus event to the queue to ensure a pending listener gets woken up. We check for didClose and would
14311
14349
  // return a doneEvent.
14312
14350
  queue.notify(null);
@@ -14378,6 +14416,7 @@ class AbstractRemote {
14378
14416
  // Helps to prevent double close scenarios
14379
14417
  rsocket.onClose(() => (rsocket = null));
14380
14418
  return await new Promise((resolve, reject) => {
14419
+ rejectPendingQueue = reject;
14381
14420
  const queueAsIterator = {
14382
14421
  next: async () => {
14383
14422
  if (didClose)
@@ -14418,14 +14457,15 @@ class AbstractRemote {
14418
14457
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
14419
14458
  abortRequest();
14420
14459
  // Handles cases where the connection failed e.g. auth error or connection error
14421
- if (!connectionEstablished) {
14460
+ if (rejectPendingQueue) {
14422
14461
  reject(e);
14462
+ rejectPendingQueue = null;
14423
14463
  }
14424
14464
  },
14425
14465
  onNext: (payload) => {
14426
14466
  // The connection is active
14427
- if (!connectionEstablished) {
14428
- connectionEstablished = true;
14467
+ if (rejectPendingQueue) {
14468
+ rejectPendingQueue = null;
14429
14469
  resolve(queueAsIterator);
14430
14470
  }
14431
14471
  const { data } = payload;
@@ -14438,6 +14478,12 @@ class AbstractRemote {
14438
14478
  requestMore();
14439
14479
  },
14440
14480
  onComplete: () => {
14481
+ console.log('onComplete', rejectPendingQueue);
14482
+ if (rejectPendingQueue) {
14483
+ // Closed without ever emitting an event? Still emit an empty queue.
14484
+ rejectPendingQueue = null;
14485
+ resolve(queueAsIterator);
14486
+ }
14441
14487
  abortRequest(); // this will also emit a done event
14442
14488
  },
14443
14489
  onExtension: () => { }
@@ -14460,7 +14506,7 @@ class AbstractRemote {
14460
14506
  * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
14461
14507
  */
14462
14508
  async fetchStreamRaw(options) {
14463
- const { data, path, headers, abortSignal } = options;
14509
+ const { data, path, headers, abortSignal, connectTimeoutMs } = options;
14464
14510
  const request = await this.buildRequest(path);
14465
14511
  /**
14466
14512
  * This abort controller will abort pending fetch requests.
@@ -14495,7 +14541,7 @@ class AbstractRemote {
14495
14541
  try {
14496
14542
  const ndJson = 'application/x-ndjson';
14497
14543
  const bson = 'application/vnd.powersync.bson-stream';
14498
- res = await this.fetch(request.url, {
14544
+ const postStream = (signal) => this.fetch(request.url, {
14499
14545
  method: 'POST',
14500
14546
  headers: {
14501
14547
  ...headers,
@@ -14503,11 +14549,15 @@ class AbstractRemote {
14503
14549
  accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
14504
14550
  },
14505
14551
  body: JSON.stringify(data),
14506
- signal: controller.signal,
14552
+ signal,
14507
14553
  cache: 'no-store',
14508
14554
  ...(this.options.fetchOptions ?? {}),
14509
14555
  ...options.fetchOptions
14510
14556
  });
14557
+ // The timeout ends once the response starts, so it never aborts the response body.
14558
+ res = await (connectTimeoutMs == null
14559
+ ? postStream(controller.signal)
14560
+ : runWithTimeout(controller.signal, connectTimeoutMs, 'Sync stream connection', postStream));
14511
14561
  if (!res.ok || !res.body) {
14512
14562
  const text = await res.text();
14513
14563
  this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
@@ -14666,7 +14716,8 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
14666
14716
  fetchStrategy: FetchStrategy.Buffered,
14667
14717
  params: {},
14668
14718
  serializedSchema: undefined,
14669
- includeDefaultStreams: true
14719
+ includeDefaultStreams: true,
14720
+ connectTimeoutMs: 30_000
14670
14721
  };
14671
14722
  /**
14672
14723
  * @internal
@@ -14680,6 +14731,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
14680
14731
  activeStreams;
14681
14732
  connectionMayHaveChanged = false;
14682
14733
  crudUploadNotifier = asyncNotifier();
14734
+ connectTimeoutMs = DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
14683
14735
  notifyCompletedUploads;
14684
14736
  handleActiveStreamsChange;
14685
14737
  syncStatus;
@@ -14749,10 +14801,10 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
14749
14801
  this.crudUpdateListener?.();
14750
14802
  this.crudUpdateListener = undefined;
14751
14803
  }
14752
- async getWriteCheckpoint() {
14804
+ async getWriteCheckpoint(abort) {
14753
14805
  const clientId = await this.options.adapter.getClientId();
14754
14806
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
14755
- const response = await this.options.remote.get(path);
14807
+ const response = await runWithTimeout(abort, this.connectTimeoutMs, 'Write checkpoint request', (signal) => this.options.remote.get(path, undefined, signal));
14756
14808
  const checkpoint = response['data']['write_checkpoint'];
14757
14809
  this.logger.debug(`Created write checkpoint: ${checkpoint}`);
14758
14810
  return checkpoint;
@@ -14805,7 +14857,7 @@ The next upload iteration will be delayed.`);
14805
14857
  }
14806
14858
  else {
14807
14859
  // Uploading is completed
14808
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
14860
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint(signal));
14809
14861
  if (neededUpdate) {
14810
14862
  this.notifyCompletedUploads?.();
14811
14863
  }
@@ -14848,6 +14900,7 @@ The next upload iteration will be delayed.`);
14848
14900
  }
14849
14901
  const controller = new AbortController();
14850
14902
  this.abortController = controller;
14903
+ this.connectTimeoutMs = options?.connectTimeoutMs ?? DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
14851
14904
  this.streamingSyncPromise = Promise.all([
14852
14905
  this.crudUploadLoop(controller.signal).catch((ex) => this.logger.error('Error in crud upload loop', ex)),
14853
14906
  this.streamingSync(controller.signal, options)
@@ -15177,7 +15230,8 @@ The next upload iteration will be delayed.`);
15177
15230
  const syncOptions = {
15178
15231
  path: '/sync/stream',
15179
15232
  abortSignal: signal,
15180
- data: startInstruction.EstablishSyncStream.request
15233
+ data: startInstruction.EstablishSyncStream.request,
15234
+ connectTimeoutMs: resolvedOptions.connectTimeoutMs
15181
15235
  };
15182
15236
  controlInvocations = injectable(syncImplementation.receiveSyncLines({
15183
15237
  options: syncOptions,