@powersync/shared-internals 1.1.0 → 1.2.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.map +1 -1
- package/dist/websockets.node.mjs.map +1 -1
- package/lib/client/BasePowerSyncDatabase.d.ts +13 -3
- package/lib/client/BasePowerSyncDatabase.js +49 -2
- package/lib/client/BasePowerSyncDatabase.js.map +1 -1
- package/lib/client/ConnectionManager.d.ts +4 -0
- package/lib/client/ConnectionManager.js +19 -1
- package/lib/client/ConnectionManager.js.map +1 -1
- package/lib/client/sync/CheckpointRequestImpl.d.ts +11 -0
- package/lib/client/sync/CheckpointRequestImpl.js +42 -0
- package/lib/client/sync/CheckpointRequestImpl.js.map +1 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +1 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -1
- package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +1 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.js +7 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -1
- package/lib/client/sync/options.js +2 -1
- package/lib/client/sync/options.js.map +1 -1
- package/lib/client/sync/stream/AbstractRemote.d.ts +7 -1
- package/lib/client/sync/stream/AbstractRemote.js +5 -3
- package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +21 -3
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +140 -16
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
- package/lib/client/sync/stream/CheckpointState.d.ts +44 -0
- package/lib/client/sync/stream/CheckpointState.js +106 -0
- package/lib/client/sync/stream/CheckpointState.js.map +1 -0
- package/lib/client/sync/stream/core-instruction.d.ts +6 -0
- package/lib/client/sync/stream/core-instruction.js.map +1 -1
- package/lib/utils/stream_transform.d.ts +1 -0
- package/lib/utils/stream_transform.js +18 -2
- package/lib/utils/stream_transform.js.map +1 -1
- package/lib/version.d.ts +1 -1
- package/lib/version.js +1 -1
- package/package.json +5 -2
- package/src/client/BasePowerSyncDatabase.ts +63 -11
- package/src/client/ConnectionManager.ts +23 -1
- package/src/client/sync/CheckpointRequestImpl.ts +54 -0
- package/src/client/sync/bucket/BucketStorageAdapter.ts +1 -0
- package/src/client/sync/bucket/SqliteBucketStorage.ts +8 -0
- package/src/client/sync/options.ts +2 -1
- package/src/client/sync/stream/AbstractRemote.ts +17 -3
- package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +165 -18
- package/src/client/sync/stream/CheckpointState.ts +136 -0
- package/src/client/sync/stream/core-instruction.ts +7 -0
- package/src/utils/stream_transform.ts +19 -3
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powersync/shared-internals",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"registry": "https://registry.npmjs.org/",
|
|
6
6
|
"access": "public"
|
|
@@ -37,6 +37,9 @@
|
|
|
37
37
|
"url": "https://github.com/powersync-ja/powersync-js/issues"
|
|
38
38
|
},
|
|
39
39
|
"homepage": "https://docs.powersync.com",
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@powersync/common": "^2.2.0"
|
|
42
|
+
},
|
|
40
43
|
"devDependencies": {
|
|
41
44
|
"@rollup/plugin-commonjs": "^29.0.0",
|
|
42
45
|
"@rollup/plugin-inject": "^5.0.5",
|
|
@@ -52,7 +55,7 @@
|
|
|
52
55
|
"rollup-plugin-dts": "^6.2.1",
|
|
53
56
|
"rsocket-core": "1.0.0-alpha.3",
|
|
54
57
|
"rsocket-websocket-client": "1.0.0-alpha.3",
|
|
55
|
-
"@powersync/common": "2.
|
|
58
|
+
"@powersync/common": "2.2.0"
|
|
56
59
|
},
|
|
57
60
|
"scripts": {
|
|
58
61
|
"build": "tsc -b && rollup -c rollup.config.mjs",
|
|
@@ -32,13 +32,10 @@ import {
|
|
|
32
32
|
WatchOnChangeHandler,
|
|
33
33
|
BaseObserver,
|
|
34
34
|
SqliteRecord,
|
|
35
|
-
SyncStreamConnectionMethod
|
|
35
|
+
SyncStreamConnectionMethod,
|
|
36
|
+
CheckpointRequest
|
|
36
37
|
} from '@powersync/common';
|
|
37
|
-
import {
|
|
38
|
-
BucketStorageAdapter,
|
|
39
|
-
PSInternalTable,
|
|
40
|
-
targetCheckpointRequestId
|
|
41
|
-
} from './sync/bucket/BucketStorageAdapter.js';
|
|
38
|
+
import { BucketStorageAdapter, PSInternalTable } from './sync/bucket/BucketStorageAdapter.js';
|
|
42
39
|
import { SyncStatusSnapshot } from '../db/crud/SyncStatus.js';
|
|
43
40
|
import {
|
|
44
41
|
ConnectionManager,
|
|
@@ -47,7 +44,10 @@ import {
|
|
|
47
44
|
} from './ConnectionManager.js';
|
|
48
45
|
import { Mutex } from '../utils/mutex.js';
|
|
49
46
|
import { TriggerManagerConfig, TriggerManagerImpl } from './triggers/TriggerManagerImpl.js';
|
|
50
|
-
import {
|
|
47
|
+
import {
|
|
48
|
+
AbstractStreamingSyncImplementationOptions,
|
|
49
|
+
StreamingSyncImplementation
|
|
50
|
+
} from './sync/stream/AbstractStreamingSyncImplementation.js';
|
|
51
51
|
import { CoreSyncStatus } from './sync/stream/core-instruction.js';
|
|
52
52
|
import { CrudEntryImpl, CrudEntryJSON } from './sync/bucket/CrudEntry.js';
|
|
53
53
|
import { OnChangeQueryProcessor } from './watched/OnChangeQueryProcessor.js';
|
|
@@ -58,6 +58,12 @@ import { CustomQuery } from './CustomQuery.js';
|
|
|
58
58
|
import { MEMORY_TRIGGER_CLAIM_MANAGER } from './triggers/MemoryTriggerClaimManager.js';
|
|
59
59
|
import { symbolAsyncIterator } from '../utils/compatibility.js';
|
|
60
60
|
import { MAX_OP_ID } from '../constants.js';
|
|
61
|
+
import { SqliteBucketStorage } from './sync/bucket/SqliteBucketStorage.js';
|
|
62
|
+
import {
|
|
63
|
+
cannotRequestDueToDisconnectedError,
|
|
64
|
+
checkpointRequestsNotEnabledError
|
|
65
|
+
} from './sync/stream/CheckpointState.js';
|
|
66
|
+
import { CheckpointRequestImpl } from './sync/CheckpointRequestImpl.js';
|
|
61
67
|
|
|
62
68
|
const POWERSYNC_TABLE_MATCH = /(^ps_data__|^ps_data_local__)/;
|
|
63
69
|
|
|
@@ -96,7 +102,7 @@ export abstract class BasePowerSyncDatabase<Options extends BasePowerSyncDatabas
|
|
|
96
102
|
|
|
97
103
|
protected bucketStorageAdapter: BucketStorageAdapter;
|
|
98
104
|
protected _isReadyPromise: Promise<void>;
|
|
99
|
-
|
|
105
|
+
connectionManager: ConnectionManager;
|
|
100
106
|
private subscriptions: InternalSubscriptionAdapter;
|
|
101
107
|
|
|
102
108
|
get syncStreamImplementation() {
|
|
@@ -257,7 +263,29 @@ export abstract class BasePowerSyncDatabase<Options extends BasePowerSyncDatabas
|
|
|
257
263
|
options: CreateSyncImplementationOptions
|
|
258
264
|
): StreamingSyncImplementation;
|
|
259
265
|
|
|
260
|
-
protected
|
|
266
|
+
protected commonSyncOptions(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions) {
|
|
267
|
+
return {
|
|
268
|
+
...options,
|
|
269
|
+
adapter: this.bucketStorageAdapter,
|
|
270
|
+
uploadCrud: async () => {
|
|
271
|
+
await this.waitForReady();
|
|
272
|
+
await connector.uploadData(this);
|
|
273
|
+
},
|
|
274
|
+
postCheckpointRequest: (clientId, requestId) => {
|
|
275
|
+
if (connector.postCheckpointRequest) {
|
|
276
|
+
return this.waitForReady().then((_) => connector.postCheckpointRequest!(clientId, requestId));
|
|
277
|
+
} else {
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
identifier: this.database.name,
|
|
282
|
+
logger: this.logger
|
|
283
|
+
} satisfies Partial<AbstractStreamingSyncImplementationOptions>;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
protected generateBucketStorageAdapter(): BucketStorageAdapter {
|
|
287
|
+
return new SqliteBucketStorage(this.database, this.logger);
|
|
288
|
+
}
|
|
261
289
|
|
|
262
290
|
async waitForReady(): Promise<void> {
|
|
263
291
|
if (this.ready) {
|
|
@@ -284,10 +312,18 @@ export abstract class BasePowerSyncDatabase<Options extends BasePowerSyncDatabas
|
|
|
284
312
|
return;
|
|
285
313
|
}
|
|
286
314
|
|
|
287
|
-
return new Promise((resolve) => {
|
|
315
|
+
return new Promise((resolve, reject) => {
|
|
288
316
|
const dispose = this.registerListener({
|
|
289
317
|
statusChanged: (status) => {
|
|
290
|
-
|
|
318
|
+
let isComplete = false;
|
|
319
|
+
try {
|
|
320
|
+
isComplete = predicate(status);
|
|
321
|
+
} catch (e) {
|
|
322
|
+
reject(e);
|
|
323
|
+
isComplete = true;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (isComplete) {
|
|
291
327
|
abort();
|
|
292
328
|
}
|
|
293
329
|
}
|
|
@@ -296,6 +332,7 @@ export abstract class BasePowerSyncDatabase<Options extends BasePowerSyncDatabas
|
|
|
296
332
|
function abort() {
|
|
297
333
|
dispose();
|
|
298
334
|
resolve();
|
|
335
|
+
signal?.removeEventListener('abort', abort);
|
|
299
336
|
}
|
|
300
337
|
|
|
301
338
|
if (signal?.aborted) {
|
|
@@ -429,6 +466,21 @@ export abstract class BasePowerSyncDatabase<Options extends BasePowerSyncDatabas
|
|
|
429
466
|
return this.connectionManager.stream(this.subscriptions, name, params ?? null);
|
|
430
467
|
}
|
|
431
468
|
|
|
469
|
+
async requestCheckpoint(): Promise<CheckpointRequest> {
|
|
470
|
+
await this.waitForReady();
|
|
471
|
+
|
|
472
|
+
const impl = this.connectionManager.syncStreamImplementation;
|
|
473
|
+
if (impl == null) {
|
|
474
|
+
throw cannotRequestDueToDisconnectedError();
|
|
475
|
+
}
|
|
476
|
+
if (this.connectionManager.connectionOptions?.checkpointMode == 'legacy') {
|
|
477
|
+
throw checkpointRequestsNotEnabledError();
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const checkpoint = await impl.requestCheckpoint();
|
|
481
|
+
return new CheckpointRequestImpl(checkpoint, this);
|
|
482
|
+
}
|
|
483
|
+
|
|
432
484
|
async close(options: PowerSyncCloseOptions = DEFAULT_POWERSYNC_CLOSE_OPTIONS) {
|
|
433
485
|
await this.waitForReady();
|
|
434
486
|
|
|
@@ -150,12 +150,21 @@ export class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
|
|
|
150
150
|
const hadPendingOptions = !!this.pendingConnectionOptions;
|
|
151
151
|
|
|
152
152
|
// Update pending options to the latest values
|
|
153
|
+
const resolvedOptions = resolveSyncOptions(options, this.options.defaultConnectionMethod);
|
|
153
154
|
this.pendingConnectionOptions = {
|
|
154
155
|
connector,
|
|
155
|
-
options:
|
|
156
|
+
options: resolvedOptions,
|
|
156
157
|
schema: serializedSchema
|
|
157
158
|
};
|
|
158
159
|
|
|
160
|
+
if (connector.postCheckpointRequest && resolvedOptions.checkpointMode == 'legacy') {
|
|
161
|
+
this.logger.log({
|
|
162
|
+
level: LogLevels.warn,
|
|
163
|
+
message:
|
|
164
|
+
'The backend connector implements postCheckpointRequest, but connect() was called without checkpoint requests enabled.'
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
159
168
|
// Disconnecting here provides aborting in progress connection attempts.
|
|
160
169
|
// The connectInternal method will clear pending options once it starts connecting (with the options).
|
|
161
170
|
// We only need to trigger a disconnect here if we have already reached the point of connecting.
|
|
@@ -225,6 +234,7 @@ export class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
|
|
|
225
234
|
|
|
226
235
|
this.pendingConnectionOptions = null;
|
|
227
236
|
|
|
237
|
+
const subscriptionsAtStart = this.subscriptionIdentity;
|
|
228
238
|
const { sync, onDispose } = await this.options.createSyncImplementation(connector, {
|
|
229
239
|
subscriptions: this.activeStreams,
|
|
230
240
|
serializedSchema: schema
|
|
@@ -233,6 +243,11 @@ export class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
|
|
|
233
243
|
this.syncStreamImplementation = sync;
|
|
234
244
|
this.syncDisposer = onDispose;
|
|
235
245
|
await this.syncStreamImplementation.waitForReady();
|
|
246
|
+
|
|
247
|
+
// Subscriptions changed while creating the sync stream implementation, update it now.
|
|
248
|
+
if (this.subscriptionIdentity !== subscriptionsAtStart) {
|
|
249
|
+
this.syncStreamImplementation.updateSubscriptions(this.activeStreams);
|
|
250
|
+
}
|
|
236
251
|
resolve();
|
|
237
252
|
} catch (error) {
|
|
238
253
|
reject(error);
|
|
@@ -355,6 +370,13 @@ export class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
|
|
|
355
370
|
return [...this.locallyActiveSubscriptions.values()].map((a) => ({ name: a.name, params: a.parameters }));
|
|
356
371
|
}
|
|
357
372
|
|
|
373
|
+
/**
|
|
374
|
+
* Identifies the current set of subscriptions, for detecting a change across an await.
|
|
375
|
+
*/
|
|
376
|
+
private get subscriptionIdentity() {
|
|
377
|
+
return [...this.locallyActiveSubscriptions.keys()].join('\n');
|
|
378
|
+
}
|
|
379
|
+
|
|
358
380
|
private subscriptionsMayHaveChanged() {
|
|
359
381
|
this.syncStreamImplementation?.updateSubscriptions(this.activeStreams);
|
|
360
382
|
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { CheckpointRequest } from '@powersync/common';
|
|
2
|
+
import { BasePowerSyncDatabase } from '../BasePowerSyncDatabase.js';
|
|
3
|
+
import {
|
|
4
|
+
cannotRequestDueToDisconnectedError,
|
|
5
|
+
checkpointRequestsNotEnabledError,
|
|
6
|
+
isCheckpointRequestApplied
|
|
7
|
+
} from './stream/CheckpointState.js';
|
|
8
|
+
import { SyncStatusSnapshot } from '../../db/crud/SyncStatus.js';
|
|
9
|
+
|
|
10
|
+
export class CheckpointRequestImpl implements CheckpointRequest {
|
|
11
|
+
constructor(
|
|
12
|
+
private readonly requestId: bigint,
|
|
13
|
+
private readonly database: BasePowerSyncDatabase
|
|
14
|
+
) {}
|
|
15
|
+
|
|
16
|
+
get hasSynced(): boolean {
|
|
17
|
+
const status = this.database.currentStatus.core;
|
|
18
|
+
return isCheckpointRequestApplied(status, this.requestId);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async waitForSync(options?: { signal?: AbortSignal }): Promise<void> {
|
|
22
|
+
if (this.hasSynced) return;
|
|
23
|
+
|
|
24
|
+
const signal = options?.signal;
|
|
25
|
+
const manager = this.database.connectionManager;
|
|
26
|
+
if (manager.syncStreamImplementation == null) {
|
|
27
|
+
throw cannotRequestDueToDisconnectedError();
|
|
28
|
+
}
|
|
29
|
+
if (manager.connectionOptions?.checkpointMode == 'legacy') {
|
|
30
|
+
throw checkpointRequestsNotEnabledError();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
await this.database.waitForStatus((status) => {
|
|
34
|
+
if (isCheckpointRequestApplied((status as SyncStatusSnapshot).core, this.requestId)) {
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const anyError = status.downloadError ?? status.uploadError;
|
|
39
|
+
if (anyError) {
|
|
40
|
+
throw new Error('Sync error while waiting for checkpoint request', { cause: anyError });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (!status.connected && !status.connecting) {
|
|
44
|
+
throw cannotRequestDueToDisconnectedError();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return false;
|
|
48
|
+
}, signal);
|
|
49
|
+
|
|
50
|
+
if (signal?.aborted) {
|
|
51
|
+
throw signal.reason;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -45,6 +45,7 @@ export interface BucketStorageAdapter extends BaseObserverInterface<BucketStorag
|
|
|
45
45
|
|
|
46
46
|
updateLocalTarget(cb: () => Promise<string>): Promise<boolean>;
|
|
47
47
|
handleCrudCheckpoint(lastClientId: number, writeCheckpoint?: string): Promise<void>;
|
|
48
|
+
readCheckpointRequestId(variant: 'next' | 'current' | 'seed', payload?: string): Promise<string>;
|
|
48
49
|
|
|
49
50
|
/**
|
|
50
51
|
* Get an unique client id.
|
|
@@ -107,6 +107,14 @@ export class SqliteBucketStorage extends BaseObserver<BucketStorageListener> imp
|
|
|
107
107
|
});
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
+
readCheckpointRequestId(variant: 'next' | 'current' | 'seed', payload: string | null = null): Promise<string> {
|
|
111
|
+
// This needs to run in a write transaction because some checkpoint request reads interact with sync client state
|
|
112
|
+
// bound to the write connection.
|
|
113
|
+
return this.db.writeTransaction(async (tx) => {
|
|
114
|
+
return (await rawPowerSyncControl(tx, `${variant}_checkpoint_request_id`, payload))!;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
110
118
|
async nextCrudItem(): Promise<CrudEntry | undefined> {
|
|
111
119
|
const next = await this.db.getOptional<CrudEntryJSON>('SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1');
|
|
112
120
|
if (!next) {
|
|
@@ -19,6 +19,7 @@ export function resolveSyncOptions(
|
|
|
19
19
|
params: options.params ?? {},
|
|
20
20
|
includeDefaultStreams: options.includeDefaultStreams ?? true,
|
|
21
21
|
retryDelayMs: options.retryDelayMs ?? 5000,
|
|
22
|
-
crudUploadThrottleMs: options.crudUploadThrottleMs ?? 1000
|
|
22
|
+
crudUploadThrottleMs: options.crudUploadThrottleMs ?? 1000,
|
|
23
|
+
checkpointMode: options.checkpointMode ?? 'legacy'
|
|
23
24
|
};
|
|
24
25
|
}
|
|
@@ -173,16 +173,30 @@ export abstract class AbstractRemote {
|
|
|
173
173
|
};
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
-
async
|
|
176
|
+
async fetchAndDecodeJson({
|
|
177
|
+
path,
|
|
178
|
+
method = 'GET',
|
|
179
|
+
headers,
|
|
180
|
+
body,
|
|
181
|
+
signal
|
|
182
|
+
}: {
|
|
183
|
+
path: string;
|
|
184
|
+
method?: string;
|
|
185
|
+
headers?: Record<string, string>;
|
|
186
|
+
body?: string;
|
|
187
|
+
signal?: AbortSignal;
|
|
188
|
+
}): Promise<any> {
|
|
177
189
|
const request = await this.buildRequest(path);
|
|
178
190
|
const res = await this.fetch({
|
|
179
191
|
resource: request.url,
|
|
180
192
|
request: {
|
|
181
|
-
method
|
|
193
|
+
method,
|
|
182
194
|
headers: {
|
|
183
195
|
...headers,
|
|
184
196
|
...request.headers
|
|
185
|
-
}
|
|
197
|
+
},
|
|
198
|
+
body,
|
|
199
|
+
signal
|
|
186
200
|
},
|
|
187
201
|
expectStreamingResponse: false
|
|
188
202
|
});
|
|
@@ -14,6 +14,7 @@ import { AbortOperation } from '../../../utils/AbortOperation.js';
|
|
|
14
14
|
import { BucketStorageAdapter, PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';
|
|
15
15
|
import { AbstractRemote, SyncStreamOptions } from './AbstractRemote.js';
|
|
16
16
|
import {
|
|
17
|
+
CheckpointRequestPayload,
|
|
17
18
|
CoreSyncStatus,
|
|
18
19
|
Instruction,
|
|
19
20
|
NonInterruptingInstruction,
|
|
@@ -29,6 +30,7 @@ import {
|
|
|
29
30
|
import { asyncNotifier } from '../../../utils/async.js';
|
|
30
31
|
import { JavaScriptSyncState, SyncStatusSnapshot } from '../../../db/crud/SyncStatus.js';
|
|
31
32
|
import { ResolvedSyncOptions } from '../options.js';
|
|
33
|
+
import { CheckpointStateSignals, isCheckpointRequestApplied } from './CheckpointState.js';
|
|
32
34
|
|
|
33
35
|
/**
|
|
34
36
|
* @internal
|
|
@@ -56,6 +58,10 @@ export interface AbstractStreamingSyncImplementationOptions {
|
|
|
56
58
|
adapter: BucketStorageAdapter;
|
|
57
59
|
subscriptions: SubscribedStream[];
|
|
58
60
|
uploadCrud: () => Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* Posts a checkpoint request with the connector, returning null if the connector doesn't support that.
|
|
63
|
+
*/
|
|
64
|
+
postCheckpointRequest: (clientId: string, requestId: string) => Promise<string | null> | null;
|
|
59
65
|
/**
|
|
60
66
|
* An identifier for which PowerSync DB this sync implementation is
|
|
61
67
|
* linked to. Most commonly DB name, but not restricted to DB name.
|
|
@@ -93,13 +99,14 @@ export interface StreamingSyncImplementation
|
|
|
93
99
|
* @throws if not connected or if abort is not controlled internally
|
|
94
100
|
*/
|
|
95
101
|
disconnect(): Promise<void>;
|
|
96
|
-
getWriteCheckpoint: () => Promise<string>;
|
|
97
102
|
isConnected: boolean;
|
|
98
103
|
triggerCrudUpload: () => void;
|
|
99
104
|
waitForReady(): Promise<void>;
|
|
100
105
|
waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
|
|
101
106
|
updateSubscriptions(subscriptions: SubscribedStream[]): void;
|
|
102
107
|
markConnectionMayHaveChanged(): void;
|
|
108
|
+
|
|
109
|
+
requestCheckpoint(): Promise<bigint>;
|
|
103
110
|
}
|
|
104
111
|
|
|
105
112
|
/**
|
|
@@ -120,11 +127,12 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
120
127
|
protected options: AbstractStreamingSyncImplementationOptions;
|
|
121
128
|
protected abortController: AbortController | null;
|
|
122
129
|
protected crudUpdateListener?: () => void;
|
|
123
|
-
protected streamingSyncPromise?: Promise<[void, void]>;
|
|
130
|
+
protected streamingSyncPromise?: Promise<[void, void, void]>;
|
|
124
131
|
protected logger: PowerSyncLogger;
|
|
125
132
|
protected activeStreams: SubscribedStream[];
|
|
126
133
|
private connectionMayHaveChanged = false;
|
|
127
134
|
private crudUploadNotifier = asyncNotifier();
|
|
135
|
+
private checkpoints = new CheckpointStateSignals();
|
|
128
136
|
|
|
129
137
|
private notifyCompletedUploads?: () => void;
|
|
130
138
|
private handleActiveStreamsChange?: () => void;
|
|
@@ -182,10 +190,40 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
182
190
|
|
|
183
191
|
abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
|
|
184
192
|
|
|
185
|
-
async
|
|
193
|
+
private async requestNextCheckpointFromService(abort: AbortSignal): Promise<string> {
|
|
194
|
+
await this.checkpoints.waitForCheckpointRequestsReady(abort);
|
|
195
|
+
|
|
196
|
+
const nextCheckpointRequestId = await this.options.adapter.readCheckpointRequestId('next');
|
|
197
|
+
const clientId = await this.options.adapter.getClientId();
|
|
198
|
+
return await this.requestCheckpointFromService(abort, {
|
|
199
|
+
client_id: clientId,
|
|
200
|
+
checkpoint_request_id: nextCheckpointRequestId
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
private async requestCheckpointFromService(signal: AbortSignal, request: CheckpointRequestPayload): Promise<string> {
|
|
205
|
+
// First, check if we can use a custom checkpoint request implementation.
|
|
206
|
+
{
|
|
207
|
+
const customResponse = await this.options.postCheckpointRequest(request.client_id, request.checkpoint_request_id);
|
|
208
|
+
if (customResponse != null) {
|
|
209
|
+
return customResponse;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const status = await this.options.remote.fetchAndDecodeJson({
|
|
214
|
+
method: 'POST',
|
|
215
|
+
path: '/sync/checkpoint-request',
|
|
216
|
+
body: JSON.stringify(request),
|
|
217
|
+
signal
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
return status.data.checkpoint_request_id;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private async getLegacyWriteCheckpoint(): Promise<string> {
|
|
186
224
|
const clientId = await this.options.adapter.getClientId();
|
|
187
225
|
let path = `/write-checkpoint2.json?client_id=${clientId}`;
|
|
188
|
-
const response = await this.options.remote.
|
|
226
|
+
const response = await this.options.remote.fetchAndDecodeJson({ path });
|
|
189
227
|
const checkpoint = response['data']['write_checkpoint'] as string;
|
|
190
228
|
this.logger.log({ level: LogLevels.debug, message: `Created write checkpoint: ${checkpoint}` });
|
|
191
229
|
return checkpoint;
|
|
@@ -239,7 +277,13 @@ The next upload iteration will be delayed.`
|
|
|
239
277
|
this.updateJsSyncState({ uploadError: undefined });
|
|
240
278
|
} else {
|
|
241
279
|
// Uploading is completed
|
|
242
|
-
const neededUpdate = await this.options.adapter.updateLocalTarget(() =>
|
|
280
|
+
const neededUpdate = await this.options.adapter.updateLocalTarget(() => {
|
|
281
|
+
if (options.checkpointMode === 'legacy') {
|
|
282
|
+
return this.getLegacyWriteCheckpoint();
|
|
283
|
+
} else {
|
|
284
|
+
return this.requestNextCheckpointFromService(signal);
|
|
285
|
+
}
|
|
286
|
+
});
|
|
243
287
|
if (neededUpdate) {
|
|
244
288
|
this.notifyCompletedUploads?.();
|
|
245
289
|
} else if (checkedCrudItem != null) {
|
|
@@ -280,8 +324,13 @@ The next upload iteration will be delayed.`
|
|
|
280
324
|
this.crudUploadLoop(controller.signal, options).catch((error) =>
|
|
281
325
|
this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error })
|
|
282
326
|
),
|
|
283
|
-
this.streamingSync(controller.signal, options)
|
|
284
|
-
|
|
327
|
+
this.streamingSync(controller.signal, options),
|
|
328
|
+
this.repostUnacknowledgedCheckpointRequests(controller.signal, options)
|
|
329
|
+
]).finally(() => {
|
|
330
|
+
// These promises only complete when we want to disconnect. No further sync iteration can resume checkpoint
|
|
331
|
+
// requests, so fail any that are still pending.
|
|
332
|
+
this.checkpoints.disconnected();
|
|
333
|
+
});
|
|
285
334
|
|
|
286
335
|
// Return a promise that resolves when the connection status is updated to indicate that we're connected. We do this
|
|
287
336
|
// by waiting for connecting to be true and then false again.
|
|
@@ -311,6 +360,11 @@ The next upload iteration will be delayed.`
|
|
|
311
360
|
});
|
|
312
361
|
}
|
|
313
362
|
|
|
363
|
+
async requestCheckpoint(): Promise<bigint> {
|
|
364
|
+
const neverAbort = new AbortController().signal;
|
|
365
|
+
return BigInt(await this.requestNextCheckpointFromService(neverAbort));
|
|
366
|
+
}
|
|
367
|
+
|
|
314
368
|
async disconnect(): Promise<void> {
|
|
315
369
|
if (!this.abortController) {
|
|
316
370
|
return;
|
|
@@ -342,11 +396,10 @@ The next upload iteration will be delayed.`
|
|
|
342
396
|
}
|
|
343
397
|
|
|
344
398
|
this.updateSyncStatus({
|
|
399
|
+
...current,
|
|
345
400
|
connected: false,
|
|
346
401
|
connecting: false,
|
|
347
|
-
|
|
348
|
-
downloading: null,
|
|
349
|
-
streams: current.streams
|
|
402
|
+
downloading: null
|
|
350
403
|
});
|
|
351
404
|
}
|
|
352
405
|
|
|
@@ -419,6 +472,7 @@ The next upload iteration will be delayed.`
|
|
|
419
472
|
|
|
420
473
|
this.updateJsSyncState({ downloadError: ex as Error });
|
|
421
474
|
} finally {
|
|
475
|
+
this.checkpoints.downloadIterationEnded();
|
|
422
476
|
this.notifyCompletedUploads = undefined;
|
|
423
477
|
|
|
424
478
|
if (!signal.aborted) {
|
|
@@ -431,7 +485,7 @@ The next upload iteration will be delayed.`
|
|
|
431
485
|
|
|
432
486
|
// On error, wait a little before retrying
|
|
433
487
|
if (shouldDelayRetry) {
|
|
434
|
-
await this.delayRetry(nestedAbortController.signal, options.retryDelayMs);
|
|
488
|
+
await this.delayRetry(nestedAbortController.signal, options.retryDelayMs, true);
|
|
435
489
|
}
|
|
436
490
|
}
|
|
437
491
|
}
|
|
@@ -550,6 +604,66 @@ The next upload iteration will be delayed.`
|
|
|
550
604
|
};
|
|
551
605
|
}
|
|
552
606
|
|
|
607
|
+
/**
|
|
608
|
+
* Watches the current checkpoint request id to re-request it if we take too long to receive it.
|
|
609
|
+
*
|
|
610
|
+
* This does not require navigator locks: It waits for checkpoints to be seeded, which can only happen in the context
|
|
611
|
+
* of a download loop.
|
|
612
|
+
*
|
|
613
|
+
* Note that requesting checkpoints with ids the service has already seen is a cheap no-op.
|
|
614
|
+
*/
|
|
615
|
+
private async repostUnacknowledgedCheckpointRequests(abort: AbortSignal, options: ResolvedSyncOptions) {
|
|
616
|
+
let retryDelay: number;
|
|
617
|
+
const mode = options.checkpointMode;
|
|
618
|
+
if (mode == 'legacy') return;
|
|
619
|
+
|
|
620
|
+
if (mode == 'requests') {
|
|
621
|
+
retryDelay = 10_000;
|
|
622
|
+
} else {
|
|
623
|
+
retryDelay = Math.max(mode.requests.retryDelay, 10_000);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
while (!abort.aborted) {
|
|
627
|
+
try {
|
|
628
|
+
await this.checkpoints.waitForCheckpointRequestsReady(abort, false);
|
|
629
|
+
|
|
630
|
+
const requestId = await this.options.adapter.readCheckpointRequestId('current');
|
|
631
|
+
// Give the request some time to sync.
|
|
632
|
+
await this.delayRetry(abort, retryDelay);
|
|
633
|
+
|
|
634
|
+
// If a new request was made, reset the timer.
|
|
635
|
+
if (requestId != (await this.options.adapter.readCheckpointRequestId('current'))) {
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// If the request was applied, we don't need to retry.
|
|
640
|
+
if (isCheckpointRequestApplied(this.syncStatus?.core, BigInt(requestId))) {
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// Make sure we're online and ready before making the request
|
|
645
|
+
await this.checkpoints.waitForCheckpointRequestsReady(abort, false);
|
|
646
|
+
|
|
647
|
+
// It's safe if this request races with a new one. The service will reject it.
|
|
648
|
+
this.logger.log({ level: LogLevels.debug, message: `Retry checkpoint request ${requestId}` });
|
|
649
|
+
await this.requestCheckpointFromService(abort, {
|
|
650
|
+
client_id: await this.options.adapter.getClientId(),
|
|
651
|
+
checkpoint_request_id: requestId
|
|
652
|
+
});
|
|
653
|
+
} catch (e) {
|
|
654
|
+
if (abort.aborted) return;
|
|
655
|
+
|
|
656
|
+
this.logger.log({ level: LogLevels.warn, error: e, message: 'Error retrying checkpoint request.' });
|
|
657
|
+
await this.delayRetry(abort, retryDelay);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
private async seedCheckpointRequestState(abort: AbortSignal, request: CheckpointRequestPayload) {
|
|
663
|
+
const seed = await this.requestCheckpointFromService(abort, request);
|
|
664
|
+
await this.options.adapter.readCheckpointRequestId('seed', seed);
|
|
665
|
+
}
|
|
666
|
+
|
|
553
667
|
private async rustSyncIteration(
|
|
554
668
|
signal: AbortSignal,
|
|
555
669
|
resolvedOptions: ResolvedSyncOptions
|
|
@@ -570,7 +684,8 @@ The next upload iteration will be delayed.`
|
|
|
570
684
|
parameters: resolvedOptions.params,
|
|
571
685
|
app_metadata: resolvedOptions.appMetadata,
|
|
572
686
|
active_streams: syncImplementation.activeStreams,
|
|
573
|
-
include_defaults: resolvedOptions.includeDefaultStreams
|
|
687
|
+
include_defaults: resolvedOptions.includeDefaultStreams,
|
|
688
|
+
checkpoint_mode: resolvedOptions.checkpointMode === 'legacy' ? 'legacy' : 'requests'
|
|
574
689
|
};
|
|
575
690
|
if (serializedSchema) {
|
|
576
691
|
options.schema = serializedSchema;
|
|
@@ -671,10 +786,11 @@ The next upload iteration will be delayed.`
|
|
|
671
786
|
|
|
672
787
|
for (const startInstruction of await startCommand()) {
|
|
673
788
|
if ('EstablishSyncStream' in startInstruction) {
|
|
789
|
+
const establish = startInstruction.EstablishSyncStream;
|
|
674
790
|
const syncOptions: SyncStreamOptions = {
|
|
675
791
|
path: '/sync/stream',
|
|
676
792
|
abortSignal: signal,
|
|
677
|
-
data:
|
|
793
|
+
data: establish.request
|
|
678
794
|
};
|
|
679
795
|
|
|
680
796
|
controlInvocations = injectable(
|
|
@@ -683,6 +799,24 @@ The next upload iteration will be delayed.`
|
|
|
683
799
|
connection: resolvedOptions
|
|
684
800
|
})
|
|
685
801
|
);
|
|
802
|
+
|
|
803
|
+
if (establish.checkpoint_request) {
|
|
804
|
+
// Start checkpoint request validation concurrently, without blocking line processing on it. We reconcile
|
|
805
|
+
// checkpoint states on each started download iteration to:
|
|
806
|
+
// 1. Align service and client checkpoint ids, allowing both parties to safely forget old checkpoints.
|
|
807
|
+
// 2. If the user id changes between connections, agreeing on the highest checkpoint request between the
|
|
808
|
+
// old and new user to make sure we'll receive that checkpoint eventually.
|
|
809
|
+
const seed = this.checkpoints.markCheckpointsReady(
|
|
810
|
+
this.seedCheckpointRequestState(signal, establish.checkpoint_request)
|
|
811
|
+
);
|
|
812
|
+
|
|
813
|
+
seed.catch((e) => {
|
|
814
|
+
// Make the download iteration fail if checkpoint requests are broken.
|
|
815
|
+
if (!signal.aborted) {
|
|
816
|
+
controlInvocations?.injectError(e);
|
|
817
|
+
}
|
|
818
|
+
});
|
|
819
|
+
}
|
|
686
820
|
} else if ('CloseSyncStream' in startInstruction) {
|
|
687
821
|
return defaultResult;
|
|
688
822
|
} else {
|
|
@@ -761,14 +895,15 @@ The next upload iteration will be delayed.`
|
|
|
761
895
|
this.updateSyncStatus(this.syncStatus.core, state);
|
|
762
896
|
}
|
|
763
897
|
|
|
764
|
-
private async delayRetry(signal: AbortSignal, delay: number): Promise<void> {
|
|
898
|
+
private async delayRetry(signal: AbortSignal, delay: number, resumeOnCheckpointRequest = false): Promise<void> {
|
|
765
899
|
return new Promise((resolve) => {
|
|
766
|
-
if (signal
|
|
900
|
+
if (signal.aborted) {
|
|
767
901
|
// If the signal is already aborted, resolve immediately
|
|
768
902
|
resolve();
|
|
769
903
|
return;
|
|
770
904
|
}
|
|
771
905
|
|
|
906
|
+
let nested: AbortController | null = null;
|
|
772
907
|
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
773
908
|
|
|
774
909
|
const endDelay = () => {
|
|
@@ -777,11 +912,23 @@ The next upload iteration will be delayed.`
|
|
|
777
912
|
clearTimeout(timeoutId);
|
|
778
913
|
timeoutId = undefined;
|
|
779
914
|
}
|
|
780
|
-
|
|
915
|
+
if (nested) {
|
|
916
|
+
nested.abort();
|
|
917
|
+
nested = null;
|
|
918
|
+
}
|
|
919
|
+
signal.removeEventListener('abort', endDelay);
|
|
781
920
|
};
|
|
782
921
|
|
|
783
|
-
signal
|
|
784
|
-
|
|
922
|
+
signal.addEventListener('abort', endDelay, { once: true });
|
|
923
|
+
|
|
924
|
+
// Add a random +/- 10% jitter to the retry delay.
|
|
925
|
+
const randomizedDelay = delay * (0.9 + Math.random() * 0.2);
|
|
926
|
+
timeoutId = setTimeout(endDelay, randomizedDelay);
|
|
927
|
+
|
|
928
|
+
if (resumeOnCheckpointRequest) {
|
|
929
|
+
nested = new AbortController();
|
|
930
|
+
this.checkpoints.waitForCheckpointWaiter(nested.signal).finally(endDelay);
|
|
931
|
+
}
|
|
785
932
|
});
|
|
786
933
|
}
|
|
787
934
|
|