@powersync/shared-internals 1.4.0 → 1.6.0

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 (85) hide show
  1. package/dist/websockets.mjs +29 -1
  2. package/dist/websockets.mjs.map +1 -1
  3. package/dist/websockets.node.mjs +29 -1
  4. package/dist/websockets.node.mjs.map +1 -1
  5. package/legacy/sync_protocol.d.ts +1 -103
  6. package/lib/client/BasePowerSyncDatabase.d.ts +12 -6
  7. package/lib/client/BasePowerSyncDatabase.js +13 -19
  8. package/lib/client/BasePowerSyncDatabase.js.map +1 -1
  9. package/lib/client/ConnectionManager.d.ts +6 -5
  10. package/lib/client/ConnectionManager.js +22 -14
  11. package/lib/client/ConnectionManager.js.map +1 -1
  12. package/lib/client/InternalConnector.d.ts +9 -0
  13. package/lib/client/InternalConnector.js +42 -0
  14. package/lib/client/InternalConnector.js.map +1 -0
  15. package/lib/client/sync/options.d.ts +4 -0
  16. package/lib/client/sync/options.js +5 -0
  17. package/lib/client/sync/options.js.map +1 -1
  18. package/lib/client/sync/stream/AbstractRemote.d.ts +7 -9
  19. package/lib/client/sync/stream/AbstractRemote.js +13 -5
  20. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  21. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +6 -13
  22. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +135 -82
  23. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  24. package/lib/client/sync/stream/WebSocketSupport.js +29 -1
  25. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -1
  26. package/lib/client/sync/stream/core-instruction.d.ts +2 -0
  27. package/lib/client/sync/stream/core-instruction.js.map +1 -1
  28. package/lib/client/watched/AbstractQueryProcessor.d.ts +5 -0
  29. package/lib/client/watched/AbstractQueryProcessor.js +18 -0
  30. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -1
  31. package/lib/client/watched/DifferentialQueryProcessor.js +5 -0
  32. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -1
  33. package/lib/index.d.ts +1 -0
  34. package/lib/index.js +1 -0
  35. package/lib/index.js.map +1 -1
  36. package/lib/standalone/api.d.ts +63 -0
  37. package/lib/standalone/api.js +17 -0
  38. package/lib/standalone/api.js.map +1 -0
  39. package/lib/standalone/client.d.ts +43 -0
  40. package/lib/standalone/client.js +172 -0
  41. package/lib/standalone/client.js.map +1 -0
  42. package/lib/standalone/client_state.d.ts +30 -0
  43. package/lib/standalone/client_state.js +224 -0
  44. package/lib/standalone/client_state.js.map +1 -0
  45. package/lib/standalone/oplog.d.ts +87 -0
  46. package/lib/standalone/oplog.js +225 -0
  47. package/lib/standalone/oplog.js.map +1 -0
  48. package/lib/standalone/requests.d.ts +22 -0
  49. package/lib/standalone/requests.js +2 -0
  50. package/lib/standalone/requests.js.map +1 -0
  51. package/lib/standalone/sync_protocol.d.ts +91 -0
  52. package/lib/standalone/sync_protocol.js +10 -0
  53. package/lib/standalone/sync_protocol.js.map +1 -0
  54. package/lib/standalone.d.ts +6 -0
  55. package/lib/standalone.js +4 -0
  56. package/lib/standalone.js.map +1 -0
  57. package/lib/utils/async.d.ts +6 -0
  58. package/lib/utils/async.js +31 -0
  59. package/lib/utils/async.js.map +1 -1
  60. package/lib/utils/stream_transform.js +2 -0
  61. package/lib/utils/stream_transform.js.map +1 -1
  62. package/lib/version.d.ts +1 -1
  63. package/lib/version.js +1 -1
  64. package/package.json +12 -3
  65. package/src/client/BasePowerSyncDatabase.ts +26 -26
  66. package/src/client/ConnectionManager.ts +25 -19
  67. package/src/client/InternalConnector.ts +68 -0
  68. package/src/client/sync/options.ts +6 -0
  69. package/src/client/sync/stream/AbstractRemote.ts +33 -25
  70. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +163 -105
  71. package/src/client/sync/stream/WebSocketSupport.ts +32 -1
  72. package/src/client/sync/stream/core-instruction.ts +1 -0
  73. package/src/client/watched/AbstractQueryProcessor.ts +19 -0
  74. package/src/client/watched/DifferentialQueryProcessor.ts +5 -0
  75. package/src/index.ts +1 -0
  76. package/src/standalone/api.ts +75 -0
  77. package/src/standalone/client.ts +216 -0
  78. package/src/standalone/client_state.ts +263 -0
  79. package/src/standalone/oplog.ts +243 -0
  80. package/src/standalone/requests.ts +25 -0
  81. package/src/standalone/sync_protocol.ts +119 -0
  82. package/src/standalone.ts +6 -0
  83. package/src/utils/async.ts +36 -0
  84. package/src/utils/stream_transform.ts +2 -0
  85. package/src/version.ts +1 -1
