@powersync/common 1.32.0 → 1.33.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.
- package/dist/bundle.cjs +22 -0
- package/dist/bundle.mjs +5 -5
- package/lib/client/ConnectionManager.js +0 -1
- package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +15 -9
- package/lib/client/sync/bucket/BucketStorageAdapter.js +9 -0
- package/lib/client/sync/bucket/CrudEntry.d.ts +2 -0
- package/lib/client/sync/bucket/CrudEntry.js +13 -2
- package/lib/client/sync/bucket/OplogEntry.d.ts +4 -4
- package/lib/client/sync/bucket/OplogEntry.js +5 -3
- package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +6 -14
- package/lib/client/sync/bucket/SqliteBucketStorage.js +24 -44
- package/lib/client/sync/bucket/SyncDataBucket.d.ts +1 -1
- package/lib/client/sync/bucket/SyncDataBucket.js +2 -2
- package/lib/client/sync/stream/AbstractRemote.d.ts +15 -3
- package/lib/client/sync/stream/AbstractRemote.js +95 -83
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +69 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +462 -217
- package/lib/client/sync/stream/core-instruction.d.ts +53 -0
- package/lib/client/sync/stream/core-instruction.js +1 -0
- package/lib/db/crud/SyncProgress.d.ts +2 -6
- package/lib/db/crud/SyncProgress.js +2 -2
- package/lib/utils/DataStream.d.ts +13 -14
- package/lib/utils/DataStream.js +27 -29
- package/package.json +4 -4
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Buffer } from 'buffer';
|
|
2
|
-
import ndjsonStream from 'can-ndjson-stream';
|
|
3
2
|
import Logger from 'js-logger';
|
|
4
3
|
import { RSocketConnector } from 'rsocket-core';
|
|
5
4
|
import PACKAGE from '../../../../package.json' with { type: 'json' };
|
|
@@ -11,8 +10,12 @@ const POWERSYNC_JS_VERSION = PACKAGE.version;
|
|
|
11
10
|
const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
|
|
12
11
|
// Keep alive message is sent every period
|
|
13
12
|
const KEEP_ALIVE_MS = 20_000;
|
|
14
|
-
//
|
|
15
|
-
const
|
|
13
|
+
// One message of any type must be received in this period.
|
|
14
|
+
const SOCKET_TIMEOUT_MS = 30_000;
|
|
15
|
+
// One keepalive message must be received in this period.
|
|
16
|
+
// If there is a backlog of messages (for example on slow connections), keepalive messages could be delayed
|
|
17
|
+
// significantly. Therefore this is longer than the socket timeout.
|
|
18
|
+
const KEEP_ALIVE_LIFETIME_MS = 90_000;
|
|
16
19
|
export const DEFAULT_REMOTE_LOGGER = Logger.get('PowerSyncRemote');
|
|
17
20
|
export var FetchStrategy;
|
|
18
21
|
(function (FetchStrategy) {
|
|
@@ -172,64 +175,75 @@ export class AbstractRemote {
|
|
|
172
175
|
}
|
|
173
176
|
return res.json();
|
|
174
177
|
}
|
|
175
|
-
async postStreaming(path, data, headers = {}, signal) {
|
|
176
|
-
const request = await this.buildRequest(path);
|
|
177
|
-
const res = await this.fetch(request.url, {
|
|
178
|
-
method: 'POST',
|
|
179
|
-
headers: { ...headers, ...request.headers },
|
|
180
|
-
body: JSON.stringify(data),
|
|
181
|
-
signal,
|
|
182
|
-
cache: 'no-store'
|
|
183
|
-
}).catch((ex) => {
|
|
184
|
-
this.logger.error(`Caught ex when POST streaming to ${path}`, ex);
|
|
185
|
-
throw ex;
|
|
186
|
-
});
|
|
187
|
-
if (res.status === 401) {
|
|
188
|
-
this.invalidateCredentials();
|
|
189
|
-
}
|
|
190
|
-
if (!res.ok) {
|
|
191
|
-
const text = await res.text();
|
|
192
|
-
this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
|
|
193
|
-
const error = new Error(`HTTP ${res.statusText}: ${text}`);
|
|
194
|
-
error.status = res.status;
|
|
195
|
-
throw error;
|
|
196
|
-
}
|
|
197
|
-
return res;
|
|
198
|
-
}
|
|
199
178
|
createSocket(url) {
|
|
200
179
|
return new WebSocket(url);
|
|
201
180
|
}
|
|
202
181
|
/**
|
|
203
|
-
* Connects to the sync/stream websocket endpoint
|
|
182
|
+
* Connects to the sync/stream websocket endpoint and delivers sync lines by decoding the BSON events
|
|
183
|
+
* sent by the server.
|
|
204
184
|
*/
|
|
205
185
|
async socketStream(options) {
|
|
186
|
+
const bson = await this.getBSON();
|
|
187
|
+
return await this.socketStreamRaw(options, (data) => bson.deserialize(data), bson);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Returns a data stream of sync line data.
|
|
191
|
+
*
|
|
192
|
+
* @param map Maps received payload frames to the typed event value.
|
|
193
|
+
* @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
|
|
194
|
+
* (required for compatibility with older sync services).
|
|
195
|
+
*/
|
|
196
|
+
async socketStreamRaw(options, map, bson) {
|
|
206
197
|
const { path, fetchStrategy = FetchStrategy.Buffered } = options;
|
|
198
|
+
const mimeType = bson == null ? 'application/json' : 'application/bson';
|
|
199
|
+
function toBuffer(js) {
|
|
200
|
+
let contents;
|
|
201
|
+
if (bson != null) {
|
|
202
|
+
contents = bson.serialize(js);
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
contents = JSON.stringify(js);
|
|
206
|
+
}
|
|
207
|
+
return Buffer.from(contents);
|
|
208
|
+
}
|
|
207
209
|
const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;
|
|
208
210
|
const request = await this.buildRequest(path);
|
|
209
|
-
const bson = await this.getBSON();
|
|
210
211
|
// Add the user agent in the setup payload - we can't set custom
|
|
211
212
|
// headers with websockets on web. The browser userAgent is however added
|
|
212
213
|
// automatically as a header.
|
|
213
214
|
const userAgent = this.getUserAgent();
|
|
215
|
+
let keepAliveTimeout;
|
|
216
|
+
const resetTimeout = () => {
|
|
217
|
+
clearTimeout(keepAliveTimeout);
|
|
218
|
+
keepAliveTimeout = setTimeout(() => {
|
|
219
|
+
this.logger.error(`No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`);
|
|
220
|
+
stream.close();
|
|
221
|
+
}, SOCKET_TIMEOUT_MS);
|
|
222
|
+
};
|
|
223
|
+
resetTimeout();
|
|
214
224
|
const url = this.options.socketUrlTransformer(request.url);
|
|
215
225
|
const connector = new RSocketConnector({
|
|
216
226
|
transport: new WebsocketClientTransport({
|
|
217
227
|
url,
|
|
218
228
|
wsCreator: (url) => {
|
|
219
|
-
|
|
229
|
+
const socket = this.createSocket(url);
|
|
230
|
+
socket.addEventListener('message', (event) => {
|
|
231
|
+
resetTimeout();
|
|
232
|
+
});
|
|
233
|
+
return socket;
|
|
220
234
|
}
|
|
221
235
|
}),
|
|
222
236
|
setup: {
|
|
223
237
|
keepAlive: KEEP_ALIVE_MS,
|
|
224
238
|
lifetime: KEEP_ALIVE_LIFETIME_MS,
|
|
225
|
-
dataMimeType:
|
|
226
|
-
metadataMimeType:
|
|
239
|
+
dataMimeType: mimeType,
|
|
240
|
+
metadataMimeType: mimeType,
|
|
227
241
|
payload: {
|
|
228
242
|
data: null,
|
|
229
|
-
metadata:
|
|
243
|
+
metadata: toBuffer({
|
|
230
244
|
token: request.headers.Authorization,
|
|
231
245
|
user_agent: userAgent
|
|
232
|
-
})
|
|
246
|
+
})
|
|
233
247
|
}
|
|
234
248
|
}
|
|
235
249
|
});
|
|
@@ -239,16 +253,20 @@ export class AbstractRemote {
|
|
|
239
253
|
}
|
|
240
254
|
catch (ex) {
|
|
241
255
|
this.logger.error(`Failed to connect WebSocket`, ex);
|
|
256
|
+
clearTimeout(keepAliveTimeout);
|
|
242
257
|
throw ex;
|
|
243
258
|
}
|
|
259
|
+
resetTimeout();
|
|
244
260
|
const stream = new DataStream({
|
|
245
261
|
logger: this.logger,
|
|
246
262
|
pressure: {
|
|
247
263
|
lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
|
|
248
|
-
}
|
|
264
|
+
},
|
|
265
|
+
mapLine: map
|
|
249
266
|
});
|
|
250
267
|
let socketIsClosed = false;
|
|
251
268
|
const closeSocket = () => {
|
|
269
|
+
clearTimeout(keepAliveTimeout);
|
|
252
270
|
if (socketIsClosed) {
|
|
253
271
|
return;
|
|
254
272
|
}
|
|
@@ -268,10 +286,10 @@ export class AbstractRemote {
|
|
|
268
286
|
const socket = await new Promise((resolve, reject) => {
|
|
269
287
|
let connectionEstablished = false;
|
|
270
288
|
const res = rsocket.requestStream({
|
|
271
|
-
data:
|
|
272
|
-
metadata:
|
|
289
|
+
data: toBuffer(options.data),
|
|
290
|
+
metadata: toBuffer({
|
|
273
291
|
path
|
|
274
|
-
})
|
|
292
|
+
})
|
|
275
293
|
}, syncQueueRequestSize, // The initial N amount
|
|
276
294
|
{
|
|
277
295
|
onError: (e) => {
|
|
@@ -310,8 +328,7 @@ export class AbstractRemote {
|
|
|
310
328
|
if (!data) {
|
|
311
329
|
return;
|
|
312
330
|
}
|
|
313
|
-
|
|
314
|
-
stream.enqueueData(deserializedData);
|
|
331
|
+
stream.enqueueData(data);
|
|
315
332
|
},
|
|
316
333
|
onComplete: () => {
|
|
317
334
|
stream.close();
|
|
@@ -347,9 +364,17 @@ export class AbstractRemote {
|
|
|
347
364
|
return stream;
|
|
348
365
|
}
|
|
349
366
|
/**
|
|
350
|
-
* Connects to the sync/stream http endpoint
|
|
367
|
+
* Connects to the sync/stream http endpoint, parsing lines as JSON.
|
|
351
368
|
*/
|
|
352
369
|
async postStream(options) {
|
|
370
|
+
return await this.postStreamRaw(options, (line) => {
|
|
371
|
+
return JSON.parse(line);
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Connects to the sync/stream http endpoint, mapping and emitting each received string line.
|
|
376
|
+
*/
|
|
377
|
+
async postStreamRaw(options, mapLine) {
|
|
353
378
|
const { data, path, headers, abortSignal } = options;
|
|
354
379
|
const request = await this.buildRequest(path);
|
|
355
380
|
/**
|
|
@@ -395,11 +420,8 @@ export class AbstractRemote {
|
|
|
395
420
|
error.status = res.status;
|
|
396
421
|
throw error;
|
|
397
422
|
}
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
* This will intercept the readable stream and close the stream if
|
|
401
|
-
* aborted.
|
|
402
|
-
*/
|
|
423
|
+
// Create a new stream splitting the response at line endings while also handling cancellations
|
|
424
|
+
// by closing the reader.
|
|
403
425
|
const reader = res.body.getReader();
|
|
404
426
|
// This will close the network request and read stream
|
|
405
427
|
const closeReader = async () => {
|
|
@@ -414,49 +436,39 @@ export class AbstractRemote {
|
|
|
414
436
|
abortSignal?.addEventListener('abort', () => {
|
|
415
437
|
closeReader();
|
|
416
438
|
});
|
|
417
|
-
const
|
|
418
|
-
|
|
419
|
-
const processStream = async () => {
|
|
420
|
-
while (!abortSignal?.aborted) {
|
|
421
|
-
try {
|
|
422
|
-
const { done, value } = await reader.read();
|
|
423
|
-
// When no more data needs to be consumed, close the stream
|
|
424
|
-
if (done) {
|
|
425
|
-
break;
|
|
426
|
-
}
|
|
427
|
-
// Enqueue the next data chunk into our target stream
|
|
428
|
-
controller.enqueue(value);
|
|
429
|
-
}
|
|
430
|
-
catch (ex) {
|
|
431
|
-
this.logger.error('Caught exception when reading sync stream', ex);
|
|
432
|
-
break;
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
if (!abortSignal?.aborted) {
|
|
436
|
-
// Close the downstream readable stream
|
|
437
|
-
await closeReader();
|
|
438
|
-
}
|
|
439
|
-
controller.close();
|
|
440
|
-
};
|
|
441
|
-
processStream();
|
|
442
|
-
}
|
|
443
|
-
});
|
|
444
|
-
const jsonS = ndjsonStream(outputStream);
|
|
439
|
+
const decoder = new TextDecoder();
|
|
440
|
+
let buffer = '';
|
|
445
441
|
const stream = new DataStream({
|
|
446
|
-
logger: this.logger
|
|
442
|
+
logger: this.logger,
|
|
443
|
+
mapLine: mapLine
|
|
447
444
|
});
|
|
448
|
-
const r = jsonS.getReader();
|
|
449
445
|
const l = stream.registerListener({
|
|
450
446
|
lowWater: async () => {
|
|
451
447
|
try {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
448
|
+
let didCompleteLine = false;
|
|
449
|
+
while (!didCompleteLine) {
|
|
450
|
+
const { done, value } = await reader.read();
|
|
451
|
+
if (done) {
|
|
452
|
+
const remaining = buffer.trim();
|
|
453
|
+
if (remaining.length != 0) {
|
|
454
|
+
stream.enqueueData(remaining);
|
|
455
|
+
}
|
|
456
|
+
stream.close();
|
|
457
|
+
await closeReader();
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
const data = decoder.decode(value, { stream: true });
|
|
461
|
+
buffer += data;
|
|
462
|
+
const lines = buffer.split('\n');
|
|
463
|
+
for (var i = 0; i < lines.length - 1; i++) {
|
|
464
|
+
var l = lines[i].trim();
|
|
465
|
+
if (l.length > 0) {
|
|
466
|
+
stream.enqueueData(l);
|
|
467
|
+
didCompleteLine = true;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
buffer = lines[lines.length - 1];
|
|
458
471
|
}
|
|
459
|
-
stream.enqueueData(value);
|
|
460
472
|
}
|
|
461
473
|
catch (ex) {
|
|
462
474
|
stream.close();
|
|
@@ -12,6 +12,48 @@ export declare enum SyncStreamConnectionMethod {
|
|
|
12
12
|
HTTP = "http",
|
|
13
13
|
WEB_SOCKET = "web-socket"
|
|
14
14
|
}
|
|
15
|
+
export declare enum SyncClientImplementation {
|
|
16
|
+
/**
|
|
17
|
+
* Decodes and handles sync lines received from the sync service in JavaScript.
|
|
18
|
+
*
|
|
19
|
+
* This is the default option.
|
|
20
|
+
*
|
|
21
|
+
* @deprecated Don't use {@link SyncClientImplementation.JAVASCRIPT} directly. Instead, use
|
|
22
|
+
* {@link DEFAULT_SYNC_CLIENT_IMPLEMENTATION} or omit the option. The explicit choice to use
|
|
23
|
+
* the JavaScript-based sync implementation will be removed from a future version of the SDK.
|
|
24
|
+
*/
|
|
25
|
+
JAVASCRIPT = "js",
|
|
26
|
+
/**
|
|
27
|
+
* This implementation offloads the sync line decoding and handling into the PowerSync
|
|
28
|
+
* core extension.
|
|
29
|
+
*
|
|
30
|
+
* @experimental
|
|
31
|
+
* While this implementation is more performant than {@link SyncClientImplementation.JAVASCRIPT},
|
|
32
|
+
* it has seen less real-world testing and is marked as __experimental__ at the moment.
|
|
33
|
+
*
|
|
34
|
+
* ## Compatibility warning
|
|
35
|
+
*
|
|
36
|
+
* The Rust sync client stores sync data in a format that is slightly different than the one used
|
|
37
|
+
* by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing
|
|
38
|
+
* databases, the PowerSync SDK will migrate the format automatically.
|
|
39
|
+
* Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
|
|
40
|
+
* the version introducing {@link RUST} as an option) also supports the new format, so you can switch
|
|
41
|
+
* back to {@link JAVASCRIPT} later.
|
|
42
|
+
*
|
|
43
|
+
* __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later
|
|
44
|
+
* downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)
|
|
45
|
+
* can lead to sync issues.
|
|
46
|
+
*/
|
|
47
|
+
RUST = "rust"
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The default {@link SyncClientImplementation} to use.
|
|
51
|
+
*
|
|
52
|
+
* Please use this field instead of {@link SyncClientImplementation.JAVASCRIPT} directly. A future version
|
|
53
|
+
* of the PowerSync SDK will enable {@link SyncClientImplementation.RUST} by default and remove the JavaScript
|
|
54
|
+
* option.
|
|
55
|
+
*/
|
|
56
|
+
export declare const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.JAVASCRIPT;
|
|
15
57
|
/**
|
|
16
58
|
* Abstract Lock to be implemented by various JS environments
|
|
17
59
|
*/
|
|
@@ -50,6 +92,14 @@ export interface PowerSyncConnectionOptions extends BaseConnectionOptions, Addit
|
|
|
50
92
|
}
|
|
51
93
|
/** @internal */
|
|
52
94
|
export interface BaseConnectionOptions {
|
|
95
|
+
/**
|
|
96
|
+
* Whether to use a JavaScript implementation to handle received sync lines from the sync
|
|
97
|
+
* service, or whether this work should be offloaded to the PowerSync core extension.
|
|
98
|
+
*
|
|
99
|
+
* This defaults to the JavaScript implementation ({@link SyncClientImplementation.JAVASCRIPT})
|
|
100
|
+
* since the ({@link SyncClientImplementation.RUST}) implementation is experimental at the moment.
|
|
101
|
+
*/
|
|
102
|
+
clientImplementation?: SyncClientImplementation;
|
|
53
103
|
/**
|
|
54
104
|
* The connection method to use when streaming updates from
|
|
55
105
|
* the PowerSync backend instance.
|
|
@@ -117,6 +167,7 @@ export declare abstract class AbstractStreamingSyncImplementation extends BaseOb
|
|
|
117
167
|
protected crudUpdateListener?: () => void;
|
|
118
168
|
protected streamingSyncPromise?: Promise<void>;
|
|
119
169
|
private pendingCrudUpload?;
|
|
170
|
+
private notifyCompletedUploads?;
|
|
120
171
|
syncStatus: SyncStatus;
|
|
121
172
|
triggerCrudUpload: () => void;
|
|
122
173
|
constructor(options: AbstractStreamingSyncImplementationOptions);
|
|
@@ -138,7 +189,25 @@ export declare abstract class AbstractStreamingSyncImplementation extends BaseOb
|
|
|
138
189
|
*/
|
|
139
190
|
streamingSync(signal?: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void>;
|
|
140
191
|
private collectLocalBucketState;
|
|
192
|
+
/**
|
|
193
|
+
* Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
|
|
194
|
+
* Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
|
|
195
|
+
* While this is not a problem as long as it's done consistently, it causes issues when a database
|
|
196
|
+
* created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
|
|
197
|
+
* is enabled.
|
|
198
|
+
*
|
|
199
|
+
* So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
|
|
200
|
+
* migration is only triggered when necessary (for now). The function returns whether the new format
|
|
201
|
+
* should be used, so that the JS SDK is able to write to updated databases.
|
|
202
|
+
*
|
|
203
|
+
* @param requireFixedKeyFormat Whether we require the new format or also support the old one.
|
|
204
|
+
* The Rust client requires the new subkey format.
|
|
205
|
+
* @returns Whether the database is now using the new, fixed subkey format.
|
|
206
|
+
*/
|
|
207
|
+
private requireKeyFormat;
|
|
141
208
|
protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void>;
|
|
209
|
+
private legacyStreamingSyncIteration;
|
|
210
|
+
private rustSyncIteration;
|
|
142
211
|
private updateSyncStatusForStartingCheckpoint;
|
|
143
212
|
private applyCheckpoint;
|
|
144
213
|
protected updateSyncStatus(options: SyncStatusOptions): void;
|