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