@powersync/shared-internals 0.0.0-dev-20260827080125

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 (152) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/websockets.mjs +7558 -0
  4. package/dist/websockets.mjs.map +1 -0
  5. package/dist/websockets.node.mjs +5189 -0
  6. package/dist/websockets.node.mjs.map +1 -0
  7. package/legacy/sync_protocol.d.ts +103 -0
  8. package/lib/client/BasePowerSyncDatabase.d.ts +156 -0
  9. package/lib/client/BasePowerSyncDatabase.js +654 -0
  10. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  11. package/lib/client/ConnectionManager.d.ts +120 -0
  12. package/lib/client/ConnectionManager.js +324 -0
  13. package/lib/client/ConnectionManager.js.map +1 -0
  14. package/lib/client/CustomQuery.d.ts +21 -0
  15. package/lib/client/CustomQuery.js +43 -0
  16. package/lib/client/CustomQuery.js.map +1 -0
  17. package/lib/client/sync/CheckpointRequestImpl.d.ts +11 -0
  18. package/lib/client/sync/CheckpointRequestImpl.js +42 -0
  19. package/lib/client/sync/CheckpointRequestImpl.js.map +1 -0
  20. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +58 -0
  21. package/lib/client/sync/bucket/BucketStorageAdapter.js +47 -0
  22. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  23. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  24. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  25. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  26. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +32 -0
  27. package/lib/client/sync/bucket/SqliteBucketStorage.js +160 -0
  28. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  29. package/lib/client/sync/options.d.ts +9 -0
  30. package/lib/client/sync/options.js +17 -0
  31. package/lib/client/sync/options.js.map +1 -0
  32. package/lib/client/sync/stream/AbstractRemote.d.ts +131 -0
  33. package/lib/client/sync/stream/AbstractRemote.js +270 -0
  34. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  35. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +156 -0
  36. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +740 -0
  37. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  38. package/lib/client/sync/stream/CheckpointState.d.ts +44 -0
  39. package/lib/client/sync/stream/CheckpointState.js +106 -0
  40. package/lib/client/sync/stream/CheckpointState.js.map +1 -0
  41. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  42. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  43. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  44. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  45. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  46. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  47. package/lib/client/sync/stream/core-instruction.d.ts +81 -0
  48. package/lib/client/sync/stream/core-instruction.js +4 -0
  49. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  50. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  51. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  52. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  53. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  54. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  55. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  56. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  57. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  58. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  59. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  60. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  61. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  63. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  64. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  66. package/lib/client/watched/WatchedQuery.js +12 -0
  67. package/lib/client/watched/WatchedQuery.js.map +1 -0
  68. package/lib/constants.d.ts +5 -0
  69. package/lib/constants.js +6 -0
  70. package/lib/constants.js.map +1 -0
  71. package/lib/db/ConnectionClosedError.d.ts +12 -0
  72. package/lib/db/ConnectionClosedError.js +23 -0
  73. package/lib/db/ConnectionClosedError.js.map +1 -0
  74. package/lib/db/crud/SyncProgress.d.ts +10 -0
  75. package/lib/db/crud/SyncProgress.js +33 -0
  76. package/lib/db/crud/SyncProgress.js.map +1 -0
  77. package/lib/db/crud/SyncStatus.d.ts +48 -0
  78. package/lib/db/crud/SyncStatus.js +178 -0
  79. package/lib/db/crud/SyncStatus.js.map +1 -0
  80. package/lib/db/openDatabase.d.ts +7 -0
  81. package/lib/db/openDatabase.js +22 -0
  82. package/lib/db/openDatabase.js.map +1 -0
  83. package/lib/index.d.ts +22 -0
  84. package/lib/index.js +22 -0
  85. package/lib/index.js.map +1 -0
  86. package/lib/utils/AbortOperation.d.ts +11 -0
  87. package/lib/utils/AbortOperation.js +21 -0
  88. package/lib/utils/AbortOperation.js.map +1 -0
  89. package/lib/utils/ControlledExecutor.d.ts +31 -0
  90. package/lib/utils/ControlledExecutor.js +58 -0
  91. package/lib/utils/ControlledExecutor.js.map +1 -0
  92. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  93. package/lib/utils/MetaBaseObserver.js +51 -0
  94. package/lib/utils/MetaBaseObserver.js.map +1 -0
  95. package/lib/utils/async.d.ts +46 -0
  96. package/lib/utils/async.js +147 -0
  97. package/lib/utils/async.js.map +1 -0
  98. package/lib/utils/compatibility.d.ts +8 -0
  99. package/lib/utils/compatibility.js +9 -0
  100. package/lib/utils/compatibility.js.map +1 -0
  101. package/lib/utils/mutex.d.ts +42 -0
  102. package/lib/utils/mutex.js +150 -0
  103. package/lib/utils/mutex.js.map +1 -0
  104. package/lib/utils/parseQuery.d.ts +12 -0
  105. package/lib/utils/parseQuery.js +20 -0
  106. package/lib/utils/parseQuery.js.map +1 -0
  107. package/lib/utils/queue.d.ts +16 -0
  108. package/lib/utils/queue.js +42 -0
  109. package/lib/utils/queue.js.map +1 -0
  110. package/lib/utils/stream_transform.d.ts +42 -0
  111. package/lib/utils/stream_transform.js +227 -0
  112. package/lib/utils/stream_transform.js.map +1 -0
  113. package/lib/version.d.ts +1 -0
  114. package/lib/version.js +4 -0
  115. package/lib/version.js.map +1 -0
  116. package/package.json +68 -0
  117. package/src/client/BasePowerSyncDatabase.ts +898 -0
  118. package/src/client/ConnectionManager.ts +441 -0
  119. package/src/client/CustomQuery.ts +60 -0
  120. package/src/client/sync/CheckpointRequestImpl.ts +54 -0
  121. package/src/client/sync/bucket/BucketStorageAdapter.ts +85 -0
  122. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  123. package/src/client/sync/bucket/SqliteBucketStorage.ts +203 -0
  124. package/src/client/sync/options.ts +25 -0
  125. package/src/client/sync/stream/AbstractRemote.ts +388 -0
  126. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +948 -0
  127. package/src/client/sync/stream/CheckpointState.ts +136 -0
  128. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  129. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  130. package/src/client/sync/stream/core-instruction.ts +85 -0
  131. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  132. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  133. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  134. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  135. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  136. package/src/client/watched/WatchedQuery.ts +14 -0
  137. package/src/constants.ts +6 -0
  138. package/src/db/ConnectionClosedError.ts +25 -0
  139. package/src/db/crud/SyncProgress.ts +39 -0
  140. package/src/db/crud/SyncStatus.ts +234 -0
  141. package/src/db/openDatabase.ts +23 -0
  142. package/src/index.ts +24 -0
  143. package/src/utils/AbortOperation.ts +19 -0
  144. package/src/utils/ControlledExecutor.ts +81 -0
  145. package/src/utils/MetaBaseObserver.ts +65 -0
  146. package/src/utils/async.ts +185 -0
  147. package/src/utils/compatibility.ts +9 -0
  148. package/src/utils/mutex.ts +186 -0
  149. package/src/utils/parseQuery.ts +31 -0
  150. package/src/utils/queue.ts +48 -0
  151. package/src/utils/stream_transform.ts +276 -0
  152. package/src/version.ts +3 -0