@@ -9,16 +9,9 @@ import {
9
9
  SimpleAsyncIterator
10
10
  } from '../../../utils/stream_transform.js';
11
11
  import { WebSocketSupport, WebSocketSyncStreamPlatform } from './WebSocketSupport.js';
12
- import { EventQueue } from '../../../utils/async.js';
12
+ import { EventQueue, runWithTimeout } from '../../../utils/async.js';
13
13
  import { POWERSYNC_JS_VERSION } from '../../../version.js';
14
-
15
- /**
16
- * @internal
17
- */
18
- export type RemoteConnector = {
19
- fetchCredentials: (signal?: AbortSignal) => Promise<PowerSyncCredentials | null>;
20
- invalidateCredentials?: () => void;
21
- };
14
+ import { InternalConnector } from '../../InternalConnector.js';
22
15
 
23
16
  const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
24
17
 
@@ -35,6 +28,10 @@ export type SyncStreamOptions = {
35
28
  path: string;
36
29
  data: unknown;
37
30
  abortSignal: AbortSignal;
31
+ /**
32
+ * How long to wait for the response to start. Without it, only {@link abortSignal} ends a pending request.
33
+ */
34
+ connectTimeoutMs?: number;
38
35
  };
39
36
 
40
37
  /**
@@ -81,7 +78,7 @@ export abstract class AbstractRemote {
81
78
  protected credentials: PowerSyncCredentials | null = null;
82
79
 
83
80
  constructor(
84
- protected connector: RemoteConnector,
81
+ protected connector: InternalConnector,
85
82
  readonly logger: PowerSyncLogger
86
83
  ) {}
87
84
 
@@ -125,7 +122,12 @@ export abstract class AbstractRemote {
125
122
  * values.
126
123
  */
