@powersync/common 0.0.0-dev-20240509081154 → 0.0.0-dev-20240516143814

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;
@@ -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
  *
@@ -192,7 +192,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
192
192
  /**
193
193
  * Connects to stream of events from the PowerSync instance.
194
194
  */
195
- async connect(connector) {
195
+ async connect(connector, options) {
196
196
  await this.waitForReady();
197
197
  // close connection if one is open
198
198
  await this.disconnect();
@@ -202,13 +202,16 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
202
202
  this.syncStreamImplementation = this.generateSyncStreamImplementation(connector);
203
203
  this.syncStatusListenerDisposer = this.syncStreamImplementation.registerListener({
204
204
  statusChanged: (status) => {
205
- this.currentStatus = new SyncStatus({ ...status.toJSON(), hasSynced: this.currentStatus?.hasSynced });
205
+ this.currentStatus = new SyncStatus({
206
+ ...status.toJSON(),
207
+ hasSynced: this.currentStatus?.hasSynced || !!status.lastSyncedAt
208
+ });
206
209
  this.iterateListeners((cb) => cb.statusChanged?.(this.currentStatus));
207
210
  }
208
211
  });
209
212
  await this.syncStreamImplementation.waitForReady();
210
213
  this.syncStreamImplementation.triggerCrudUpload();
211
- await this.syncStreamImplementation.connect();
214
+ await this.syncStreamImplementation.connect(options);
212
215
  }
213
216
  /**
214
217
  * Close the sync connection.
@@ -528,7 +531,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
528
531
  .filter((row) => row.opcode == 'OpenRead' && row.p3 == 0 && typeof row.p2 == 'number')
529
532
  .map((row) => row.p2);
530
533
  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) {
534
+ for (const table of tables) {
532
535
  resolvedTables.push(table.tbl_name.replace(POWERSYNC_TABLE_MATCH, ''));
533
536
  }
534
537
  }
@@ -631,7 +634,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
631
634
  const mappedTableNames = rawTableNames
632
635
  ? filteredTables
633
636
  : filteredTables.map((t) => t.replace(POWERSYNC_TABLE_MATCH, ''));
634
- for (let table of mappedTableNames) {
637
+ for (const table of mappedTableNames) {
635
638
  changedTables.add(table);
636
639
  }
637
640
  }
@@ -82,5 +82,5 @@ export declare class CrudEntry {
82
82
  /**
83
83
  * Generates an array for use in deep comparison operations
84
84
  */
85
- toComparisonArray(): (string | number | Record<string, any>)[];
85
+ toComparisonArray(): (string | number | Record<string, any> | undefined)[];
86
86
  }
@@ -12,7 +12,7 @@ export declare class CrudTransaction extends CrudBatch {
12
12
  /**
13
13
  * If null, this contains a list of changes recorded without an explicit transaction associated.
14
14
  */
15
- transactionId?: number;
15
+ transactionId?: number | undefined;
16
16
  constructor(
17
17
  /**
18
18
  * List of client-side changes.
@@ -25,5 +25,5 @@ export declare class CrudTransaction extends CrudBatch {
25
25
  /**
26
26
  * If null, this contains a list of changes recorded without an explicit transaction associated.
27
27
  */
28
- transactionId?: number);
28
+ transactionId?: number | undefined);
29
29
  }
@@ -14,10 +14,10 @@ export declare class OplogEntry {
14
14
  op: OpType;
15
15
  checksum: number;
16
16
  subkey: string;
17
- object_type?: string;
18
- object_id?: string;
19
- data?: string;
17
+ object_type?: string | undefined;
18
+ object_id?: string | undefined;
19
+ data?: string | undefined;
20
20
  static fromRow(row: OplogEntryJSON): OplogEntry;
21
- constructor(op_id: OpId, op: OpType, checksum: number, subkey: string, object_type?: string, object_id?: string, data?: string);
21
+ constructor(op_id: OpId, op: OpType, checksum: number, subkey: string, object_type?: string | undefined, object_id?: string | undefined, data?: string | undefined);
22
22
  toJSON(): OplogEntryJSON;
23
23
  }
@@ -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,4 +1,3 @@
1
- import { OpId } from './CrudEntry';
2
1
  import { OplogEntry, OplogEntryJSON } from './OplogEntry';
