@powersync/common 0.0.0-dev-20240509084320 → 0.0.0-dev-20240606141637

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.
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { Mutex } from 'async-mutex';
3
2
  import { ILogger } from 'js-logger';
4
3
  import { DBAdapter, QueryResult, Transaction } from '../db/DBAdapter';
@@ -10,7 +9,7 @@ import { PowerSyncBackendConnector } from './connection/PowerSyncBackendConnecto
10
9
  import { BucketStorageAdapter } from './sync/bucket/BucketStorageAdapter';
11
10
  import { CrudBatch } from './sync/bucket/CrudBatch';
12
11
  import { CrudTransaction } from './sync/bucket/CrudTransaction';
13
- import { AbstractStreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncImplementation } from './sync/stream/AbstractStreamingSyncImplementation';
12
+ import { AbstractStreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncImplementation, PowerSyncConnectionOptions } from './sync/stream/AbstractStreamingSyncImplementation';
14
13
  export interface DisconnectAndClearOptions {
15
14
  /** When set to false, data in local-only tables is preserved. */
16
15
  clearLocal?: boolean;
@@ -51,7 +50,7 @@ export interface WatchHandler {
51
50
  onError?: (error: Error) => void;
52
51
  }
53
52
  export interface WatchOnChangeHandler {
54
- onChange: (event: WatchOnChangeEvent) => void;
53
+ onChange: (event: WatchOnChangeEvent) => Promise<void> | void;
55
54
  onError?: (error: Error) => void;
56
55
  }
57
56
  export interface PowerSyncDBListener extends StreamingSyncImplementationListener {
@@ -153,7 +152,7 @@ export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<Pow
153
152
  /**
154
153
  * Connects to stream of events from the PowerSync instance.
155
154
  */
156
- connect(connector: PowerSyncBackendConnector): Promise<void>;
155
+ connect(connector: PowerSyncBackendConnector, options?: PowerSyncConnectionOptions): Promise<void>;
157
156
  /**
158
157
  * Close the sync connection.
159
158
  *
@@ -13,6 +13,7 @@ import { CrudBatch } from './sync/bucket/CrudBatch';
13
13
  import { CrudEntry } from './sync/bucket/CrudEntry';
14
14
  import { CrudTransaction } from './sync/bucket/CrudTransaction';
15
15
  import { DEFAULT_CRUD_UPLOAD_THROTTLE_MS } from './sync/stream/AbstractStreamingSyncImplementation';
16
+ import { ControlledExecutor } from '../utils/ControlledExecutor';
16
17
  const POWERSYNC_TABLE_MATCH = /(^ps_data__|^ps_data_local__)/;
17
18
  const DEFAULT_DISCONNECT_CLEAR_OPTIONS = {
18
19
  clearLocal: true
@@ -192,7 +193,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
192
193
  /**
193
194
  * Connects to stream of events from the PowerSync instance.
194
195
  */
195
- async connect(connector) {
196
+ async connect(connector, options) {
196
197
  await this.waitForReady();
197
198
  // close connection if one is open
198
199
  await this.disconnect();
@@ -202,13 +203,16 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
202
203
  this.syncStreamImplementation = this.generateSyncStreamImplementation(connector);
203
204
  this.syncStatusListenerDisposer = this.syncStreamImplementation.registerListener({
204
205
  statusChanged: (status) => {
205
- this.currentStatus = new SyncStatus({ ...status.toJSON(), hasSynced: this.currentStatus?.hasSynced });
206
+ this.currentStatus = new SyncStatus({
207
+ ...status.toJSON(),
208
+ hasSynced: this.currentStatus?.hasSynced || !!status.lastSyncedAt
209
+ });
206
210
  this.iterateListeners((cb) => cb.statusChanged?.(this.currentStatus));
207
211
  }
208
212
  });
209
213
  await this.syncStreamImplementation.waitForReady();
210
214
  this.syncStreamImplementation.triggerCrudUpload();
211
- await this.syncStreamImplementation.connect();
215
+ await this.syncStreamImplementation.connect(options);
212
216
  }
213
217
  /**
214
218
  * Close the sync connection.
@@ -528,7 +532,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
528
532
  .filter((row) => row.opcode == 'OpenRead' && row.p3 == 0 && typeof row.p2 == 'number')
529
533
  .map((row) => row.p2);
530
534
  const tables = await this.getAll(`SELECT DISTINCT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?))`, [JSON.stringify(rootPages)]);
531
- for (let table of tables) {
535
+ for (const table of tables) {
532
536
  resolvedTables.push(table.tbl_name.replace(POWERSYNC_TABLE_MATCH, ''));
533
537
  }
534
538
  }
@@ -562,10 +566,13 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
562
566
  const watchedTables = new Set(resolvedOptions.tables ?? []);
563
567
  const changedTables = new Set();
564
568
  const throttleMs = resolvedOptions.throttleMs ?? DEFAULT_WATCH_THROTTLE_MS;
569
+ const executor = new ControlledExecutor(async (e) => {
570
+ await onChange(e);
571
+ });
565
572
  const flushTableUpdates = throttle(() => this.handleTableChanges(changedTables, watchedTables, (intersection) => {
566
573
  if (resolvedOptions?.signal?.aborted)
567
574
  return;
568
- onChange({ changedTables: intersection });
575
+ executor.schedule({ changedTables: intersection });
569
576
  }), throttleMs, { leading: false, trailing: true });
570
577
  const dispose = this.database.registerListener({
571
578
  tablesUpdated: async (update) => {
@@ -580,6 +587,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
580
587
  }
581
588
  });
582
589
  resolvedOptions.signal?.addEventListener('abort', () => {
590
+ executor.dispose();
583
591
  dispose();
584
592
  });
585
593
  return () => dispose();
@@ -631,7 +639,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
631
639
  const mappedTableNames = rawTableNames
632
640
  ? filteredTables
633
641
  : filteredTables.map((t) => t.replace(POWERSYNC_TABLE_MATCH, ''));
634
- for (let table of mappedTableNames) {
642
+ for (const table of mappedTableNames) {
635
643
  changedTables.add(table);
636
644
  }
637
645
  }
@@ -2,4 +2,5 @@ export interface PowerSyncCredentials {
2
2
  endpoint: string;
3
3
  token: string;
4
4
  expiresAt?: Date;
5
+ params?: Record<string, string>;
5
6
  }
@@ -1,4 +1,3 @@
1
- import { v4 as uuid } from 'uuid';
2
1
  import { extractTableUpdates } from '../../../db/DBAdapter';
3
2
  import { PSInternalTable } from './BucketStorageAdapter';
4
3
  import { OpTypeEnum } from './OpType';
@@ -84,10 +83,10 @@ export class SqliteBucketStorage extends BaseObserver {
84
83
  // To achieve this, we rename the bucket to a new temp name, and change all ops to remove.
85
84
  // By itself, this new bucket would ensure that the previous objects are deleted if they contain no more references.
86
85
  // If the old bucket is re-added, this new bucket would have no effect.
87
- const newName = `$delete_${bucket}_${uuid()}`;
88
- this.logger.debug('Deleting bucket', bucket);
89
- // This
90
86
  await this.writeTransaction(async (tx) => {
87
+ const { uuid } = await tx.get('select uuid() as uuid');
88
+ const newName = `$delete_${bucket}_${uuid}`;
89
+ this.logger.debug('Deleting bucket', bucket);
91
90
  await tx.execute(`UPDATE ps_oplog SET op=${OpTypeEnum.REMOVE}, data=NULL WHERE op=${OpTypeEnum.PUT} AND superseded=0 AND bucket=?`, [bucket]);
92
91
  // Rename bucket
93
92
  await tx.execute('UPDATE ps_oplog SET bucket=? WHERE bucket=?', [newName, bucket]);
@@ -1,15 +1,57 @@
1
- /// <reference types="node" />
2
1
  import { ILogger } from 'js-logger';
2
+ import { fetch } from 'cross-fetch';
3
3
  import { PowerSyncCredentials } from '../../connection/PowerSyncCredentials';
4
+ import { StreamingSyncLine, StreamingSyncRequest } from './streaming-sync-types';
5
+ import { DataStream } from '../../../utils/DataStream';
6
+ import type { BSON } from 'bson';
7
+ export type BSONImplementation = typeof BSON;
4
8
  export type RemoteConnector = {
5
9
  fetchCredentials: () => Promise<PowerSyncCredentials | null>;
6
10
  };
7
11
  export declare const DEFAULT_REMOTE_LOGGER: ILogger;
12
+ export type SyncStreamOptions = {
13
+ path: string;
14
+ data: StreamingSyncRequest;
15
+ headers?: Record<string, string>;
16
+ abortSignal?: AbortSignal;
17
+ fetchOptions?: Request;
18
+ };
19
+ export type FetchImplementation = typeof fetch;
20
+ /**
21
+ * Class wrapper for providing a fetch implementation.
22
+ * The class wrapper is used to distinguish the fetchImplementation
23
+ * option in [AbstractRemoteOptions] from the general fetch method
24
+ * which is typeof "function"
25
+ */
26
+ export declare class FetchImplementationProvider {
27
+ getFetch(): FetchImplementation;
28
+ }
29
+ export type AbstractRemoteOptions = {
30
+ /**
31
+ * Transforms the PowerSync base URL which might contain
32
+ * `http(s)://` to the corresponding WebSocket variant
33
+ * e.g. `ws(s)://`
34
+ */
35
+ socketUrlTransformer: (url: string) => string;
36
+ /**
37
+ * Optionally provide the fetch implementation to use.
38
+ * Note that this usually needs to be bound to the global scope.
39
+ * Binding should be done before passing here.
40
+ */
41
+ fetchImplementation: FetchImplementation | FetchImplementationProvider;
42
+ };
43
+ export declare const DEFAULT_REMOTE_OPTIONS: AbstractRemoteOptions;
8
44
  export declare abstract class AbstractRemote {
9
45
  protected connector: RemoteConnector;
10
46
  protected logger: ILogger;
11
47
  protected credentials: PowerSyncCredentials | null;
12
- constructor(connector: RemoteConnector, logger?: ILogger);
48
+ protected options: AbstractRemoteOptions;
49
+ constructor(connector: RemoteConnector, logger?: ILogger, options?: Partial<AbstractRemoteOptions>);
50
+ /**
51
+ * @returns a fetch implementation (function)
52
+ * which can be called to perform fetch requests
53
+ */
54
+ get fetch(): FetchImplementation;
13
55
  getCredentials(): Promise<PowerSyncCredentials | null>;
14
56
  protected buildRequest(path: string): Promise<{
15
57
  url: string;
@@ -18,8 +60,19 @@ export declare abstract class AbstractRemote {
18
60
  Authorization: string;
19
61
  };
20
62
  }>;
21
- abstract post(path: string, data: any, headers?: Record<string, string>): Promise<any>;
22
- abstract get(path: string, headers?: Record<string, string>): Promise<any>;
23
- abstract postStreaming(path: string, data: any, headers?: Record<string, string>, signal?: AbortSignal): Promise<any>;
24
- isAvailable(): boolean;
63
+ post(path: string, data: any, headers?: Record<string, string>): Promise<any>;
64
+ get(path: string, headers?: Record<string, string>): Promise<any>;
65
+ postStreaming(path: string, data: any, headers?: Record<string, string>, signal?: AbortSignal): Promise<any>;
66
+ /**
67
+ * Provides a BSON implementation. The import nature of this varies depending on the platform
68
+ */
69
+ abstract getBSON(): Promise<BSONImplementation>;
70
+ /**
71
+ * Connects to the sync/stream websocket endpoint
72
+ */
73
+ socketStream(options: SyncStreamOptions): Promise<DataStream<StreamingSyncLine>>;
74
+ /**
75
+ * Connects to the sync/stream http endpoint
76
+ */
77
+ postStream(options: SyncStreamOptions): Promise<DataStream<StreamingSyncLine>>;
25
78
  }
@@ -1,14 +1,59 @@
1
1
  import Logger from 'js-logger';
2
+ import { fetch } from 'cross-fetch';
3
+ import { DataStream } from '../../../utils/DataStream';
4
+ import ndjsonStream from 'can-ndjson-stream';
5
+ import { RSocketConnector } from 'rsocket-core';
6
+ import { WebsocketClientTransport } from 'rsocket-websocket-client';
7
+ import { AbortOperation } from '../../../utils/AbortOperation';
8
+ import { Buffer } from 'buffer';
2
9
  // Refresh at least 30 sec before it expires
3
10
  const REFRESH_CREDENTIALS_SAFETY_PERIOD_MS = 30_000;
11
+ const SYNC_QUEUE_REQUEST_N = 10;
12
+ const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
13
+ // Keep alive message is sent every period
14
+ const KEEP_ALIVE_MS = 20_000;
15
+ // The ACK must be received in this period
16
+ const KEEP_ALIVE_LIFETIME_MS = 30_000;
4
17
  export const DEFAULT_REMOTE_LOGGER = Logger.get('PowerSyncRemote');
18
+ /**
19
+ * Class wrapper for providing a fetch implementation.
20
+ * The class wrapper is used to distinguish the fetchImplementation
21
+ * option in [AbstractRemoteOptions] from the general fetch method
22
+ * which is typeof "function"
23
+ */
24
+ export class FetchImplementationProvider {
25
+ getFetch() {
26
+ return fetch.bind(globalThis);
27
+ }
28
+ }
29
+ export const DEFAULT_REMOTE_OPTIONS = {
30
+ socketUrlTransformer: (url) => url.replace(/^https?:\/\//, function (match) {
31
+ return match === 'https://' ? 'wss://' : 'ws://';
32
+ }),
33
+ fetchImplementation: new FetchImplementationProvider()
34
+ };
5
35
  export class AbstractRemote {
6
36
  connector;
7
37
  logger;
8
38
  credentials = null;
9
- constructor(connector, logger = DEFAULT_REMOTE_LOGGER) {
39
+ options;
40
+ constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {
10
41
  this.connector = connector;
11
42
  this.logger = logger;
43
+ this.options = {
44
+ ...DEFAULT_REMOTE_OPTIONS,
45
+ ...(options ?? {})
46
+ };
47
+ }
48
+ /**
49
+ * @returns a fetch implementation (function)
50
+ * which can be called to perform fetch requests
51
+ */
52
+ get fetch() {
53
+ const { fetchImplementation } = this.options;
54
+ return fetchImplementation instanceof FetchImplementationProvider
55
+ ? fetchImplementation.getFetch()
56
+ : fetchImplementation;
12
57
  }
13
58
  async getCredentials() {
14
59
  const { expiresAt } = this.credentials ?? {};
@@ -36,7 +81,300 @@ export class AbstractRemote {
36
81
  }
37
82
  };
38
83
  }
39
- isAvailable() {
40
- return true;
84
+ async post(path, data, headers = {}) {
85
+ const request = await this.buildRequest(path);
86
+ const res = await fetch(request.url, {
87
+ method: 'POST',
88
+ headers: {
89
+ ...headers,
90
+ ...request.headers
91
+ },
92
+ body: JSON.stringify(data)
93
+ });
94
+ if (!res.ok) {
95
+ throw new Error(`Received ${res.status} - ${res.statusText} when posting to ${path}: ${await res.text()}}`);
96
+ }
97
+ return res.json();
98
+ }
99
+ async get(path, headers) {
100
+ const request = await this.buildRequest(path);
101
+ const res = await this.fetch(request.url, {
102
+ method: 'GET',
103
+ headers: {
104
+ ...headers,
105
+ ...request.headers
106
+ }
107
+ });
108
+ if (!res.ok) {
109
+ throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
110
+ }
111
+ return res.json();
112
+ }
113
+ async postStreaming(path, data, headers = {}, signal) {
114
+ const request = await this.buildRequest(path);
115
+ const res = await this.fetch(request.url, {
116
+ method: 'POST',
117
+ headers: { ...headers, ...request.headers },
118
+ body: JSON.stringify(data),
119
+ signal,
120
+ cache: 'no-store'
121
+ }).catch((ex) => {
122
+ this.logger.error(`Caught ex when POST streaming to ${path}`, ex);
123
+ throw ex;
124
+ });
125
+ if (!res.ok) {
126
+ const text = await res.text();
127
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
128
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
129
+ error.status = res.status;
130
+ throw error;
131
+ }
132
+ return res;
133
+ }
134
+ /**
135
+ * Connects to the sync/stream websocket endpoint
136
+ */
137
+ async socketStream(options) {
138
+ const { path } = options;
139
+ const request = await this.buildRequest(path);
140
+ const bson = await this.getBSON();
141
+ const connector = new RSocketConnector({
142
+ transport: new WebsocketClientTransport({
143
+ url: this.options.socketUrlTransformer(request.url)
144
+ }),
145
+ setup: {
146
+ keepAlive: KEEP_ALIVE_MS,
147
+ lifetime: KEEP_ALIVE_LIFETIME_MS,
148
+ dataMimeType: 'application/bson',
149
+ metadataMimeType: 'application/bson',
150
+ payload: {
151
+ data: null,
152
+ metadata: Buffer.from(bson.serialize({
153
+ token: request.headers.Authorization
154
+ }))
155
+ }
156
+ }
157
+ });
158
+ let rsocket;
159
+ try {
160
+ rsocket = await connector.connect();
161
+ }
162
+ catch (ex) {
163
+ /**
164
+ * On React native the connection exception can be `undefined` this causes issues
165
+ * with detecting the exception inside async-mutex
166
+ */
167
+ throw new Error(`Could not connect to PowerSync instance: ${JSON.stringify(ex)}`);
168
+ }
169
+ const stream = new DataStream({
170
+ logger: this.logger,
171
+ pressure: {
172
+ lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
173
+ }
174
+ });
175
+ let socketIsClosed = false;
176
+ const closeSocket = () => {
177
+ if (socketIsClosed) {
178
+ return;
179
+ }
180
+ socketIsClosed = true;
181
+ rsocket.close();
182
+ };
183
+ // We initially request this amount and expect these to arrive eventually
184
+ let pendingEventsCount = SYNC_QUEUE_REQUEST_N;
185
+ const socket = await new Promise((resolve, reject) => {
186
+ let connectionEstablished = false;
187
+ const res = rsocket.requestStream({
188
+ data: Buffer.from(bson.serialize(options.data)),
189
+ metadata: Buffer.from(bson.serialize({
190
+ path
191
+ }))
192
+ }, SYNC_QUEUE_REQUEST_N, // The initial N amount
193
+ {
194
+ onError: (e) => {
195
+ // Don't log closed as an error
196
+ if (e.message !== 'Closed. ') {
197
+ this.logger.error(e);
198
+ }
199
+ // RSocket will close this automatically
200
+ // Attempting to close multiple times causes a console warning
201
+ socketIsClosed = true;
202
+ stream.close();
203
+ // Handles cases where the connection failed e.g. auth error or connection error
204
+ if (!connectionEstablished) {
205
+ reject(e);
206
+ }
207
+ },
208
+ onNext: (payload) => {
209
+ // The connection is active
210
+ if (!connectionEstablished) {
211
+ connectionEstablished = true;
212
+ resolve(res);
213
+ }
214
+ const { data } = payload;
215
+ // Less events are now pending
216
+ pendingEventsCount--;
217
+ if (!data) {
218
+ return;
219
+ }
220
+ const deserializedData = bson.deserialize(data);
221
+ stream.enqueueData(deserializedData);
222
+ },
223
+ onComplete: () => {
224
+ stream.close();
225
+ },
226
+ onExtension: () => { }
227
+ });
228
+ });
229
+ const l = stream.registerListener({
230
+ lowWater: async () => {
231
+ // Request to fill up the queue
232
+ const required = SYNC_QUEUE_REQUEST_N - pendingEventsCount;
233
+ if (required > 0) {
234
+ socket.request(SYNC_QUEUE_REQUEST_N - pendingEventsCount);
235
+ pendingEventsCount = SYNC_QUEUE_REQUEST_N;
236
+ }
237
+ },
238
+ closed: () => {
239
+ closeSocket();
240
+ l?.();
241
+ }
242
+ });
243
+ /**
244
+ * Handle abort operations here.
245
+ * Unfortunately cannot insert them into the connection.
246
+ */
247
+ if (options.abortSignal?.aborted) {
248
+ stream.close();
249
+ }
250
+ else {
251
+ options.abortSignal?.addEventListener('abort', () => {
252
+ stream.close();
253
+ });
254
+ }
255
+ return stream;
256
+ }
257
+ /**
258
+ * Connects to the sync/stream http endpoint
259
+ */
260
+ async postStream(options) {
261
+ const { data, path, headers, abortSignal } = options;
262
+ const request = await this.buildRequest(path);
263
+ /**
264
+ * This abort controller will abort pending fetch requests.
265
+ * If the request has resolved, it will be used to close the readable stream.
266
+ * Which will cancel the network request.
267
+ *
268
+ * This nested controller is required since:
269
+ * Aborting the active fetch request while it is being consumed seems to throw
270
+ * an unhandled exception on the window level.
271
+ */
272
+ const controller = new AbortController();
273
+ let requestResolved = false;
274
+ abortSignal?.addEventListener('abort', () => {
275
+ if (!requestResolved) {
276
+ // Only abort via the abort controller if the request has not resolved yet
277
+ controller.abort(abortSignal.reason ??
278
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));
279
+ }
280
+ });
281
+ const res = await this.fetch(request.url, {
282
+ method: 'POST',
283
+ headers: { ...headers, ...request.headers },
284
+ body: JSON.stringify(data),
285
+ signal: controller.signal,
286
+ cache: 'no-store',
287
+ ...options.fetchOptions
288
+ }).catch((ex) => {
289
+ if (ex.name == 'AbortError') {
290
+ throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
291
+ }
292
+ throw ex;
293
+ });
294
+ if (!res) {
295
+ throw new Error('Fetch request was aborted');
296
+ }
297
+ requestResolved = true;
298
+ if (!res.ok || !res.body) {
299
+ const text = await res.text();
300
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
301
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
302
+ error.status = res.status;
303
+ throw error;
304
+ }
305
+ /**
306
+ * The can-ndjson-stream does not handle aborted streams well.
307
+ * This will intercept the readable stream and close the stream if
308
+ * aborted.
309
+ */
310
+ const reader = res.body.getReader();
311
+ // This will close the network request and read stream
312
+ const closeReader = async () => {
313
+ try {
314
+ await reader.cancel();
315
+ }
316
+ catch (ex) {
317
+ // an error will throw if the reader hasn't been used yet
318
+ }
319
+ reader.releaseLock();
320
+ };
321
+ abortSignal?.addEventListener('abort', () => {
322
+ closeReader();
323
+ });
324
+ const outputStream = new ReadableStream({
325
+ start: (controller) => {
326
+ const processStream = async () => {
327
+ while (!abortSignal?.aborted) {
328
+ try {
329
+ const { done, value } = await reader.read();
330
+ // When no more data needs to be consumed, close the stream
331
+ if (done) {
332
+ break;
333
+ }
334
+ // Enqueue the next data chunk into our target stream
335
+ controller.enqueue(value);
336
+ }
337
+ catch (ex) {
338
+ this.logger.error('Caught exception when reading sync stream', ex);
339
+ break;
340
+ }
341
+ }
342
+ if (!abortSignal?.aborted) {
343
+ // Close the downstream readable stream
344
+ await closeReader();
345
+ }
346
+ controller.close();
347
+ };
348
+ processStream();
349
+ }
350
+ });
351
+ const jsonS = ndjsonStream(new Response(outputStream).body);
352
+ const stream = new DataStream({
353
+ logger: this.logger
354
+ });
355
+ const r = jsonS.getReader();
356
+ const l = stream.registerListener({
357
+ lowWater: async () => {
358
+ try {
359
+ const { done, value } = await r.read();
360
+ // Exit if we're done
361
+ if (done) {
362
+ stream.close();
363
+ l?.();
364
+ return;
365
+ }
366
+ stream.enqueueData(value);
367
+ }
368
+ catch (ex) {
369
+ stream.close();
370
+ throw ex;
371
+ }
372
+ },
373
+ closed: () => {
374
+ closeReader();
375
+ l?.();
376
+ }
377
+ });
378
+ return stream;
41
379
  }
42
380
  }
@@ -1,6 +1,4 @@
1
- /// <reference types="node" />
2
1
  import { ILogger } from 'js-logger';
3
- import { StreamingSyncLine, StreamingSyncRequest } from './streaming-sync-types';
4
2
  import { AbstractRemote } from './AbstractRemote';
5
3
  import { BucketStorageAdapter } from '../bucket/BucketStorageAdapter';
6
4
  import { SyncStatus, SyncStatusOptions } from '../../../db/crud/SyncStatus';
@@ -9,6 +7,10 @@ export declare enum LockType {
9
7
  CRUD = "crud",
10
8
  SYNC = "sync"
11
9
  }
10
+ export declare enum SyncStreamConnectionMethod {
11
+ HTTP = "http",
12
+ WEB_SOCKET = "web-socket"
13
+ }
12
14
  /**
13
15
  * Abstract Lock to be implemented by various JS environments
14
16
  */
@@ -41,11 +43,23 @@ export interface StreamingSyncImplementationListener extends BaseListener {
41
43
  */
42
44
  statusChanged?: ((status: SyncStatus) => void) | undefined;
43
45
  }
46
+ /**
47
+ * Configurable options to be used when connecting to the PowerSync
48
+ * backend instance.
49
+ */
50
+ export interface PowerSyncConnectionOptions {
51
+ /**
52
+ * The connection method to use when streaming updates from
53
+ * the PowerSync backend instance.
54
+ * Defaults to a HTTP streaming connection.
55
+ */
56
+ connectionMethod?: SyncStreamConnectionMethod;
57
+ }
44
58
  export interface StreamingSyncImplementation extends BaseObserver<StreamingSyncImplementationListener>, Disposable {
45
59
  /**
46
60
  * Connects to the sync service
47
61
  */
48
- connect(): Promise<void>;
62
+ connect(options?: PowerSyncConnectionOptions): Promise<void>;
49
63
  /**
50
64
  * Disconnects from the sync services.
51
65
  * @throws if not connected or if abort is not controlled internally
@@ -66,6 +80,7 @@ export declare const DEFAULT_STREAMING_SYNC_OPTIONS: {
66
80
  logger: ILogger;
67
81
  crudUploadThrottleMs: number;
68
82
  };
83
+ export declare const DEFAULT_STREAM_CONNECTION_OPTIONS: Required<PowerSyncConnectionOptions>;
69
84
  export declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<StreamingSyncImplementationListener> implements StreamingSyncImplementation {
70
85
  protected _lastSyncedAt: Date | null;
71
86
  protected options: AbstractStreamingSyncImplementationOptions;
@@ -86,16 +101,15 @@ export declare abstract class AbstractStreamingSyncImplementation extends BaseOb
86
101
  getWriteCheckpoint(): Promise<string>;
87
102
  protected _uploadAllCrud(): Promise<void>;
88
103
  protected uploadCrudBatch(): Promise<boolean>;
89
- connect(): Promise<void>;
104
+ connect(options?: PowerSyncConnectionOptions): Promise<void>;
90
105
  disconnect(): Promise<void>;
91
106
  /**
92
107
  * @deprecated use [connect instead]
93
108
  */
94
- streamingSync(signal?: AbortSignal): Promise<void>;
95
- protected streamingSyncIteration(signal: AbortSignal, progress?: () => void): Promise<{
109
+ streamingSync(signal?: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void>;
110
+ protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<{
96
111
  retry?: boolean;
97
112
  }>;
98
- protected streamingSyncRequest(req: StreamingSyncRequest, signal?: AbortSignal): AsyncGenerator<StreamingSyncLine>;
99
113
  protected updateSyncStatus(options: SyncStatusOptions): void;
100
114
  private delayRetry;
101
115
  }
@@ -1,7 +1,6 @@
1
1
  import throttle from 'lodash/throttle';
2
2
  import Logger from 'js-logger';
3
3
  import { isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncData } from './streaming-sync-types';
4
- import ndjsonStream from 'can-ndjson-stream';
5
4
  import { SyncStatus } from '../../../db/crud/SyncStatus';
6
5
  import { SyncDataBucket } from '../bucket/SyncDataBucket';
7
6
  import { BaseObserver } from '../../../utils/BaseObserver';
@@ -11,12 +10,20 @@ export var LockType;
11
10
  LockType["CRUD"] = "crud";
12
11
  LockType["SYNC"] = "sync";
13
12
  })(LockType || (LockType = {}));
13
+ export var SyncStreamConnectionMethod;
14
+ (function (SyncStreamConnectionMethod) {
15
+ SyncStreamConnectionMethod["HTTP"] = "http";
16
+ SyncStreamConnectionMethod["WEB_SOCKET"] = "web-socket";
17
+ })(SyncStreamConnectionMethod || (SyncStreamConnectionMethod = {}));
14
18
  export const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
15
19
  export const DEFAULT_STREAMING_SYNC_OPTIONS = {
16
20
  retryDelayMs: 5000,
17
21
  logger: Logger.get('PowerSyncStream'),
18
22
  crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS
19
23
  };
24
+ export const DEFAULT_STREAM_CONNECTION_OPTIONS = {
25
+ connectionMethod: SyncStreamConnectionMethod.HTTP
26
+ };
20
27
  export class AbstractStreamingSyncImplementation extends BaseObserver {
21
28
  _lastSyncedAt;
22
29
  options;
@@ -139,12 +146,12 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
139
146
  return true;
140
147
  }
141
148
  }
142
- async connect() {
149
+ async connect(options) {
143
150
  if (this.abortController) {
144
151
  await this.disconnect();
145
152
  }
146
153
  this.abortController = new AbortController();
147
- this.streamingSyncPromise = this.streamingSync(this.abortController.signal);
154
+ this.streamingSyncPromise = this.streamingSync(this.abortController.signal, options);
148
155
  // Return a promise that resolves when the connection status is updated
149
156
  return new Promise((resolve) => {
150
157
  const l = this.registerListener({
@@ -189,7 +196,7 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
189
196
  /**
190
197
  * @deprecated use [connect instead]
191
198
  */
192
- async streamingSync(signal) {
199
+ async streamingSync(signal, options) {
193
200
  if (!signal) {
194
201
  this.abortController = new AbortController();
195
202
  signal = this.abortController.signal;
@@ -231,7 +238,7 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
231
238
  if (signal?.aborted) {
232
239
  break;
233
240
  }
234
- const { retry } = await this.streamingSyncIteration(nestedAbortController.signal);
241
+ const { retry } = await this.streamingSyncIteration(nestedAbortController.signal, options);
235
242
  if (!retry) {
236
243
  /**
237
244
  * A sync error ocurred that we cannot recover from here.
@@ -273,11 +280,15 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
273
280
  // Mark as disconnected if here
274
281
  this.updateSyncStatus({ connected: false });
275
282
  }
276
- async streamingSyncIteration(signal, progress) {
283
+ async streamingSyncIteration(signal, options) {
277
284
  return await this.obtainLock({
278
285
  type: LockType.SYNC,
279
286
  signal,
280
287
  callback: async () => {
288
+ const resolvedOptions = {
289
+ ...DEFAULT_STREAM_CONNECTION_OPTIONS,
290
+ ...(options ?? {})
291
+ };
281
292
  this.logger.debug('Streaming sync iteration started');
282
293
  this.options.adapter.startSession();
283
294
  const bucketEntries = await this.options.adapter.getBucketStates();
@@ -294,11 +305,36 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
294
305
  let validatedCheckpoint = null;
295
306
  let appliedCheckpoint = null;
296
307
  let bucketSet = new Set(initialBuckets.keys());
297
- for await (const line of this.streamingSyncRequest({
298
- buckets: req,
299
- include_checksum: true,
300
- raw_data: true
301
- }, signal)) {
308
+ const { params = undefined } = (await this.options.remote.getCredentials()) ?? {};
309
+ this.logger.debug('Requesting stream from server');
310
+ const syncOptions = {
311
+ path: '/sync/stream',
312
+ abortSignal: signal,
313
+ data: {
314
+ buckets: req,
315
+ include_checksum: true,
316
+ raw_data: true,
317
+ parameters: params
318
+ }
319
+ };
320
+ const stream = resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP
321
+ ? await this.options.remote.postStream(syncOptions)
322
+ : await this.options.remote.socketStream(syncOptions);
323
+ this.logger.debug('Stream established. Processing events');
324
+ while (!stream.closed) {
325
+ const line = await stream.read();
326
+ if (!line) {
327
+ // The stream has closed while waiting
328
+ return { retry: true };
329
+ }
330
+ // A connection is active and messages are being received
331
+ if (!this.syncStatus.connected) {
332
+ // There is a connection now
333
+ Promise.resolve().then(() => this.triggerCrudUpload());
334
+ this.updateSyncStatus({
335
+ connected: true
336
+ });
337
+ }
302
338
  if (isStreamingSyncCheckpoint(line)) {
303
339
  targetCheckpoint = line.checkpoint;
304
340
  const bucketsToDelete = new Set(bucketSet);
@@ -385,6 +421,11 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
385
421
  if (remaining_seconds == 0) {
386
422
  // Connection would be closed automatically right after this
387
423
  this.logger.debug('Token expiring; reconnect');
424
+ /**
425
+ * For a rare case where the backend connector does not update the token
426
+ * (uses the same one), this should have some delay.
427
+ */
428
+ await this.delayRetry();
388
429
  return { retry: true };
389
430
  }
390
431
  this.triggerCrudUpload();
@@ -421,7 +462,6 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
421
462
  }
422
463
  }
423
464
  }
424
- progress?.();
425
465
  }
426
466
  this.logger.debug('Stream input empty');
427
467
  // Connection closed. Likely due to auth issue.
@@ -429,31 +469,6 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
429
469
  }
430
470
  });
431
471
  }
432
- async *streamingSyncRequest(req, signal) {
433
- const body = await this.options.remote.postStreaming('/sync/stream', req, {}, signal);
434
- // A connection is active
435
- // There is a connection now
436
- Promise.resolve().then(() => this.triggerCrudUpload());
437
- this.updateSyncStatus({
438
- connected: true
439
- });
440
- const stream = ndjsonStream(body);
441
- const reader = stream.getReader();
442
- try {
443
- while (true) {
444
- // Read from the stream
445
- const { done, value } = await reader.read();
446
- // Exit if we're done
447
- if (done)
448
- return;
449
- // Else yield the chunk
450
- yield value;
451
- }
452
- }
453
- finally {
454
- reader.releaseLock();
455
- }
456
- }
457
472
  updateSyncStatus(options) {
458
473
  const updatedStatus = new SyncStatus({
459
474
  connected: options.connected ?? this.syncStatus.connected,
@@ -59,6 +59,10 @@ export interface StreamingSyncRequest {
59
59
  * Changes the response to stringified data in each OplogEntry
60
60
  */
61
61
  raw_data: boolean;
62
+ /**
63
+ * Client parameters to be passed to the sync rules.
64
+ */
65
+ parameters?: Record<string, string>;
62
66
  }
63
67
  export interface StreamingSyncCheckpoint {
64
68
  checkpoint: Checkpoint;
package/lib/index.d.ts CHANGED
@@ -28,5 +28,6 @@ export * from './db/schema/TableV2';
28
28
  export * from './utils/AbortOperation';
29
29
  export * from './utils/BaseObserver';
30
30
  export * from './utils/strings';
31
+ export * from './utils/DataStream';
31
32
  export * from './utils/parseQuery';
32
33
  export * from './types/types';
package/lib/index.js CHANGED
@@ -28,5 +28,6 @@ export * from './db/schema/TableV2';
28
28
  export * from './utils/AbortOperation';
29
29
  export * from './utils/BaseObserver';
30
30
  export * from './utils/strings';
31
+ export * from './utils/DataStream';
31
32
  export * from './utils/parseQuery';
32
33
  export * from './types/types';
@@ -8,13 +8,12 @@ export type BaseListener = {
8
8
  [key: string]: ((...event: any) => any) | undefined;
9
9
  };
10
10
  export declare class BaseObserver<T extends BaseListener = BaseListener> implements BaseObserverInterface<T> {
11
- protected listeners: {
12
- [id: string]: Partial<T>;
13
- };
11
+ protected listeners: Set<Partial<T>>;
14
12
  constructor();
15
13
  /**
16
14
  * Register a listener for updates to the PowerSync client.
17
15
  */
18
16
  registerListener(listener: Partial<T>): () => void;
19
17
  iterateListeners(cb: (listener: Partial<T>) => any): void;
18
+ iterateAsyncListeners(cb: (listener: Partial<T>) => Promise<any>): Promise<void>;
20
19
  }
@@ -1,22 +1,23 @@
1
- import { v4 } from 'uuid';
2
1
  export class BaseObserver {
3
- listeners;
4
- constructor() {
5
- this.listeners = {};
6
- }
2
+ listeners = new Set();
3
+ constructor() { }
7
4
  /**
8
5
  * Register a listener for updates to the PowerSync client.
9
6
  */
10
7
  registerListener(listener) {
11
- const id = v4();
12
- this.listeners[id] = listener;
8
+ this.listeners.add(listener);
13
9
  return () => {
14
- delete this.listeners[id];
10
+ this.listeners.delete(listener);
15
11
  };
16
12
  }
17
13
  iterateListeners(cb) {
18
- for (const i in this.listeners) {
19
- cb(this.listeners[i]);
14
+ for (const listener of this.listeners) {
15
+ cb(listener);
16
+ }
17
+ }
18
+ async iterateAsyncListeners(cb) {
19
+ for (let i of Array.from(this.listeners.values())) {
20
+ await cb(i);
20
21
  }
21
22
  }
22
23
  }
@@ -0,0 +1,25 @@
1
+ export interface ControlledExecutorOptions {
2
+ /**
3
+ * If throttling is enabled, it ensures only one task runs at a time,
4
+ * and only one additional task can be scheduled to run after the current task completes. The pending task will be overwritten by the latest task.
5
+ * Enabled by default.
6
+ */
7
+ throttleEnabled?: boolean;
8
+ }
9
+ export declare class ControlledExecutor<T> {
10
+ private task;
11
+ /**
12
+ * Represents the currently running task, which could be a Promise or undefined if no task is running.
13
+ */
14
+ private runningTask;
15
+ private pendingTaskParam;
16
+ /**
17
+ * Flag to determine if throttling is enabled, which controls whether tasks are queued or run immediately.
18
+ */
19
+ private isThrottling;
20
+ private closed;
21
+ constructor(task: (param: T) => Promise<void> | void, options?: ControlledExecutorOptions);
22
+ schedule(param: T): void;
23
+ dispose(): void;
24
+ private execute;
25
+ }
@@ -0,0 +1,50 @@
1
+ export class ControlledExecutor {
2
+ task;
3
+ /**
4
+ * Represents the currently running task, which could be a Promise or undefined if no task is running.
5
+ */
6
+ runningTask;
7
+ pendingTaskParam;
8
+ /**
9
+ * Flag to determine if throttling is enabled, which controls whether tasks are queued or run immediately.
10
+ */
11
+ isThrottling;
12
+ closed;
13
+ constructor(task, options) {
14
+ this.task = task;
15
+ const { throttleEnabled = true } = options ?? {};
16
+ this.isThrottling = throttleEnabled;
17
+ this.closed = false;
18
+ }
19
+ schedule(param) {
20
+ if (this.closed) {
21
+ return;
22
+ }
23
+ if (!this.isThrottling) {
24
+ this.task(param);
25
+ return;
26
+ }
27
+ if (this.runningTask) {
28
+ // set or replace the pending task param with latest one
29
+ this.pendingTaskParam = param;
30
+ return;
31
+ }
32
+ this.execute(param);
33
+ }
34
+ dispose() {
35
+ this.closed = true;
36
+ if (this.runningTask) {
37
+ this.runningTask = undefined;
38
+ }
39
+ }
40
+ async execute(param) {
41
+ this.runningTask = this.task(param);
42
+ await this.runningTask;
43
+ this.runningTask = undefined;
44
+ if (this.pendingTaskParam) {
45
+ const pendingParam = this.pendingTaskParam;
46
+ this.pendingTaskParam = undefined;
47
+ this.execute(pendingParam);
48
+ }
49
+ }
50
+ }
@@ -0,0 +1,63 @@
1
+ import { ILogger } from 'js-logger';
2
+ import { BaseListener, BaseObserver } from './BaseObserver';
3
+ export type DataStreamOptions = {
4
+ /**
5
+ * Close the stream if any consumer throws an error
6
+ */
7
+ closeOnError?: boolean;
8
+ pressure?: {
9
+ highWaterMark?: number;
10
+ lowWaterMark?: number;
11
+ };
12
+ logger?: ILogger;
13
+ };
14
+ export type DataStreamCallback<Data extends any = any> = (data: Data) => Promise<void>;
15
+ export interface DataStreamListener<Data extends any = any> extends BaseListener {
16
+ data: (data: Data) => Promise<void>;
17
+ closed: () => void;
18
+ error: (error: Error) => void;
19
+ highWater: () => Promise<void>;
20
+ lowWater: () => Promise<void>;
21
+ }
22
+ export declare const DEFAULT_PRESSURE_LIMITS: {
23
+ highWater: number;
24
+ lowWater: number;
25
+ };
26
+ /**
27
+ * A very basic implementation of a data stream with backpressure support which does not use
28
+ * native JS streams or async iterators.
29
+ * This is handy for environments such as React Native which need polyfills for the above.
30
+ */
31
+ export declare class DataStream<Data extends any = any> extends BaseObserver<DataStreamListener<Data>> {
32
+ protected options?: DataStreamOptions | undefined;
33
+ dataQueue: Data[];
34
+ protected isClosed: boolean;
35
+ protected processingPromise: Promise<void> | null;
36
+ protected logger: ILogger;
37
+ constructor(options?: DataStreamOptions | undefined);
38
+ get highWatermark(): number;
39
+ get lowWatermark(): number;
40
+ get closed(): boolean;
41
+ close(): Promise<void>;
42
+ /**
43
+ * Enqueues data for the consumers to read
44
+ */
45
+ enqueueData(data: Data): void;
46
+ /**
47
+ * Reads data once from the data stream
48
+ * @returns a Data payload or Null if the stream closed.
49
+ */
50
+ read(): Promise<Data | null>;
51
+ /**
52
+ * Executes a callback for each data item in the stream
53
+ */
54
+ forEach(callback: DataStreamCallback<Data>): () => void;
55
+ protected processQueue(): Promise<void>;
56
+ /**
57
+ * Creates a new data stream which is a map of the original
58
+ */
59
+ map<ReturnData>(callback: (data: Data) => ReturnData): DataStream<ReturnData>;
60
+ protected hasDataReader(): boolean;
61
+ protected _processQueue(): Promise<void>;
62
+ protected iterateAsyncErrored(cb: (l: BaseListener) => Promise<void>): Promise<void>;
63
+ }
@@ -0,0 +1,162 @@
1
+ import Logger from 'js-logger';
2
+ import { BaseObserver } from './BaseObserver';
3
+ export const DEFAULT_PRESSURE_LIMITS = {
4
+ highWater: 10,
5
+ lowWater: 0
6
+ };
7
+ /**
8
+ * A very basic implementation of a data stream with backpressure support which does not use
9
+ * native JS streams or async iterators.
10
+ * This is handy for environments such as React Native which need polyfills for the above.
11
+ */
12
+ export class DataStream extends BaseObserver {
13
+ options;
14
+ dataQueue;
15
+ isClosed;
16
+ processingPromise;
17
+ logger;
18
+ constructor(options) {
19
+ super();
20
+ this.options = options;
21
+ this.processingPromise = null;
22
+ this.isClosed = false;
23
+ this.dataQueue = [];
24
+ this.logger = options?.logger ?? Logger.get('DataStream');
25
+ if (options?.closeOnError) {
26
+ const l = this.registerListener({
27
+ error: (ex) => {
28
+ l?.();
29
+ this.close();
30
+ }
31
+ });
32
+ }
33
+ }
34
+ get highWatermark() {
35
+ return this.options?.pressure?.highWaterMark ?? DEFAULT_PRESSURE_LIMITS.highWater;
36
+ }
37
+ get lowWatermark() {
38
+ return this.options?.pressure?.lowWaterMark ?? DEFAULT_PRESSURE_LIMITS.lowWater;
39
+ }
40
+ get closed() {
41
+ return this.isClosed;
42
+ }
43
+ async close() {
44
+ this.isClosed = true;
45
+ await this.processingPromise;
46
+ this.iterateListeners((l) => l.closed?.());
47
+ // Discard any data in the queue
48
+ this.dataQueue = [];
49
+ this.listeners.clear();
50
+ }
51
+ /**
52
+ * Enqueues data for the consumers to read
53
+ */
54
+ enqueueData(data) {
55
+ if (this.isClosed) {
56
+ throw new Error('Cannot enqueue data into closed stream.');
57
+ }
58
+ this.dataQueue.push(data);
59
+ this.processQueue();
60
+ }
61
+ /**
62
+ * Reads data once from the data stream
63
+ * @returns a Data payload or Null if the stream closed.
64
+ */
65
+ async read() {
66
+ if (this.dataQueue.length <= this.lowWatermark) {
67
+ await this.iterateAsyncErrored(async (l) => l.lowWater?.());
68
+ }
69
+ if (this.closed) {
70
+ return null;
71
+ }
72
+ return new Promise((resolve, reject) => {
73
+ const l = this.registerListener({
74
+ data: async (data) => {
75
+ resolve(data);
76
+ // Remove the listener
77
+ l?.();
78
+ },
79
+ closed: () => {
80
+ resolve(null);
81
+ l?.();
82
+ },
83
+ error: (ex) => {
84
+ reject(ex);
85
+ l?.();
86
+ }
87
+ });
88
+ this.processQueue();
89
+ });
90
+ }
91
+ /**
92
+ * Executes a callback for each data item in the stream
93
+ */
94
+ forEach(callback) {
95
+ if (this.dataQueue.length <= this.lowWatermark) {
96
+ this.iterateAsyncErrored(async (l) => l.lowWater?.());
97
+ }
98
+ return this.registerListener({
99
+ data: callback
100
+ });
101
+ }
102
+ async processQueue() {
103
+ if (this.processingPromise) {
104
+ return;
105
+ }
106
+ /**
107
+ * Allow listeners to mutate the queue before processing.
108
+ * This allows for operations such as dropping or compressing data
109
+ * on high water or requesting more data on low water.
110
+ */
111
+ if (this.dataQueue.length >= this.highWatermark) {
112
+ await this.iterateAsyncErrored(async (l) => l.highWater?.());
113
+ }
114
+ return (this.processingPromise = this._processQueue());
115
+ }
116
+ /**
117
+ * Creates a new data stream which is a map of the original
118
+ */
119
+ map(callback) {
120
+ const stream = new DataStream(this.options);
121
+ const l = this.registerListener({
122
+ data: async (data) => {
123
+ stream.enqueueData(callback(data));
124
+ },
125
+ closed: () => {
126
+ stream.close();
127
+ l?.();
128
+ }
129
+ });
130
+ return stream;
131
+ }
132
+ hasDataReader() {
133
+ return Array.from(this.listeners.values()).some((l) => !!l.data);
134
+ }
135
+ async _processQueue() {
136
+ if (!this.dataQueue.length || this.isClosed || !this.hasDataReader()) {
137
+ Promise.resolve().then(() => (this.processingPromise = null));
138
+ return;
139
+ }
140
+ const data = this.dataQueue.shift();
141
+ await this.iterateAsyncErrored(async (l) => l.data?.(data));
142
+ if (this.dataQueue.length <= this.lowWatermark) {
143
+ await this.iterateAsyncErrored(async (l) => l.lowWater?.());
144
+ }
145
+ this.processingPromise = null;
146
+ if (this.dataQueue.length) {
147
+ // Next tick
148
+ setTimeout(() => this.processQueue());
149
+ }
150
+ }
151
+ async iterateAsyncErrored(cb) {
152
+ for (let i of Array.from(this.listeners.values())) {
153
+ try {
154
+ await cb(i);
155
+ }
156
+ catch (ex) {
157
+ this.logger.error(ex);
158
+ this.iterateListeners((l) => l.error?.(ex));
159
+ }
160
+ }
161
+ }
162
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/common",
3
- "version": "0.0.0-dev-20240509084320",
3
+ "version": "0.0.0-dev-20240606141637",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org/",
6
6
  "access": "public"
@@ -23,18 +23,22 @@
23
23
  "homepage": "https://docs.powersync.com/resources/api-reference",
24
24
  "dependencies": {
25
25
  "async-mutex": "^0.4.0",
26
+ "buffer": "^6.0.3",
26
27
  "can-ndjson-stream": "^1.0.2",
28
+ "cross-fetch": "^4.0.0",
27
29
  "event-iterator": "^2.0.0",
28
30
  "js-logger": "^1.6.1",
29
31
  "lodash": "^4.17.21",
30
- "uuid": "^9.0.1"
32
+ "rsocket-core": "1.0.0-alpha.3",
33
+ "rsocket-websocket-client": "1.0.0-alpha.3"
31
34
  },
32
35
  "devDependencies": {
33
36
  "@types/lodash": "^4.14.197",
34
37
  "@types/node": "^20.5.9",
35
38
  "@types/uuid": "^9.0.1",
36
39
  "typescript": "^5.1.3",
37
- "vitest": "^1.5.2"
40
+ "vitest": "^1.5.2",
41
+ "bson": "^6.6.0"
38
42
  },
39
43
  "scripts": {
40
44
  "build": "tsc -b",