@powersync/shared-internals 1.1.1 → 1.3.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 (47) hide show
  1. package/dist/websockets.mjs.map +1 -1
  2. package/dist/websockets.node.mjs.map +1 -1
  3. package/lib/client/BasePowerSyncDatabase.d.ts +13 -3
  4. package/lib/client/BasePowerSyncDatabase.js +59 -5
  5. package/lib/client/BasePowerSyncDatabase.js.map +1 -1
  6. package/lib/client/ConnectionManager.d.ts +4 -0
  7. package/lib/client/ConnectionManager.js +19 -1
  8. package/lib/client/ConnectionManager.js.map +1 -1
  9. package/lib/client/sync/CheckpointRequestImpl.d.ts +11 -0
  10. package/lib/client/sync/CheckpointRequestImpl.js +42 -0
  11. package/lib/client/sync/CheckpointRequestImpl.js.map +1 -0
  12. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +1 -0
  13. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -1
  14. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +1 -0
  15. package/lib/client/sync/bucket/SqliteBucketStorage.js +7 -0
  16. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -1
  17. package/lib/client/sync/options.js +2 -1
  18. package/lib/client/sync/options.js.map +1 -1
  19. package/lib/client/sync/stream/AbstractRemote.d.ts +12 -6
  20. package/lib/client/sync/stream/AbstractRemote.js +16 -14
  21. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  22. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +29 -4
  23. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +177 -23
  24. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  25. package/lib/client/sync/stream/CheckpointState.d.ts +44 -0
  26. package/lib/client/sync/stream/CheckpointState.js +111 -0
  27. package/lib/client/sync/stream/CheckpointState.js.map +1 -0
  28. package/lib/client/sync/stream/core-instruction.d.ts +6 -0
  29. package/lib/client/sync/stream/core-instruction.js.map +1 -1
  30. package/lib/utils/stream_transform.d.ts +1 -0
  31. package/lib/utils/stream_transform.js +18 -2
  32. package/lib/utils/stream_transform.js.map +1 -1
  33. package/lib/version.d.ts +1 -1
  34. package/lib/version.js +1 -1
  35. package/package.json +4 -3
  36. package/src/client/BasePowerSyncDatabase.ts +71 -14
  37. package/src/client/ConnectionManager.ts +23 -1
  38. package/src/client/sync/CheckpointRequestImpl.ts +54 -0
  39. package/src/client/sync/bucket/BucketStorageAdapter.ts +1 -0
  40. package/src/client/sync/bucket/SqliteBucketStorage.ts +8 -0
  41. package/src/client/sync/options.ts +2 -1
  42. package/src/client/sync/stream/AbstractRemote.ts +29 -15
  43. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +217 -28
  44. package/src/client/sync/stream/CheckpointState.ts +142 -0
  45. package/src/client/sync/stream/core-instruction.ts +7 -0
  46. package/src/utils/stream_transform.ts +19 -3
  47. package/src/version.ts +1 -1
@@ -16,7 +16,7 @@ import { POWERSYNC_JS_VERSION } from '../../../version.js';
16
16
  * @internal
17
17
  */
18
18
  export type RemoteConnector = {
19
- fetchCredentials: () => Promise<PowerSyncCredentials | null>;
19
+ fetchCredentials: (signal?: AbortSignal) => Promise<PowerSyncCredentials | null>;
20
20
  invalidateCredentials?: () => void;
21
21
  };
22
22
 