3
2
  export type SyncDataBucketJSON = {
4
3
  bucket: string;
@@ -18,11 +17,11 @@ export declare class SyncDataBucket {
18
17
  /**
19
18
  * The `after` specified in the request.
20
19
  */
21
- after?: OpId;
20
+ after?: string | undefined;
22
21
  /**
23
22
  * Use this for the next request.
24
23
  */
25
- next_after?: OpId;
24
+ next_after?: string | undefined;
26
25
  static fromRow(row: SyncDataBucketJSON): SyncDataBucket;
27
26
  constructor(bucket: string, data: OplogEntry[],
28
27
  /**
@@ -32,10 +31,10 @@ export declare class SyncDataBucket {
32
31
  /**
33
32
  * The `after` specified in the request.
34
33
  */
35
- after?: OpId,
34
+ after?: string | undefined,
36
35
  /**
37
36
  * Use this for the next request.
38
37
  */
39
- next_after?: OpId);
38
+ next_after?: string | undefined);
40
39
  toJSON(): SyncDataBucketJSON;
41
40
  }
@@ -1,15 +1,43 @@
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 AbstractRemoteOptions = {
20
+ /**
21
+ * Transforms the PowerSync base URL which might contain
22
+ * `http(s)://` to the corresponding WebSocket variant
23
+ * e.g. `ws(s)://`
24
+ */
25
+ socketUrlTransformer: (url: string) => string;
26
+ /**
27
+ * Optionally provide the fetch implementation to use.
28
+ * Note that this usually needs to be bound to the global scope.
29
+ * Binding should be done before passing here.
30
+ */
31
+ fetchImplementation: typeof fetch;
32
+ };
33
+ export declare const DEFAULT_REMOTE_OPTIONS: AbstractRemoteOptions;
8
34
  export declare abstract class AbstractRemote {
9
35
  protected connector: RemoteConnector;
10
36
  protected logger: ILogger;
11
37
  protected credentials: PowerSyncCredentials | null;
12
- constructor(connector: RemoteConnector, logger?: ILogger);
38
+ protected options: AbstractRemoteOptions;
39
+ constructor(connector: RemoteConnector, logger?: ILogger, options?: Partial<AbstractRemoteOptions>);
40
+ get fetch(): typeof globalThis.fetch;
13
41
  getCredentials(): Promise<PowerSyncCredentials | null>;
14
42
  protected buildRequest(path: string): Promise<{
15
43
  url: string;
@@ -18,8 +46,19 @@ export declare abstract class AbstractRemote {
18
46
  Authorization: string;
19
47
  };
20
48
  }>;
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;
49
+ post(path: string, data: any, headers?: Record<string, string>): Promise<any>;
50
+ get(path: string, headers?: Record<string, string>): Promise<any>;
51
+ postStreaming(path: string, data: any, headers?: Record<string, string>, signal?: AbortSignal): Promise<any>;
52
+ /**
53
+ * Provides a BSON implementation. The import nature of this varies depending on the platform
54
+ */
55
+ abstract getBSON(): Promise<BSONImplementation>;
56
+ /**
57
+ * Connects to the sync/stream websocket endpoint
58
+ */
59
+ socketStream(options: SyncStreamOptions): Promise<DataStream<StreamingSyncLine>>;
60
+ /**
61
+ * Connects to the sync/stream http endpoint
62
+ */
63
+ postStream(options: SyncStreamOptions): Promise<DataStream<StreamingSyncLine>>;
25
64
  }
