@powersync/web 1.39.0 → 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.
Files changed (35) hide show
  1. package/dist/index.umd.js +85 -32
  2. package/dist/index.umd.js.map +1 -1
  3. package/dist/worker/SharedSyncImplementation.umd.js +83 -23
  4. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  5. package/dist/worker/WASQLiteDB.umd.js +92 -23
  6. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  7. package/lib/package.json +2 -2
  8. package/lib/src/db/adapters/AsyncWebAdapter.js +1 -1
  9. package/lib/src/db/adapters/AsyncWebAdapter.js.map +1 -1
  10. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +8 -0
  11. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js +9 -0
  12. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js.map +1 -1
  13. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +8 -2
  14. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +1 -1
  15. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.d.ts +1 -0
  16. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +10 -5
  17. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js.map +1 -1
  18. package/lib/src/worker/db/open-worker-database.d.ts +3 -2
  19. package/lib/src/worker/db/open-worker-database.js +30 -22
  20. package/lib/src/worker/db/open-worker-database.js.map +1 -1
  21. package/lib/src/worker/errors.d.ts +2 -0
  22. package/lib/src/worker/errors.js +7 -0
  23. package/lib/src/worker/errors.js.map +1 -0
  24. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +1 -0
  25. package/lib/src/worker/sync/SharedSyncImplementation.js +2 -1
  26. package/lib/src/worker/sync/SharedSyncImplementation.js.map +1 -1
  27. package/lib/tsconfig.tsbuildinfo +1 -1
  28. package/package.json +3 -3
  29. package/src/db/adapters/AsyncWebAdapter.ts +1 -1
  30. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +10 -0
  31. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +24 -9
  32. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +17 -11
  33. package/src/worker/db/open-worker-database.ts +34 -22
  34. package/src/worker/errors.ts +9 -0
  35. package/src/worker/sync/SharedSyncImplementation.ts +3 -1
@@ -1054,6 +1054,7 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
1054
1054
  syncStatus;
1055
1055
  broadCastLogger;
1056
1056
  database = this.generateReconnectableDatabase();
1057
+ sharedCloseSignal = (0,_shared_tab_close_signal_js__WEBPACK_IMPORTED_MODULE_6__.generateTabCloseSignal)();
1057
1058
  constructor() {
1058
1059
  super();
1059
1060
  this.ports = [];
@@ -1387,7 +1388,7 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
1387
1388
  });
1388
1389
  const remote = comlink__WEBPACK_IMPORTED_MODULE_1__.wrap(workerPort);
1389
1390
  const identifier = this.syncParams.dbParams.dbFilename;
