@powersync/common 0.0.0-dev-20250526133243 → 0.0.0-dev-20250529141956

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.
@@ -5,6 +5,7 @@ import { SyncStatus } from '../db/crud/SyncStatus.js';
5
5
  import { UploadQueueStats } from '../db/crud/UploadQueueStatus.js';
6
6
  import { Schema } from '../db/schema/Schema.js';
7
7
  import { BaseObserver } from '../utils/BaseObserver.js';
8
+ import { ConnectionManager } from './ConnectionManager.js';
8
9
  import { SQLOpenFactory, SQLOpenOptions } from './SQLOpenFactory.js';
9
10
  import { PowerSyncBackendConnector } from './connection/PowerSyncBackendConnector.js';
10
11
  import { BucketStorageAdapter } from './sync/bucket/BucketStorageAdapter.js';
@@ -79,10 +80,6 @@ export interface PowerSyncCloseOptions {
79
80
  */
80
81
  disconnect?: boolean;
81
82
  }
82
- type StoredConnectionOptions = {
83
- connector: PowerSyncBackendConnector;
84
- options: PowerSyncConnectionOptions;
85
- };
86
83
  export declare const DEFAULT_POWERSYNC_CLOSE_OPTIONS: PowerSyncCloseOptions;
87
84
  export declare const DEFAULT_WATCH_THROTTLE_MS = 30;
88
85
  export declare const DEFAULT_POWERSYNC_DB_OPTIONS: {
@@ -118,36 +115,14 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
118
115
  * Current connection status.
119
116
  */
120
117
  currentStatus: SyncStatus;
121
- syncStreamImplementation?: StreamingSyncImplementation;
122
118
  sdkVersion: string;
123
119
  protected bucketStorageAdapter: BucketStorageAdapter;
124
- private syncStatusListenerDisposer?;
125
120
  protected _isReadyPromise: Promise<void>;
121
+ protected connectionManager: ConnectionManager;
122
+ get syncStreamImplementation(): StreamingSyncImplementation | null;
126
123
  protected _schema: Schema;
127
124
  private _database;
128
- /**
129
- * Tracks active connection attempts
130
- */
131
- protected connectingPromise: Promise<void> | null;
132
- /**
133
- * Tracks actively instantiating a streaming sync implementation.
134
- */
135
- protected syncStreamInitPromise: Promise<void> | null;
136
- /**
137
- * Active disconnect operation. Calling disconnect multiple times
138
- * will resolve to the same operation.
139
- */
140
- protected disconnectingPromise: Promise<void> | null;
141
- /**
142
- * Tracks the last parameters supplied to `connect` calls.
143
- * Calling `connect` multiple times in succession will result in:
144
- * - 1 pending connection operation which will be aborted.
145
- * - updating the last set of parameters while waiting for the pending
146
- * attempt to be aborted
147
- * - internally connecting with the last set of parameters
148
- */
149
- protected pendingConnectionOptions: StoredConnectionOptions | null;
150
- protected connectionMutex: Mutex;
125
+ protected runExclusiveMutex: Mutex;
151
126
  constructor(options: PowerSyncDatabaseOptionsWithDBAdapter);
152
127
  constructor(options: PowerSyncDatabaseOptionsWithOpenFactory);
153
128
  constructor(options: PowerSyncDatabaseOptionsWithSettings);
@@ -222,7 +197,6 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
222
197
  * Locking here is mostly only important on web for multiple tab scenarios.
223
198
  */
224
199
  protected runExclusive<T>(callback: () => Promise<T>): Promise<T>;
225
- protected connectInternal(): Promise<void>;
226
200
  /**
227
201
  * Connects to stream of events from the PowerSync instance.
228
202
  */
@@ -233,8 +207,6 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
233
207
  * Use {@link connect} to connect again.
234
208
  */
235
209
  disconnect(): Promise<void>;
236
- protected disconnectInternal(): Promise<void>;
237
- protected performDisconnect(): Promise<void>;
238
210
  /**
239
211
  * Disconnect and clear the database.
240
212
  * Use this when logging out.
@@ -519,4 +491,3 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
519
491
  */
520
492
  private executeReadOnly;
521
493
  }