127
124
  async fetchCredentials(signal?: AbortSignal) {
128
- const credentials = await this.connector.fetchCredentials(signal);
125
+ const fetchCredentials = this.connector.fetchCredentials;
126
+ if (!fetchCredentials) {
127
+ throw new Error('No connector configured for downloads');
128
+ }
129
+
130
+ const credentials = await fetchCredentials(signal);
129
131
  if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {
130
132
  throw new Error(
131
133
  `A trailing forward slash "/" was found in the fetchCredentials endpoint: "${credentials.endpoint}". Remove the trailing forward slash "/" to fix this error.`
@@ -264,7 +266,7 @@ export abstract class AbstractRemote {
264
266
  protected async fetchStreamRaw(
265
267
  options: SyncStreamOptions
266
268
  ): Promise<{ isBson: boolean; stream: SimpleAsyncIterator<Uint8Array> }> {
267
- const { data, path, abortSignal } = options;
269
+ const { data, path, abortSignal, connectTimeoutMs } = options;
268
270
  const request = await this.buildRequest(path, abortSignal);
269
271
 
270
272
  /**
@@ -304,20 +306,26 @@ export abstract class AbstractRemote {
304
306
  const ndJson = 'application/x-ndjson';
305
307
  const bson = 'application/vnd.powersync.bson-stream';
306
308
 
307
- res = await this.fetch({
308
- resource: request.url,
309
- request: {
310
- method: 'POST',
311
- headers: {
312
- ...request.headers,
313
- accept: `${bson};q=0.9,${ndJson};q=0.8`
309
+ const postStream = (signal: AbortSignal) =>
310
+ this.fetch({
311
+ resource: request.url,
312
+ request: {
313
+ method: 'POST',
314
+ headers: {
315
+ ...request.headers,
316
+ accept: `${bson};q=0.9,${ndJson};q=0.8`
317
+ },
318
+ body: JSON.stringify(data),
319
+ signal,
320
+ cache: 'no-store'
314
321
  },
315
- body: JSON.stringify(data),
316
- signal: controller.signal,
317
- cache: 'no-store'
318
- },
319
- expectStreamingResponse: true
320
- });
322
+ expectStreamingResponse: true
323
+ });
324
+
325
+ // The timeout ends once the response starts, so it never aborts the response body.
326
+ res = await (connectTimeoutMs == null
327
+ ? postStream(controller.signal)
328
+ : runWithTimeout(controller.signal, connectTimeoutMs, 'Sync stream connection', postStream));
321
329
 
322
330
  if (!res.ok || !res.body) {
323
331
  const text = await res.text();
@@ -28,10 +28,11 @@ import {
28
28
  SimpleAsyncIterator,
29
29
  valueResult
30
30
  } from '../../../utils/stream_transform.js';
31
- import { asyncNotifier } from '../../../utils/async.js';
31
+ import { asyncNotifier, runWithTimeout } from '../../../utils/async.js';
32
32
  import { JavaScriptSyncState, SyncStatusSnapshot } from '../../../db/crud/SyncStatus.js';
33
- import { ResolvedSyncOptions } from '../options.js';
33
+ import { DEFAULT_CONNECT_TIMEOUT_MS, ResolvedSyncOptions } from '../options.js';
34
34
  import { CheckpointStateSignals, isCheckpointRequestApplied } from './CheckpointState.js';
35
+ import { InternalConnector } from '../../InternalConnector.js';
35
36
 
36
37
  /**
37
38
  * @internal
@@ -58,18 +59,7 @@ export interface LockOptions<T> {
58
59
  export interface AbstractStreamingSyncImplementationOptions {
59
60
  adapter: BucketStorageAdapter;
60
61
  subscriptions: SubscribedStream[];
61
- /**
62
- * Uploads pending CRUD data.
63
- * Cross-context implementations must stop waiting when `signal` aborts
64
- * on disconnect, allowing the sync loops to finish.
65
- */
66
- uploadCrud: (signal?: AbortSignal) => Promise<void>;
67
- /**
68
- * Posts a checkpoint request with the connector, returning null if the connector doesn't support that.
69
- *
70
- * See {@link AbstractStreamingSyncImplementationOptions.uploadCrud} for the semantics of `signal`.
71
- */
72
- postCheckpointRequest: (clientId: string, requestId: string, signal?: AbortSignal) => Promise<string | null> | null;
62
+ connector: InternalConnector;
73
63
  /**
74
64
  * An identifier for which PowerSync DB this sync implementation is
75
65
  * linked to. Most commonly DB name, but not restricted to DB name.
@@ -135,12 +125,13 @@ export abstract class AbstractStreamingSyncImplementation
135
125
  protected options: AbstractStreamingSyncImplementationOptions;
136
126
  protected abortController: AbortController | null;
137
127
  protected crudUpdateListener?: () => void;
138
- protected streamingSyncPromise?: Promise<[void, void, void]>;
128
+ protected streamingSyncPromise?: Promise<void[]>;
139
129
  protected logger: PowerSyncLogger;
140
130
  protected activeStreams: SubscribedStream[];
141
131
  private connectionMayHaveChanged = false;
142
132
  private crudUploadNotifier = asyncNotifier();
143
133
  private checkpoints = new CheckpointStateSignals();
134
+ private connectTimeoutMs = DEFAULT_CONNECT_TIMEOUT_MS;
144
135
 
145
136
  private notifyCompletedUploads?: () => void;
146
137
  private handleActiveStreamsChange?: () => void;
@@ -217,39 +208,49 @@ export abstract class AbstractStreamingSyncImplementation
217
208
  });
218
209
  }
219
210
 
220
- private async requestCheckpointFromService(signal: AbortSignal, request: CheckpointRequestPayload): Promise<string> {
221
- // First, check if we can use a custom checkpoint request implementation.
222
- {
223
- const customResponse = await this.options.postCheckpointRequest(
224
- request.client_id,
225
- request.checkpoint_request_id,
226
- signal
227
- );
228
- if (customResponse != null) {
229
- return customResponse;
211
+ private requestCheckpointFromService(abort: AbortSignal, request: CheckpointRequestPayload): Promise<string> {
212
+ return runWithTimeout(abort, this.connectTimeoutMs, 'Checkpoint request', async (signal) => {
213
+ // First, check if we can use a custom checkpoint request implementation.
214
+ const custom = this.options.connector.postCheckpointRequest;
215
+ if (custom) {
216
+ const customResponse = await custom(request.client_id, request.checkpoint_request_id, signal);
217
+ if (customResponse != null) {
218
+ return customResponse;
219
+ }
230
220
  }
231
- }
232
221
 
233
- const status = await this.options.remote.fetchAndDecodeJson({
234
- method: 'POST',
235
- path: '/sync/checkpoint-request',
236
- body: JSON.stringify(request),
237
- signal
238
- });
222
+ const status = await this.options.remote.fetchAndDecodeJson({
223
+ method: 'POST',
224
+ path: '/sync/checkpoint-request',
225
+ body: JSON.stringify(request),
226
+ signal
227
+ });
239
228
 
240
- return status.data.checkpoint_request_id;
229
+ return status.data.checkpoint_request_id;
230
+ });
241
231
  }
242
232
 
243
- private async getLegacyWriteCheckpoint(): Promise<string> {
233
+ private async getLegacyWriteCheckpoint(abort: AbortSignal): Promise<string> {
244
234
  const clientId = await this.options.adapter.getClientId();
245
235
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
246
- const response = await this.options.remote.fetchAndDecodeJson({ path });
236
+ const response = await runWithTimeout(abort, this.connectTimeoutMs, 'Write checkpoint request', (signal) =>
237
+ this.options.remote.fetchAndDecodeJson({ path, signal })
238
+ );
247
239
  const checkpoint = response['data']['write_checkpoint'] as string;
248
240
  this.logger.log({ level: LogLevels.debug, message: `Created write checkpoint: ${checkpoint}` });
249
241
  return checkpoint;
250
242
  }
251
243
 
252
244
  private async crudUploadLoop(signal: AbortSignal, options: ResolvedSyncOptions): Promise<void> {
245
+ this.crudUpdateListener = this.options.adapter.registerListener({
246
+ crudUpdate: () => this.triggerCrudUpload()
247
+ });
248
+
249
+ signal.addEventListener('abort', () => {
250
+ this.crudUpdateListener?.();
251
+ this.crudUpdateListener = undefined;
252
+ });
253
+
253
254
  while (!signal.aborted) {
254
255
  await Promise.all([
255
256
  // Start the initial CRUD upload on connect. Then, keep polling until we're done.
@@ -293,20 +294,13 @@ The next upload iteration will be delayed.`
293
294
  }
294
295
 
295
296
  checkedCrudItem = nextCrudItem;
296
- await this.options.uploadCrud(signal);
297
+ await this.options.connector.uploadCrud!(signal);
297
298
  this.updateJsSyncState({ uploadError: undefined });
298
299
  } else {
299
300
  // Uploading is completed
300
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => {
301
- if (options.checkpointMode === 'legacy') {
302
- return this.getLegacyWriteCheckpoint();
303
- } else {
304
- return this.requestNextCheckpointFromService(signal);
305
- }
306
- });
307
- if (neededUpdate) {
308
- this.notifyCompletedUploads?.();
309
- } else if (checkedCrudItem != null) {
301
+ const neededUpdate =
302
+ this.options.connector.fetchCredentials && (await this.updateLocalTarget(signal, options));
303
+ if (!neededUpdate && checkedCrudItem != null) {
310
304
  // Only log this if there was something to upload
311
305
  this.logger.log({ level: LogLevels.debug, message: 'Upload complete, no write checkpoint needed.' });
312
306
  }
@@ -316,8 +310,9 @@ The next upload iteration will be delayed.`
316
310
  checkedCrudItem = undefined;
317
311
  this.updateJsSyncState({ uploading: false, uploadError: ex as Error });
318
312
  await this.delayRetry(signal, options.retryDelayMs);
319
- if (!this.isConnected) {
320
- // Exit the upload loop if the sync stream is no longer connected
313
+ if (this.options.connector.fetchCredentials && !this.isConnected) {
314
+ // Exit the upload loop if the sync stream is no longer connected. The upload is triggered again once it
315
+ // reconnects. In upload-only mode, there is no sync stream and we keep retrying.
321
316
  break;
322
317
  }
323
318
  this.logger.log({
@@ -333,6 +328,22 @@ The next upload iteration will be delayed.`
333
328
  });
334
329
  }
335
330
 
331
+ private async updateLocalTarget(signal: AbortSignal, options: ResolvedSyncOptions): Promise<boolean> {
332
+ const didUpdate = await this.options.adapter.updateLocalTarget(() => {
333
+ if (options.checkpointMode === 'legacy') {
334
+ return this.getLegacyWriteCheckpoint(signal);
335
+ } else {
336
+ return this.requestNextCheckpointFromService(signal);
337
+ }
338
+ });
339
+
340
+ if (didUpdate) {
341
+ this.notifyCompletedUploads?.();
342
+ }
343
+
344
+ return didUpdate;
345
+ }
346
+
336
347
  async connect(options: ResolvedSyncOptions) {
337
348
  if (this.abortController) {
338
349
  await this.disconnect();
@@ -340,68 +351,97 @@ The next upload iteration will be delayed.`
340
351
 
341
352
  const controller = new AbortController();
342
353
  this.abortController = controller;
354
+ this.connectTimeoutMs = options.connectTimeoutMs;
343
355
  const signal = controller.signal;
344
- this.streamingSyncPromise = Promise.all([
345
- this.crudUploadLoop(signal, options).catch((error) => {
346
- // Requesting the crud lock when aborted will file, but that's not something worth logging.
347
- if (signal.reason !== error) {
348
- this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error });
349
- }
350
- }),
351
- this.streamingSync(signal, options),
352
- this.repostUnacknowledgedCheckpointRequests(signal, options)
353
- ]).finally(() => {
356
+
357
+ const syncTasks: Promise<void>[] = [];
358
+ const connector = this.options.connector;
359
+ if (connector.uploadCrud) {
360
+ syncTasks.push(
361
+ this.crudUploadLoop(signal, options).catch((error) => {
362
+ // Requesting the crud lock when aborted will file, but that's not something worth logging.
363
+ if (signal.reason !== error) {
364
+ this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error });
365
+ }
366
+ })
367
+ );
368
+ }
369
+
370
+ if (connector.fetchCredentials) {
371
+ if (!connector.uploadCrud) {
372
+ // We can't upload mutations, but we can request a checkpoint for mutations that have already been uploaded from a
373
+ // potential prior upload-only connection.
374
+ syncTasks.push(
375
+ this.updateLocalTarget(signal, options)
376
+ .then(() => {})
377
+ .catch((error) => {
378
+ if (signal.reason !== error) {
379
+ this.logger.log({ level: LogLevels.error, message: 'Could not update local target', error });
380
+ }
381
+ })
382
+ );
383
+ }
384
+
385
+ syncTasks.push(this.streamingSync(signal, options));
386
+ syncTasks.push(this.repostUnacknowledgedCheckpointRequests(signal, options));
387
+ }
388
+
389
+ this.streamingSyncPromise = Promise.all(syncTasks).finally(() => {
354
390
  // These promises only complete when we want to disconnect. No further sync iteration can resume checkpoint
355
391
  // requests, so fail any that are still pending.
356
392
  this.checkpoints.disconnected();
357
393
  });
358
394
 
359
- // Return a promise that resolves when the connection status is updated to indicate that we're connected, or when
360
- // this connection attempt is aborted (e.g. superseded by another connect() call) before that happens. We do this
361
- // by waiting for connecting to be true and then false again.
362
- return new Promise<void>((resolve) => {
363
- let sawStartOfConnection = false;
364
- let settled = false;
365
-
366
- const finish = () => {
367
- if (settled) {
368
- return;
369
- }
370
- settled = true;
371
- disposer();
372
- signal.removeEventListener('abort', finish);
373
- resolve();
374
- };
395
+ if (connector.fetchCredentials) {
396
+ // Return a promise that resolves when the connection status is updated to indicate that we're connected, or when
397
+ // this connection attempt is aborted (e.g. superseded by another connect() call) before that happens. We do this
398
+ // by waiting for connecting to be true and then false again.
399
+ return new Promise<void>((resolve) => {
400
+ let sawStartOfConnection = false;
401
+ let settled = false;
375
402
 
376
- const disposer = this.registerListener({
377
- statusChanged: (snapshot) => {
378
- if (snapshot.connecting) {
379
- sawStartOfConnection = true;
403
+ const finish = () => {
404
+ if (settled) {
405
+ return;
380
406
  }
407
+ settled = true;
408
+ disposer();
409
+ signal.removeEventListener('abort', finish);
410
+ resolve();
411
+ };
412
+
413
+ const disposer = this.registerListener({
414
+ statusChanged: (snapshot) => {
415
+ if (snapshot.connecting) {
416
+ sawStartOfConnection = true;
417
+ }
381
418
 
382
- if (snapshot.downloadError != null) {
383
- this.logger.log({
384
- level: LogLevels.warn,
385
- message: 'Initial connect attempt did not successfully connect to server'
386
- });
387
- } else if (!sawStartOfConnection || snapshot.connecting) {
388
- // Still connecting.
389
- return;
419
+ if (snapshot.downloadError != null) {
420
+ this.logger.log({
421
+ level: LogLevels.warn,
422
+ message: 'Initial connect attempt did not successfully connect to server'
423
+ });
424
+ } else if (!sawStartOfConnection || snapshot.connecting) {
425
+ // Still connecting.
426
+ return;
427
+ }
428
+
429
+ finish();
390
430
  }
431
+ });
391
432
 
392
- finish();
393
- }
433
+ // If this attempt is aborted (disconnected) before a `statusChanged` event ever fires - which can happen when
434
+ // the instance never got as far as reporting a connecting status - there's nothing left to wait for.
435
+ signal.addEventListener('abort', finish, { once: true });
394
436
  });
395
-
396
- // If this attempt is aborted (disconnected) before a `statusChanged` event ever fires - which can happen when
397
- // the instance never got as far as reporting a connecting status - there's nothing left to wait for.
398
- signal.addEventListener('abort', finish, { once: true });
399
- });
437
+ }
400
438
  }
401
439
 
402
440
  async requestCheckpoint(): Promise<bigint> {
403
441
  const neverAbort = new AbortController().signal;
404
- return BigInt(await this.requestNextCheckpointFromService(neverAbort));
442
+ // disconnect() aborts the connection's signal. It is missing only when called before connect() starts.
443
+ const untilDisconnected = this.abortController?.signal ?? neverAbort;
444
+ return BigInt(await this.requestNextCheckpointFromService(untilDisconnected));
405
445
  }
406
446
 
407
447
  async disconnect(): Promise<void> {
@@ -443,13 +483,6 @@ The next upload iteration will be delayed.`
443
483
  }
444
484
 
445
485
  private async streamingSync(signal: AbortSignal, options: ResolvedSyncOptions): Promise<void> {
446
- /**
447
- * Listen for CRUD updates and trigger upstream uploads
448
- */
449
- this.crudUpdateListener = this.options.adapter.registerListener({
450
- crudUpdate: () => this.triggerCrudUpload()
451
- });
452
-
453
486
  /**
454
487
  * Create a new abort controller which aborts items downstream.
455
488
  * This is needed to close any previous connections on exception.
@@ -462,8 +495,6 @@ The next upload iteration will be delayed.`
462
495
  * to the nested abort controller.
463
496
  */
464
497
  nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
465
- this.crudUpdateListener?.();
466
- this.crudUpdateListener = undefined;
467
498
  this.markAsDisconnected();
468
499
  });
469
500
 
@@ -501,7 +532,10 @@ The next upload iteration will be delayed.`
501
532
  this.logger.log({ level: LogLevels.warn, message: 'Sync aborted', error: ex });
502
533
  shouldDelayRetry = false;
503
534
  // A disconnect was requested, we should not delay since there is no explicit retry
504
- } else if (this.connectionMayHaveChanged && (ex as Error).message?.indexOf('No iteration is active') >= 0) {
535
+ } else if (
536
+ this.connectionMayHaveChanged &&
537
+ (ex as Error | null | undefined)?.message?.includes('No iteration is active')
538
+ ) {
505
539
  this.connectionMayHaveChanged = false;
506
540
  this.logger.log({
507
541
  level: LogLevels.info,
@@ -607,7 +641,7 @@ The next upload iteration will be delayed.`
607
641
 
608
642
  const openInner = async () => {
609
643
  if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
610
- return await remote.fetchStream(options);
644
+ return await remote.fetchStream({ ...options, connectTimeoutMs: connection.connectTimeoutMs });
611
645
  } else {
612
646
  return await this.options.remote.socketStreamRaw({
613
647
  ...options,
@@ -713,6 +747,14 @@ The next upload iteration will be delayed.`
713
747
  await this.options.adapter.readCheckpointRequestId('seed', seed);
714
748
  }
715
749
 
750
+ private async willUpload(): Promise<boolean> {
751
+ if (this.options.connector.uploadCrud) return true;
752
+
753
+ // If we're connected in download-only mode, we can still request checkpoints. But if there's a local write, that
754
+ // won't be uploaded.
755
+ return !(await this.options.adapter.hasCrud());
756
+ }
757
+
716
758
  private async rustSyncIteration(
717
759
  signal: AbortSignal,
718
760
  resolvedOptions: ResolvedSyncOptions
@@ -829,6 +871,14 @@ The next upload iteration will be delayed.`
829
871
  syncImplementation.updateJsSyncState({ downloadError: undefined });
830
872
  } else if ('HandleDiagnostics' in instruction) {
831
873
  syncImplementation.emitDiagnostics(instruction.HandleDiagnostics);
874
+ } else if ('CheckpointDelayedDueToLocalData' in instruction) {
875
+ if (!(await syncImplementation.willUpload())) {
876
+ const message =
877
+ 'Applying checkpoint is blocked on local mutations, but no uploader is set. The sync client cannot proceed.';
878
+
879
+ syncImplementation.logger.log({ level: LogLevels.error, message });
880
+ syncImplementation.updateJsSyncState({ downloadError: new Error(message) });
881
+ }
832
882
  }
833
883
  }
834
884
 
@@ -924,6 +974,14 @@ The next upload iteration will be delayed.`
924
974
  }
925
975
  }
926
976
  }
977
+ } catch (e) {
978
+ if (!signal.aborted) {
979
+ // The stop() call in finally resets the sync status to disconnected. If we're calling that due to an error, we
980
+ // want to show the error first.
981
+ this.updateJsSyncState({ downloadError: e as Error });
982
+ }
983
+
984
+ throw e;
927
985
  } finally {
928
986
  this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
929
987
  notifyTokenRefreshed = undefined;
@@ -69,6 +69,9 @@ export class WebSocketSupport {
69
69
  // While we're connecting (a process that can't be aborted in RSocket), the WebSocket instance to close if we wanted
70
70
  // to abort the connection.
71
71
  let pendingSocket: WebSocket | null = null;
72
+ // The transport's connect() only settles on `open` or `error`, but a socket that closes while it's still opening fires
73
+ // only `close` on React Native iOS and no event at all on Android. So we fail it ourselves.
74
+ let failPendingConnect: ((error: Error) => void) | null = null;
72
75
  let keepAliveTimeout: any;
73
76
  let rsocket: RSocket | null = null;
74
77
  let paused = false;
@@ -96,6 +99,7 @@ export class WebSocketSupport {
96
99
  if (pendingSocket) {
97
100
  pendingSocket.close();
98
101
  }
102
+ failPendingConnect?.(new Error('WebSocket connection closed while opening'));
99
103
 
100
104
  if (rsocket) {
101
105
  rsocket.close();
@@ -149,6 +153,9 @@ export class WebSocketSupport {
149
153
  socket.addEventListener('message', () => {
150
154
  resetTimeout();
151
155
  });
156
+ socket.addEventListener('close', () => {
157
+ failPendingConnect?.(new Error('WebSocket connection closed while opening'));
158
+ });
152
159
  return socket;
153
160
  }
154
161
  }),
@@ -168,9 +175,20 @@ export class WebSocketSupport {
168
175
  });
169
176
 
170
177
  try {
171
- rsocket = await connector.connect();
178
+ rsocket = await new Promise<RSocket>((resolve, reject) => {
179
+ failPendingConnect = reject;
180
+ connector.connect().then((socket) => {
181
+ if (didClose) {
182
+ // We already gave up on this connection, don't leave it open.
183
+ socket.close();
184
+ } else {
185
+ resolve(socket);
186
+ }
187
+ }, reject);
188
+ });
172
189
  // The connection is established, we no longer need to monitor the initial timeout
173
190
  pendingSocket = null;
191
+ failPendingConnect = null;
174
192
  } catch (ex) {
175
193
  remote.logger.log({ level: this.#platform.LogLevels.error, message: `Failed to connect WebSocket`, error: ex });
176
194
  abortRequest();
@@ -184,6 +202,8 @@ export class WebSocketSupport {
184
202
  rsocket.onClose(() => (rsocket = null));
185
203
 
186
204
  return await new Promise((resolve, reject) => {
205
+ failPendingConnect = reject;
206
+
187
207
  const queueAsIterator: SimpleAsyncIterator<Uint8Array> = {
188
208
  next: async () => {
189
209
  if (didClose) return doneResult;
@@ -222,8 +242,11 @@ export class WebSocketSupport {
222
242
  if (e.message !== 'Closed. ') {
223
243
  remote.logger.log({ level: this.#platform.LogLevels.error, message: 'RSocket error', error: e });
224
244
  }
245
+ failPendingConnect = null; // We'll fail this ourselves
246
+
225
247
  // RSocket will close the RSocket stream automatically
226
248
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
249
+
227
250
  abortRequest();
228
251
  // Handles cases where the connection failed e.g. auth error or connection error
229
252
  if (!connectionEstablished) {
@@ -232,6 +255,7 @@ export class WebSocketSupport {
232
255
  },
233
256
  onNext: (payload) => {
234
257
  // The connection is active
258
+ failPendingConnect = null;
235
259
  if (!connectionEstablished) {
236
260
  connectionEstablished = true;
237
261
  resolve(queueAsIterator);
@@ -249,7 +273,14 @@ export class WebSocketSupport {
249
273
  requestMore();
250
274
  },
251
275
  onComplete: () => {
276
+ failPendingConnect = null; // We'll fail this ourselves
252
277
  abortRequest(); // this will also emit a done event
278
+
279
+ if (!connectionEstablished) {
280
+ // Closed without ever emitting an event? Still emit an empty queue.
281
+ connectionEstablished = true;
282
+ resolve(queueAsIterator);
283
+ }
253
284
  },
254
285
  onExtension: () => {}
255
286
  }
@@ -17,6 +17,7 @@ export type NonInterruptingInstruction =
17
17
  | { FetchCredentials: FetchCredentials }
18
18
  | { FlushFileSystem: any }
19
19
  | { DidCompleteSync: any }
20
+ | { CheckpointDelayedDueToLocalData: any }
20
21
  | { HandleDiagnostics: DiagnosticsEvent };
21
22
 
22
23
  /**
@@ -132,12 +132,31 @@ export abstract class AbstractQueryProcessor<
132
132
  */
133
133
  protected abstract linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
134
134
 
135
+ /**
136
+ * Whether any of the registered listeners handles errors itself.
137
+ * These are the listeners which {@link AbstractQueryProcessor.updateState} reports errors to.
138
+ */
139
+ protected get hasErrorListener(): boolean {
140
+ return (this.listenerCounts[WatchedQueryListenerEvent.ON_ERROR] ?? 0) > 0;
141
+ }
142
+
135
143
  protected async updateState(update: Partial<MutableWatchedQueryState<Data>>) {
136
144
  if (this._closed) {
137
145
  return;
138
146
  }
139
147
 
140
148
  if (typeof update.error !== 'undefined') {
149
+ // `error: null` is used to clear a previous error, which should not be logged.
150
+ if (update.error && !this.hasErrorListener) {
151
+ // Errors are also reported on the query state, but that is easy to miss. Logging makes failures such as
152
+ // invalid SQL discoverable without extra wiring. Listeners which registered an `onError` handler report
153
+ // errors themselves, so logging here would only duplicate their output.
154
+ this.options.db.logger.log({
155
+ level: LogLevels.error,
156
+ message: 'Error in watched query',
157
+ error: update.error
158
+ });
159
+ }
141
160
  await this.iterateAsyncListenersWithError(async (l) => l.onError?.(update.error!));
142
161
  // An error always stops for the current fetching state
143
162
  update.isFetching = false;
@@ -83,6 +83,7 @@ export class DifferentialQueryProcessor<RowType>
83
83
  let hasChanged = false;
84
84
  const currentMap = new Map<string, { hash: string; item: RowType }>();
85
85
  const removedTracker = new Set(previousMap.keys());
86
+ const previousKeys = previousMap.keys();
86
87
 
87
88
  // Allow mutating to populate the data temporarily.
88
89
  const diff = {
@@ -100,6 +101,10 @@ export class DifferentialQueryProcessor<RowType>
100
101
  */
101
102
  for (const item of current) {
102
103
  const key = keyBy(item);
104
+ // Maps preserve insertion order, so compare the keys pairwise.
105
+ if (!hasChanged && previousKeys.next().value !== key) {
106
+ hasChanged = true;
107
+ }
103
108
  const hash = compareBy(item);
104
109
  currentMap.set(key, { hash, item });
105
110
 
package/src/index.ts CHANGED
@@ -11,6 +11,7 @@ export * from './db/crud/SyncStatus.js';
11
11
  export * from './client/ConnectionManager.js';
12
12
  export * from './client/sync/options.js';
13
13
 
14
+ export * from './client/InternalConnector.js';
14
15
  export { MEMORY_TRIGGER_CLAIM_MANAGER } from './client/triggers/MemoryTriggerClaimManager.js';
15
16
  export * from './client/triggers/TriggerManagerImpl.js';
16
17
  export * from './client/watched/DifferentialQueryProcessor.js';