@powersync/common 1.7.1 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/lib/client/AbstractPowerSyncDatabase.d.ts +2 -3
  2. package/lib/client/AbstractPowerSyncDatabase.js +2 -3
  3. package/lib/client/AbstractPowerSyncOpenFactory.js +0 -1
  4. package/lib/client/connection/PowerSyncBackendConnector.js +0 -1
  5. package/lib/client/connection/PowerSyncCredentials.js +0 -1
  6. package/lib/client/sync/bucket/BucketStorageAdapter.js +0 -1
  7. package/lib/client/sync/bucket/CrudBatch.js +0 -1
  8. package/lib/client/sync/bucket/CrudEntry.js +0 -1
  9. package/lib/client/sync/bucket/CrudTransaction.js +0 -1
  10. package/lib/client/sync/bucket/OpType.js +0 -1
  11. package/lib/client/sync/bucket/OplogEntry.js +0 -1
  12. package/lib/client/sync/bucket/SqliteBucketStorage.js +3 -5
  13. package/lib/client/sync/bucket/SyncDataBatch.js +0 -1
  14. package/lib/client/sync/bucket/SyncDataBucket.js +0 -1
  15. package/lib/client/sync/stream/AbstractRemote.d.ts +39 -6
  16. package/lib/client/sync/stream/AbstractRemote.js +323 -4
  17. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +21 -7
  18. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +50 -38
  19. package/lib/client/sync/stream/streaming-sync-types.js +0 -1
  20. package/lib/db/Column.js +0 -1
  21. package/lib/db/DBAdapter.js +0 -1
  22. package/lib/db/crud/SyncStatus.js +0 -1
  23. package/lib/db/crud/UploadQueueStatus.js +0 -1
  24. package/lib/db/schema/Index.js +0 -1
  25. package/lib/db/schema/IndexedColumn.js +0 -1
  26. package/lib/db/schema/Schema.js +0 -1
  27. package/lib/db/schema/Table.js +0 -1
  28. package/lib/db/schema/TableV2.js +0 -1
  29. package/lib/index.d.ts +1 -0
  30. package/lib/index.js +1 -1
  31. package/lib/types/types.js +0 -1
  32. package/lib/utils/AbortOperation.js +0 -1
  33. package/lib/utils/BaseObserver.d.ts +2 -3
  34. package/lib/utils/BaseObserver.js +11 -11
  35. package/lib/utils/DataStream.d.ts +63 -0
  36. package/lib/utils/DataStream.js +162 -0
  37. package/lib/utils/mutex.js +0 -1
  38. package/lib/utils/parseQuery.js +0 -1
  39. package/lib/utils/strings.js +0 -1
  40. package/package.json +6 -2
  41. package/lib/client/AbstractPowerSyncDatabase.js.map +0 -1
  42. package/lib/client/AbstractPowerSyncOpenFactory.js.map +0 -1
  43. package/lib/client/connection/PowerSyncBackendConnector.js.map +0 -1
  44. package/lib/client/connection/PowerSyncCredentials.js.map +0 -1
  45. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +0 -1
  46. package/lib/client/sync/bucket/CrudBatch.js.map +0 -1
  47. package/lib/client/sync/bucket/CrudEntry.js.map +0 -1
  48. package/lib/client/sync/bucket/CrudTransaction.js.map +0 -1
  49. package/lib/client/sync/bucket/OpType.js.map +0 -1
  50. package/lib/client/sync/bucket/OplogEntry.js.map +0 -1
  51. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +0 -1
  52. package/lib/client/sync/bucket/SyncDataBatch.js.map +0 -1
  53. package/lib/client/sync/bucket/SyncDataBucket.js.map +0 -1
  54. package/lib/client/sync/stream/AbstractRemote.js.map +0 -1
  55. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +0 -1
  56. package/lib/client/sync/stream/streaming-sync-types.js.map +0 -1
  57. package/lib/db/Column.js.map +0 -1
  58. package/lib/db/DBAdapter.js.map +0 -1
  59. package/lib/db/crud/SyncStatus.js.map +0 -1
  60. package/lib/db/crud/UploadQueueStatus.js.map +0 -1
  61. package/lib/db/schema/Index.js.map +0 -1
  62. package/lib/db/schema/IndexedColumn.js.map +0 -1
  63. package/lib/db/schema/Schema.js.map +0 -1
  64. package/lib/db/schema/Table.js.map +0 -1
  65. package/lib/db/schema/TableV2.js.map +0 -1
  66. package/lib/index.js.map +0 -1
  67. package/lib/types/types.js.map +0 -1
  68. package/lib/utils/AbortOperation.js.map +0 -1
  69. package/lib/utils/BaseObserver.js.map +0 -1
  70. package/lib/utils/mutex.js.map +0 -1
  71. package/lib/utils/parseQuery.js.map +0 -1
  72. package/lib/utils/strings.js.map +0 -1
@@ -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();
@@ -211,7 +211,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
211
211
  });
