@powersync/shared-internals 1.3.1 → 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 +7 -5
- package/lib/client/ConnectionManager.js +29 -15
- 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 +7 -1
- 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 +12 -14
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +147 -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 +28 -1
- 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/db/crud/SyncStatus.d.ts +2 -5
- package/lib/db/crud/SyncStatus.js +5 -18
- package/lib/db/crud/SyncStatus.js.map +1 -1
- package/lib/index.d.ts +3 -0
- package/lib/index.js +2 -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/utils/error-serialization.d.ts +27 -0
- package/lib/utils/error-serialization.js +90 -0
- package/lib/utils/error-serialization.js.map +1 -0
- 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 +32 -19
- package/src/client/InternalConnector.ts +68 -0
- package/src/client/sync/options.ts +8 -1
- package/src/client/sync/stream/AbstractRemote.ts +33 -25
- package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +177 -106
- package/src/client/sync/stream/WebSocketSupport.ts +32 -1
- package/src/client/sync/stream/core-instruction.ts +25 -2
- package/src/client/watched/DifferentialQueryProcessor.ts +5 -0
- package/src/db/crud/SyncStatus.ts +6 -19
- package/src/index.ts +3 -0
- package/src/utils/async.ts +36 -0
- package/src/utils/error-serialization.ts +116 -0
- package/src/version.ts +1 -1
|
@@ -18,7 +18,8 @@ import {
|
|
|
18
18
|
CoreSyncStatus,
|
|
19
19
|
Instruction,
|
|
20
20
|
NonInterruptingInstruction,
|
|
21
|
-
isInterruptingInstruction
|
|
21
|
+
isInterruptingInstruction,
|
|
22
|
+
DiagnosticsEvent
|
|
22
23
|
} from './core-instruction.js';
|
|
23
24
|
import {
|
|
24
25
|
doneResult,
|
|
@@ -27,10 +28,11 @@ import {
|
|
|
27
28
|
SimpleAsyncIterator,
|
|
28
29
|
valueResult
|
|
29
30
|
} from '../../../utils/stream_transform.js';
|
|
30
|
-
import { asyncNotifier } from '../../../utils/async.js';
|
|
31
|
+
import { asyncNotifier, runWithTimeout } from '../../../utils/async.js';
|
|
31
32
|
import { JavaScriptSyncState, SyncStatusSnapshot } from '../../../db/crud/SyncStatus.js';
|
|
32
|
-
import { ResolvedSyncOptions } from '../options.js';
|
|
33
|
+
import { DEFAULT_CONNECT_TIMEOUT_MS, ResolvedSyncOptions } from '../options.js';
|
|
33
34
|
import { CheckpointStateSignals, isCheckpointRequestApplied } from './CheckpointState.js';
|
|
35
|
+
import { InternalConnector } from '../../InternalConnector.js';
|
|
34
36
|
|
|
35
37
|
/**
|
|
36
38
|
* @internal
|
|
@@ -57,18 +59,7 @@ export interface LockOptions<T> {
|
|
|
57
59
|
export interface AbstractStreamingSyncImplementationOptions {
|
|
58
60
|
adapter: BucketStorageAdapter;
|
|
59
61
|
subscriptions: SubscribedStream[];
|
|
60
|
-
|
|
61
|
-
* Uploads pending CRUD data.
|
|
62
|
-
* Cross-context implementations must stop waiting when `signal` aborts
|
|
63
|
-
* on disconnect, allowing the sync loops to finish.
|
|
64
|
-
*/
|
|
65
|
-
uploadCrud: (signal?: AbortSignal) => Promise<void>;
|
|
66
|
-
/**
|
|
67
|
-
* Posts a checkpoint request with the connector, returning null if the connector doesn't support that.
|
|
68
|
-
*
|
|
69
|
-
* See {@link AbstractStreamingSyncImplementationOptions.uploadCrud} for the semantics of `signal`.
|
|
70
|
-
*/
|
|
71
|
-
postCheckpointRequest: (clientId: string, requestId: string, signal?: AbortSignal) => Promise<string | null> | null;
|
|
62
|
+
connector: InternalConnector;
|
|
72
63
|
/**
|
|
73
64
|
* An identifier for which PowerSync DB this sync implementation is
|
|
74
65
|
* linked to. Most commonly DB name, but not restricted to DB name.
|
|
@@ -134,12 +125,13 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
134
125
|
protected options: AbstractStreamingSyncImplementationOptions;
|
|
135
126
|
protected abortController: AbortController | null;
|
|
136
127
|
protected crudUpdateListener?: () => void;
|
|
137
|
-
protected streamingSyncPromise?: Promise<[
|
|
128
|
+
protected streamingSyncPromise?: Promise<void[]>;
|
|
138
129
|
protected logger: PowerSyncLogger;
|
|
139
130
|
protected activeStreams: SubscribedStream[];
|
|
140
131
|
private connectionMayHaveChanged = false;
|
|
141
132
|
private crudUploadNotifier = asyncNotifier();
|
|
142
133
|
private checkpoints = new CheckpointStateSignals();
|
|
134
|
+
private connectTimeoutMs = DEFAULT_CONNECT_TIMEOUT_MS;
|
|
143
135
|
|
|
144
136
|
private notifyCompletedUploads?: () => void;
|
|
145
137
|
private handleActiveStreamsChange?: () => void;
|
|
@@ -195,6 +187,12 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
195
187
|
this.crudUpdateListener = undefined;
|
|
196
188
|
}
|
|
197
189
|
|
|
190
|
+
/**
|
|
191
|
+
* Receives a core diagnostics event (emitted only when diagnostics are enabled on the sync stream).
|
|
192
|
+
* Does nothing here; an SDK with diagnostics tooling overrides it to hand the event on.
|
|
193
|
+
*/
|
|
194
|
+
protected emitDiagnostics(_event: DiagnosticsEvent): void {}
|
|
195
|
+
|
|
198
196
|
abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
|
|
199
197
|
|
|
200
198
|
private async requestNextCheckpointFromService(abort: AbortSignal): Promise<string> {
|
|
@@ -210,39 +208,49 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
210
208
|
});
|
|
211
209
|
}
|
|
212
210
|
|
|
213
|
-
private
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
request.checkpoint_request_id,
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
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
|
+
}
|
|
223
220
|
}
|
|
224
|
-
}
|
|
225
221
|
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
222
|
+
const status = await this.options.remote.fetchAndDecodeJson({
|
|
223
|
+
method: 'POST',
|
|
224
|
+
path: '/sync/checkpoint-request',
|
|
225
|
+
body: JSON.stringify(request),
|
|
226
|
+
signal
|
|
227
|
+
});
|
|
232
228
|
|
|
233
|
-
|
|
229
|
+
return status.data.checkpoint_request_id;
|
|
230
|
+
});
|
|
234
231
|
}
|
|
235
232
|
|
|
236
|
-
private async getLegacyWriteCheckpoint(): Promise<string> {
|
|
233
|
+
private async getLegacyWriteCheckpoint(abort: AbortSignal): Promise<string> {
|
|
237
234
|
const clientId = await this.options.adapter.getClientId();
|
|
238
235
|
let path = `/write-checkpoint2.json?client_id=${clientId}`;
|
|
239
|
-
const response = await this.
|
|
236
|
+
const response = await runWithTimeout(abort, this.connectTimeoutMs, 'Write checkpoint request', (signal) =>
|
|
237
|
+
this.options.remote.fetchAndDecodeJson({ path, signal })
|
|
238
|
+
);
|
|
240
239
|
const checkpoint = response['data']['write_checkpoint'] as string;
|
|
241
240
|
this.logger.log({ level: LogLevels.debug, message: `Created write checkpoint: ${checkpoint}` });
|
|
242
241
|
return checkpoint;
|
|
243
242
|
}
|
|
244
243
|
|
|
245
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
|
+
|
|
246
254
|
while (!signal.aborted) {
|
|
247
255
|
await Promise.all([
|
|
248
256
|
// Start the initial CRUD upload on connect. Then, keep polling until we're done.
|
|
@@ -286,20 +294,13 @@ The next upload iteration will be delayed.`
|
|
|
286
294
|
}
|
|
287
295
|
|
|
288
296
|
checkedCrudItem = nextCrudItem;
|
|
289
|
-
await this.options.uploadCrud(signal);
|
|
297
|
+
await this.options.connector.uploadCrud!(signal);
|
|
290
298
|
this.updateJsSyncState({ uploadError: undefined });
|
|
291
299
|
} else {
|
|
292
300
|
// Uploading is completed
|
|
293
|
-
const neededUpdate =
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
} else {
|
|
297
|
-
return this.requestNextCheckpointFromService(signal);
|
|
298
|
-
}
|
|
299
|
-
});
|
|
300
|
-
if (neededUpdate) {
|
|
301
|
-
this.notifyCompletedUploads?.();
|
|
302
|
-
} else if (checkedCrudItem != null) {
|
|
301
|
+
const neededUpdate =
|
|
302
|
+
this.options.connector.fetchCredentials && (await this.updateLocalTarget(signal, options));
|
|
303
|
+
if (!neededUpdate && checkedCrudItem != null) {
|
|
303
304
|
// Only log this if there was something to upload
|
|
304
305
|
this.logger.log({ level: LogLevels.debug, message: 'Upload complete, no write checkpoint needed.' });
|
|
305
306
|
}
|
|
@@ -309,8 +310,9 @@ The next upload iteration will be delayed.`
|
|
|
309
310
|
checkedCrudItem = undefined;
|
|
310
311
|
this.updateJsSyncState({ uploading: false, uploadError: ex as Error });
|
|
311
312
|
await this.delayRetry(signal, options.retryDelayMs);
|
|
312
|
-
if (!this.isConnected) {
|
|
313
|
-
// 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.
|
|
314
316
|
break;
|
|
315
317
|
}
|
|
316
318
|
this.logger.log({
|
|
@@ -326,6 +328,22 @@ The next upload iteration will be delayed.`
|
|
|
326
328
|
});
|
|
327
329
|
}
|
|
328
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
|
+
|
|
329
347
|
async connect(options: ResolvedSyncOptions) {
|
|
330
348
|
if (this.abortController) {
|
|
331
349
|
await this.disconnect();
|
|
@@ -333,68 +351,97 @@ The next upload iteration will be delayed.`
|
|
|
333
351
|
|
|
334
352
|
const controller = new AbortController();
|
|
335
353
|
this.abortController = controller;
|
|
354
|
+
this.connectTimeoutMs = options.connectTimeoutMs;
|
|
336
355
|
const signal = controller.signal;
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
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(() => {
|
|
347
390
|
// These promises only complete when we want to disconnect. No further sync iteration can resume checkpoint
|
|
348
391
|
// requests, so fail any that are still pending.
|
|
349
392
|
this.checkpoints.disconnected();
|
|
350
393
|
});
|
|
351
394
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
const finish = () => {
|
|
360
|
-
if (settled) {
|
|
361
|
-
return;
|
|
362
|
-
}
|
|
363
|
-
settled = true;
|
|
364
|
-
disposer();
|
|
365
|
-
signal.removeEventListener('abort', finish);
|
|
366
|
-
resolve();
|
|
367
|
-
};
|
|
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;
|
|
368
402
|
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
sawStartOfConnection = true;
|
|
403
|
+
const finish = () => {
|
|
404
|
+
if (settled) {
|
|
405
|
+
return;
|
|
373
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
|
+
}
|
|
374
418
|
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
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();
|
|
383
430
|
}
|
|
431
|
+
});
|
|
384
432
|
|
|
385
|
-
|
|
386
|
-
|
|
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 });
|
|
387
436
|
});
|
|
388
|
-
|
|
389
|
-
// If this attempt is aborted (disconnected) before a `statusChanged` event ever fires - which can happen when
|
|
390
|
-
// the instance never got as far as reporting a connecting status - there's nothing left to wait for.
|
|
391
|
-
signal.addEventListener('abort', finish, { once: true });
|
|
392
|
-
});
|
|
437
|
+
}
|
|
393
438
|
}
|
|
394
439
|
|
|
395
440
|
async requestCheckpoint(): Promise<bigint> {
|
|
396
441
|
const neverAbort = new AbortController().signal;
|
|
397
|
-
|
|
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));
|
|
398
445
|
}
|
|
399
446
|
|
|
400
447
|
async disconnect(): Promise<void> {
|
|
@@ -436,13 +483,6 @@ The next upload iteration will be delayed.`
|
|
|
436
483
|
}
|
|
437
484
|
|
|
438
485
|
private async streamingSync(signal: AbortSignal, options: ResolvedSyncOptions): Promise<void> {
|
|
439
|
-
/**
|
|
440
|
-
* Listen for CRUD updates and trigger upstream uploads
|
|
441
|
-
*/
|
|
442
|
-
this.crudUpdateListener = this.options.adapter.registerListener({
|
|
443
|
-
crudUpdate: () => this.triggerCrudUpload()
|
|
444
|
-
});
|
|
445
|
-
|
|
446
486
|
/**
|
|
447
487
|
* Create a new abort controller which aborts items downstream.
|
|
448
488
|
* This is needed to close any previous connections on exception.
|
|
@@ -455,8 +495,6 @@ The next upload iteration will be delayed.`
|
|
|
455
495
|
* to the nested abort controller.
|
|
456
496
|
*/
|
|
457
497
|
nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
|
|
458
|
-
this.crudUpdateListener?.();
|
|
459
|
-
this.crudUpdateListener = undefined;
|
|
460
498
|
this.markAsDisconnected();
|
|
461
499
|
});
|
|
462
500
|
|
|
@@ -494,7 +532,10 @@ The next upload iteration will be delayed.`
|
|
|
494
532
|
this.logger.log({ level: LogLevels.warn, message: 'Sync aborted', error: ex });
|
|
495
533
|
shouldDelayRetry = false;
|
|
496
534
|
// A disconnect was requested, we should not delay since there is no explicit retry
|
|
497
|
-
} else if (
|
|
535
|
+
} else if (
|
|
536
|
+
this.connectionMayHaveChanged &&
|
|
537
|
+
(ex as Error | null | undefined)?.message?.includes('No iteration is active')
|
|
538
|
+
) {
|
|
498
539
|
this.connectionMayHaveChanged = false;
|
|
499
540
|
this.logger.log({
|
|
500
541
|
level: LogLevels.info,
|
|
@@ -600,7 +641,7 @@ The next upload iteration will be delayed.`
|
|
|
600
641
|
|
|
601
642
|
const openInner = async () => {
|
|
602
643
|
if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
|
|
603
|
-
return await remote.fetchStream(options);
|
|
644
|
+
return await remote.fetchStream({ ...options, connectTimeoutMs: connection.connectTimeoutMs });
|
|
604
645
|
} else {
|
|
605
646
|
return await this.options.remote.socketStreamRaw({
|
|
606
647
|
...options,
|
|
@@ -706,6 +747,14 @@ The next upload iteration will be delayed.`
|
|
|
706
747
|
await this.options.adapter.readCheckpointRequestId('seed', seed);
|
|
707
748
|
}
|
|
708
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
|
+
|
|
709
758
|
private async rustSyncIteration(
|
|
710
759
|
signal: AbortSignal,
|
|
711
760
|
resolvedOptions: ResolvedSyncOptions
|
|
@@ -732,6 +781,10 @@ The next upload iteration will be delayed.`
|
|
|
732
781
|
if (serializedSchema) {
|
|
733
782
|
options.schema = serializedSchema;
|
|
734
783
|
}
|
|
784
|
+
if (resolvedOptions.diagnostics) {
|
|
785
|
+
// An empty object enables the core's diagnostics event stream (Option<DiagnosticOptions>).
|
|
786
|
+
options.diagnostics = {};
|
|
787
|
+
}
|
|
735
788
|
|
|
736
789
|
return invokePowerSyncControl(PowerSyncControlCommand.START, JSON.stringify(options));
|
|
737
790
|
}
|
|
@@ -816,6 +869,16 @@ The next upload iteration will be delayed.`
|
|
|
816
869
|
// Not necessary on JS platforms.
|
|
817
870
|
} else if ('DidCompleteSync' in instruction) {
|
|
818
871
|
syncImplementation.updateJsSyncState({ downloadError: undefined });
|
|
872
|
+
} else if ('HandleDiagnostics' in instruction) {
|
|
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
|
+
}
|
|
819
882
|
}
|
|
820
883
|
}
|
|
821
884
|
|
|
@@ -911,6 +974,14 @@ The next upload iteration will be delayed.`
|
|
|
911
974
|
}
|
|
912
975
|
}
|
|
913
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;
|
|
914
985
|
} finally {
|
|
915
986
|
this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
|
|
916
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
|
}
|
|
@@ -16,7 +16,30 @@ export type NonInterruptingInstruction =
|
|
|
16
16
|
| { UpdateSyncStatus: UpdateSyncStatus }
|
|
17
17
|
| { FetchCredentials: FetchCredentials }
|
|
18
18
|
| { FlushFileSystem: any }
|
|
19
|
-
| { DidCompleteSync: any }
|
|
19
|
+
| { DidCompleteSync: any }
|
|
20
|
+
| { CheckpointDelayedDueToLocalData: any }
|
|
21
|
+
| { HandleDiagnostics: DiagnosticsEvent };
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Emitted by the core extension when diagnostics are enabled on the sync stream (see
|
|
25
|
+
* {@link https://github.com/powersync-ja/powersync-sqlite-core/blob/main/crates/core/src/sync/diagnostics.rs diagnostics.rs}). Reports detailed
|
|
26
|
+
* per-bucket download state — including the per-bucket `target_count` that is otherwise internal to
|
|
27
|
+
* the core — and inferred column types as data is downloaded.
|
|
28
|
+
*/
|
|
29
|
+
export type DiagnosticsEvent =
|
|
30
|
+
| { BucketStateChange: { changes: BucketDownloadState[]; incremental: boolean } }
|
|
31
|
+
| { SchemaChange: ObservedSchemaColumn };
|
|
32
|
+
|
|
33
|
+
export interface BucketDownloadState {
|
|
34
|
+
name: string;
|
|
35
|
+
progress: BucketProgress;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ObservedSchemaColumn {
|
|
39
|
+
table: string;
|
|
40
|
+
column: string;
|
|
41
|
+
value_type: 'Null' | 'String' | 'Integer' | 'Real';
|
|
42
|
+
}
|
|
20
43
|
|
|
21
44
|
export interface LogLine {
|
|
22
45
|
severity: 'DEBUG' | 'INFO' | 'WARNING';
|
|
@@ -56,7 +79,7 @@ export interface CoreStreamSubscription {
|
|
|
56
79
|
|
|
57
80
|
export interface SyncPriorityStatus {
|
|
58
81
|
priority: number;
|
|
59
|
-
last_synced_at: number |
|
|
82
|
+
last_synced_at: number | null;
|
|
60
83
|
has_synced: boolean | null;
|
|
61
84
|
}
|
|
62
85
|
|
|
@@ -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
|
|
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
} from '@powersync/common';
|
|
10
10
|
import { CoreStreamSubscription, CoreSyncStatus } from '../../client/sync/stream/core-instruction.js';
|
|
11
11
|
import { SyncPriorityStatus as CoreSyncPriorityStatus } from '../../client/sync/stream/core-instruction.js';
|
|
12
|
+
import { SerializedRelayError, serializeErrorForRelay } from '../../utils/error-serialization.js';
|
|
12
13
|
import { SyncProgressImpl } from './SyncProgress.js';
|
|
13
14
|
import { FULL_SYNC_PRIORITY } from '../../constants.js';
|
|
14
15
|
|
|
@@ -156,26 +157,12 @@ export class SyncStatusSnapshot implements SyncStatus {
|
|
|
156
157
|
};
|
|
157
158
|
}
|
|
158
159
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
* This explicitly serializes errors in the SyncStatus.
|
|
162
|
-
*/
|
|
163
|
-
serializeError(error?: Error) {
|
|
160
|
+
// Must stay deterministic: isEqual() serializes both sides of a comparison.
|
|
161
|
+
serializeError(error?: Error): SerializedRelayError | undefined {
|
|
164
162
|
if (typeof error == 'undefined') {
|
|
165
163
|
return undefined;
|
|
166
164
|
}
|
|
167
|
-
|
|
168
|
-
name: error.name,
|
|
169
|
-
message: error.message,
|
|
170
|
-
stack: error.stack
|
|
171
|
-
};
|
|
172
|
-
// `Error.cause` can be any value (the spec types it as unknown). Preserve it
|
|
173
|
-
// so consumers reading uploadError/downloadError keep the failure context.
|
|
174
|
-
// Recurse for Error causes so the whole chain is flattened the same way.
|
|
175
|
-
if (typeof error.cause != 'undefined') {
|
|
176
|
-
serialized.cause = error.cause instanceof Error ? this.serializeError(error.cause) : error.cause;
|
|
177
|
-
}
|
|
178
|
-
return serialized;
|
|
165
|
+
return serializeErrorForRelay(error);
|
|
179
166
|
}
|
|
180
167
|
}
|
|
181
168
|
|
|
@@ -210,9 +197,9 @@ class SyncStreamStatusView implements SyncStreamStatus {
|
|
|
210
197
|
active: core.active,
|
|
211
198
|
isDefault: core.is_default,
|
|
212
199
|
hasExplicitSubscription: core.has_explicit_subscription,
|
|
213
|
-
expiresAt:
|
|
200
|
+
expiresAt: coreTimestampToDate(core.expires_at) ?? null,
|
|
214
201
|
hasSynced: core.last_synced_at != null,
|
|
215
|
-
lastSyncedAt:
|
|
202
|
+
lastSyncedAt: coreTimestampToDate(core.last_synced_at) ?? null
|
|
216
203
|
};
|
|
217
204
|
}
|
|
218
205
|
|
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';
|
|
@@ -18,6 +19,8 @@ export * from './client/watched/OnChangeQueryProcessor.js';
|
|
|
18
19
|
|
|
19
20
|
export * from './utils/AbortOperation.js';
|
|
20
21
|
export * from './utils/compatibility.js';
|
|
22
|
+
export { serializeErrorForRelay } from './utils/error-serialization.js';
|
|
23
|
+
export type { SerializedRelayError, ErrorRelayState } from './utils/error-serialization.js';
|
|
21
24
|
export * from './utils/ControlledExecutor.js';
|
|
22
25
|
export * from './utils/mutex.js';
|
|
23
26
|
export * from './utils/parseQuery.js';
|