@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.
@@ -4485,6 +4485,37 @@ class EventQueue {
4485
4485
  };
4486
4486
  }
4487
4487
  }
4488
+ /**
4489
+ * Runs `action` with a signal that aborts once `signal` aborts or after `timeoutMs`, whichever comes first.
4490
+ *
4491
+ * @param description Names the operation in the error thrown when it times out.
4492
+ */
4493
+ async function runWithTimeout(signal, timeoutMs, description, action) {
4494
+ const controller = new AbortController();
4495
+ const timeoutError = new Error(`${description} timed out after ${timeoutMs}ms`);
4496
+ const onAbort = () => controller.abort(signal?.reason);
4497
+ if (signal?.aborted) {
4498
+ onAbort();
4499
+ }
4500
+ else {
4501
+ signal?.addEventListener('abort', onAbort, { once: true });
4502
+ }
4503
+ const timeout = setTimeout(() => controller.abort(timeoutError), timeoutMs);
4504
+ try {
4505
+ return await action(controller.signal);
4506
+ }
4507
+ catch (error) {
4508
+ // Some fetch implementations reject with a generic abort error instead of the signal's reason.
4509
+ if (controller.signal.reason === timeoutError) {
4510
+ throw timeoutError;
4511
+ }
4512
+ throw error;
4513
+ }
4514
+ finally {
4515
+ clearTimeout(timeout);
4516
+ signal?.removeEventListener('abort', onAbort);
4517
+ }
4518
+ }
4488
4519
 
4489
4520
  /**
4490
4521
  * @internal
@@ -12714,7 +12745,7 @@ function requireDist () {
12714
12745
 
12715
12746
  var distExports = requireDist();
12716
12747
 
12717
- var version = "1.57.3";
12748
+ var version = "1.58.0";
12718
12749
  var PACKAGE = {
12719
12750
  version: version};
12720
12751
 
@@ -13049,14 +13080,15 @@ class AbstractRemote {
13049
13080
  }
13050
13081
  return res.json();
13051
13082
  }
13052
- async get(path, headers) {
13083
+ async get(path, headers, signal) {
13053
13084
  const request = await this.buildRequest(path);
13054
13085
  const res = await this.fetch(request.url, {
13055
13086
  method: 'GET',
13056
13087
  headers: {
13057
13088
  ...headers,
13058
13089
  ...request.headers
13059
- }
13090
+ },
13091
+ signal
13060
13092
  });
13061
13093
  if (res.status === 401) {
13062
13094
  this.invalidateCredentials();
@@ -13109,9 +13141,11 @@ class AbstractRemote {
13109
13141
  }
13110
13142
  });
13111
13143
  let didClose = false;
13112
- let connectionEstablished = false;
13113
13144
  let pendingEventsCount = syncQueueRequestSize;
13114
13145
  let res = null;
13146
+ // Function to reject the promise returned by this method. Set to null while initializing the socket, and after the
13147
+ // promise was resolved.
13148
+ let rejectPendingQueue = null;
13115
13149
  const abortRequest = () => {
13116
13150
  if (didClose) {
13117
13151
  return;
@@ -13124,6 +13158,10 @@ class AbstractRemote {
13124
13158
  if (rsocket) {
13125
13159
  rsocket.close();
13126
13160
  }
13161
+ if (rejectPendingQueue) {
13162
+ rejectPendingQueue(new Error('Connection aborted'));
13163
+ rejectPendingQueue = null;
13164
+ }
13127
13165
  // Send a bogus event to the queue to ensure a pending listener gets woken up. We check for didClose and would
13128
13166
  // return a doneEvent.
13129
13167
  queue.notify(null);
@@ -13195,6 +13233,7 @@ class AbstractRemote {
13195
13233
  // Helps to prevent double close scenarios
13196
13234
  rsocket.onClose(() => (rsocket = null));
13197
13235
  return await new Promise((resolve, reject) => {
13236
+ rejectPendingQueue = reject;
13198
13237
  const queueAsIterator = {
13199
13238
  next: async () => {
13200
13239
  if (didClose)
@@ -13235,14 +13274,15 @@ class AbstractRemote {
13235
13274
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
13236
13275
  abortRequest();
13237
13276
  // Handles cases where the connection failed e.g. auth error or connection error
13238
- if (!connectionEstablished) {
13277
+ if (rejectPendingQueue) {
13239
13278
  reject(e);
13279
+ rejectPendingQueue = null;
13240
13280
  }
13241
13281
  },
13242
13282
  onNext: (payload) => {
13243
13283
  // The connection is active
13244
- if (!connectionEstablished) {
13245
- connectionEstablished = true;
13284
+ if (rejectPendingQueue) {
13285
+ rejectPendingQueue = null;
13246
13286
  resolve(queueAsIterator);
13247
13287
  }
13248
13288
  const { data } = payload;
@@ -13255,6 +13295,12 @@ class AbstractRemote {
13255
13295
  requestMore();
13256
13296
  },
13257
13297
  onComplete: () => {
13298
+ console.log('onComplete', rejectPendingQueue);
13299
+ if (rejectPendingQueue) {
13300
+ // Closed without ever emitting an event? Still emit an empty queue.
13301
+ rejectPendingQueue = null;
13302
+ resolve(queueAsIterator);
13303
+ }
13258
13304
  abortRequest(); // this will also emit a done event
13259
13305
  },
13260
13306
  onExtension: () => { }
@@ -13277,7 +13323,7 @@ class AbstractRemote {
13277
13323
  * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
13278
13324
  */