@@ -1,14 +1,41 @@
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
+ export const DEFAULT_REMOTE_OPTIONS = {
19
+ socketUrlTransformer: (url) => url.replace(/^https?:\/\//, function (match) {
20
+ return match === 'https://' ? 'wss://' : 'ws://';
21
+ }),
22
+ fetchImplementation: fetch.bind(globalThis)
23
+ };
5
24
  export class AbstractRemote {
6
25
  connector;
7
26
  logger;
8
27
  credentials = null;
9
- constructor(connector, logger = DEFAULT_REMOTE_LOGGER) {
28
+ options;
29
+ constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {
10
30
  this.connector = connector;
11
31
  this.logger = logger;
32
+ this.options = {
33
+ ...DEFAULT_REMOTE_OPTIONS,
34
+ ...(options ?? {})
35
+ };
36
+ }
37
+ get fetch() {
38
+ return this.options.fetchImplementation;
12
39
  }
13
40
  async getCredentials() {
14
41
  const { expiresAt } = this.credentials ?? {};
@@ -36,7 +63,300 @@ export class AbstractRemote {
36
63
  }
37
64
  };
38
65
  }
39
- isAvailable() {
40
- return true;
66
+ async post(path, data, headers = {}) {
67
+ const request = await this.buildRequest(path);
68
+ const res = await fetch(request.url, {
69
+ method: 'POST',
70
+ headers: {
71
+ ...headers,
72
+ ...request.headers
73
+ },
74
+ body: JSON.stringify(data)
75
+ });
76
+ if (!res.ok) {
77
+ throw new Error(`Received ${res.status} - ${res.statusText} when posting to ${path}: ${await res.text()}}`);
78
+ }
79
+ return res.json();
80
+ }
81
+ async get(path, headers) {
82
+ const request = await this.buildRequest(path);
83
+ const res = await this.fetch(request.url, {
84
+ method: 'GET',
85
+ headers: {
86
+ ...headers,
87
+ ...request.headers
88
+ }
89
+ });
90
+ if (!res.ok) {
91
+ throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
92
+ }
93
+ return res.json();
94
+ }
95
+ async postStreaming(path, data, headers = {}, signal) {
96
+ const request = await this.buildRequest(path);
97
+ const res = await this.fetch(request.url, {
98
+ method: 'POST',
99
+ headers: { ...headers, ...request.headers },
100
+ body: JSON.stringify(data),
101
+ signal,
102
+ cache: 'no-store'
103
+ }).catch((ex) => {
104
+ this.logger.error(`Caught ex when POST streaming to ${path}`, ex);
105
+ throw ex;
106
+ });
107
+ if (!res.ok) {
108
+ const text = await res.text();
109
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
110
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
111
+ error.status = res.status;
112
+ throw error;
113
+ }
114
+ return res;
115
+ }
116
+ /**
117
+ * Connects to the sync/stream websocket endpoint
118
+ */
119
+ async socketStream(options) {
120
+ const { path } = options;
121
+ const request = await this.buildRequest(path);
122
+ const BSON = await this.getBSON();
123
+ const connector = new RSocketConnector({
124
+ transport: new WebsocketClientTransport({
125
+ url: this.options.socketUrlTransformer(request.url)
126
+ }),
127
+ setup: {
128
+ keepAlive: KEEP_ALIVE_MS,
129
+ lifetime: KEEP_ALIVE_LIFETIME_MS,
130
+ dataMimeType: 'application/bson',
131
+ metadataMimeType: 'application/bson',
132
+ payload: {
133
+ data: null,
134
+ metadata: Buffer.from(BSON.serialize({
135
+ token: request.headers.Authorization
136
+ }))
137
+ }
138
+ }
139
+ });
140
+ let rsocket;
141
+ try {
142
+ rsocket = await connector.connect();
143
+ }
144
+ catch (ex) {
145
+ /**
146
+ * On React native the connection exception can be `undefined` this causes issues
147
+ * with detecting the exception inside async-mutex
148
+ */
149
+ throw new Error(`Could not connect to PowerSync instance: ${JSON.stringify(ex)}`);
150
+ }
151
+ const stream = new DataStream({
152
+ logger: this.logger,
153
+ pressure: {
154
+ lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
155
+ }
156
+ });
157
+ let socketIsClosed = false;
158
+ const closeSocket = () => {
159
+ if (socketIsClosed) {
160
+ return;
161
+ }
162
+ socketIsClosed = true;
163
+ rsocket.close();
164
+ };
165
+ // We initially request this amount and expect these to arrive eventually
166
+ let pendingEventsCount = SYNC_QUEUE_REQUEST_N;
167
+ const socket = await new Promise((resolve, reject) => {
168
+ let connectionEstablished = false;
169
+ const res = rsocket.requestStream({
170
+ data: Buffer.from(BSON.serialize(options.data)),
171
+ metadata: Buffer.from(BSON.serialize({
172
+ path
173
+ }))
174
+ }, SYNC_QUEUE_REQUEST_N, // The initial N amount
175
+ {
176
+ onError: (e) => {
177
+ // Don't log closed as an error
178
+ if (e.message !== 'Closed. ') {
179
+ this.logger.error(e);
180
+ }
181
+ // RSocket will close this automatically
182
+ // Attempting to close multiple times causes a console warning
183
+ socketIsClosed = true;
184
+ stream.close();
185
+ // Handles cases where the connection failed e.g. auth error or connection error
186
+ if (!connectionEstablished) {
187
+ reject(e);
188
+ }
189
+ },
190
+ onNext: (payload) => {
191
+ // The connection is active
192
+ if (!connectionEstablished) {
193
+ connectionEstablished = true;
194
+ resolve(res);
195
+ }
196
+ const { data } = payload;
197
+ // Less events are now pending
198
+ pendingEventsCount--;
199
+ if (!data) {
200
+ return;
201
+ }
202
+ const deserializedData = BSON.deserialize(data);
203
+ stream.enqueueData(deserializedData);
204
+ },
205
+ onComplete: () => {
206
+ stream.close();
207
+ },
208
+ onExtension: () => { }
209
+ });
210
+ });
211
+ const l = stream.registerListener({
212
+ lowWater: async () => {
213
+ // Request to fill up the queue
214
+ const required = SYNC_QUEUE_REQUEST_N - pendingEventsCount;
215
+ if (required > 0) {
216
+ socket.request(SYNC_QUEUE_REQUEST_N - pendingEventsCount);
217
+ pendingEventsCount = SYNC_QUEUE_REQUEST_N;
218
+ }
219
+ },
220
+ closed: () => {
221
+ closeSocket();
222
+ l?.();
223
+ }
224
+ });
225
+ /**
226
+ * Handle abort operations here.
227
+ * Unfortunately cannot insert them into the connection.
228
+ */
229
+ if (options.abortSignal?.aborted) {
230
+ stream.close();
231
+ }
232
+ else {
233
+ options.abortSignal?.addEventListener('abort', () => {
234
+ stream.close();
235
+ });
236
+ }
237
+ return stream;
238
+ }
239
+ /**
240
+ * Connects to the sync/stream http endpoint
241
+ */
242
+ async postStream(options) {
243
+ const { data, path, headers, abortSignal } = options;
244
+ const request = await this.buildRequest(path);
245
+ /**
246
+ * This abort controller will abort pending fetch requests.
247
+ * If the request has resolved, it will be used to close the readable stream.
248
+ * Which will cancel the network request.
249
+ *
250
+ * This nested controller is required since:
251
+ * Aborting the active fetch request while it is being consumed seems to throw
252
+ * an unhandled exception on the window level.
253
+ */
254
+ const controller = new AbortController();
255
+ let requestResolved = false;
256
+ abortSignal?.addEventListener('abort', () => {
257
+ if (!requestResolved) {
258
+ // Only abort via the abort controller if the request has not resolved yet
259
+ controller.abort(abortSignal.reason ??
260
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));
261
+ }
262
+ });
263
+ const res = await this.fetch(request.url, {
264
+ method: 'POST',
265
+ headers: { ...headers, ...request.headers },
266
+ body: JSON.stringify(data),
267
+ signal: controller.signal,
268
+ cache: 'no-store',
269
+ ...options.fetchOptions
270
+ }).catch((ex) => {
271
+ if (ex.name == 'AbortError') {
272
+ throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
273
+ }
274
+ throw ex;
275
+ });
276
+ if (!res) {
277
+ throw new Error('Fetch request was aborted');
278
+ }
279
+ requestResolved = true;
280
+ if (!res.ok || !res.body) {
281
+ const text = await res.text();
282
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
283
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
284
+ error.status = res.status;
285
+ throw error;
286
+ }
287
+ /**
288
+ * The can-ndjson-stream does not handle aborted streams well.
289
+ * This will intercept the readable stream and close the stream if
290
+ * aborted.
291
+ */
292
+ const reader = res.body.getReader();
293
+ // This will close the network request and read stream
294
+ const closeReader = async () => {
295
+ try {
296
+ await reader.cancel();
297
+ }
298
+ catch (ex) {
299
+ // an error will throw if the reader hasn't been used yet
300
+ }
301
+ reader.releaseLock();
302
+ };
303
+ abortSignal?.addEventListener('abort', () => {
304
+ closeReader();
305
+ });
306
+ const outputStream = new ReadableStream({
307
+ start: (controller) => {
308
+ const processStream = async () => {
309
+ while (!abortSignal?.aborted) {
310
+ try {
311
+ const { done, value } = await reader.read();
312
+ // When no more data needs to be consumed, close the stream
313
+ if (done) {
314
+ break;
315
+ }
316
+ // Enqueue the next data chunk into our target stream
317
+ controller.enqueue(value);
318
+ }
319
+ catch (ex) {
320
+ this.logger.error('Caught exception when reading sync stream', ex);
321
+ break;
322
+ }
323
+ }
324
+ if (!abortSignal?.aborted) {
325
+ // Close the downstream readable stream
326
+ await closeReader();
327
+ }
328
+ controller.close();
329
+ };
330
+ processStream();
331
+ }
332
+ });
333
+ const jsonS = ndjsonStream(new Response(outputStream).body);
334
+ const stream = new DataStream({
335
+ logger: this.logger
336
+ });
337
+ const r = jsonS.getReader();
338
+ const l = stream.registerListener({
339
+ lowWater: async () => {
340
+ try {
341
+ const { done, value } = await r.read();
342
+ // Exit if we're done
343
+ if (done) {
344
+ stream.close();
345
+ l?.();
346
+ return;
347
+ }
348
+ stream.enqueueData(value);
349
+ }
350
+ catch (ex) {
351
+ stream.close();
352
+ throw ex;
353
+ }
354
+ },
355
+ closed: () => {
356
+ closeReader();
357
+ l?.();
358
+ }
359
+ });
360
+ return stream;
41
361
  }
42
362
  }