@@ -96,12 +96,12 @@ export abstract class AbstractRemote {
96
96
  *
97
97
  * These credentials may have expired already.
98
98
  */
99
- async getCredentials(): Promise<PowerSyncCredentials | null> {
99
+ async getCredentials(signal?: AbortSignal): Promise<PowerSyncCredentials | null> {
100
100
  if (this.credentials) {
101
101
  return this.credentials;
102
102
  }
103
103
 
104
- return this.prefetchCredentials();
104
+ return this.prefetchCredentials(signal);
105
105
  }
106
106
 
107
107
  /**
@@ -112,8 +112,8 @@ export abstract class AbstractRemote {
112
112
  *
113
113
  * This may be called before the current credentials have expired.
114
114
  */
115
- async prefetchCredentials() {
116
- this.credentials = await this.fetchCredentials();
115
+ async prefetchCredentials(signal?: AbortSignal) {
116
+ this.credentials = await this.fetchCredentials(signal);
117
117
 
118
118
  return this.credentials;
119
119
  }
@@ -124,8 +124,8 @@ export abstract class AbstractRemote {
124
124
  * This should always fetch a fresh set of credentials - don't use cached
125
125
  * values.
126
126
  */
127
- async fetchCredentials() {
128
- const credentials = await this.connector.fetchCredentials();
127
+ async fetchCredentials(signal?: AbortSignal) {
128
+ const credentials = await this.connector.fetchCredentials(signal);
129
129
  if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {
130
130
  throw new Error(
131
131
  `A trailing forward slash "/" was found in the fetchCredentials endpoint: "${credentials.endpoint}". Remove the trailing forward slash "/" to fix this error.`
@@ -149,8 +149,8 @@ export abstract class AbstractRemote {
149
149
  return `powersync-js/${POWERSYNC_JS_VERSION}`;
150
150
  }
151
151
 
152
- protected async buildRequest(path: string): Promise<PreparedRequest> {
153
- const credentials = await this.getCredentials();
152
+ protected async buildRequest(path: string, signal?: AbortSignal): Promise<PreparedRequest> {
153
+ const credentials = await this.getCredentials(signal);
154
154
  if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
155
155
  throw new Error('PowerSync endpoint not configured');
156
156
  } else if (credentials?.token == null || credentials?.token == '') {
@@ -173,16 +173,30 @@ export abstract class AbstractRemote {
173
173
  };
174
174
  }
175
175
 
176
- async get(path: string, headers?: Record<string, string>): Promise<any> {
177
- const request = await this.buildRequest(path);
176
+ async fetchAndDecodeJson({
177
+ path,
178
+ method = 'GET',
179
+ headers,
180
+ body,
181
+ signal
182
+ }: {
183
+ path: string;
184
+ method?: string;
185
+ headers?: Record<string, string>;
186
+ body?: string;
187
+ signal?: AbortSignal;
188
+ }): Promise<any> {
189
+ const request = await this.buildRequest(path, signal);
178
190
  const res = await this.fetch({
179
191
  resource: request.url,
180
192
  request: {
181
- method: 'GET',
193
+ method,
182
194
  headers: {
183
195
  ...headers,
184
196
  ...request.headers
185
- }
197
+ },
198
+ body,
199
+ signal
186
200
  },
187
201
  expectStreamingResponse: false
188
202
  });
@@ -226,7 +240,7 @@ export abstract class AbstractRemote {
226
240
  async socketStreamRaw(options: SocketSyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array>> {
227
241
  const support = await this.loadWebSocketSupport(webSocketPlatform);
228
242
 
229
- const request = await this.buildRequest(options.path);
243
+ const request = await this.buildRequest(options.path, options.abortSignal);
230
244
  request.url = request.url.replace(/^https?:\/\//, function (match) {
231
245
  return match === 'https://' ? 'wss://' : 'ws://';
232
246
  });
@@ -251,7 +265,7 @@ export abstract class AbstractRemote {
251
265
  options: SyncStreamOptions
252
266
  ): Promise<{ isBson: boolean; stream: SimpleAsyncIterator<Uint8Array> }> {
253
267
  const { data, path, abortSignal } = options;
254
- const request = await this.buildRequest(path);
268
+ const request = await this.buildRequest(path, abortSignal);
255
269
 
256
270
  /**
257
271
  * This abort controller will abort pending fetch requests.
@@ -14,6 +14,7 @@ import { AbortOperation } from '../../../utils/AbortOperation.js';
14
14
  import { BucketStorageAdapter, PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';
15
15
  import { AbstractRemote, SyncStreamOptions } from './AbstractRemote.js';
16
16
  import {
17
+ CheckpointRequestPayload,
17
18
  CoreSyncStatus,
18
19
  Instruction,
19
20
  NonInterruptingInstruction,
@@ -29,6 +30,7 @@ import {
29
30
  import { asyncNotifier } from '../../../utils/async.js';
30
31
  import { JavaScriptSyncState, SyncStatusSnapshot } from '../../../db/crud/SyncStatus.js';
31
32
  import { ResolvedSyncOptions } from '../options.js';
33
+ import { CheckpointStateSignals, isCheckpointRequestApplied } from './CheckpointState.js';
32
34
 
33
35
  /**
34
36
  * @internal
@@ -55,7 +57,18 @@ export interface LockOptions<T> {
55
57
  export interface AbstractStreamingSyncImplementationOptions {
56
58
  adapter: BucketStorageAdapter;
57
59
  subscriptions: SubscribedStream[];
58
- uploadCrud: () => Promise<void>;
60
+ /**
61
+ * Uploads pending CRUD data.
62
+ * Cross-context implementations must stop waiting when `signal` aborts
63
+ * on disconnect, allowing the sync loops to finish.
64
+ */
65
+ uploadCrud: (signal?: AbortSignal) => Promise<void>;
66
+ /**
67
+ * Posts a checkpoint request with the connector, returning null if the connector doesn't support that.
68
+ *
69
+ * See {@link AbstractStreamingSyncImplementationOptions.uploadCrud} for the semantics of `signal`.
70
+ */
71
+ postCheckpointRequest: (clientId: string, requestId: string, signal?: AbortSignal) => Promise<string | null> | null;
59
72
  /**
60
73
  * An identifier for which PowerSync DB this sync implementation is
61
74
  * linked to. Most commonly DB name, but not restricted to DB name.
@@ -93,13 +106,14 @@ export interface StreamingSyncImplementation
93
106
  * @throws if not connected or if abort is not controlled internally
94
107
  */
95
108
  disconnect(): Promise<void>;
96
- getWriteCheckpoint: () => Promise<string>;
97
109
  isConnected: boolean;
98
110
  triggerCrudUpload: () => void;
99
111
  waitForReady(): Promise<void>;
100
112
  waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
101
113
  updateSubscriptions(subscriptions: SubscribedStream[]): void;
102
114
  markConnectionMayHaveChanged(): void;
115
+
116
+ requestCheckpoint(): Promise<bigint>;
103
117
  }
104
118
 
105
119
  /**
@@ -120,11 +134,12 @@ export abstract class AbstractStreamingSyncImplementation
120
134
  protected options: AbstractStreamingSyncImplementationOptions;
121
135
  protected abortController: AbortController | null;
122
136
  protected crudUpdateListener?: () => void;
123
- protected streamingSyncPromise?: Promise<[void, void]>;
137
+ protected streamingSyncPromise?: Promise<[void, void, void]>;
124
138
  protected logger: PowerSyncLogger;
125
139
  protected activeStreams: SubscribedStream[];
126
140
  private connectionMayHaveChanged = false;
127
141
  private crudUploadNotifier = asyncNotifier();
142
+ private checkpoints = new CheckpointStateSignals();
128
143
 
129
144
  private notifyCompletedUploads?: () => void;
130
145
  private handleActiveStreamsChange?: () => void;
@@ -182,10 +197,46 @@ export abstract class AbstractStreamingSyncImplementation
182
197
 
183
198
  abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
184
199
 
185
- async getWriteCheckpoint(): Promise<string> {
200
+ private async requestNextCheckpointFromService(abort: AbortSignal): Promise<string> {
201
+ if (!(await this.checkpoints.waitForCheckpointRequestsReady(abort))) {
202
+ throw abort.reason;
203
+ }
204
+
205
+ const nextCheckpointRequestId = await this.options.adapter.readCheckpointRequestId('next');
206
+ const clientId = await this.options.adapter.getClientId();
207
+ return await this.requestCheckpointFromService(abort, {
208
+ client_id: clientId,
209
+ checkpoint_request_id: nextCheckpointRequestId
210
+ });
211
+ }
212
+
213
+ private async requestCheckpointFromService(signal: AbortSignal, request: CheckpointRequestPayload): Promise<string> {
214
+ // First, check if we can use a custom checkpoint request implementation.
215
+ {
216
+ const customResponse = await this.options.postCheckpointRequest(
217
+ request.client_id,
218
+ request.checkpoint_request_id,
219
+ signal
220
+ );
221
+ if (customResponse != null) {
222
+ return customResponse;
223
+ }
224
+ }
225
+
226
+ const status = await this.options.remote.fetchAndDecodeJson({
227
+ method: 'POST',
228
+ path: '/sync/checkpoint-request',
229
+ body: JSON.stringify(request),
230
+ signal
231
+ });
232
+
233
+ return status.data.checkpoint_request_id;
234
+ }
235
+
236
+ private async getLegacyWriteCheckpoint(): Promise<string> {
186
237
  const clientId = await this.options.adapter.getClientId();
187
238
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
188
- const response = await this.options.remote.get(path);
239
+ const response = await this.options.remote.fetchAndDecodeJson({ path });
189
240
  const checkpoint = response['data']['write_checkpoint'] as string;
190
241
  this.logger.log({ level: LogLevels.debug, message: `Created write checkpoint: ${checkpoint}` });
191
242
  return checkpoint;
@@ -235,11 +286,17 @@ The next upload iteration will be delayed.`
235
286
  }
236
287
 
237
288
  checkedCrudItem = nextCrudItem;
238
- await this.options.uploadCrud();
289
+ await this.options.uploadCrud(signal);
239
290
  this.updateJsSyncState({ uploadError: undefined });
240
291
  } else {
241
292
  // Uploading is completed
242
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
293
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => {
294
+ if (options.checkpointMode === 'legacy') {
295
+ return this.getLegacyWriteCheckpoint();
296
+ } else {
297
+ return this.requestNextCheckpointFromService(signal);
298
+ }
299
+ });
243
300
  if (neededUpdate) {
244
301
  this.notifyCompletedUploads?.();
245
302
  } else if (checkedCrudItem != null) {
@@ -276,17 +333,38 @@ The next upload iteration will be delayed.`
276
333
 
277
334
  const controller = new AbortController();
278
335
  this.abortController = controller;
336
+ const signal = controller.signal;
279
337
  this.streamingSyncPromise = Promise.all([
280
- this.crudUploadLoop(controller.signal, options).catch((error) =>
281
- this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error })
282
- ),
283
- this.streamingSync(controller.signal, options)
284
- ]);
338
+ this.crudUploadLoop(signal, options).catch((error) => {
339
+ // Requesting the crud lock when aborted will file, but that's not something worth logging.
340
+ if (signal.reason !== error) {
341
+ this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error });
342
+ }
343
+ }),
344
+ this.streamingSync(signal, options),
345
+ this.repostUnacknowledgedCheckpointRequests(signal, options)
346
+ ]).finally(() => {
347
+ // These promises only complete when we want to disconnect. No further sync iteration can resume checkpoint
348
+ // requests, so fail any that are still pending.
349
+ this.checkpoints.disconnected();
350
+ });
285
351
 
286
- // Return a promise that resolves when the connection status is updated to indicate that we're connected. We do this
352
+ // Return a promise that resolves when the connection status is updated to indicate that we're connected, or when
353
+ // this connection attempt is aborted (e.g. superseded by another connect() call) before that happens. We do this
287
354
  // by waiting for connecting to be true and then false again.
288
355
  return new Promise<void>((resolve) => {
289
356
  let sawStartOfConnection = false;
357
+ let settled = false;
358
+
359
+ const finish = () => {
360
+ if (settled) {
361
+ return;
362
+ }
363
+ settled = true;
364
+ disposer();
365
+ signal.removeEventListener('abort', finish);
366
+ resolve();
367
+ };
290
368
 
291
369
  const disposer = this.registerListener({
292
370
  statusChanged: (snapshot) => {
@@ -304,13 +382,21 @@ The next upload iteration will be delayed.`
304
382
  return;
305
383
  }
306
384
 
307
- disposer();
308
- resolve();
385
+ finish();
309
386
  }
310
387
  });
388
+
389
+ // If this attempt is aborted (disconnected) before a `statusChanged` event ever fires - which can happen when
390
+ // the instance never got as far as reporting a connecting status - there's nothing left to wait for.
391
+ signal.addEventListener('abort', finish, { once: true });
311
392
  });
312
393
  }
313
394
 
395
+ async requestCheckpoint(): Promise<bigint> {
396
+ const neverAbort = new AbortController().signal;
397
+ return BigInt(await this.requestNextCheckpointFromService(neverAbort));
398
+ }
399
+
314
400
  async disconnect(): Promise<void> {
315
401
  if (!this.abortController) {
316
402
  return;
@@ -342,11 +428,10 @@ The next upload iteration will be delayed.`
342
428
  }
343
429
 
344
430
  this.updateSyncStatus({
431
+ ...current,
345
432
  connected: false,
346
433
  connecting: false,
347
- priority_status: current.priority_status,
348
- downloading: null,
349
- streams: current.streams
434
+ downloading: null
350
435
  });
351
436
  }
352
437
 
@@ -402,7 +487,10 @@ The next upload iteration will be delayed.`
402
487
  * The WebRemote should only abort pending fetch requests or close active Readable streams.
403
488
  */
404
489
 
405
- if (ex instanceof AbortOperation) {
490
+ // Check the disconnect signal: other aborts must still be reported and retried.
491
+ const stoppedOnRequest = signal.aborted;
492
+
493
+ if (stoppedOnRequest) {
406
494
  this.logger.log({ level: LogLevels.warn, message: 'Sync aborted', error: ex });
407
495
  shouldDelayRetry = false;
408
496
  // A disconnect was requested, we should not delay since there is no explicit retry
@@ -417,8 +505,12 @@ The next upload iteration will be delayed.`
417
505
  this.logger.log({ level: LogLevels.error, message: 'Sync error', error: ex });
418
506
  }
419
507
 
420
- this.updateJsSyncState({ downloadError: ex as Error });
508
+ if (!stoppedOnRequest) {
509
+ // Don't record intentional disconnects as errors: they persist until a successful sync.
510
+ this.updateJsSyncState({ downloadError: ex as Error });
511
+ }
421
512
  } finally {
513
+ this.checkpoints.downloadIterationEnded();
422
514
  this.notifyCompletedUploads = undefined;
423
515
 
424
516
  if (!signal.aborted) {
@@ -431,7 +523,7 @@ The next upload iteration will be delayed.`
431
523
 
432
524
  // On error, wait a little before retrying
433
525
  if (shouldDelayRetry) {
434
- await this.delayRetry(nestedAbortController.signal, options.retryDelayMs);
526
+ await this.delayRetry(nestedAbortController.signal, options.retryDelayMs, true);
435
527
  }
436
528
  }
437
529
  }
@@ -550,6 +642,70 @@ The next upload iteration will be delayed.`
550
642
  };
551
643
  }
552
644
 
645
+ /**
646
+ * Watches the current checkpoint request id to re-request it if we take too long to receive it.
647
+ *
648
+ * This does not require navigator locks: It waits for checkpoints to be seeded, which can only happen in the context
649
+ * of a download loop.
650
+ *
651
+ * Note that requesting checkpoints with ids the service has already seen is a cheap no-op.
652
+ */
653
+ private async repostUnacknowledgedCheckpointRequests(abort: AbortSignal, options: ResolvedSyncOptions) {
654
+ let retryDelay: number;
655
+ const mode = options.checkpointMode;
656
+ if (mode == 'legacy') return;
657
+
658
+ if (mode == 'requests') {
659
+ retryDelay = 10_000;
660
+ } else {
661
+ retryDelay = Math.max(mode.requests.retryDelay, 10_000);
662
+ }
663
+
664
+ while (!abort.aborted) {
665
+ try {
666
+ if (!(await this.checkpoints.waitForCheckpointRequestsReady(abort, false))) {
667
+ return;
668
+ }
669
+
670
+ const requestId = await this.options.adapter.readCheckpointRequestId('current');
671
+ // Give the request some time to sync.
672
+ await this.delayRetry(abort, retryDelay);
673
+
674
+ // If a new request was made, reset the timer.
675
+ if (requestId != (await this.options.adapter.readCheckpointRequestId('current'))) {
676
+ continue;
677
+ }
678
+
679
+ // If the request was applied, we don't need to retry.
680
+ if (isCheckpointRequestApplied(this.syncStatus?.core, BigInt(requestId))) {
681
+ continue;
682
+ }
683
+
684
+ // Make sure we're online and ready before making the request
685
+ if (!(await this.checkpoints.waitForCheckpointRequestsReady(abort, false))) {
686
+ return;
687
+ }
688
+
689
+ // It's safe if this request races with a new one. The service will reject it.
690
+ this.logger.log({ level: LogLevels.debug, message: `Retry checkpoint request ${requestId}` });
691
+ await this.requestCheckpointFromService(abort, {
692
+ client_id: await this.options.adapter.getClientId(),
693
+ checkpoint_request_id: requestId
694
+ });
695
+ } catch (e) {
696
+ if (abort.aborted) return;
697
+
698
+ this.logger.log({ level: LogLevels.warn, error: e, message: 'Error retrying checkpoint request.' });
699
+ await this.delayRetry(abort, retryDelay);
700
+ }
701
+ }
702
+ }
703
+
704
+ private async seedCheckpointRequestState(abort: AbortSignal, request: CheckpointRequestPayload) {
705
+ const seed = await this.requestCheckpointFromService(abort, request);
706
+ await this.options.adapter.readCheckpointRequestId('seed', seed);
707
+ }
708
+
553
709
  private async rustSyncIteration(
554
710
  signal: AbortSignal,
555
711
  resolvedOptions: ResolvedSyncOptions
@@ -570,7 +726,8 @@ The next upload iteration will be delayed.`
570
726
  parameters: resolvedOptions.params,
571
727
  app_metadata: resolvedOptions.appMetadata,
572
728
  active_streams: syncImplementation.activeStreams,
573
- include_defaults: resolvedOptions.includeDefaultStreams
729
+ include_defaults: resolvedOptions.includeDefaultStreams,
730
+ checkpoint_mode: resolvedOptions.checkpointMode === 'legacy' ? 'legacy' : 'requests'
574
731
  };
575
732
  if (serializedSchema) {
576
733
  options.schema = serializedSchema;
@@ -671,10 +828,11 @@ The next upload iteration will be delayed.`
671
828
 
672
829
  for (const startInstruction of await startCommand()) {
673
830
  if ('EstablishSyncStream' in startInstruction) {
831
+ const establish = startInstruction.EstablishSyncStream;
674
832
  const syncOptions: SyncStreamOptions = {
675
833
  path: '/sync/stream',
676
834
  abortSignal: signal,
677
- data: startInstruction.EstablishSyncStream.request
835
+ data: establish.request
678
836
  };
679
837
 
680
838
  controlInvocations = injectable(
@@ -683,6 +841,24 @@ The next upload iteration will be delayed.`
683
841
  connection: resolvedOptions
684
842
  })
685
843
  );
844
+
845
+ if (establish.checkpoint_request) {
846
+ // Start checkpoint request validation concurrently, without blocking line processing on it. We reconcile
847
+ // checkpoint states on each started download iteration to:
848
+ // 1. Align service and client checkpoint ids, allowing both parties to safely forget old checkpoints.
849
+ // 2. If the user id changes between connections, agreeing on the highest checkpoint request between the
850
+ // old and new user to make sure we'll receive that checkpoint eventually.
851
+ const seed = this.checkpoints.markCheckpointsReady(
852
+ this.seedCheckpointRequestState(signal, establish.checkpoint_request)
853
+ );
854
+
855
+ seed.catch((e) => {
856
+ // Make the download iteration fail if checkpoint requests are broken.
857
+ if (!signal.aborted) {
858
+ controlInvocations?.injectError(e);
859
+ }
860
+ });
861
+ }
686
862
  } else if ('CloseSyncStream' in startInstruction) {
687
863
  return defaultResult;
688
864
  } else {
@@ -761,14 +937,15 @@ The next upload iteration will be delayed.`
761
937
  this.updateSyncStatus(this.syncStatus.core, state);
762
938
  }
763
939
 
764
- private async delayRetry(signal: AbortSignal, delay: number): Promise<void> {
940
+ private async delayRetry(signal: AbortSignal, delay: number, resumeOnCheckpointRequest = false): Promise<void> {
765
941
  return new Promise((resolve) => {
766
- if (signal?.aborted) {
942
+ if (signal.aborted) {
767
943
  // If the signal is already aborted, resolve immediately
768
944
  resolve();
769
945
  return;
770
946
  }
771
947
 
948
+ let nested: AbortController | null = null;
772
949
  let timeoutId: ReturnType<typeof setTimeout> | undefined;
773
950
 
774
951
  const endDelay = () => {
@@ -777,11 +954,23 @@ The next upload iteration will be delayed.`
777
954
  clearTimeout(timeoutId);
778
955
  timeoutId = undefined;
779
956
  }
780
- signal?.removeEventListener('abort', endDelay);
957
+ if (nested) {
958
+ nested.abort();
959
+ nested = null;
960
+ }
961
+ signal.removeEventListener('abort', endDelay);
781
962
  };
782
963
 
783
- signal?.addEventListener('abort', endDelay, { once: true });
784
- timeoutId = setTimeout(endDelay, delay);
964
+ signal.addEventListener('abort', endDelay, { once: true });
965
+
966
+ // Add a random +/- 10% jitter to the retry delay.
967
+ const randomizedDelay = delay * (0.9 + Math.random() * 0.2);
968
+ timeoutId = setTimeout(endDelay, randomizedDelay);
969
+
970
+ if (resumeOnCheckpointRequest) {
971
+ nested = new AbortController();
972
+ this.checkpoints.waitForCheckpointWaiter(nested.signal).finally(endDelay);
973
+ }
785
974
  });
786
975
  }
787
976
 
@@ -0,0 +1,142 @@
1
+ import { BaseListener, BaseObserver } from '@powersync/common';
2
+ import { asyncNotifier, EventQueue } from '../../../utils/async.js';
3
+ import { CoreSyncStatus } from './core-instruction.js';
4
+
5
+ export type CheckpointState =
6
+ | { state: 'pending' }
7
+ | { state: 'disconnected' }
8
+ | { state: 'ready' }
9
+ | { state: 'error'; error: unknown };
10
+
11
+ const pending: CheckpointState = { state: 'pending' };
12
+
13
+ export class CheckpointStateSignals {
14
+ private currentState: CheckpointState = pending;
15
+ private readonly stateChanged = new BaseObserver<CheckpointStateListener>();
16
+
17
+ /**
18
+ * Use to immediately restart another download iteration if it is retry delay when a new checkpoint is requested.
19
+ */
20
+ private waitingForCheckpointsReady = asyncNotifier();
21
+
22
+ private updateState(state: CheckpointState) {
23
+ this.currentState = state;
24
+ this.stateChanged.iterateListeners((l) => l.stateChanged?.());
25
+ }
26
+
27
+ /**
28
+ * Marks the current download iteration as ended, blocking new checkpoint requests until the seed performed in the
29
+ * next iteration.
30
+ */
31
+ downloadIterationEnded() {
32
+ this.updateState(pending);
33
+
34
+ // Checkpoint waiters called after this should be able to resume the download iteration.
35
+ this.waitingForCheckpointsReady = asyncNotifier();
36
+ }
37
+
38
+ /**
39
+ * Marks the sync client as disconnected, failing all outstanding checkpoint requests and preventing new ones.
40
+ */
41
+ disconnected() {
42
+ this.updateState({ state: 'disconnected' });
43
+ }
44
+
45
+ /**
46
+ * Returns a promise that resolves with the abort signal or when we have a waiter wanting to request a checkpoint.
47
+ */
48
+ waitForCheckpointWaiter(signal: AbortSignal) {
49
+ return this.waitingForCheckpointsReady.waitForNotification(signal);
50
+ }
51
+
52
+ markCheckpointsReady(completion: Promise<void>): Promise<void> {
53
+ return completion.then(
54
+ (_) => this.updateState({ state: 'ready' }),
55
+ (error) => {
56
+ this.updateState({ state: 'error', error });
57
+ throw error;
58
+ }
59
+ );
60
+ }
61
+
62
+ /**
63
+ * Waits until a download iteration is active and has seeded the checkpoint state, meaning that checkpoint ids can
64
+ * safely be allocated.
65
+ *
66
+ * @returns Turue if checkpoints are ready, false if aborted.
67
+ */
68
+ async waitForCheckpointRequestsReady(abort: AbortSignal, wakeDownloadLoop = true): Promise<boolean> {
69
+ return new Promise((resolve, reject) => {
70
+ // A retry can reach this waiter after disconnect has already aborted its signal.
71
+ if (abort.aborted) {
72
+ resolve(false);
73
+ return;
74
+ }
75
+
76
+ // Resolves the promise from the current state if possible, returning true if it was.
77
+ const handleState = () => {
78
+ const state = this.currentState;
79
+ switch (state.state) {
80
+ case 'disconnected':
81
+ reject(cannotRequestDueToDisconnectedError());
82
+ return true;
83
+ case 'ready':
84
+ resolve(true);
85
+ return true;
86
+ case 'error':
87
+ reject(state.error);
88
+ return true;
89
+ case 'pending': {
90
+ // Wait for the next event.
91
+ if (wakeDownloadLoop) {
92
+ this.waitingForCheckpointsReady.notify();
93
+ }
94
+ return false;
95
+ }
96
+ }
97
+ };
98
+
99
+ if (handleState()) {
100
+ return;
101
+ }
102
+
103
+ let removeListener: () => void;
104
+ let onAbort: () => void;
105
+
106
+ function cleanup() {
107
+ removeListener();
108
+ abort.removeEventListener('abort', onAbort);
109
+ }
110
+
111
+ onAbort = () => {
112
+ resolve(false);
113
+ cleanup();
114
+ };
115
+ removeListener = this.stateChanged.registerListener({
116
+ stateChanged() {
117
+ if (handleState()) {
118
+ cleanup();
119
+ }
120
+ }
121
+ });
122
+ abort.addEventListener('abort', onAbort);
123
+ });
124
+ }
125
+ }
126
+
127
+ interface CheckpointStateListener extends BaseListener {
128
+ stateChanged(): void;
129
+ }
130
+
131
+ export function cannotRequestDueToDisconnectedError(): Error {
132
+ return new Error('Cannot request checkpoints, sync client is disconnected.');
133
+ }
134
+
135
+ export function checkpointRequestsNotEnabledError(): Error {
136
+ return new Error('Connected with legacy checkpoint mode, cannot request checkpoints.');
137
+ }
138
+
139
+ export function isCheckpointRequestApplied(status: CoreSyncStatus | null, requestId: bigint): boolean {
140
+ const applied = status?.internal_last_applied_checkpoint_request_id;
141
+ return applied != null && BigInt(applied) >= requestId;
142
+ }
@@ -25,6 +25,7 @@ export interface LogLine {
25
25
 
26
26
  export interface EstablishSyncStream {
27
27
  request: unknown;
28
+ checkpoint_request?: CheckpointRequestPayload;
28
29
  }
29
30
 
30
31
  export interface UpdateSyncStatus {
@@ -37,6 +38,7 @@ export interface CoreSyncStatus {
37
38
  priority_status: SyncPriorityStatus[];
38
39
  downloading: DownloadProgress | null;
39
40
  streams: CoreStreamSubscription[];
41
+ internal_last_applied_checkpoint_request_id?: string;
40
42
  }
41
43
 
42
44
  /// An `ActiveStreamSubscription` from the core extension + serialized progress information.
@@ -73,6 +75,11 @@ export interface FetchCredentials {
73
75
  did_expire: boolean;
74
76
  }
75
77
 
78
+ export interface CheckpointRequestPayload {
79
+ client_id: string;
80
+ checkpoint_request_id: string;
81
+ }
82
+
76
83
  export function isInterruptingInstruction(instruction: Instruction): instruction is InterruptingInstruction {
77
84
  return 'EstablishSyncStream' in instruction || 'CloseSyncStream' in instruction;
78
85
  }