13279
13325
  async fetchStreamRaw(options) {
13280
- const { data, path, headers, abortSignal } = options;
13326
+ const { data, path, headers, abortSignal, connectTimeoutMs } = options;
13281
13327
  const request = await this.buildRequest(path);
13282
13328
  /**
13283
13329
  * This abort controller will abort pending fetch requests.
@@ -13312,7 +13358,7 @@ class AbstractRemote {
13312
13358
  try {
13313
13359
  const ndJson = 'application/x-ndjson';
13314
13360
  const bson = 'application/vnd.powersync.bson-stream';
13315
- res = await this.fetch(request.url, {
13361
+ const postStream = (signal) => this.fetch(request.url, {
13316
13362
  method: 'POST',
13317
13363
  headers: {
13318
13364
  ...headers,
@@ -13320,11 +13366,15 @@ class AbstractRemote {
13320
13366
  accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
13321
13367
  },
13322
13368
  body: JSON.stringify(data),
13323
- signal: controller.signal,
13369
+ signal,
13324
13370
  cache: 'no-store',
13325
13371
  ...(this.options.fetchOptions ?? {}),
13326
13372
  ...options.fetchOptions
13327
13373
  });
13374
+ // The timeout ends once the response starts, so it never aborts the response body.
13375
+ res = await (connectTimeoutMs == null
13376
+ ? postStream(controller.signal)
13377
+ : runWithTimeout(controller.signal, connectTimeoutMs, 'Sync stream connection', postStream));
13328
13378
  if (!res.ok || !res.body) {
13329
13379
  const text = await res.text();
13330
13380
  this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
@@ -13483,7 +13533,8 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
13483
13533
  fetchStrategy: FetchStrategy.Buffered,
13484
13534
  params: {},
13485
13535
  serializedSchema: undefined,
13486
- includeDefaultStreams: true
13536
+ includeDefaultStreams: true,
13537
+ connectTimeoutMs: 30_000
13487
13538
  };
13488
13539
  /**
13489
13540
  * @internal
@@ -13497,6 +13548,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
13497
13548
  activeStreams;
13498
13549
  connectionMayHaveChanged = false;
13499
13550
  crudUploadNotifier = asyncNotifier();
13551
+ connectTimeoutMs = DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
13500
13552
  notifyCompletedUploads;
13501
13553
  handleActiveStreamsChange;
13502
13554
  syncStatus;
@@ -13566,10 +13618,10 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
13566
13618
  this.crudUpdateListener?.();
13567
13619
  this.crudUpdateListener = undefined;
13568
13620
  }
13569
- async getWriteCheckpoint() {
13621
+ async getWriteCheckpoint(abort) {
13570
13622
  const clientId = await this.options.adapter.getClientId();
13571
13623
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
13572
- const response = await this.options.remote.get(path);
13624
+ const response = await runWithTimeout(abort, this.connectTimeoutMs, 'Write checkpoint request', (signal) => this.options.remote.get(path, undefined, signal));
13573
13625
  const checkpoint = response['data']['write_checkpoint'];
13574
13626
  this.logger.debug(`Created write checkpoint: ${checkpoint}`);
13575
13627
  return checkpoint;
@@ -13622,7 +13674,7 @@ The next upload iteration will be delayed.`);
13622
13674
  }
13623
13675
  else {
13624
13676
  // Uploading is completed
13625
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
13677
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint(signal));
13626
13678
  if (neededUpdate) {
13627
13679
  this.notifyCompletedUploads?.();
13628
13680
  }
@@ -13665,6 +13717,7 @@ The next upload iteration will be delayed.`);
13665
13717
  }
13666
13718
  const controller = new AbortController();
13667
13719
  this.abortController = controller;
13720
+ this.connectTimeoutMs = options?.connectTimeoutMs ?? DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
13668
13721
  this.streamingSyncPromise = Promise.all([
13669
13722
  this.crudUploadLoop(controller.signal).catch((ex) => this.logger.error('Error in crud upload loop', ex)),
13670
13723
  this.streamingSync(controller.signal, options)
@@ -13994,7 +14047,8 @@ The next upload iteration will be delayed.`);
13994
14047
  const syncOptions = {
13995
14048
  path: '/sync/stream',
13996
14049
  abortSignal: signal,
13997
- data: startInstruction.EstablishSyncStream.request
14050
+ data: startInstruction.EstablishSyncStream.request,
14051
+ connectTimeoutMs: resolvedOptions.connectTimeoutMs
13998
14052
  };
13999
14053
  controlInvocations = injectable(syncImplementation.receiveSyncLines({
14000
14054
  options: syncOptions,