212
212
  await this.syncStreamImplementation.waitForReady();
213
213
  this.syncStreamImplementation.triggerCrudUpload();
214
- await this.syncStreamImplementation.connect();
214
+ await this.syncStreamImplementation.connect(options);
215
215
  }
216
216
  /**
217
217
  * Close the sync connection.
@@ -646,4 +646,3 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
646
646
  return this.database.readLock((tx) => tx.execute(sql, params));
647
647
  }
648
648
  }
649
- //# sourceMappingURL=AbstractPowerSyncDatabase.js.map
@@ -22,4 +22,3 @@ export class AbstractPowerSyncDatabaseOpenFactory {
22
22
  return this.generateInstance(options);
23
23
  }
24
24
  }
25
- //# sourceMappingURL=AbstractPowerSyncOpenFactory.js.map
@@ -1,2 +1 @@
1
1
  export {};
2
- //# sourceMappingURL=PowerSyncBackendConnector.js.map
@@ -1,2 +1 @@
1
1
  export {};
2
- //# sourceMappingURL=PowerSyncCredentials.js.map
@@ -6,4 +6,3 @@ export var PSInternalTable;
6
6
  PSInternalTable["OPLOG"] = "ps_oplog";
7
7
  PSInternalTable["UNTYPED"] = "ps_untyped";
8
8
  })(PSInternalTable || (PSInternalTable = {}));
9
- //# sourceMappingURL=BucketStorageAdapter.js.map
@@ -23,4 +23,3 @@ export class CrudBatch {
23
23
  this.complete = complete;
24
24
  }
25
25
  }
26
- //# sourceMappingURL=CrudBatch.js.map
@@ -82,4 +82,3 @@ export class CrudEntry {
82
82
  return [this.transactionId, this.clientId, this.op, this.table, this.id, this.opData];
83
83
  }
84
84
  }
85
- //# sourceMappingURL=CrudEntry.js.map
@@ -22,4 +22,3 @@ export class CrudTransaction extends CrudBatch {
22
22
  this.transactionId = transactionId;
23
23
  }
24
24
  }
25
- //# sourceMappingURL=CrudTransaction.js.map
@@ -20,4 +20,3 @@ export class OpType {
20
20
  return Object.entries(OpTypeEnum).find(([, value]) => value === this.value)[0];
21
21
  }
22
22
  }
23
- //# sourceMappingURL=OpType.js.map
@@ -31,4 +31,3 @@ export class OplogEntry {
31
31
  };
32
32
  }
33
33
  }
34
- //# sourceMappingURL=OplogEntry.js.map
@@ -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]);
@@ -296,4 +295,3 @@ export class SqliteBucketStorage extends BaseObserver {
296
295
  // No-op for now
297
296
  }
298
297
  }
299
- //# sourceMappingURL=SqliteBucketStorage.js.map
@@ -9,4 +9,3 @@ export class SyncDataBatch {
9
9
  this.buckets = buckets;
10
10
  }
11
11
  }
12
- //# sourceMappingURL=SyncDataBatch.js.map
@@ -38,4 +38,3 @@ export class SyncDataBucket {
38
38
  };
39
39
  }
40
40
  }
41
- //# sourceMappingURL=SyncDataBucket.js.map
@@ -1,15 +1,41 @@
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';
4
6
  export type RemoteConnector = {
5
7
  fetchCredentials: () => Promise<PowerSyncCredentials | null>;
6
8
  };
7
9
  export declare const DEFAULT_REMOTE_LOGGER: ILogger;
10
+ export type SyncStreamOptions = {
11
+ path: string;
12
+ data: StreamingSyncRequest;
13
+ headers?: Record<string, string>;
14
+ abortSignal?: AbortSignal;
15
+ fetchOptions?: Request;
16
+ };
17
+ export type AbstractRemoteOptions = {
18
+ /**
19
+ * Transforms the PowerSync base URL which might contain
20
+ * `http(s)://` to the corresponding WebSocket variant
21
+ * e.g. `ws(s)://`
22
+ */
23
+ socketUrlTransformer: (url: string) => string;
24
+ /**
25
+ * Optionally provide the fetch implementation to use.
26
+ * Note that this usually needs to be bound to the global scope.
27
+ * Binding should be done before passing here.
28
+ */
29
+ fetchImplementation: typeof fetch;
30
+ };
31
+ export declare const DEFAULT_REMOTE_OPTIONS: AbstractRemoteOptions;
8
32
  export declare abstract class AbstractRemote {
9
33
  protected connector: RemoteConnector;
10
34
  protected logger: ILogger;
11
35
  protected credentials: PowerSyncCredentials | null;
12
- constructor(connector: RemoteConnector, logger?: ILogger);
36
+ protected options: AbstractRemoteOptions;
37
+ constructor(connector: RemoteConnector, logger?: ILogger, options?: Partial<AbstractRemoteOptions>);
38
+ get fetch(): typeof globalThis.fetch;
13
39
  getCredentials(): Promise<PowerSyncCredentials | null>;
14
40
  protected buildRequest(path: string): Promise<{
15
41
  url: string;
@@ -18,8 +44,15 @@ export declare abstract class AbstractRemote {
18
44
  Authorization: string;
19
45
  };
20
46
  }>;
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;
47
+ post(path: string, data: any, headers?: Record<string, string>): Promise<any>;
48
+ get(path: string, headers?: Record<string, string>): Promise<any>;
49
+ postStreaming(path: string, data: any, headers?: Record<string, string>, signal?: AbortSignal): Promise<any>;
50
+ /**
51
+ * Connects to the sync/stream websocket endpoint
52
+ */
53
+ socketStream(options: SyncStreamOptions): Promise<DataStream<StreamingSyncLine>>;
54
+ /**
55
+ * Connects to the sync/stream http endpoint
56
+ */
57
+ postStream(options: SyncStreamOptions): Promise<DataStream<StreamingSyncLine>>;
25
58
  }
