@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
@@ -2414,12 +2414,21 @@ class DatabaseServer {
2414
2414
 
2415
2415
  __webpack_require__.r(__webpack_exports__);
2416
2416
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2417
- /* harmony export */ RawSqliteConnection: () => (/* binding */ RawSqliteConnection)
2417
+ /* harmony export */ RawSqliteConnection: () => (/* binding */ RawSqliteConnection),
2418
+ /* harmony export */ maxPathNameLength: () => (/* binding */ maxPathNameLength)
2418
2419
  /* harmony export */ });
2419
2420
  /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
2420
2421
  /* harmony import */ var _vfs_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vfs.js */ "./lib/src/db/adapters/wa-sqlite/vfs.js");
2421
2422
 
2422
2423
 
2424
+ /**
2425
+ * The maximum length of a db filename we support.
2426
+ *
2427
+ * We configure the same on WA-SQLite (which otherwise defaults to a maximum length of 64). We don't want to support
2428
+ * very long path names as Safari maps OPFS files directly to OS files, and APFS has a 255-byte filename limit. Since
2429
+ * some VFS append additional characters for pooled file access handles, we want to stay well below that.
2430
+ */
2431
+ const maxPathNameLength = 128;
2423
2432
  /**
2424
2433
  * A small wrapper around WA-sqlite to help with opening databases and running statements by preparing them internally.
2425
2434
  *
@@ -2452,6 +2461,7 @@ class RawSqliteConnection {
2452
2461
  }
2453
2462
  async openSQLiteAPI() {
2454
2463
  const { module, vfs } = await (0,_vfs_js__WEBPACK_IMPORTED_MODULE_1__.loadModuleAndVfs)(this.options);
2464
+ vfs.mxPathname = maxPathNameLength;
2455
2465
  const sqlite3 = (0,_journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.Factory)(module);
2456
2466
  sqlite3.vfs_register(vfs, true);
2457
2467
  /**
@@ -5298,12 +5308,16 @@ class ControlledExecutor {
5298
5308
  }
5299
5309
  async execute(param) {
5300
5310
  this.runningTask = this.task(param);
5301
- await this.runningTask;
5302
- this.runningTask = undefined;
5303
- if (this.pendingTaskParam) {
5304
- const pendingParam = this.pendingTaskParam;
5305
- this.pendingTaskParam = undefined;
5306
- this.execute(pendingParam);
5311
+ try {
5312
+ await this.runningTask;
5313
+ }
5314
+ finally {
5315
+ this.runningTask = undefined;
5316
+ if (this.pendingTaskParam) {
5317
+ const pendingParam = this.pendingTaskParam;
5318
+ this.pendingTaskParam = undefined;
5319
+ this.execute(pendingParam);
5320
+ }
5307
5321
  }
5308
5322
  }
5309
5323
  }
@@ -5654,6 +5668,37 @@ class EventQueue {
5654
5668
  };
5655
5669
  }
5656
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
+ }
5657
5702
 
5658
5703
  /**
5659
5704
  * @internal
@@ -13883,7 +13928,7 @@ function requireDist () {
13883
13928
 
13884
13929
  var distExports = requireDist();
13885
13930
 
13886
- var version = "1.57.2";
13931
+ var version = "1.58.0";
13887
13932
  var PACKAGE = {
13888
13933
  version: version};
13889
13934
 
@@ -14218,14 +14263,15 @@ class AbstractRemote {
14218
14263
  }
14219
14264
  return res.json();
14220
14265
  }
14221
- async get(path, headers) {
14266
+ async get(path, headers, signal) {
14222
14267
  const request = await this.buildRequest(path);
14223
14268
  const res = await this.fetch(request.url, {
14224
14269
  method: 'GET',
14225
14270
  headers: {
14226
14271
  ...headers,
14227
14272
  ...request.headers
14228
- }
14273
+ },
14274
+ signal
14229
14275
  });
14230
14276
  if (res.status === 401) {
14231
14277
  this.invalidateCredentials();
@@ -14278,9 +14324,11 @@ class AbstractRemote {
14278
14324
  }
14279
14325
  });
14280
14326
  let didClose = false;
14281
- let connectionEstablished = false;
14282
14327
  let pendingEventsCount = syncQueueRequestSize;
14283
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;
14284
14332
  const abortRequest = () => {
14285
14333
  if (didClose) {
14286
14334
  return;
@@ -14293,6 +14341,10 @@ class AbstractRemote {
14293
14341
  if (rsocket) {
14294
14342
  rsocket.close();
14295
14343
  }
14344
+ if (rejectPendingQueue) {
14345
+ rejectPendingQueue(new Error('Connection aborted'));
14346
+ rejectPendingQueue = null;
14347
+ }
14296
14348
  // Send a bogus event to the queue to ensure a pending listener gets woken up. We check for didClose and would
14297
14349
  // return a doneEvent.
14298
14350
  queue.notify(null);
@@ -14364,6 +14416,7 @@ class AbstractRemote {
14364
14416
  // Helps to prevent double close scenarios
14365
14417
  rsocket.onClose(() => (rsocket = null));
14366
14418
  return await new Promise((resolve, reject) => {
14419
+ rejectPendingQueue = reject;
14367
14420
  const queueAsIterator = {
14368
14421
  next: async () => {
14369
14422
  if (didClose)
@@ -14404,14 +14457,15 @@ class AbstractRemote {
14404
14457
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
14405
14458
  abortRequest();
14406
14459
  // Handles cases where the connection failed e.g. auth error or connection error
14407
- if (!connectionEstablished) {
14460
+ if (rejectPendingQueue) {
14408
14461
  reject(e);
14462
+ rejectPendingQueue = null;
14409
14463
  }
14410
14464
  },
14411
14465
  onNext: (payload) => {
14412
14466
  // The connection is active
14413
- if (!connectionEstablished) {
14414
- connectionEstablished = true;
14467
+ if (rejectPendingQueue) {
14468
+ rejectPendingQueue = null;
14415
14469
  resolve(queueAsIterator);
14416
14470
  }
14417
14471
  const { data } = payload;
@@ -14424,6 +14478,12 @@ class AbstractRemote {
14424
14478
  requestMore();
14425
14479
  },
14426
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
+ }
14427
14487
  abortRequest(); // this will also emit a done event
14428
14488
  },
14429
14489
  onExtension: () => { }
@@ -14446,7 +14506,7 @@ class AbstractRemote {
14446
14506
  * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
14447
14507
  */