522
- export {};
@@ -9,6 +9,7 @@ import { BaseObserver } from '../utils/BaseObserver.js';
9
9
  import { ControlledExecutor } from '../utils/ControlledExecutor.js';
10
10
  import { throttleTrailing } from '../utils/async.js';
11
11
  import { mutexRunExclusive } from '../utils/mutex.js';
12
+ import { ConnectionManager } from './ConnectionManager.js';
12
13
  import { isDBAdapter, isSQLOpenFactory, isSQLOpenOptions } from './SQLOpenFactory.js';
13
14
  import { runOnSchemaChange } from './runOnSchemaChange.js';
14
15
  import { PSInternalTable } from './sync/bucket/BucketStorageAdapter.js';
@@ -59,36 +60,16 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
59
60
  * Current connection status.
60
61
  */
61
62
  currentStatus;
62
- syncStreamImplementation;
63
63
  sdkVersion;
64
64
  bucketStorageAdapter;
65
- syncStatusListenerDisposer;
66
65
  _isReadyPromise;
66
+ connectionManager;
67
+ get syncStreamImplementation() {
68
+ return this.connectionManager.syncStreamImplementation;
69
+ }
67
70
  _schema;
68
71
  _database;
69
- /**
70
- * Tracks active connection attempts
71
- */
72
- connectingPromise;
73
- /**
74
- * Tracks actively instantiating a streaming sync implementation.
75
- */
76
- syncStreamInitPromise;
77
- /**
78
- * Active disconnect operation. Calling disconnect multiple times
79
- * will resolve to the same operation.
80
- */
81
- disconnectingPromise;
82
- /**
83
- * Tracks the last parameters supplied to `connect` calls.
84
- * Calling `connect` multiple times in succession will result in:
85
- * - 1 pending connection operation which will be aborted.
86
- * - updating the last set of parameters while waiting for the pending
87
- * attempt to be aborted
88
- * - internally connecting with the last set of parameters
89
- */
90
- pendingConnectionOptions;
91
- connectionMutex;
72
+ runExclusiveMutex;
92
73
  constructor(options) {
93
74
  super();
94
75
  this.options = options;
@@ -115,11 +96,31 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
115
96
  this._schema = schema;
116
97
  this.ready = false;
117
98
  this.sdkVersion = '';
118
- this.connectingPromise = null;
119
- this.syncStreamInitPromise = null;
120
- this.pendingConnectionOptions = null;
121
- this.connectionMutex = new Mutex();
99
+ this.runExclusiveMutex = new Mutex();
122
100
  // Start async init
101
+ this.connectionManager = new ConnectionManager({
102
+ createSyncImplementation: async (connector, options) => {
103
+ await this.waitForReady();
104
+ return this.runExclusive(async () => {
105
+ const sync = this.generateSyncStreamImplementation(connector, this.resolvedConnectionOptions(options));
106
+ const onDispose = sync.registerListener({
107
+ statusChanged: (status) => {
108
+ this.currentStatus = new SyncStatus({
109
+ ...status.toJSON(),
110
+ hasSynced: this.currentStatus?.hasSynced || !!status.lastSyncedAt
111
+ });
112
+ this.iterateListeners((cb) => cb.statusChanged?.(this.currentStatus));
113
+ }
114
+ });
115
+ await sync.waitForReady();
116
+ return {
117
+ sync,
118
+ onDispose
119
+ };
120
+ });
121
+ },
122
+ logger: this.logger
123
+ });
123
124
  this._isReadyPromise = this.initialize();
124
125
  }
125
126
  /**
@@ -297,95 +298,13 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
297
298
  * Locking here is mostly only important on web for multiple tab scenarios.
298
299
  */