@@ -0,0 +1,740 @@
1
+ import { LogLevels, SyncStreamConnectionMethod, BaseObserver } from '@powersync/common';
2
+ import { AbortOperation } from '../../../utils/AbortOperation.js';
3
+ import { PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';
4
+ import { isInterruptingInstruction } from './core-instruction.js';
5
+ import { doneResult, injectable, valueResult } from '../../../utils/stream_transform.js';
6
+ import { asyncNotifier } from '../../../utils/async.js';
7
+ import { SyncStatusSnapshot } from '../../../db/crud/SyncStatus.js';
8
+ import { CheckpointStateSignals, isCheckpointRequestApplied } from './CheckpointState.js';
9
+ /**
10
+ * @internal
11
+ */
12
+ export var LockType;
13
+ (function (LockType) {
14
+ LockType["CRUD"] = "crud";
15
+ LockType["SYNC"] = "sync";
16
+ })(LockType || (LockType = {}));
17
+ /**
18
+ * @internal
19
+ */
20
+ export class AbstractStreamingSyncImplementation extends BaseObserver {
21
+ options;
22
+ abortController;
23
+ crudUpdateListener;
24
+ streamingSyncPromise;
25
+ logger;
26
+ activeStreams;
27
+ connectionMayHaveChanged = false;
28
+ crudUploadNotifier = asyncNotifier();
29
+ checkpoints = new CheckpointStateSignals();
30
+ notifyCompletedUploads;
31
+ handleActiveStreamsChange;
32
+ syncStatus;
33
+ constructor(options) {
34
+ super();
35
+ this.options = options;
36
+ this.activeStreams = options.subscriptions;
37
+ this.logger = options.logger;
38
+ this.syncStatus = new SyncStatusSnapshot(null, {});
39
+ this.abortController = null;
40
+ }
41
+ triggerCrudUpload() {
42
+ this.crudUploadNotifier.notify();
43
+ }
44
+ async waitForReady() { }
45
+ waitUntilStatusMatches(predicate) {
46
+ return new Promise((resolve) => {
47
+ if (predicate(this.syncStatus)) {
48
+ resolve();
49
+ return;
50
+ }
51
+ const l = this.registerListener({
52
+ statusChanged: () => {
53
+ if (predicate(this.syncStatus)) {
54
+ resolve();
55
+ l?.();
56
+ }
57
+ }
58
+ });
59
+ });
60
+ }
61
+ get lastSyncedAt() {
62
+ const lastSynced = this.syncStatus.lastSyncedAt;
63
+ return lastSynced && new Date(lastSynced);
64
+ }
65
+ get isConnected() {
66
+ return this.syncStatus.connected;
67
+ }
68
+ async dispose() {
69
+ super.dispose();
70
+ this.crudUpdateListener?.();
71
+ this.crudUpdateListener = undefined;
72
+ }
73
+ async requestNextCheckpointFromService(abort) {
74
+ await this.checkpoints.waitForCheckpointRequestsReady(abort);
75
+ const nextCheckpointRequestId = await this.options.adapter.readCheckpointRequestId('next');
76
+ const clientId = await this.options.adapter.getClientId();
77
+ return await this.requestCheckpointFromService(abort, {
78
+ client_id: clientId,
79
+ checkpoint_request_id: nextCheckpointRequestId
80
+ });
81
+ }
82
+ async requestCheckpointFromService(signal, request) {
83
+ // First, check if we can use a custom checkpoint request implementation.
84
+ {
85
+ const customResponse = await this.options.postCheckpointRequest(request.client_id, request.checkpoint_request_id);
86
+ if (customResponse != null) {
87
+ return customResponse;
88
+ }
89
+ }
90
+ const status = await this.options.remote.fetchAndDecodeJson({
91
+ method: 'POST',
92
+ path: '/sync/checkpoint-request',
93
+ body: JSON.stringify(request),
94
+ signal
95
+ });
96
+ return status.data.checkpoint_request_id;
97
+ }
98
+ async getLegacyWriteCheckpoint() {
99
+ const clientId = await this.options.adapter.getClientId();
100
+ let path = `/write-checkpoint2.json?client_id=${clientId}`;
101
+ const response = await this.options.remote.fetchAndDecodeJson({ path });
102
+ const checkpoint = response['data']['write_checkpoint'];
103
+ this.logger.log({ level: LogLevels.debug, message: `Created write checkpoint: ${checkpoint}` });
104
+ return checkpoint;
105
+ }
106
+ async crudUploadLoop(signal, options) {
107
+ while (!signal.aborted) {
108
+ await Promise.all([
109
+ // Start the initial CRUD upload on connect. Then, keep polling until we're done.
110
+ this._uploadAllCrud(signal, options),
111
+ this.delayRetry(signal, options.crudUploadThrottleMs)
112
+ ]);
113
+ await this.crudUploadNotifier.waitForNotification(signal);
114
+ }
115
+ }
116
+ async _uploadAllCrud(signal, options) {
117
+ return this.obtainLock({
118
+ type: LockType.CRUD,
119
+ signal,
120
+ callback: async () => {
121
+ /**
122
+ * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
123
+ */
124
+ let checkedCrudItem;
125
+ while (!signal.aborted) {
126
+ try {
127
+ /**
128
+ * This is the first item in the FIFO CRUD queue.
129
+ */
130
+ const nextCrudItem = await this.options.adapter.nextCrudItem();
131
+ if (nextCrudItem) {
132
+ this.updateJsSyncState({ uploading: true });
133
+ if (nextCrudItem.clientId == checkedCrudItem?.clientId) {
134
+ // This will force a higher log level than exceptions which are caught here.
135
+ this.logger.log({
136
+ level: LogLevels.warn,
137
+ message: `Potentially previously uploaded CRUD entries are still present in the upload queue.
138
+ Make sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.
139
+ The next upload iteration will be delayed.`
140
+ });
141
+ throw new Error('Delaying due to previously encountered CRUD item.');
142
+ }
143
+ checkedCrudItem = nextCrudItem;
144
+ await this.options.uploadCrud();
145
+ this.updateJsSyncState({ uploadError: undefined });
146
+ }
147
+ else {
148
+ // Uploading is completed
149
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => {
150
+ if (options.checkpointMode === 'legacy') {
151
+ return this.getLegacyWriteCheckpoint();
152
+ }
153
+ else {
154
+ return this.requestNextCheckpointFromService(signal);
155
+ }
156
+ });
157
+ if (neededUpdate) {
158
+ this.notifyCompletedUploads?.();
159
+ }
160
+ else if (checkedCrudItem != null) {
161
+ // Only log this if there was something to upload
162
+ this.logger.log({ level: LogLevels.debug, message: 'Upload complete, no write checkpoint needed.' });
163
+ }
164
+ break;
165
+ }
166
+ }
167
+ catch (ex) {
168
+ checkedCrudItem = undefined;
169
+ this.updateJsSyncState({ uploading: false, uploadError: ex });
170
+ await this.delayRetry(signal, options.retryDelayMs);
171
+ if (!this.isConnected) {
172
+ // Exit the upload loop if the sync stream is no longer connected
173
+ break;
174
+ }
175
+ this.logger.log({
176
+ level: LogLevels.debug,
177
+ message: `Caught exception when uploading. Upload will retry after a delay.`,
178
+ error: ex
179
+ });
180
+ }
181
+ finally {
182
+ this.updateJsSyncState({ uploading: false });
183
+ }
184
+ }
185
+ }
186
+ });
187
+ }
188
+ async connect(options) {
189
+ if (this.abortController) {
190
+ await this.disconnect();
191
+ }
192
+ const controller = new AbortController();
193
+ this.abortController = controller;
194
+ this.streamingSyncPromise = Promise.all([
195
+ this.crudUploadLoop(controller.signal, options).catch((error) => this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error })),
196
+ this.streamingSync(controller.signal, options),
197
+ this.repostUnacknowledgedCheckpointRequests(controller.signal, options)
198
+ ]).finally(() => {
199
+ // These promises only complete when we want to disconnect. No further sync iteration can resume checkpoint
200
+ // requests, so fail any that are still pending.
201
+ this.checkpoints.disconnected();
202
+ });
203
+ // Return a promise that resolves when the connection status is updated to indicate that we're connected. We do this
204
+ // by waiting for connecting to be true and then false again.
205
+ return new Promise((resolve) => {
206
+ let sawStartOfConnection = false;
207
+ const disposer = this.registerListener({
208
+ statusChanged: (snapshot) => {
209
+ if (snapshot.connecting) {
210
+ sawStartOfConnection = true;
211
+ }
212
+ if (snapshot.downloadError != null) {
213
+ this.logger.log({
214
+ level: LogLevels.warn,
215
+ message: 'Initial connect attempt did not successfully connect to server'
216
+ });
217
+ }
218
+ else if (!sawStartOfConnection || snapshot.connecting) {
219
+ // Still connecting.
220
+ return;
221
+ }
222
+ disposer();
223
+ resolve();
224
+ }
225
+ });
226
+ });
227
+ }
228
+ async requestCheckpoint() {
229
+ const neverAbort = new AbortController().signal;
230
+ return BigInt(await this.requestNextCheckpointFromService(neverAbort));
231
+ }
232
+ async disconnect() {
233
+ if (!this.abortController) {
234
+ return;
235
+ }
236
+ // This might be called multiple times
237
+ if (!this.abortController.signal.aborted) {
238
+ this.abortController.abort(new AbortOperation('Disconnect has been requested'));
239
+ }
240
+ // Await any pending operations before completing the disconnect operation
241
+ try {
242
+ await this.streamingSyncPromise;
243
+ }
244
+ catch (ex) {
245
+ // The operation might have failed, all we care about is if it has completed
246
+ this.logger.log({ level: LogLevels.warn, message: 'Error in sync while disconnecting', error: ex });
247
+ }
248
+ this.streamingSyncPromise = undefined;
249
+ this.abortController = null;
250
+ this.markAsDisconnected();
251
+ }
252
+ markAsDisconnected() {
253
+ const current = this.syncStatus.core;
254
+ if (current == null) {
255
+ // There's no connection attempt for which state could be cleared.
256
+ return;
257
+ }
258
+ this.updateSyncStatus({
259
+ ...current,
260
+ connected: false,
261
+ connecting: false,
262
+ downloading: null
263
+ });
264
+ }
265
+ async streamingSync(signal, options) {
266
+ /**
267
+ * Listen for CRUD updates and trigger upstream uploads
268
+ */
269
+ this.crudUpdateListener = this.options.adapter.registerListener({
270
+ crudUpdate: () => this.triggerCrudUpload()
271
+ });
272
+ /**
273
+ * Create a new abort controller which aborts items downstream.
274
+ * This is needed to close any previous connections on exception.
275
+ */
276
+ let nestedAbortController = new AbortController();
277
+ signal.addEventListener('abort', () => {
278
+ /**
279
+ * A request for disconnect was received upstream. Relay the request
280
+ * to the nested abort controller.
281
+ */
282
+ nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
283
+ this.crudUpdateListener?.();
284
+ this.crudUpdateListener = undefined;
285
+ this.markAsDisconnected();
286
+ });
287
+ /**
288
+ * This loops runs until [retry] is false or the abort signal is set to aborted.
289
+ * Aborting the nestedAbortController will:
290
+ * - Abort any pending fetch requests
291
+ * - Close any sync stream ReadableStreams (which will also close any established network requests)
292
+ */
293
+ while (true) {
294
+ let shouldDelayRetry = true;
295
+ let result = null;
296
+ try {
297
+ if (signal?.aborted) {
298
+ break;
299
+ }
300
+ result = await this.streamingSyncIteration(nestedAbortController.signal, options);
301
+ // Continue immediately, streamingSyncIteration will wait before completing if necessary.
302
+ }
303
+ catch (ex) {
304
+ /**
305
+ * Either:
306
+ * - A network request failed with a failed connection or not OKAY response code.
307
+ * - There was a sync processing error.
308
+ * - The connection was aborted.
309
+ * This loop will retry after a delay if the connection was not aborted.
310
+ * The nested abort controller will cleanup any open network requests and streams.
311
+ * The WebRemote should only abort pending fetch requests or close active Readable streams.
312
+ */
313
+ if (ex instanceof AbortOperation) {
314
+ this.logger.log({ level: LogLevels.warn, message: 'Sync aborted', error: ex });
315
+ shouldDelayRetry = false;
316
+ // A disconnect was requested, we should not delay since there is no explicit retry
317
+ }
318
+ else if (this.connectionMayHaveChanged && ex.message?.indexOf('No iteration is active') >= 0) {
319
+ this.connectionMayHaveChanged = false;
320
+ this.logger.log({
321
+ level: LogLevels.info,
322
+ message: 'Sync error after changed connection, retrying immediately'
323
+ });
324
+ shouldDelayRetry = false;
325
+ }
326
+ else {
327
+ this.logger.log({ level: LogLevels.error, message: 'Sync error', error: ex });
328
+ }
329
+ this.updateJsSyncState({ downloadError: ex });
330
+ }
331
+ finally {
332
+ this.checkpoints.downloadIterationEnded();
333
+ this.notifyCompletedUploads = undefined;
334
+ if (!signal.aborted) {
335
+ nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));
336
+ nestedAbortController = new AbortController();
337
+ }
338
+ if (result?.immediateRestart != true) {
339
+ this.markAsDisconnected();
340
+ // On error, wait a little before retrying
341
+ if (shouldDelayRetry) {
342
+ await this.delayRetry(nestedAbortController.signal, options.retryDelayMs, true);
343
+ }
344
+ }
345
+ }
346
+ }
347
+ // Mark as disconnected if here
348
+ this.markAsDisconnected();
349
+ }
350
+ markConnectionMayHaveChanged() {
351
+ // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
352
+ // an active sync iteration on the connection in use.
353
+ this.connectionMayHaveChanged = true;
354
+ // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
355
+ // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
356
+ // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
357
+ this.handleActiveStreamsChange?.();
358
+ }
359
+ /**
360
+ * Older versions of the JS SDK used to encode subkeys as JSON in `OplogEntry.toJSON`.
361
+ * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
362
+ * While this is not a problem as long as it's done consistently, it causes issues when a database
363
+ * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
364
+ * is enabled.
365
+ *
366
+ * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
367
+ * migration is only triggered when necessary (for now). The function returns whether the new format
368
+ * should be used, so that the JS SDK is able to write to updated databases.
369
+ *
370
+ * @param requireFixedKeyFormat - Whether we require the new format or also support the old one.
371
+ * The Rust client requires the new subkey format.
372
+ * @returns Whether the database is now using the new, fixed subkey format.
373
+ */
374
+ async requireKeyFormat(requireFixedKeyFormat) {
375
+ const hasMigrated = await this.options.adapter.hasMigratedSubkeys();
376
+ if (requireFixedKeyFormat && !hasMigrated) {
377
+ await this.options.adapter.migrateToFixedSubkeys();
378
+ return true;
379
+ }
380
+ else {
381
+ return hasMigrated;
382
+ }
383
+ }
384
+ streamingSyncIteration(signal, options) {
385
+ return this.obtainLock({
386
+ type: LockType.SYNC,
387
+ signal,
388
+ callback: async () => {
389
+ // Validate app metadata
390
+ const invalidMetadata = Object.entries(options.appMetadata).filter(([_, value]) => typeof value != 'string');
391
+ if (invalidMetadata.length > 0) {
392
+ throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);
393
+ }
394
+ await this.requireKeyFormat(true);
395
+ return await this.rustSyncIteration(signal, options);
396
+ }
397
+ });
398
+ }
399
+ receiveSyncLines(data) {
400
+ const { options, connection } = data;
401
+ const remote = this.options.remote;
402
+ const openInner = async () => {
403
+ if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
404
+ return await remote.fetchStream(options);
405
+ }
406
+ else {
407
+ return await this.options.remote.socketStreamRaw({
408
+ ...options,
409
+ ...{ fetchStrategy: connection.fetchStrategy }
410
+ });
411
+ }
412
+ };
413
+ let inner;
414
+ let done = false;
415
+ return {
416
+ async next() {
417
+ if (done) {
418
+ return doneResult;
419
+ }
420
+ else if (inner == null) {
421
+ inner = await openInner();
422
+ // We're connected here, so we can tell the core extension about it.
423
+ return valueResult({
424
+ command: PowerSyncControlCommand.CONNECTION_STATE,
425
+ payload: 'established'
426
+ });
427
+ }
428
+ else {
429
+ const event = await inner.next();
430
+ if (event.done) {
431
+ done = true;
432
+ return valueResult({ command: PowerSyncControlCommand.CONNECTION_STATE, payload: 'end' });
433
+ }
434
+ else {
435
+ return valueResult({
436
+ command: typeof event.value == 'string'
437
+ ? PowerSyncControlCommand.PROCESS_TEXT_LINE
438
+ : PowerSyncControlCommand.PROCESS_BSON_LINE,
439
+ payload: event.value
440
+ });
441
+ }
442
+ }
443
+ }
444
+ };
445
+ }
446
+ /**
447
+ * Watches the current checkpoint request id to re-request it if we take too long to receive it.
448
+ *
449
+ * This does not require navigator locks: It waits for checkpoints to be seeded, which can only happen in the context
450
+ * of a download loop.
451
+ *
452
+ * Note that requesting checkpoints with ids the service has already seen is a cheap no-op.
453
+ */
454
+ async repostUnacknowledgedCheckpointRequests(abort, options) {
455
+ let retryDelay;
456
+ const mode = options.checkpointMode;
457
+ if (mode == 'legacy')
458
+ return;
459
+ if (mode == 'requests') {
460
+ retryDelay = 10_000;
461
+ }
462
+ else {
463
+ retryDelay = Math.max(mode.requests.retryDelay, 10_000);
464
+ }
465
+ while (!abort.aborted) {
466
+ try {
467
+ await this.checkpoints.waitForCheckpointRequestsReady(abort, false);
468
+ const requestId = await this.options.adapter.readCheckpointRequestId('current');
469
+ // Give the request some time to sync.
470
+ await this.delayRetry(abort, retryDelay);
471
+ // If a new request was made, reset the timer.
472
+ if (requestId != (await this.options.adapter.readCheckpointRequestId('current'))) {
473
+ continue;
474
+ }
475
+ // If the request was applied, we don't need to retry.
476
+ if (isCheckpointRequestApplied(this.syncStatus?.core, BigInt(requestId))) {
477
+ continue;
478
+ }
479
+ // Make sure we're online and ready before making the request
480
+ await this.checkpoints.waitForCheckpointRequestsReady(abort, false);
481
+ // It's safe if this request races with a new one. The service will reject it.
482
+ this.logger.log({ level: LogLevels.debug, message: `Retry checkpoint request ${requestId}` });
483
+ await this.requestCheckpointFromService(abort, {
484
+ client_id: await this.options.adapter.getClientId(),
485
+ checkpoint_request_id: requestId
486
+ });
487
+ }
488
+ catch (e) {
489
+ if (abort.aborted)
490
+ return;
491
+ this.logger.log({ level: LogLevels.warn, error: e, message: 'Error retrying checkpoint request.' });
492
+ await this.delayRetry(abort, retryDelay);
493
+ }
494
+ }
495
+ }
496
+ async seedCheckpointRequestState(abort, request) {
497
+ const seed = await this.requestCheckpointFromService(abort, request);
498
+ await this.options.adapter.readCheckpointRequestId('seed', seed);
499
+ }
500
+ async rustSyncIteration(signal, resolvedOptions) {
501
+ const syncImplementation = this;
502
+ const adapter = this.options.adapter;
503
+ const remote = this.options.remote;
504
+ let hideDisconnectOnRestart = false;
505
+ let notifyTokenRefreshed;
506
+ if (signal.aborted) {
507
+ throw new AbortOperation('Connection request has been aborted');
508
+ }
509
+ const serializedSchema = this.options.serializedSchema;
510
+ function startCommand() {
511
+ const options = {
512
+ parameters: resolvedOptions.params,
513
+ app_metadata: resolvedOptions.appMetadata,
514
+ active_streams: syncImplementation.activeStreams,
515
+ include_defaults: resolvedOptions.includeDefaultStreams,
516
+ checkpoint_mode: resolvedOptions.checkpointMode === 'legacy' ? 'legacy' : 'requests'
517
+ };
518
+ if (serializedSchema) {
519
+ options.schema = serializedSchema;
520
+ }
521
+ return invokePowerSyncControl(PowerSyncControlCommand.START, JSON.stringify(options));
522
+ }
523
+ async function stop() {
524
+ const instructions = await invokePowerSyncControl(PowerSyncControlCommand.STOP);
525
+ for (const instruction of instructions) {
526
+ // We don't need to handle interrupting instructions since we're unconditionally ending the sync iteration at
527
+ // this point.
528
+ if (isInterruptingInstruction(instruction))
529
+ continue;
530
+ await handleInstruction(instruction);
531
+ }
532
+ }
533
+ async function invokePowerSyncControl(op, payload) {
534
+ const rawResponse = await adapter.control(op, payload ?? null);
535
+ const payloadDesc = payload == null || typeof payload == 'string' ? payload : '<bytes>';
536
+ syncImplementation.logger.log({
537
+ level: LogLevels.trace,
538
+ message: `powersync_control(${op}, ${payloadDesc}) -> ${rawResponse}`
539
+ });
540
+ if (op != PowerSyncControlCommand.STOP) {
541
+ // Evidently we have a working connection here, otherwise powersync_control would have failed.
542
+ syncImplementation.connectionMayHaveChanged = false;
543
+ }
544
+ return JSON.parse(rawResponse);
545
+ }
546
+ async function handleInstruction(instruction) {
547
+ if ('LogLine' in instruction) {
548
+ const { severity, line } = instruction.LogLine;
549
+ switch (severity) {
550
+ case 'DEBUG':
551
+ syncImplementation.logger.log({
552
+ level: LogLevels.debug,
553
+ message: line
554
+ });
555
+ break;
556
+ case 'INFO':
557
+ syncImplementation.logger.log({
558
+ level: LogLevels.info,
559
+ message: line
560
+ });
561
+ break;
562
+ case 'WARNING':
563
+ syncImplementation.logger.log({
564
+ level: LogLevels.warn,
565
+ message: line
566
+ });
567
+ break;
568
+ }
569
+ }
570
+ else if ('UpdateSyncStatus' in instruction) {
571
+ syncImplementation.updateSyncStatus(instruction.UpdateSyncStatus.status);
572
+ }
573
+ else if ('FetchCredentials' in instruction) {
574
+ if (instruction.FetchCredentials.did_expire) {
575
+ remote.invalidateCredentials();
576
+ }
577
+ else {
578
+ remote.invalidateCredentials();
579
+ // Restart iteration after the credentials have been refreshed.
580
+ remote.fetchCredentials().then((_) => {
581
+ notifyTokenRefreshed?.();
582
+ }, (err) => {
583
+ syncImplementation.logger.log({
584
+ level: LogLevels.warn,
585
+ message: 'Could not prefetch credentials',
586
+ error: err
587
+ });
588
+ });
589
+ }
590
+ }
591
+ else if ('FlushFileSystem' in instruction) {
592
+ // Not necessary on JS platforms.
593
+ }
594
+ else if ('DidCompleteSync' in instruction) {
595
+ syncImplementation.updateJsSyncState({ downloadError: undefined });
596
+ }
597
+ }
598
+ try {
599
+ const defaultResult = { immediateRestart: false };
600
+ // Pending sync lines received from the service, as well as local events that trigger a powersync_control
601
+ // invocation (local events include refreshed tokens and completed uploads).
602
+ // This is a single data stream so that we can handle all control calls from a single place.
603
+ let controlInvocations = null;
604
+ for (const startInstruction of await startCommand()) {
605
+ if ('EstablishSyncStream' in startInstruction) {
606
+ const establish = startInstruction.EstablishSyncStream;
607
+ const syncOptions = {
608
+ path: '/sync/stream',
609
+ abortSignal: signal,
610
+ data: establish.request
611
+ };
612
+ controlInvocations = injectable(syncImplementation.receiveSyncLines({
613
+ options: syncOptions,
614
+ connection: resolvedOptions
615
+ }));
616
+ if (establish.checkpoint_request) {
617
+ // Start checkpoint request validation concurrently, without blocking line processing on it. We reconcile
618
+ // checkpoint states on each started download iteration to:
619
+ // 1. Align service and client checkpoint ids, allowing both parties to safely forget old checkpoints.
620
+ // 2. If the user id changes between connections, agreeing on the highest checkpoint request between the
621
+ // old and new user to make sure we'll receive that checkpoint eventually.
622
+ const seed = this.checkpoints.markCheckpointsReady(this.seedCheckpointRequestState(signal, establish.checkpoint_request));
623
+ seed.catch((e) => {
624
+ // Make the download iteration fail if checkpoint requests are broken.
625
+ if (!signal.aborted) {
626
+ controlInvocations?.injectError(e);
627
+ }
628
+ });
629
+ }
630
+ }
631
+ else if ('CloseSyncStream' in startInstruction) {
632
+ return defaultResult;
633
+ }
634
+ else {
635
+ await handleInstruction(startInstruction);
636
+ }
637
+ }
638
+ if (controlInvocations == null)
639
+ return defaultResult;
640
+ this.notifyCompletedUploads = () => {
641
+ controlInvocations.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
642
+ };
643
+ this.handleActiveStreamsChange = () => {
644
+ controlInvocations.inject({
645
+ command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
646
+ payload: JSON.stringify(this.activeStreams)
647
+ });
648
+ };
649
+ notifyTokenRefreshed = () => {
650
+ controlInvocations.inject({
651
+ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED
652
+ });
653
+ };
654
+ let hadSyncLine = false;
655
+ loop: while (true) {
656
+ const { done, value } = await controlInvocations.next();
657
+ if (done)
658
+ break;
659
+ if (!hadSyncLine) {
660
+ // Trigger a local CRUD upload when the first sync line has been received, this allows uploading local changes
661
+ // that have been made while offline or disconnected.
662
+ if (value.command == PowerSyncControlCommand.PROCESS_TEXT_LINE ||
663
+ value.command == PowerSyncControlCommand.PROCESS_BSON_LINE) {
664
+ hadSyncLine = true;
665
+ this.triggerCrudUpload?.();
666
+ }
667
+ }
668
+ const instructions = await invokePowerSyncControl(value.command, value.payload);
669
+ for (const instruction of instructions) {
670
+ if ('EstablishSyncStream' in instruction) {
671
+ throw new Error('Received EstablishSyncStream while already connected.');
672
+ }
673
+ else if ('CloseSyncStream' in instruction) {
674
+ hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
675
+ break loop;
676
+ }
677
+ else {
678
+ await handleInstruction(instruction);
679
+ }
680
+ }
681
+ }
682
+ }
683
+ finally {
684
+ this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
685
+ notifyTokenRefreshed = undefined;
686
+ await stop();
687
+ }
688
+ return { immediateRestart: hideDisconnectOnRestart };
689
+ }
690
+ updateSyncStatus(core, jsState) {
691
+ const updated = new SyncStatusSnapshot(core, {
692
+ ...this.syncStatus.jsState,
693
+ ...jsState
694
+ });
695
+ if (!this.syncStatus.isEqual(updated)) {
696
+ this.syncStatus = updated;
697
+ // Only trigger this is there was a change
698
+ this.iterateListeners((cb) => cb.statusChanged?.(updated));
699
+ }
700
+ }
701
+ updateJsSyncState(state) {
702
+ this.updateSyncStatus(this.syncStatus.core, state);
703
+ }
704
+ async delayRetry(signal, delay, resumeOnCheckpointRequest = false) {
705
+ return new Promise((resolve) => {
706
+ if (signal.aborted) {
707
+ // If the signal is already aborted, resolve immediately
708
+ resolve();
709
+ return;
710
+ }
711
+ let nested = null;
712
+ let timeoutId;
713
+ const endDelay = () => {
714
+ resolve();
715
+ if (timeoutId) {
716
+ clearTimeout(timeoutId);
717
+ timeoutId = undefined;
718
+ }
719
+ if (nested) {
720
+ nested.abort();
721
+ nested = null;
722
+ }
723
+ signal.removeEventListener('abort', endDelay);
724
+ };
725
+ signal.addEventListener('abort', endDelay, { once: true });
726
+ // Add a random +/- 10% jitter to the retry delay.
727
+ const randomizedDelay = delay * (0.9 + Math.random() * 0.2);
728
+ timeoutId = setTimeout(endDelay, randomizedDelay);
729
+ if (resumeOnCheckpointRequest) {
730
+ nested = new AbortController();
731
+ this.checkpoints.waitForCheckpointWaiter(nested.signal).finally(endDelay);
732
+ }
733
+ });
734
+ }
735
+ updateSubscriptions(subscriptions) {
736
+ this.activeStreams = subscriptions;
737
+ this.handleActiveStreamsChange?.();
738
+ }
739
+ }
740
+ //# sourceMappingURL=AbstractStreamingSyncImplementation.js.map