14448
14508
  async fetchStreamRaw(options) {
14449
- const { data, path, headers, abortSignal } = options;
14509
+ const { data, path, headers, abortSignal, connectTimeoutMs } = options;
14450
14510
  const request = await this.buildRequest(path);
14451
14511
  /**
14452
14512
  * This abort controller will abort pending fetch requests.
@@ -14481,7 +14541,7 @@ class AbstractRemote {
14481
14541
  try {
14482
14542
  const ndJson = 'application/x-ndjson';
14483
14543
  const bson = 'application/vnd.powersync.bson-stream';
14484
- res = await this.fetch(request.url, {
14544
+ const postStream = (signal) => this.fetch(request.url, {
14485
14545
  method: 'POST',
14486
14546
  headers: {
14487
14547
  ...headers,
@@ -14489,11 +14549,15 @@ class AbstractRemote {
14489
14549
  accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
14490
14550
  },
14491
14551
  body: JSON.stringify(data),
14492
- signal: controller.signal,
14552
+ signal,
14493
14553
  cache: 'no-store',
14494
14554
  ...(this.options.fetchOptions ?? {}),
14495
14555
  ...options.fetchOptions
14496
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));
14497
14561
  if (!res.ok || !res.body) {
14498
14562
  const text = await res.text();
14499
14563
  this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
@@ -14652,7 +14716,8 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
14652
14716
  fetchStrategy: FetchStrategy.Buffered,
14653
14717
  params: {},
14654
14718
  serializedSchema: undefined,
14655
- includeDefaultStreams: true
14719
+ includeDefaultStreams: true,
14720
+ connectTimeoutMs: 30_000
14656
14721
  };
14657
14722
  /**
14658
14723
  * @internal
@@ -14666,6 +14731,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
14666
14731
  activeStreams;
14667
14732
  connectionMayHaveChanged = false;
14668
14733
  crudUploadNotifier = asyncNotifier();
14734
+ connectTimeoutMs = DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
14669
14735
  notifyCompletedUploads;
14670
14736
  handleActiveStreamsChange;
14671
14737
  syncStatus;
@@ -14735,10 +14801,10 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
14735
14801
  this.crudUpdateListener?.();
14736
14802
  this.crudUpdateListener = undefined;
14737
14803
  }
14738
- async getWriteCheckpoint() {
14804
+ async getWriteCheckpoint(abort) {
14739
14805
  const clientId = await this.options.adapter.getClientId();
14740
14806
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
14741
- 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));
14742
14808
  const checkpoint = response['data']['write_checkpoint'];
14743
14809
  this.logger.debug(`Created write checkpoint: ${checkpoint}`);
14744
14810
  return checkpoint;
@@ -14756,6 +14822,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
14756
14822
  async _uploadAllCrud(signal) {
14757
14823
  return this.obtainLock({
14758
14824
  type: LockType.CRUD,
14825
+ signal,
14759
14826
  callback: async () => {
14760
14827
  /**
14761
14828
  * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
@@ -14790,7 +14857,7 @@ The next upload iteration will be delayed.`);
14790
14857
  }
14791
14858
  else {
14792
14859
  // Uploading is completed
14793
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
14860
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint(signal));
14794
14861
  if (neededUpdate) {
14795
14862
  this.notifyCompletedUploads?.();
14796
14863
  }
@@ -14833,6 +14900,7 @@ The next upload iteration will be delayed.`);
14833
14900
  }
14834
14901
  const controller = new AbortController();
14835
14902
  this.abortController = controller;
14903
+ this.connectTimeoutMs = options?.connectTimeoutMs ?? DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
14836
14904
  this.streamingSyncPromise = Promise.all([
14837
14905
  this.crudUploadLoop(controller.signal).catch((ex) => this.logger.error('Error in crud upload loop', ex)),
14838
14906
  this.streamingSync(controller.signal, options)
@@ -15162,7 +15230,8 @@ The next upload iteration will be delayed.`);
15162
15230
  const syncOptions = {
15163
15231
  path: '/sync/stream',
15164
15232
  abortSignal: signal,
15165
- data: startInstruction.EstablishSyncStream.request
15233
+ data: startInstruction.EstablishSyncStream.request,
15234
+ connectTimeoutMs: resolvedOptions.connectTimeoutMs
15166
15235
  };
15167
15236
  controlInvocations = injectable(syncImplementation.receiveSyncLines({
15168
15237
  options: syncOptions,
@@ -16380,7 +16449,7 @@ SELECT * FROM crud_entries;
16380
16449
  }
16381
16450
  /**
16382
16451
  * Open a read-only transaction.
16383
- * Read transactions can run concurrently to a write transaction.
16452
+ * When multiple connections are available, read transactions can run concurrently to a write transaction.
16384
16453
  * Changes from any write transaction are not visible to read transactions started before it.
16385
16454
  *
16386
16455
  * @param callback - Function to execute within the transaction