1390
- const clientLockName = await (0,_shared_tab_close_signal_js__WEBPACK_IMPORTED_MODULE_6__.generateTabCloseSignal)();
1391
+ const clientLockName = await this.sharedCloseSignal;
1391
1392
  /**
1392
1393
  * The open could fail if the tab is closed while we're busy opening the database.
1393
1394
  * This operation is typically executed inside an exclusive portMutex lock.
@@ -4124,12 +4125,16 @@ class ControlledExecutor {
4124
4125
  }
4125
4126
  async execute(param) {
4126
4127
  this.runningTask = this.task(param);
4127
- await this.runningTask;
4128
- this.runningTask = undefined;
4129
- if (this.pendingTaskParam) {
4130
- const pendingParam = this.pendingTaskParam;
4131
- this.pendingTaskParam = undefined;
4132
- this.execute(pendingParam);
4128
+ try {
4129
+ await this.runningTask;
4130
+ }
4131
+ finally {
4132
+ this.runningTask = undefined;
4133
+ if (this.pendingTaskParam) {
4134
+ const pendingParam = this.pendingTaskParam;
4135
+ this.pendingTaskParam = undefined;
4136
+ this.execute(pendingParam);
4137
+ }
4133
4138
  }
4134
4139
  }
4135
4140
  }
@@ -4480,6 +4485,37 @@ class EventQueue {
4480
4485
  };
4481
4486
  }
4482
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
+ }
4483
4519
 
4484
4520
  /**
4485
4521
  * @internal
@@ -12709,7 +12745,7 @@ function requireDist () {
12709
12745
 
12710
12746
  var distExports = requireDist();
12711
12747
 
12712
- var version = "1.57.2";
12748
+ var version = "1.58.0";
12713
12749
  var PACKAGE = {
12714
12750
  version: version};
12715
12751
 
@@ -13044,14 +13080,15 @@ class AbstractRemote {
13044
13080
  }
13045
13081
  return res.json();
13046
13082
  }
13047
- async get(path, headers) {
13083
+ async get(path, headers, signal) {
13048
13084
  const request = await this.buildRequest(path);
13049
13085
  const res = await this.fetch(request.url, {
13050
13086
  method: 'GET',
13051
13087
  headers: {
13052
13088
  ...headers,
13053
13089
  ...request.headers
13054
- }
13090
+ },
13091
+ signal
13055
13092
  });
13056
13093
  if (res.status === 401) {
13057
13094
  this.invalidateCredentials();
@@ -13104,9 +13141,11 @@ class AbstractRemote {
13104
13141
  }
13105
13142
  });
13106
13143
  let didClose = false;
13107
- let connectionEstablished = false;
13108
13144
  let pendingEventsCount = syncQueueRequestSize;
13109
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;
13110
13149
  const abortRequest = () => {
13111
13150
  if (didClose) {
13112
13151
  return;
@@ -13119,6 +13158,10 @@ class AbstractRemote {
13119
13158
  if (rsocket) {
13120
13159
  rsocket.close();
13121
13160
  }
13161
+ if (rejectPendingQueue) {
13162
+ rejectPendingQueue(new Error('Connection aborted'));
13163
+ rejectPendingQueue = null;
13164
+ }
13122
13165
  // Send a bogus event to the queue to ensure a pending listener gets woken up. We check for didClose and would
13123
13166
  // return a doneEvent.
13124
13167
  queue.notify(null);
@@ -13190,6 +13233,7 @@ class AbstractRemote {
13190
13233
  // Helps to prevent double close scenarios
13191
13234
  rsocket.onClose(() => (rsocket = null));
13192
13235
  return await new Promise((resolve, reject) => {
13236
+ rejectPendingQueue = reject;
13193
13237
  const queueAsIterator = {
13194
13238
  next: async () => {
13195
13239
  if (didClose)
@@ -13230,14 +13274,15 @@ class AbstractRemote {
13230
13274
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
13231
13275
  abortRequest();
13232
13276
  // Handles cases where the connection failed e.g. auth error or connection error
13233
- if (!connectionEstablished) {
13277
+ if (rejectPendingQueue) {
13234
13278
  reject(e);
13279
+ rejectPendingQueue = null;
13235
13280
  }
13236
13281
  },
13237
13282
  onNext: (payload) => {
13238
13283
  // The connection is active
13239
- if (!connectionEstablished) {
13240
- connectionEstablished = true;
13284
+ if (rejectPendingQueue) {
13285
+ rejectPendingQueue = null;
13241
13286
  resolve(queueAsIterator);
13242
13287
  }
13243
13288
  const { data } = payload;
@@ -13250,6 +13295,12 @@ class AbstractRemote {
13250
13295
  requestMore();
13251
13296
  },
13252
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
+ }
13253
13304
  abortRequest(); // this will also emit a done event
13254
13305
  },
13255
13306
  onExtension: () => { }
@@ -13272,7 +13323,7 @@ class AbstractRemote {
13272
13323
  * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
13273
13324
  */