299
300
  runExclusive(callback) {
300
- return this.connectionMutex.runExclusive(callback);
301
- }
302
- async connectInternal() {
303
- let appliedOptions = null;
304
- // This method ensures a disconnect before any connection attempt
305
- await this.disconnectInternal();
306
- /**
307
- * This portion creates a sync implementation which can be racy when disconnecting or
308
- * if multiple tabs on web are in use.
309
- * This is protected in an exclusive lock.
310
- * The promise tracks the creation which is used to synchronize disconnect attempts.
311
- */
312
- this.syncStreamInitPromise = this.runExclusive(async () => {
313
- if (this.closed) {
314
- throw new Error('Cannot connect using a closed client');
315
- }
316
- // Always await this if present since we will be populating a new sync implementation shortly
317
- await this.disconnectingPromise;
318
- if (!this.pendingConnectionOptions) {
319
- // A disconnect could have cleared this.
320
- return;
321
- }
322
- // get pending options and clear it in order for other connect attempts to queue other options
323
- const { connector, options } = this.pendingConnectionOptions;
324
- appliedOptions = options;
325
- this.pendingConnectionOptions = null;
326
- this.syncStreamImplementation = this.generateSyncStreamImplementation(connector, this.resolvedConnectionOptions(options));
327
- this.syncStatusListenerDisposer = this.syncStreamImplementation.registerListener({
328
- statusChanged: (status) => {
329
- this.currentStatus = new SyncStatus({
330
- ...status.toJSON(),
331
- hasSynced: this.currentStatus?.hasSynced || !!status.lastSyncedAt
332
- });
333
- this.iterateListeners((cb) => cb.statusChanged?.(this.currentStatus));
334
- }
335
- });
336
- await this.syncStreamImplementation.waitForReady();
337
- });
338
- await this.syncStreamInitPromise;
339
- this.syncStreamInitPromise = null;
340
- if (!appliedOptions) {
341
- // A disconnect could have cleared the options which did not create a syncStreamImplementation
342
- return;
343
- }
344
- // It might be possible that a disconnect triggered between the last check
345
- // and this point. Awaiting here allows the sync stream to be cleared if disconnected.
346
- await this.disconnectingPromise;
347
- this.syncStreamImplementation?.triggerCrudUpload();
348
- this.options.logger?.debug('Attempting to connect to PowerSync instance');
349
- await this.syncStreamImplementation?.connect(appliedOptions);
301
+ return this.runExclusiveMutex.runExclusive(callback);
350
302
  }
351
303
  /**
352
304
  * Connects to stream of events from the PowerSync instance.
353
305
  */
354
306
  async connect(connector, options) {
355
- // Keep track if there were pending operations before this call
356
- const hadPendingOptions = !!this.pendingConnectionOptions;
357
- // Update pending options to the latest values
358
- this.pendingConnectionOptions = {
359
- connector,
360
- options: options ?? {}
361
- };
362
- await this.waitForReady();
363
- // Disconnecting here provides aborting in progress connection attempts.
364
- // The connectInternal method will clear pending options once it starts connecting (with the options).
365
- // We only need to trigger a disconnect here if we have already reached the point of connecting.
366
- // If we do already have pending options, a disconnect has already been performed.
367
- // The connectInternal method also does a sanity disconnect to prevent straggler connections.
368
- if (!hadPendingOptions) {
369
- await this.disconnectInternal();
370
- }
371
- // Triggers a connect which checks if pending options are available after the connect completes.
372
- // The completion can be for a successful, unsuccessful or aborted connection attempt.
373
- // If pending options are available another connection will be triggered.
374
- const checkConnection = async () => {
375
- if (this.pendingConnectionOptions) {
376
- // Pending options have been placed while connecting.
377
- // Need to reconnect.
378
- this.connectingPromise = this.connectInternal().finally(checkConnection);
379
- return this.connectingPromise;
380
- }
381
- else {
382
- // Clear the connecting promise, done.
383
- this.connectingPromise = null;
384
- return;
385
- }
386
- };
387
- this.connectingPromise ??= this.connectInternal().finally(checkConnection);
388
- return this.connectingPromise;
307
+ return this.connectionManager.connect(connector, options);
389
308
  }
390
309
  /**
391
310
  * Close the sync connection.
@@ -393,28 +312,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
393
312
  * Use {@link connect} to connect again.
394
313
  */
