@powersync/shared-internals 1.1.0 → 1.2.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 +49 -2
  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 +7 -1
  20. package/lib/client/sync/stream/AbstractRemote.js +5 -3
  21. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  22. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +21 -3
  23. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +140 -16
  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 +106 -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 +5 -2
  36. package/src/client/BasePowerSyncDatabase.ts +63 -11
  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 +17 -3
  43. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +165 -18
  44. package/src/client/sync/stream/CheckpointState.ts +136 -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
@@ -0,0 +1,136 @@
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
+ // Resolves the promise from the current state if possible, returning true if it was.
71
+ const handleState = () => {
72
+ const state = this.currentState;
73
+ switch (state.state) {
74
+ case 'disconnected':
75
+ reject(cannotRequestDueToDisconnectedError());
76
+ return true;
77
+ case 'ready':
78
+ resolve(true);
79
+ return true;
80
+ case 'error':
81
+ reject(state.error);
82
+ return true;
83
+ case 'pending': {
84
+ // Wait for the next event.
85
+ if (wakeDownloadLoop) {
86
+ this.waitingForCheckpointsReady.notify();
87
+ }
88
+ return false;
89
+ }
90
+ }
91
+ };
92
+
93
+ if (handleState()) {
94
+ return;
95
+ }
96
+
97
+ let removeListener: () => void;
98
+ let onAbort: () => void;
99
+
100
+ function cleanup() {
101
+ removeListener();
102
+ abort.removeEventListener('abort', onAbort);
103
+ }
104
+
105
+ onAbort = () => {
106
+ resolve(false);
107
+ cleanup();
108
+ };
109
+ removeListener = this.stateChanged.registerListener({
110
+ stateChanged() {
111
+ if (handleState()) {
112
+ cleanup();
113
+ }
114
+ }
115
+ });
116
+ abort.addEventListener('abort', onAbort);
117
+ });
118
+ }
119
+ }
120
+
121
+ interface CheckpointStateListener extends BaseListener {
122
+ stateChanged(): void;
123
+ }
124
+
125
+ export function cannotRequestDueToDisconnectedError(): Error {
126
+ return new Error('Cannot request checkpoints, sync client is disconnected.');
127
+ }
128
+
129
+ export function checkpointRequestsNotEnabledError(): Error {
130
+ return new Error('Connected with legacy checkpoint mode, cannot request checkpoints.');
131
+ }
132
+
133
+ export function isCheckpointRequestApplied(status: CoreSyncStatus | null, requestId: bigint): boolean {
134
+ const applied = status?.internal_last_applied_checkpoint_request_id;
135
+ return applied != null && BigInt(applied) >= requestId;
136
+ }
@@ -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
  }
@@ -34,6 +34,7 @@ export function map<T1, T2>(source: SimpleAsyncIterator<T1>, map: (source: T1) =
34
34
 
35
35
  export interface InjectableIterator<T> extends SimpleAsyncIterator<T> {
36
36
  inject(event: T): void;
37
+ injectError(error: unknown): void;
37
38
  }
38
39
 
39
40
  /**
@@ -54,7 +55,7 @@ export function injectable<T>(source: SimpleAsyncIterator<T>): InjectableIterato
54
55
  let pendingSourceEvent: ((w: Waiter) => void) | null = null;
55
56
  let sourceFetchInFlight = false;
56
57
 
57
- let pendingInjectedEvents: T[] = [];
58
+ let pendingInjectedEvents: PromiseSettledResult<T>[] = [];
58
59
 
59
60
  const consumeWaiter = () => {
60
61
  const pending = waiter;
@@ -102,7 +103,14 @@ export function injectable<T>(source: SimpleAsyncIterator<T>): InjectableIterato
102
103
 
103
104
  // Second priority: Dispatch injected events
104
105
  if (pendingInjectedEvents.length) {
105
- return resolve(valueResult(pendingInjectedEvents.shift()!));
106
+ const event = pendingInjectedEvents.shift()!;
107
+ if (event.status === 'fulfilled') {
108
+ resolve(valueResult(event.value));
109
+ } else {
110
+ reject(event.reason);
111
+ }
112
+
113
+ return;
106
114
  }
107
115
 
108
116
  // Nothing pending? Fetch from source
@@ -117,7 +125,15 @@ export function injectable<T>(source: SimpleAsyncIterator<T>): InjectableIterato
117
125
  if (pending != null) {
118
126
  pending.resolve(valueResult(event));
119
127
  } else {
120
- pendingInjectedEvents.push(event);
128
+ pendingInjectedEvents.push({ status: 'fulfilled', value: event });
129
+ }
130
+ },
131
+ injectError(error) {
132
+ const pending = consumeWaiter();
133
+ if (pending != null) {
134
+ pending.reject(error);
135
+ } else {
136
+ pendingInjectedEvents.push({ status: 'rejected', reason: error });
121
137
  }
122
138
  }
123
139
  };
package/src/version.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  // Note: This file gets updated by tool/update_version.js script as part of the Changesets release workflow.
2
2
  // The update happens in the changesets PR, before the package is built.
3
- export const POWERSYNC_JS_VERSION = '1.1.0';
3
+ export const POWERSYNC_JS_VERSION = '1.2.0';