@@ -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;
@@ -77,7 +92,7 @@ export declare abstract class AbstractStreamingSyncImplementation extends BaseOb
77
92
  constructor(options: AbstractStreamingSyncImplementationOptions);
78
93
  waitForReady(): Promise<void>;
79
94
  waitForStatus(status: SyncStatusOptions): Promise<void>;
80
- get lastSyncedAt(): Date;
95
+ get lastSyncedAt(): Date | undefined;
81
96
  get isConnected(): boolean;
82
97
  protected get logger(): ILogger;
83
98
  dispose(): Promise<void>;
@@ -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,34 @@ 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
+ this.logger.debug('Requesting stream from server');
309
+ const syncOptions = {
310
+ path: '/sync/stream',
311
+ abortSignal: signal,
312
+ data: {
313
+ buckets: req,
314
+ include_checksum: true,
315
+ raw_data: true
316
+ }
317
+ };
318
+ const stream = resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP
319
+ ? await this.options.remote.postStream(syncOptions)
320
+ : await this.options.remote.socketStream(syncOptions);
321
+ this.logger.debug('Stream established. Processing events');
322
+ while (!stream.closed) {
323
+ const line = await stream.read();
324
+ if (!line) {
325
+ // The stream has closed while waiting
326
+ return { retry: true };
327
+ }
328
+ // A connection is active and messages are being received
329
+ if (!this.syncStatus.connected) {
330
+ // There is a connection now
331
+ Promise.resolve().then(() => this.triggerCrudUpload());
332
+ this.updateSyncStatus({
333
+ connected: true
334
+ });
335
+ }
302
336
  if (isStreamingSyncCheckpoint(line)) {
303
337
  targetCheckpoint = line.checkpoint;
304
338
  const bucketsToDelete = new Set(bucketSet);
@@ -385,6 +419,11 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
385
419
  if (remaining_seconds == 0) {
386
420
  // Connection would be closed automatically right after this
387
421
  this.logger.debug('Token expiring; reconnect');
422
+ /**
423
+ * For a rare case where the backend connector does not update the token
424
+ * (uses the same one), this should have some delay.
425
+ */
426
+ await this.delayRetry();
388
427
  return { retry: true };
389
428
  }
390
429
  this.triggerCrudUpload();
@@ -421,7 +460,6 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
421
460
  }
422
461
  }