395
314
  async disconnect() {
396
- await this.waitForReady();
397
- // This will help abort pending connects
398
- this.pendingConnectionOptions = null;
399
- await this.disconnectInternal();
400
- }
401
- async disconnectInternal() {
402
- if (this.disconnectingPromise) {
403
- // A disconnect is already in progress
404
- return this.disconnectingPromise;
405
- }
406
- // Wait if a sync stream implementation is being created before closing it
407
- // (syncStreamImplementation must be assigned before we can properly dispose it)
408
- await this.syncStreamInitPromise;
409
- this.disconnectingPromise = this.performDisconnect();
410
- await this.disconnectingPromise;
411
- this.disconnectingPromise = null;
412
- }
413
- async performDisconnect() {
414
- await this.syncStreamImplementation?.disconnect();
415
- this.syncStatusListenerDisposer?.();
416
- await this.syncStreamImplementation?.dispose();
417
- this.syncStreamImplementation = undefined;
315
+ return this.connectionManager.disconnect();
418
316
  }
419
317
  /**
420
318
  * Disconnect and clear the database.
@@ -453,7 +351,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
453
351
  if (disconnect) {
454
352
  await this.disconnect();
455
353
  }
456
- await this.syncStreamImplementation?.dispose();
354
+ await this.connectionManager.close();
457
355
  await this.database.close();
458
356
  this.closed = true;
459
357
  }
@@ -0,0 +1,80 @@
1
+ import { ILogger } from 'js-logger';
2
+ import { BaseListener, BaseObserver } from '../utils/BaseObserver.js';
3
+ import { PowerSyncBackendConnector } from './connection/PowerSyncBackendConnector.js';
4
+ import { PowerSyncConnectionOptions, StreamingSyncImplementation } from './sync/stream/AbstractStreamingSyncImplementation.js';
5
+ /**
6
+ * @internal
7
+ */
8
+ export interface ConnectionManagerSyncImplementationResult {
9
+ sync: StreamingSyncImplementation;
10
+ /**
11
+ * Additional cleanup function which is called after the sync stream implementation
12
+ * is disposed.
13
+ */
14
+ onDispose: () => Promise<void> | void;
15
+ }
16
+ /**
17
+ * @internal
18
+ */
19
+ export interface ConnectionManagerOptions {
20
+ createSyncImplementation(connector: PowerSyncBackendConnector, options: PowerSyncConnectionOptions): Promise<ConnectionManagerSyncImplementationResult>;
21
+ logger: ILogger;
22
+ }
23
+ type StoredConnectionOptions = {
24
+ connector: PowerSyncBackendConnector;
25
+ options: PowerSyncConnectionOptions;
26
+ };
27
+ /**
28
+ * @internal
29
+ */
30
+ export interface ConnectionManagerListener extends BaseListener {
31
+ syncStreamCreated: (sync: StreamingSyncImplementation) => void;
32
+ }
33
+ /**
34
+ * @internal
35
+ */
36
+ export declare class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
37
+ protected options: ConnectionManagerOptions;
38
+ /**
39
+ * Tracks active connection attempts
40
+ */
41
+ protected connectingPromise: Promise<void> | null;
42
+ /**
43
+ * Tracks actively instantiating a streaming sync implementation.
44
+ */
45
+ protected syncStreamInitPromise: Promise<void> | null;
46
+ /**
47
+ * Active disconnect operation. Calling disconnect multiple times
48
+ * will resolve to the same operation.
49
+ */
50
+ protected disconnectingPromise: Promise<void> | null;
51
+ /**
52
+ * Tracks the last parameters supplied to `connect` calls.
53
+ * Calling `connect` multiple times in succession will result in:
54
+ * - 1 pending connection operation which will be aborted.
55
+ * - updating the last set of parameters while waiting for the pending
56
+ * attempt to be aborted
57
+ * - internally connecting with the last set of parameters
58
+ */
59
+ protected pendingConnectionOptions: StoredConnectionOptions | null;
60
+ syncStreamImplementation: StreamingSyncImplementation | null;
61
+ /**
62
+ * Additional cleanup function which is called after the sync stream implementation
63
+ * is disposed.
64
+ */
65
+ protected syncDisposer: (() => Promise<void> | void) | null;
66
+ constructor(options: ConnectionManagerOptions);
67
+ get logger(): ILogger;
68
+ close(): Promise<void>;
69
+ connect(connector: PowerSyncBackendConnector, options?: PowerSyncConnectionOptions): Promise<void>;
70
+ protected connectInternal(): Promise<void>;
71
+ /**
72
+ * Close the sync connection.
73
+ *
74
+ * Use {@link connect} to connect again.
75
+ */
76
+ disconnect(): Promise<void>;
77
+ protected disconnectInternal(): Promise<void>;
78
+ protected performDisconnect(): Promise<void>;
79
+ }
80
+ export {};
@@ -0,0 +1,169 @@
1
+ import { BaseObserver } from '../utils/BaseObserver.js';
2
+ /**
3
+ * @internal
4
+ */
5
+ export class ConnectionManager extends BaseObserver {
6
+ options;
7
+ /**
8
+ * Tracks active connection attempts
9
+ */
10
+ connectingPromise;
11
+ /**
12
+ * Tracks actively instantiating a streaming sync implementation.
13
+ */
14
+ syncStreamInitPromise;
15
+ /**
16
+ * Active disconnect operation. Calling disconnect multiple times
17
+ * will resolve to the same operation.
18
+ */
19
+ disconnectingPromise;
20
+ /**
21
+ * Tracks the last parameters supplied to `connect` calls.
22
+ * Calling `connect` multiple times in succession will result in:
23
+ * - 1 pending connection operation which will be aborted.
24
+ * - updating the last set of parameters while waiting for the pending
25
+ * attempt to be aborted
26
+ * - internally connecting with the last set of parameters
27
+ */
28
+ pendingConnectionOptions;
29
+ syncStreamImplementation;
30
+ /**
31
+ * Additional cleanup function which is called after the sync stream implementation
32
+ * is disposed.
33
+ */
34
+ syncDisposer;
35
+ constructor(options) {
36
+ super();
37
+ this.options = options;
38
+ this.connectingPromise = null;
39
+ this.syncStreamInitPromise = null;
40
+ this.disconnectingPromise = null;
41
+ this.pendingConnectionOptions = null;
42
+ this.syncStreamImplementation = null;
43
+ this.syncDisposer = null;
44
+ }
45
+ get logger() {
46
+ return this.options.logger;
47
+ }
48
+ async close() {
49
+ await this.syncStreamImplementation?.dispose();
50
+ await this.syncDisposer?.();
51
+ }
52
+ async connect(connector, options) {
53
+ // Keep track if there were pending operations before this call
54
+ const hadPendingOptions = !!this.pendingConnectionOptions;
55
+ // Update pending options to the latest values
56
+ this.pendingConnectionOptions = {
57
+ connector,
58
+ options: options ?? {}
59
+ };
60
+ // Disconnecting here provides aborting in progress connection attempts.
61
+ // The connectInternal method will clear pending options once it starts connecting (with the options).
62
+ // We only need to trigger a disconnect here if we have already reached the point of connecting.
63
+ // If we do already have pending options, a disconnect has already been performed.
64
+ // The connectInternal method also does a sanity disconnect to prevent straggler connections.
65
+ // We should also disconnect if we have already completed a connection attempt.
66
+ if (!hadPendingOptions || this.syncStreamImplementation) {
67
+ await this.disconnectInternal();
68
+ }
69
+ // Triggers a connect which checks if pending options are available after the connect completes.
70
+ // The completion can be for a successful, unsuccessful or aborted connection attempt.
71
+ // If pending options are available another connection will be triggered.
72
+ const checkConnection = async () => {
73
+ if (this.pendingConnectionOptions) {
74
+ // Pending options have been placed while connecting.
75
+ // Need to reconnect.
76
+ this.connectingPromise = this.connectInternal().finally(checkConnection);
77
+ return this.connectingPromise;
78
+ }
79
+ else {
80
+ // Clear the connecting promise, done.
81
+ this.connectingPromise = null;
82
+ return;
83
+ }
84
+ };
85
+ this.connectingPromise ??= this.connectInternal().finally(checkConnection);
86
+ return this.connectingPromise;
87
+ }
88
+ async connectInternal() {
89
+ let appliedOptions = null;
90
+ // This method ensures a disconnect before any connection attempt
91
+ await this.disconnectInternal();
92
+ /**
93
+ * This portion creates a sync implementation which can be racy when disconnecting or
94
+ * if multiple tabs on web are in use.
95
+ * This is protected in an exclusive lock.
96
+ * The promise tracks the creation which is used to synchronize disconnect attempts.
97
+ */
98
+ this.syncStreamInitPromise = new Promise(async (resolve, reject) => {
99
+ try {
100
+ if (!this.pendingConnectionOptions) {
101
+ this.logger.debug('No pending connection options found, not creating sync stream implementation');
102
+ // A disconnect could have cleared this.
103
+ return;
104
+ }
105
+ if (this.disconnectingPromise) {
106
+ return;
107
+ }
108
+ const { connector, options } = this.pendingConnectionOptions;
109
+ appliedOptions = options;
110
+ this.pendingConnectionOptions = null;
111
+ const { sync, onDispose } = await this.options.createSyncImplementation(connector, options);
112
+ this.iterateListeners((l) => l.syncStreamCreated?.(sync));
113
+ this.syncStreamImplementation = sync;
114
+ this.syncDisposer = onDispose;
115
+ await this.syncStreamImplementation.waitForReady();
116
+ resolve();
117
+ }
118
+ catch (error) {
119
+ reject(error);
120
+ }
121
+ });
122
+ await this.syncStreamInitPromise;
123
+ this.syncStreamInitPromise = null;
124
+ if (!appliedOptions) {
125
+ // A disconnect could have cleared the options which did not create a syncStreamImplementation
126
+ return;
127
+ }
128
+ // It might be possible that a disconnect triggered between the last check
129
+ // and this point. Awaiting here allows the sync stream to be cleared if disconnected.
130
+ await this.disconnectingPromise;
131
+ this.logger.debug('Attempting to connect to PowerSync instance');
132
+ await this.syncStreamImplementation?.connect(appliedOptions);
133
+ this.syncStreamImplementation?.triggerCrudUpload();
134
+ }
135
+ /**
136
+ * Close the sync connection.
137
+ *
138
+ * Use {@link connect} to connect again.
139
+ */
140
+ async disconnect() {
141
+ // This will help abort pending connects
142
+ this.pendingConnectionOptions = null;
143
+ await this.disconnectInternal();
144
+ }
145
+ async disconnectInternal() {
146
+ if (this.disconnectingPromise) {
147
+ // A disconnect is already in progress
148
+ return this.disconnectingPromise;
149
+ }
150
+ this.disconnectingPromise = this.performDisconnect();
151
+ await this.disconnectingPromise;
152
+ this.disconnectingPromise = null;
153
+ }
154
+ async performDisconnect() {
155
+ // Wait if a sync stream implementation is being created before closing it
156
+ // (syncStreamImplementation must be assigned before we can properly dispose it)
157
+ await this.syncStreamInitPromise;
158
+ // Keep reference to the sync stream implementation and disposer
159
+ // The class members will be cleared before we trigger the disconnect
160
+ // to prevent any further calls to the sync stream implementation.
161
+ const sync = this.syncStreamImplementation;
162
+ this.syncStreamImplementation = null;
163
+ const disposer = this.syncDisposer;
164
+ this.syncDisposer = null;
165
+ await sync?.disconnect();
166
+ await sync?.dispose();
167
+ await disposer?.();
168
+ }
169
+ }
@@ -2,10 +2,10 @@ import { Buffer } from 'buffer';
2
2
  import ndjsonStream from 'can-ndjson-stream';