@@ -1,14 +1,42 @@
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 { serialize, deserialize } from 'bson';
8
+ import { AbortOperation } from '../../../utils/AbortOperation';
9
+ import { Buffer } from 'buffer';
2
10
  // Refresh at least 30 sec before it expires
3
11
  const REFRESH_CREDENTIALS_SAFETY_PERIOD_MS = 30_000;
12
+ const SYNC_QUEUE_REQUEST_N = 10;
13
+ const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
14
+ // Keep alive message is sent every period
15
+ const KEEP_ALIVE_MS = 20_000;
16
+ // The ACK must be received in this period
17
+ const KEEP_ALIVE_LIFETIME_MS = 30_000;
4
18
  export const DEFAULT_REMOTE_LOGGER = Logger.get('PowerSyncRemote');
19
+ export const DEFAULT_REMOTE_OPTIONS = {
20
+ socketUrlTransformer: (url) => url.replace(/^https?:\/\//, function (match) {
21
+ return match === 'https://' ? 'wss://' : 'ws://';
22
+ }),
23
+ fetchImplementation: fetch.bind(globalThis)
24
+ };
5
25
  export class AbstractRemote {
6
26
  connector;
7
27
  logger;
8
28
  credentials = null;
9
- constructor(connector, logger = DEFAULT_REMOTE_LOGGER) {
29
+ options;
30
+ constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {
10
31
  this.connector = connector;
11
32
  this.logger = logger;
33
+ this.options = {
34
+ ...DEFAULT_REMOTE_OPTIONS,
35
+ ...(options ?? {})
36
+ };
37
+ }
38
+ get fetch() {
39
+ return this.options.fetchImplementation;
12
40
  }
13
41
  async getCredentials() {
14
42
  const { expiresAt } = this.credentials ?? {};
@@ -36,8 +64,299 @@ export class AbstractRemote {
36
64
  }
37
65
  };
38
66
  }
39
- isAvailable() {
40
- return true;
67
+ async post(path, data, headers = {}) {
68
+ const request = await this.buildRequest(path);
69
+ const res = await fetch(request.url, {
70
+ method: 'POST',
71
+ headers: {
72
+ ...headers,
73
+ ...request.headers
74
+ },
75
+ body: JSON.stringify(data)
76
+ });
77
+ if (!res.ok) {
78
+ throw new Error(`Received ${res.status} - ${res.statusText} when posting to ${path}: ${await res.text()}}`);
79
+ }
80
+ return res.json();
81
+ }
82
+ async get(path, headers) {
83
+ const request = await this.buildRequest(path);
84
+ const res = await this.fetch(request.url, {
85
+ method: 'GET',
86
+ headers: {
87
+ ...headers,
88
+ ...request.headers
89
+ }
90
+ });
91
+ if (!res.ok) {
92
+ throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
93
+ }
94
+ return res.json();
95
+ }
96
+ async postStreaming(path, data, headers = {}, signal) {
97
+ const request = await this.buildRequest(path);
98
+ const res = await this.fetch(request.url, {
99
+ method: 'POST',
100
+ headers: { ...headers, ...request.headers },
101
+ body: JSON.stringify(data),
102
+ signal,
103
+ cache: 'no-store'
104
+ }).catch((ex) => {
105
+ this.logger.error(`Caught ex when POST streaming to ${path}`, ex);
106
+ throw ex;
107
+ });
108
+ if (!res.ok) {
109
+ const text = await res.text();
110
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
111
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
112
+ error.status = res.status;
113
+ throw error;
114
+ }
115
+ return res;
116
+ }
117
+ /**
118
+ * Connects to the sync/stream websocket endpoint
119
+ */
120
+ async socketStream(options) {
121
+ const { path } = options;
122
+ const request = await this.buildRequest(path);
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(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(serialize(options.data)),
171
+ metadata: Buffer.from(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 = 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
  }
43
- //# sourceMappingURL=AbstractRemote.js.map
@@ -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
  }