13274
13325
  async fetchStreamRaw(options) {
13275
- const { data, path, headers, abortSignal } = options;
13326
+ const { data, path, headers, abortSignal, connectTimeoutMs } = options;
13276
13327
  const request = await this.buildRequest(path);
13277
13328
  /**
13278
13329
  * This abort controller will abort pending fetch requests.
@@ -13307,7 +13358,7 @@ class AbstractRemote {
13307
13358
  try {
13308
13359
  const ndJson = 'application/x-ndjson';
13309
13360
  const bson = 'application/vnd.powersync.bson-stream';
13310
- res = await this.fetch(request.url, {
13361
+ const postStream = (signal) => this.fetch(request.url, {
13311
13362
  method: 'POST',
13312
13363
  headers: {
13313
13364
  ...headers,
@@ -13315,11 +13366,15 @@ class AbstractRemote {
13315
13366
  accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
13316
13367
  },
13317
13368
  body: JSON.stringify(data),
13318
- signal: controller.signal,
13369
+ signal,
13319
13370
  cache: 'no-store',
13320
13371
  ...(this.options.fetchOptions ?? {}),
13321
13372
  ...options.fetchOptions
13322
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));
13323
13378
  if (!res.ok || !res.body) {
13324
13379
  const text = await res.text();
13325
13380
  this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
@@ -13478,7 +13533,8 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
13478
13533
  fetchStrategy: FetchStrategy.Buffered,
13479
13534
  params: {},
13480
13535
  serializedSchema: undefined,
13481
- includeDefaultStreams: true
13536
+ includeDefaultStreams: true,
13537
+ connectTimeoutMs: 30_000
13482
13538
  };
13483
13539
  /**
13484
13540
  * @internal
@@ -13492,6 +13548,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
13492
13548
  activeStreams;
13493
13549
  connectionMayHaveChanged = false;
13494
13550
  crudUploadNotifier = asyncNotifier();
13551
+ connectTimeoutMs = DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
13495
13552
  notifyCompletedUploads;
13496
13553
  handleActiveStreamsChange;
13497
13554
  syncStatus;
@@ -13561,10 +13618,10 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
13561
13618
  this.crudUpdateListener?.();
13562
13619
  this.crudUpdateListener = undefined;
13563
13620
  }
13564
- async getWriteCheckpoint() {
13621
+ async getWriteCheckpoint(abort) {
13565
13622
  const clientId = await this.options.adapter.getClientId();
13566
13623
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
13567
- 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));
13568
13625
  const checkpoint = response['data']['write_checkpoint'];
13569
13626
  this.logger.debug(`Created write checkpoint: ${checkpoint}`);
13570
13627
  return checkpoint;
@@ -13582,6 +13639,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
13582
13639
  async _uploadAllCrud(signal) {
13583
13640
  return this.obtainLock({
13584
13641
  type: LockType.CRUD,
13642
+ signal,
13585
13643
  callback: async () => {
13586
13644
  /**
13587
13645
  * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
@@ -13616,7 +13674,7 @@ The next upload iteration will be delayed.`);
13616
13674
  }
13617
13675
  else {
13618
13676
  // Uploading is completed
13619
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
13677
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint(signal));
13620
13678
  if (neededUpdate) {
13621
13679
  this.notifyCompletedUploads?.();
13622
13680
  }
@@ -13659,6 +13717,7 @@ The next upload iteration will be delayed.`);
13659
13717
  }
13660
13718
  const controller = new AbortController();
13661
13719
  this.abortController = controller;
13720
+ this.connectTimeoutMs = options?.connectTimeoutMs ?? DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
13662
13721
  this.streamingSyncPromise = Promise.all([
13663
13722
  this.crudUploadLoop(controller.signal).catch((ex) => this.logger.error('Error in crud upload loop', ex)),
13664
13723
  this.streamingSync(controller.signal, options)
@@ -13988,7 +14047,8 @@ The next upload iteration will be delayed.`);
13988
14047
  const syncOptions = {
13989
14048
  path: '/sync/stream',
13990
14049
  abortSignal: signal,
13991
- data: startInstruction.EstablishSyncStream.request
14050
+ data: startInstruction.EstablishSyncStream.request,
14051
+ connectTimeoutMs: resolvedOptions.connectTimeoutMs
13992
14052
  };
13993
14053
  controlInvocations = injectable(syncImplementation.receiveSyncLines({
13994
14054
  options: syncOptions,
@@ -15206,7 +15266,7 @@ SELECT * FROM crud_entries;
15206
15266
  }
15207
15267
  /**
15208
15268
  * Open a read-only transaction.
15209
- * Read transactions can run concurrently to a write transaction.
15269
+ * When multiple connections are available, read transactions can run concurrently to a write transaction.
15210
15270
  * Changes from any write transaction are not visible to read transactions started before it.
15211
15271
  *
15212
15272
  * @param callback - Function to execute within the transaction