3
3
  import Logger from 'js-logger';
4
4
  import { RSocketConnector } from 'rsocket-core';
5
- import { WebsocketClientTransport } from 'rsocket-websocket-client';
6
5
  import PACKAGE from '../../../../package.json' with { type: 'json' };
7
6
  import { AbortOperation } from '../../../utils/AbortOperation.js';
8
7
  import { DataStream } from '../../../utils/DataStream.js';
8
+ import { WebsocketClientTransport } from './WebsocketClientTransport.js';
9
9
  const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
10
10
  const POWERSYNC_JS_VERSION = PACKAGE.version;
11
11
  const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
@@ -298,12 +298,16 @@ The next upload iteration will be delayed.`);
298
298
  * Either:
299
299
  * - A network request failed with a failed connection or not OKAY response code.
300
300
  * - There was a sync processing error.
301
- * This loop will retry.
301
+ * - The connection was aborted.
302
+ * This loop will retry after a delay if the connection was not aborted.
302
303
  * The nested abort controller will cleanup any open network requests and streams.
303
304
  * The WebRemote should only abort pending fetch requests or close active Readable streams.
304
305
  */
306
+ let delay = true;
305
307
  if (ex instanceof AbortOperation) {
306
308
  this.logger.warn(ex);
309
+ delay = false;
310
+ // A disconnect was requested, we should not delay since there is no explicit retry
307
311
  }
308
312
  else {
309
313
  this.logger.error(ex);
@@ -314,7 +318,9 @@ The next upload iteration will be delayed.`);
314
318
  }