423
462
  }
424
- progress?.();
425
463
  }
426
464
  this.logger.debug('Stream input empty');
427
465
  // Connection closed. Likely due to auth issue.
@@ -429,31 +467,6 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
429
467
  }
430
468
  });
431
469
  }
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
470
  updateSyncStatus(options) {
458
471
  const updatedStatus = new SyncStatus({
459
472
  connected: options.connected ?? this.syncStatus.connected,
@@ -11,9 +11,9 @@ export declare class Column {
11
11
  protected options: ColumnOptions;
12
12
  constructor(options: ColumnOptions);
13
13
  get name(): string;
14
- get type(): ColumnType;
14
+ get type(): ColumnType | undefined;
15
15
  toJSON(): {
16
16
  name: string;
17
- type: ColumnType;
17
+ type: ColumnType | undefined;
18
18
  };
19
19
  }
@@ -19,12 +19,12 @@ export declare class SyncStatus {
19
19
  * Time that a last sync has fully completed, if any.
20
20
  * Currently this is reset to null after a restart.
21
21
  */
22
- get lastSyncedAt(): Date;
22
+ get lastSyncedAt(): Date | undefined;
23
23
  /**
24
24
  * Indicates whether there has been at least one full sync, if any.
25
25
  * Is undefined when unknown, for example when state is still being loaded from the database.
26
26
  */
27
- get hasSynced(): boolean;
27
+ get hasSynced(): boolean | undefined;
28
28
  /**
29
29
  * Upload/download status
30
30
  */
@@ -15,7 +15,7 @@ export declare class Index {
15
15
  name: string;
16
16
  columns: {
17
17
  name: string;
18
- ascending: boolean;
18
+ ascending: boolean | undefined;
19
19
  type: import("../Column").ColumnType;
20
20
  }[];
21
21
  };
@@ -10,10 +10,10 @@ export declare class IndexedColumn {
10
10
  static createAscending(column: string): IndexedColumn;
11
11
  constructor(options: IndexColumnOptions);
12
12
  get name(): string;
13
- get ascending(): boolean;
13
+ get ascending(): boolean | undefined;
14
14
  toJSON(table: Table): {
15
15
  name: string;
16
- ascending: boolean;
16
+ ascending: boolean | undefined;
17
17
  type: ColumnType;
18
18
  };
19
19
  }
@@ -21,13 +21,13 @@ export declare class Schema<S extends SchemaType = SchemaType> {
21
21
  insert_only: boolean;
22
22
  columns: {
23
23
  name: string;
24
- type: import("../Column").ColumnType;
24
+ type: import("../Column").ColumnType | undefined;
25
25
  }[];
26
26
  indexes: {
27
27
  name: string;
28
28
  columns: {
29
29
  name: string;
30
- ascending: boolean;
30
+ ascending: boolean | undefined;
31
31
  type: import("../Column").ColumnType;
32
32
  }[];
33
33
  }[];
@@ -21,7 +21,7 @@ export declare class Table {
21
21
  static createTable(name: string, table: TableV2): Table;
22
22
  constructor(options: TableOptions);
23
23
  get name(): string;
24
- get viewNameOverride(): string;
24
+ get viewNameOverride(): string | undefined;
25
25
  get viewName(): string;
26
26
  get columns(): Column[];
27
27
  get indexes(): Index[];
@@ -37,13 +37,13 @@ export declare class Table {
37
37
  insert_only: boolean;
38
38
  columns: {
39
39
  name: string;
40
- type: import("../Column").ColumnType;
40
+ type: import("../Column").ColumnType | undefined;
41
41
  }[];
42
42
  indexes: {
43
43
  name: string;
44
44
  columns: {
45
45
  name: string;
46
- ascending: boolean;
46
+ ascending: boolean | undefined;
47
47
  type: import("../Column").ColumnType;
48
48
  }[];
49
49
  }[];
@@ -4,9 +4,9 @@ export type BaseColumnType<T extends number | string | null> = {
4
4
  type: ColumnType;
5
5
  };
6
6
  export declare const column: {
7
- text: BaseColumnType<string>;
8
- integer: BaseColumnType<number>;
9
- real: BaseColumnType<number>;
7
+ text: BaseColumnType<string | null>;
8
+ integer: BaseColumnType<number | null>;
9
+ real: BaseColumnType<number | null>;
10
10
  };
11
11
  export type ColumnsType = Record<string, BaseColumnType<any>>;
12
12
  export type ExtractColumnValueType<T extends BaseColumnType<any>> = T extends BaseColumnType<infer R> ? R : unknown;
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,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-20240509081154",
3
+ "version": "0.0.0-dev-20240516143814",
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",