@powersync/shared-internals 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/websockets.mjs +29 -1
- package/dist/websockets.mjs.map +1 -1
- package/dist/websockets.node.mjs +29 -1
- package/dist/websockets.node.mjs.map +1 -1
- package/lib/client/BasePowerSyncDatabase.d.ts +12 -6
- package/lib/client/BasePowerSyncDatabase.js +11 -15
- package/lib/client/BasePowerSyncDatabase.js.map +1 -1
- package/lib/client/ConnectionManager.d.ts +6 -5
- package/lib/client/ConnectionManager.js +22 -14
- package/lib/client/ConnectionManager.js.map +1 -1
- package/lib/client/InternalConnector.d.ts +9 -0
- package/lib/client/InternalConnector.js +42 -0
- package/lib/client/InternalConnector.js.map +1 -0
- package/lib/client/sync/options.d.ts +4 -0
- package/lib/client/sync/options.js +5 -0
- package/lib/client/sync/options.js.map +1 -1
- package/lib/client/sync/stream/AbstractRemote.d.ts +7 -9
- package/lib/client/sync/stream/AbstractRemote.js +13 -5
- package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +6 -13
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +135 -82
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
- package/lib/client/sync/stream/WebSocketSupport.js +29 -1
- package/lib/client/sync/stream/WebSocketSupport.js.map +1 -1
- package/lib/client/sync/stream/core-instruction.d.ts +2 -0
- package/lib/client/sync/stream/core-instruction.js.map +1 -1
- package/lib/client/watched/DifferentialQueryProcessor.js +5 -0
- package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/lib/utils/async.d.ts +6 -0
- package/lib/utils/async.js +31 -0
- package/lib/utils/async.js.map +1 -1
- package/lib/version.d.ts +1 -1
- package/lib/version.js +1 -1
- package/package.json +3 -3
- package/src/client/BasePowerSyncDatabase.ts +24 -19
- package/src/client/ConnectionManager.ts +25 -19
- package/src/client/InternalConnector.ts +68 -0
- package/src/client/sync/options.ts +6 -0
- package/src/client/sync/stream/AbstractRemote.ts +33 -25
- package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +163 -105
- package/src/client/sync/stream/WebSocketSupport.ts +32 -1
- package/src/client/sync/stream/core-instruction.ts +1 -0
- package/src/client/watched/DifferentialQueryProcessor.ts +5 -0
- package/src/index.ts +1 -0
- package/src/utils/async.ts +36 -0
- package/src/version.ts +1 -1
|
@@ -28,10 +28,11 @@ import {
|
|
|
28
28
|
SimpleAsyncIterator,
|
|
29
29
|
valueResult
|
|
30
30
|
} from '../../../utils/stream_transform.js';
|
|
31
|
-
import { asyncNotifier } from '../../../utils/async.js';
|
|
31
|
+
import { asyncNotifier, runWithTimeout } from '../../../utils/async.js';
|
|
32
32
|
import { JavaScriptSyncState, SyncStatusSnapshot } from '../../../db/crud/SyncStatus.js';
|
|
33
|
-
import { ResolvedSyncOptions } from '../options.js';
|
|
33
|
+
import { DEFAULT_CONNECT_TIMEOUT_MS, ResolvedSyncOptions } from '../options.js';
|
|
34
34
|
import { CheckpointStateSignals, isCheckpointRequestApplied } from './CheckpointState.js';
|
|
35
|
+
import { InternalConnector } from '../../InternalConnector.js';
|
|
35
36
|
|
|
36
37
|
/**
|
|
37
38
|
* @internal
|
|
@@ -58,18 +59,7 @@ export interface LockOptions<T> {
|
|
|
58
59
|
export interface AbstractStreamingSyncImplementationOptions {
|
|
59
60
|
adapter: BucketStorageAdapter;
|
|
60
61
|
subscriptions: SubscribedStream[];
|
|
61
|
-
|
|
62
|
-
* Uploads pending CRUD data.
|
|
63
|
-
* Cross-context implementations must stop waiting when `signal` aborts
|
|
64
|
-
* on disconnect, allowing the sync loops to finish.
|
|
65
|
-
*/
|
|
66
|
-
uploadCrud: (signal?: AbortSignal) => Promise<void>;
|
|
67
|
-
/**
|
|
68
|
-
* Posts a checkpoint request with the connector, returning null if the connector doesn't support that.
|
|
69
|
-
*
|
|
70
|
-
* See {@link AbstractStreamingSyncImplementationOptions.uploadCrud} for the semantics of `signal`.
|
|
71
|
-
*/
|
|
72
|
-
postCheckpointRequest: (clientId: string, requestId: string, signal?: AbortSignal) => Promise<string | null> | null;
|
|
62
|
+
connector: InternalConnector;
|
|
73
63
|
/**
|
|
74
64
|
* An identifier for which PowerSync DB this sync implementation is
|
|
75
65
|
* linked to. Most commonly DB name, but not restricted to DB name.
|
|
@@ -135,12 +125,13 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
135
125
|
protected options: AbstractStreamingSyncImplementationOptions;
|
|
136
126
|
protected abortController: AbortController | null;
|
|
137
127
|
protected crudUpdateListener?: () => void;
|
|
138
|
-
protected streamingSyncPromise?: Promise<[
|
|
128
|
+
protected streamingSyncPromise?: Promise<void[]>;
|
|
139
129
|
protected logger: PowerSyncLogger;
|
|
140
130
|
protected activeStreams: SubscribedStream[];
|
|
141
131
|
private connectionMayHaveChanged = false;
|
|
142
132
|
private crudUploadNotifier = asyncNotifier();
|
|
143
133
|
private checkpoints = new CheckpointStateSignals();
|
|
134
|
+
private connectTimeoutMs = DEFAULT_CONNECT_TIMEOUT_MS;
|
|
144
135
|
|
|
145
136
|
private notifyCompletedUploads?: () => void;
|
|
146
137
|
private handleActiveStreamsChange?: () => void;
|
|
@@ -217,39 +208,49 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
217
208
|
});
|
|
218
209
|
}
|
|
219
210
|
|
|
220
|
-
private
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
request.checkpoint_request_id,
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
return customResponse;
|
|
211
|
+
private requestCheckpointFromService(abort: AbortSignal, request: CheckpointRequestPayload): Promise<string> {
|
|
212
|
+
return runWithTimeout(abort, this.connectTimeoutMs, 'Checkpoint request', async (signal) => {
|
|
213
|
+
// First, check if we can use a custom checkpoint request implementation.
|
|
214
|
+
const custom = this.options.connector.postCheckpointRequest;
|
|
215
|
+
if (custom) {
|
|
216
|
+
const customResponse = await custom(request.client_id, request.checkpoint_request_id, signal);
|
|
217
|
+
if (customResponse != null) {
|
|
218
|
+
return customResponse;
|
|
219
|
+
}
|
|
230
220
|
}
|
|
231
|
-
}
|
|
232
221
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
222
|
+
const status = await this.options.remote.fetchAndDecodeJson({
|
|
223
|
+
method: 'POST',
|
|
224
|
+
path: '/sync/checkpoint-request',
|
|
225
|
+
body: JSON.stringify(request),
|
|
226
|
+
signal
|
|
227
|
+
});
|
|
239
228
|
|
|
240
|
-
|
|
229
|
+
return status.data.checkpoint_request_id;
|
|
230
|
+
});
|
|
241
231
|
}
|
|
242
232
|
|
|
243
|
-
private async getLegacyWriteCheckpoint(): Promise<string> {
|
|
233
|
+
private async getLegacyWriteCheckpoint(abort: AbortSignal): Promise<string> {
|
|
244
234
|
const clientId = await this.options.adapter.getClientId();
|
|
245
235
|
let path = `/write-checkpoint2.json?client_id=${clientId}`;
|
|
246
|
-
const response = await this.
|
|
236
|
+
const response = await runWithTimeout(abort, this.connectTimeoutMs, 'Write checkpoint request', (signal) =>
|
|
237
|
+
this.options.remote.fetchAndDecodeJson({ path, signal })
|
|
238
|
+
);
|
|
247
239
|
const checkpoint = response['data']['write_checkpoint'] as string;
|
|
248
240
|
this.logger.log({ level: LogLevels.debug, message: `Created write checkpoint: ${checkpoint}` });
|
|
249
241
|
return checkpoint;
|
|
250
242
|
}
|
|
251
243
|
|
|
252
244
|
private async crudUploadLoop(signal: AbortSignal, options: ResolvedSyncOptions): Promise<void> {
|
|
245
|
+
this.crudUpdateListener = this.options.adapter.registerListener({
|
|
246
|
+
crudUpdate: () => this.triggerCrudUpload()
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
signal.addEventListener('abort', () => {
|
|
250
|
+
this.crudUpdateListener?.();
|
|
251
|
+
this.crudUpdateListener = undefined;
|
|
252
|
+
});
|
|
253
|
+
|
|
253
254
|
while (!signal.aborted) {
|
|
254
255
|
await Promise.all([
|
|
255
256
|
// Start the initial CRUD upload on connect. Then, keep polling until we're done.
|
|
@@ -293,20 +294,13 @@ The next upload iteration will be delayed.`
|
|
|
293
294
|
}
|
|
294
295
|
|
|
295
296
|
checkedCrudItem = nextCrudItem;
|
|
296
|
-
await this.options.uploadCrud(signal);
|
|
297
|
+
await this.options.connector.uploadCrud!(signal);
|
|
297
298
|
this.updateJsSyncState({ uploadError: undefined });
|
|
298
299
|
} else {
|
|
299
300
|
// Uploading is completed
|
|
300
|
-
const neededUpdate =
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
} else {
|
|
304
|
-
return this.requestNextCheckpointFromService(signal);
|
|
305
|
-
}
|
|
306
|
-
});
|
|
307
|
-
if (neededUpdate) {
|
|
308
|
-
this.notifyCompletedUploads?.();
|
|
309
|
-
} else if (checkedCrudItem != null) {
|
|
301
|
+
const neededUpdate =
|
|
302
|
+
this.options.connector.fetchCredentials && (await this.updateLocalTarget(signal, options));
|
|
303
|
+
if (!neededUpdate && checkedCrudItem != null) {
|
|
310
304
|
// Only log this if there was something to upload
|
|
311
305
|
this.logger.log({ level: LogLevels.debug, message: 'Upload complete, no write checkpoint needed.' });
|
|
312
306
|
}
|
|
@@ -316,8 +310,9 @@ The next upload iteration will be delayed.`
|
|
|
316
310
|
checkedCrudItem = undefined;
|
|
317
311
|
this.updateJsSyncState({ uploading: false, uploadError: ex as Error });
|
|
318
312
|
await this.delayRetry(signal, options.retryDelayMs);
|
|
319
|
-
if (!this.isConnected) {
|
|
320
|
-
// Exit the upload loop if the sync stream is no longer connected
|
|
313
|
+
if (this.options.connector.fetchCredentials && !this.isConnected) {
|
|
314
|
+
// Exit the upload loop if the sync stream is no longer connected. The upload is triggered again once it
|
|
315
|
+
// reconnects. In upload-only mode, there is no sync stream and we keep retrying.
|
|
321
316
|
break;
|
|
322
317
|
}
|
|
323
318
|
this.logger.log({
|
|
@@ -333,6 +328,22 @@ The next upload iteration will be delayed.`
|
|
|
333
328
|
});
|
|
334
329
|
}
|
|
335
330
|
|
|
331
|
+
private async updateLocalTarget(signal: AbortSignal, options: ResolvedSyncOptions): Promise<boolean> {
|
|
332
|
+
const didUpdate = await this.options.adapter.updateLocalTarget(() => {
|
|
333
|
+
if (options.checkpointMode === 'legacy') {
|
|
334
|
+
return this.getLegacyWriteCheckpoint(signal);
|
|
335
|
+
} else {
|
|
336
|
+
return this.requestNextCheckpointFromService(signal);
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
if (didUpdate) {
|
|
341
|
+
this.notifyCompletedUploads?.();
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
return didUpdate;
|
|
345
|
+
}
|
|
346
|
+
|
|
336
347
|
async connect(options: ResolvedSyncOptions) {
|
|
337
348
|
if (this.abortController) {
|
|
338
349
|
await this.disconnect();
|
|
@@ -340,68 +351,97 @@ The next upload iteration will be delayed.`
|
|
|
340
351
|
|
|
341
352
|
const controller = new AbortController();
|
|
342
353
|
this.abortController = controller;
|
|
354
|
+
this.connectTimeoutMs = options.connectTimeoutMs;
|
|
343
355
|
const signal = controller.signal;
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
356
|
+
|
|
357
|
+
const syncTasks: Promise<void>[] = [];
|
|
358
|
+
const connector = this.options.connector;
|
|
359
|
+
if (connector.uploadCrud) {
|
|
360
|
+
syncTasks.push(
|
|
361
|
+
this.crudUploadLoop(signal, options).catch((error) => {
|
|
362
|
+
// Requesting the crud lock when aborted will file, but that's not something worth logging.
|
|
363
|
+
if (signal.reason !== error) {
|
|
364
|
+
this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error });
|
|
365
|
+
}
|
|
366
|
+
})
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (connector.fetchCredentials) {
|
|
371
|
+
if (!connector.uploadCrud) {
|
|
372
|
+
// We can't upload mutations, but we can request a checkpoint for mutations that have already been uploaded from a
|
|
373
|
+
// potential prior upload-only connection.
|
|
374
|
+
syncTasks.push(
|
|
375
|
+
this.updateLocalTarget(signal, options)
|
|
376
|
+
.then(() => {})
|
|
377
|
+
.catch((error) => {
|
|
378
|
+
if (signal.reason !== error) {
|
|
379
|
+
this.logger.log({ level: LogLevels.error, message: 'Could not update local target', error });
|
|
380
|
+
}
|
|
381
|
+
})
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
syncTasks.push(this.streamingSync(signal, options));
|
|
386
|
+
syncTasks.push(this.repostUnacknowledgedCheckpointRequests(signal, options));
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
this.streamingSyncPromise = Promise.all(syncTasks).finally(() => {
|
|
354
390
|
// These promises only complete when we want to disconnect. No further sync iteration can resume checkpoint
|
|
355
391
|
// requests, so fail any that are still pending.
|
|
356
392
|
this.checkpoints.disconnected();
|
|
357
393
|
});
|
|
358
394
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
const finish = () => {
|
|
367
|
-
if (settled) {
|
|
368
|
-
return;
|
|
369
|
-
}
|
|
370
|
-
settled = true;
|
|
371
|
-
disposer();
|
|
372
|
-
signal.removeEventListener('abort', finish);
|
|
373
|
-
resolve();
|
|
374
|
-
};
|
|
395
|
+
if (connector.fetchCredentials) {
|
|
396
|
+
// Return a promise that resolves when the connection status is updated to indicate that we're connected, or when
|
|
397
|
+
// this connection attempt is aborted (e.g. superseded by another connect() call) before that happens. We do this
|
|
398
|
+
// by waiting for connecting to be true and then false again.
|
|
399
|
+
return new Promise<void>((resolve) => {
|
|
400
|
+
let sawStartOfConnection = false;
|
|
401
|
+
let settled = false;
|
|
375
402
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
sawStartOfConnection = true;
|
|
403
|
+
const finish = () => {
|
|
404
|
+
if (settled) {
|
|
405
|
+
return;
|
|
380
406
|
}
|
|
407
|
+
settled = true;
|
|
408
|
+
disposer();
|
|
409
|
+
signal.removeEventListener('abort', finish);
|
|
410
|
+
resolve();
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
const disposer = this.registerListener({
|
|
414
|
+
statusChanged: (snapshot) => {
|
|
415
|
+
if (snapshot.connecting) {
|
|
416
|
+
sawStartOfConnection = true;
|
|
417
|
+
}
|
|
381
418
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
419
|
+
if (snapshot.downloadError != null) {
|
|
420
|
+
this.logger.log({
|
|
421
|
+
level: LogLevels.warn,
|
|
422
|
+
message: 'Initial connect attempt did not successfully connect to server'
|
|
423
|
+
});
|
|
424
|
+
} else if (!sawStartOfConnection || snapshot.connecting) {
|
|
425
|
+
// Still connecting.
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
finish();
|
|
390
430
|
}
|
|
431
|
+
});
|
|
391
432
|
|
|
392
|
-
|
|
393
|
-
|
|
433
|
+
// If this attempt is aborted (disconnected) before a `statusChanged` event ever fires - which can happen when
|
|
434
|
+
// the instance never got as far as reporting a connecting status - there's nothing left to wait for.
|
|
435
|
+
signal.addEventListener('abort', finish, { once: true });
|
|
394
436
|
});
|
|
395
|
-
|
|
396
|
-
// If this attempt is aborted (disconnected) before a `statusChanged` event ever fires - which can happen when
|
|
397
|
-
// the instance never got as far as reporting a connecting status - there's nothing left to wait for.
|
|
398
|
-
signal.addEventListener('abort', finish, { once: true });
|
|
399
|
-
});
|
|
437
|
+
}
|
|
400
438
|
}
|
|
401
439
|
|
|
402
440
|
async requestCheckpoint(): Promise<bigint> {
|
|
403
441
|
const neverAbort = new AbortController().signal;
|
|
404
|
-
|
|
442
|
+
// disconnect() aborts the connection's signal. It is missing only when called before connect() starts.
|
|
443
|
+
const untilDisconnected = this.abortController?.signal ?? neverAbort;
|
|
444
|
+
return BigInt(await this.requestNextCheckpointFromService(untilDisconnected));
|
|
405
445
|
}
|
|
406
446
|
|
|
407
447
|
async disconnect(): Promise<void> {
|
|
@@ -443,13 +483,6 @@ The next upload iteration will be delayed.`
|
|
|
443
483
|
}
|
|
444
484
|
|
|
445
485
|
private async streamingSync(signal: AbortSignal, options: ResolvedSyncOptions): Promise<void> {
|
|
446
|
-
/**
|
|
447
|
-
* Listen for CRUD updates and trigger upstream uploads
|
|
448
|
-
*/
|
|
449
|
-
this.crudUpdateListener = this.options.adapter.registerListener({
|
|
450
|
-
crudUpdate: () => this.triggerCrudUpload()
|
|
451
|
-
});
|
|
452
|
-
|
|
453
486
|
/**
|
|
454
487
|
* Create a new abort controller which aborts items downstream.
|
|
455
488
|
* This is needed to close any previous connections on exception.
|
|
@@ -462,8 +495,6 @@ The next upload iteration will be delayed.`
|
|
|
462
495
|
* to the nested abort controller.
|
|
463
496
|
*/
|
|
464
497
|
nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
|
|
465
|
-
this.crudUpdateListener?.();
|
|
466
|
-
this.crudUpdateListener = undefined;
|
|
467
498
|
this.markAsDisconnected();
|
|
468
499
|
});
|
|
469
500
|
|
|
@@ -501,7 +532,10 @@ The next upload iteration will be delayed.`
|
|
|
501
532
|
this.logger.log({ level: LogLevels.warn, message: 'Sync aborted', error: ex });
|
|
502
533
|
shouldDelayRetry = false;
|
|
503
534
|
// A disconnect was requested, we should not delay since there is no explicit retry
|
|
504
|
-
} else if (
|
|
535
|
+
} else if (
|
|
536
|
+
this.connectionMayHaveChanged &&
|
|
537
|
+
(ex as Error | null | undefined)?.message?.includes('No iteration is active')
|
|
538
|
+
) {
|
|
505
539
|
this.connectionMayHaveChanged = false;
|
|
506
540
|
this.logger.log({
|
|
507
541
|
level: LogLevels.info,
|
|
@@ -607,7 +641,7 @@ The next upload iteration will be delayed.`
|
|
|
607
641
|
|
|
608
642
|
const openInner = async () => {
|
|
609
643
|
if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
|
|
610
|
-
return await remote.fetchStream(options);
|
|
644
|
+
return await remote.fetchStream({ ...options, connectTimeoutMs: connection.connectTimeoutMs });
|
|
611
645
|
} else {
|
|
612
646
|
return await this.options.remote.socketStreamRaw({
|
|
613
647
|
...options,
|
|
@@ -713,6 +747,14 @@ The next upload iteration will be delayed.`
|
|
|
713
747
|
await this.options.adapter.readCheckpointRequestId('seed', seed);
|
|
714
748
|
}
|
|
715
749
|
|
|
750
|
+
private async willUpload(): Promise<boolean> {
|
|
751
|
+
if (this.options.connector.uploadCrud) return true;
|
|
752
|
+
|
|
753
|
+
// If we're connected in download-only mode, we can still request checkpoints. But if there's a local write, that
|
|
754
|
+
// won't be uploaded.
|
|
755
|
+
return !(await this.options.adapter.hasCrud());
|
|
756
|
+
}
|
|
757
|
+
|
|
716
758
|
private async rustSyncIteration(
|
|
717
759
|
signal: AbortSignal,
|
|
718
760
|
resolvedOptions: ResolvedSyncOptions
|
|
@@ -829,6 +871,14 @@ The next upload iteration will be delayed.`
|
|
|
829
871
|
syncImplementation.updateJsSyncState({ downloadError: undefined });
|
|
830
872
|
} else if ('HandleDiagnostics' in instruction) {
|
|
831
873
|
syncImplementation.emitDiagnostics(instruction.HandleDiagnostics);
|
|
874
|
+
} else if ('CheckpointDelayedDueToLocalData' in instruction) {
|
|
875
|
+
if (!(await syncImplementation.willUpload())) {
|
|
876
|
+
const message =
|
|
877
|
+
'Applying checkpoint is blocked on local mutations, but no uploader is set. The sync client cannot proceed.';
|
|
878
|
+
|
|
879
|
+
syncImplementation.logger.log({ level: LogLevels.error, message });
|
|
880
|
+
syncImplementation.updateJsSyncState({ downloadError: new Error(message) });
|
|
881
|
+
}
|
|
832
882
|
}
|
|
833
883
|
}
|
|
834
884
|
|
|
@@ -924,6 +974,14 @@ The next upload iteration will be delayed.`
|
|
|
924
974
|
}
|
|
925
975
|
}
|
|
926
976
|
}
|
|
977
|
+
} catch (e) {
|
|
978
|
+
if (!signal.aborted) {
|
|
979
|
+
// The stop() call in finally resets the sync status to disconnected. If we're calling that due to an error, we
|
|
980
|
+
// want to show the error first.
|
|
981
|
+
this.updateJsSyncState({ downloadError: e as Error });
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
throw e;
|
|
927
985
|
} finally {
|
|
928
986
|
this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
|
|
929
987
|
notifyTokenRefreshed = undefined;
|
|
@@ -69,6 +69,9 @@ export class WebSocketSupport {
|
|
|
69
69
|
// While we're connecting (a process that can't be aborted in RSocket), the WebSocket instance to close if we wanted
|
|
70
70
|
// to abort the connection.
|
|
71
71
|
let pendingSocket: WebSocket | null = null;
|
|
72
|
+
// The transport's connect() only settles on `open` or `error`, but a socket that closes while it's still opening fires
|
|
73
|
+
// only `close` on React Native iOS and no event at all on Android. So we fail it ourselves.
|
|
74
|
+
let failPendingConnect: ((error: Error) => void) | null = null;
|
|
72
75
|
let keepAliveTimeout: any;
|
|
73
76
|
let rsocket: RSocket | null = null;
|
|
74
77
|
let paused = false;
|
|
@@ -96,6 +99,7 @@ export class WebSocketSupport {
|
|
|
96
99
|
if (pendingSocket) {
|
|
97
100
|
pendingSocket.close();
|
|
98
101
|
}
|
|
102
|
+
failPendingConnect?.(new Error('WebSocket connection closed while opening'));
|
|
99
103
|
|
|
100
104
|
if (rsocket) {
|
|
101
105
|
rsocket.close();
|
|
@@ -149,6 +153,9 @@ export class WebSocketSupport {
|
|
|
149
153
|
socket.addEventListener('message', () => {
|
|
150
154
|
resetTimeout();
|
|
151
155
|
});
|
|
156
|
+
socket.addEventListener('close', () => {
|
|
157
|
+
failPendingConnect?.(new Error('WebSocket connection closed while opening'));
|
|
158
|
+
});
|
|
152
159
|
return socket;
|
|
153
160
|
}
|
|
154
161
|
}),
|
|
@@ -168,9 +175,20 @@ export class WebSocketSupport {
|
|
|
168
175
|
});
|
|
169
176
|
|
|
170
177
|
try {
|
|
171
|
-
rsocket = await
|
|
178
|
+
rsocket = await new Promise<RSocket>((resolve, reject) => {
|
|
179
|
+
failPendingConnect = reject;
|
|
180
|
+
connector.connect().then((socket) => {
|
|
181
|
+
if (didClose) {
|
|
182
|
+
// We already gave up on this connection, don't leave it open.
|
|
183
|
+
socket.close();
|
|
184
|
+
} else {
|
|
185
|
+
resolve(socket);
|
|
186
|
+
}
|
|
187
|
+
}, reject);
|
|
188
|
+
});
|
|
172
189
|
// The connection is established, we no longer need to monitor the initial timeout
|
|
173
190
|
pendingSocket = null;
|
|
191
|
+
failPendingConnect = null;
|
|
174
192
|
} catch (ex) {
|
|
175
193
|
remote.logger.log({ level: this.#platform.LogLevels.error, message: `Failed to connect WebSocket`, error: ex });
|
|
176
194
|
abortRequest();
|
|
@@ -184,6 +202,8 @@ export class WebSocketSupport {
|
|
|
184
202
|
rsocket.onClose(() => (rsocket = null));
|
|
185
203
|
|
|
186
204
|
return await new Promise((resolve, reject) => {
|
|
205
|
+
failPendingConnect = reject;
|
|
206
|
+
|
|
187
207
|
const queueAsIterator: SimpleAsyncIterator<Uint8Array> = {
|
|
188
208
|
next: async () => {
|
|
189
209
|
if (didClose) return doneResult;
|
|
@@ -222,8 +242,11 @@ export class WebSocketSupport {
|
|
|
222
242
|
if (e.message !== 'Closed. ') {
|
|
223
243
|
remote.logger.log({ level: this.#platform.LogLevels.error, message: 'RSocket error', error: e });
|
|
224
244
|
}
|
|
245
|
+
failPendingConnect = null; // We'll fail this ourselves
|
|
246
|
+
|
|
225
247
|
// RSocket will close the RSocket stream automatically
|
|
226
248
|
// Close the downstream stream as well - this will close the RSocket connection and WebSocket
|
|
249
|
+
|
|
227
250
|
abortRequest();
|
|
228
251
|
// Handles cases where the connection failed e.g. auth error or connection error
|
|
229
252
|
if (!connectionEstablished) {
|
|
@@ -232,6 +255,7 @@ export class WebSocketSupport {
|
|
|
232
255
|
},
|
|
233
256
|
onNext: (payload) => {
|
|
234
257
|
// The connection is active
|
|
258
|
+
failPendingConnect = null;
|
|
235
259
|
if (!connectionEstablished) {
|
|
236
260
|
connectionEstablished = true;
|
|
237
261
|
resolve(queueAsIterator);
|
|
@@ -249,7 +273,14 @@ export class WebSocketSupport {
|
|
|
249
273
|
requestMore();
|
|
250
274
|
},
|
|
251
275
|
onComplete: () => {
|
|
276
|
+
failPendingConnect = null; // We'll fail this ourselves
|
|
252
277
|
abortRequest(); // this will also emit a done event
|
|
278
|
+
|
|
279
|
+
if (!connectionEstablished) {
|
|
280
|
+
// Closed without ever emitting an event? Still emit an empty queue.
|
|
281
|
+
connectionEstablished = true;
|
|
282
|
+
resolve(queueAsIterator);
|
|
283
|
+
}
|
|
253
284
|
},
|
|
254
285
|
onExtension: () => {}
|
|
255
286
|
}
|
|
@@ -83,6 +83,7 @@ export class DifferentialQueryProcessor<RowType>
|
|
|
83
83
|
let hasChanged = false;
|
|
84
84
|
const currentMap = new Map<string, { hash: string; item: RowType }>();
|
|
85
85
|
const removedTracker = new Set(previousMap.keys());
|
|
86
|
+
const previousKeys = previousMap.keys();
|
|
86
87
|
|
|
87
88
|
// Allow mutating to populate the data temporarily.
|
|
88
89
|
const diff = {
|
|
@@ -100,6 +101,10 @@ export class DifferentialQueryProcessor<RowType>
|
|
|
100
101
|
*/
|
|
101
102
|
for (const item of current) {
|
|
102
103
|
const key = keyBy(item);
|
|
104
|
+
// Maps preserve insertion order, so compare the keys pairwise.
|
|
105
|
+
if (!hasChanged && previousKeys.next().value !== key) {
|
|
106
|
+
hasChanged = true;
|
|
107
|
+
}
|
|
103
108
|
const hash = compareBy(item);
|
|
104
109
|
currentMap.set(key, { hash, item });
|
|
105
110
|
|
package/src/index.ts
CHANGED
|
@@ -11,6 +11,7 @@ export * from './db/crud/SyncStatus.js';
|
|
|
11
11
|
export * from './client/ConnectionManager.js';
|
|
12
12
|
export * from './client/sync/options.js';
|
|
13
13
|
|
|
14
|
+
export * from './client/InternalConnector.js';
|
|
14
15
|
export { MEMORY_TRIGGER_CLAIM_MANAGER } from './client/triggers/MemoryTriggerClaimManager.js';
|
|
15
16
|
export * from './client/triggers/TriggerManagerImpl.js';
|
|
16
17
|
export * from './client/watched/DifferentialQueryProcessor.js';
|
package/src/utils/async.ts
CHANGED
|
@@ -183,3 +183,39 @@ export class EventQueue<T> {
|
|
|
183
183
|
};
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Runs `action` with a signal that aborts once `signal` aborts or after `timeoutMs`, whichever comes first.
|
|
189
|
+
*
|
|
190
|
+
* @param description Names the operation in the error thrown when it times out.
|
|
191
|
+
*/
|
|
192
|
+
export async function runWithTimeout<T>(
|
|
193
|
+
signal: AbortSignal | undefined,
|
|
194
|
+
timeoutMs: number,
|
|
195
|
+
description: string,
|
|
196
|
+
action: (signal: AbortSignal) => Promise<T>
|
|
197
|
+
): Promise<T> {
|
|
198
|
+
const controller = new AbortController();
|
|
199
|
+
const timeoutError = new Error(`${description} timed out after ${timeoutMs}ms`);
|
|
200
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
201
|
+
|
|
202
|
+
if (signal?.aborted) {
|
|
203
|
+
onAbort();
|
|
204
|
+
} else {
|
|
205
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
206
|
+
}
|
|
207
|
+
const timeout = setTimeout(() => controller.abort(timeoutError), timeoutMs);
|
|
208
|
+
|
|
209
|
+
try {
|
|
210
|
+
return await action(controller.signal);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
// Some fetch implementations reject with a generic abort error instead of the signal's reason.
|
|
213
|
+
if (controller.signal.reason === timeoutError) {
|
|
214
|
+
throw timeoutError;
|
|
215
|
+
}
|
|
216
|
+
throw error;
|
|
217
|
+
} finally {
|
|
218
|
+
clearTimeout(timeout);
|
|
219
|
+
signal?.removeEventListener('abort', onAbort);
|
|
220
|
+
}
|
|
221
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Note: This file gets updated by tool/update_version.js script as part of the Changesets release workflow.
|
|
2
2
|
// The update happens in the changesets PR, before the package is built.
|
|
3
|
-
export const POWERSYNC_JS_VERSION = '1.
|
|
3
|
+
export const POWERSYNC_JS_VERSION = '1.5.0';
|