315
319
  });
316
320
  // On error, wait a little before retrying
317
- await this.delayRetry();
321
+ if (delay) {
322
+ await this.delayRetry();
323
+ }
318
324
  }
319
325
  finally {
320
326
  if (!signal.aborted) {
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Adapted from rsocket-websocket-client
3
+ * https://github.com/rsocket/rsocket-js/blob/e224cf379e747c4f1ddc4f2fa111854626cc8575/packages/rsocket-websocket-client/src/WebsocketClientTransport.ts#L17
4
+ * This adds additional error handling for React Native iOS.
5
+ * This particularly adds a close listener to handle cases where the WebSocket
6
+ * connection closes immediately after opening without emitting an error.
7
+ */
8
+ import { ClientTransport, Closeable, Demultiplexer, DuplexConnection, FrameHandler, Multiplexer, Outbound } from 'rsocket-core';
9
+ import { ClientOptions } from 'rsocket-websocket-client';
10
+ export declare class WebsocketClientTransport implements ClientTransport {
11
+ private readonly url;
12
+ private readonly factory;
13
+ constructor(options: ClientOptions);
14
+ connect(multiplexerDemultiplexerFactory: (outbound: Outbound & Closeable) => Multiplexer & Demultiplexer & FrameHandler): Promise<DuplexConnection>;
15
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Adapted from rsocket-websocket-client
3
+ * https://github.com/rsocket/rsocket-js/blob/e224cf379e747c4f1ddc4f2fa111854626cc8575/packages/rsocket-websocket-client/src/WebsocketClientTransport.ts#L17
4
+ * This adds additional error handling for React Native iOS.
5
+ * This particularly adds a close listener to handle cases where the WebSocket
6
+ * connection closes immediately after opening without emitting an error.
7
+ */
8
+ import { Deserializer } from 'rsocket-core';
9
+ import { WebsocketDuplexConnection } from 'rsocket-websocket-client/dist/WebsocketDuplexConnection.js';
10
+ export class WebsocketClientTransport {
11
+ url;
12
+ factory;
13
+ constructor(options) {
14
+ this.url = options.url;
15
+ this.factory = options.wsCreator ?? ((url) => new WebSocket(url));
16
+ }
17
+ connect(multiplexerDemultiplexerFactory) {
18
+ return new Promise((resolve, reject) => {
19
+ const websocket = this.factory(this.url);
20
+ websocket.binaryType = 'arraybuffer';
21
+ let removeListeners;
22
+ const openListener = () => {
23
+ removeListeners();
24
+ resolve(new WebsocketDuplexConnection(websocket, new Deserializer(), multiplexerDemultiplexerFactory));
25
+ };
26
+ const errorListener = (ev) => {
27
+ removeListeners();
28
+ reject(ev.error);
29
+ };
30
+ /**
31
+ * In some cases, such as React Native iOS, the WebSocket connection may close immediately after opening
32
+ * without and error. In such cases, we need to handle the close event to reject the promise.
33
+ */
34
+ const closeListener = () => {
35
+ removeListeners();
36
+ reject(new Error('WebSocket connection closed while opening'));
37
+ };
38
+ removeListeners = () => {
39
+ websocket.removeEventListener('open', openListener);
40
+ websocket.removeEventListener('error', errorListener);
41
+ websocket.removeEventListener('close', closeListener);
42
+ };
43
+ websocket.addEventListener('open', openListener);
44
+ websocket.addEventListener('error', errorListener);
45
+ websocket.addEventListener('close', closeListener);
46
+ });
47
+ }
48
+ }