@powersync/shared-internals 0.0.0-dev-20260827080125
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/LICENSE +201 -0
- package/README.md +5 -0
- package/dist/websockets.mjs +7558 -0
- package/dist/websockets.mjs.map +1 -0
- package/dist/websockets.node.mjs +5189 -0
- package/dist/websockets.node.mjs.map +1 -0
- package/legacy/sync_protocol.d.ts +103 -0
- package/lib/client/BasePowerSyncDatabase.d.ts +156 -0
- package/lib/client/BasePowerSyncDatabase.js +654 -0
- package/lib/client/BasePowerSyncDatabase.js.map +1 -0
- package/lib/client/ConnectionManager.d.ts +120 -0
- package/lib/client/ConnectionManager.js +324 -0
- package/lib/client/ConnectionManager.js.map +1 -0
- package/lib/client/CustomQuery.d.ts +21 -0
- package/lib/client/CustomQuery.js +43 -0
- package/lib/client/CustomQuery.js.map +1 -0
- 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 +58 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.js +47 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
- package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
- package/lib/client/sync/bucket/CrudEntry.js +60 -0
- package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +32 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.js +160 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
- package/lib/client/sync/options.d.ts +9 -0
- package/lib/client/sync/options.js +17 -0
- package/lib/client/sync/options.js.map +1 -0
- package/lib/client/sync/stream/AbstractRemote.d.ts +131 -0
- package/lib/client/sync/stream/AbstractRemote.js +270 -0
- package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +156 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +740 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
- 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/WebSocketSupport.d.ts +26 -0
- package/lib/client/sync/stream/WebSocketSupport.js +198 -0
- package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
- package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
- package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
- package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
- package/lib/client/sync/stream/core-instruction.d.ts +81 -0
- package/lib/client/sync/stream/core-instruction.js +4 -0
- package/lib/client/sync/stream/core-instruction.js.map +1 -0
- package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
- package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
- package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
- package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
- package/lib/client/triggers/TriggerManagerImpl.js +415 -0
- package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
- package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
- package/lib/client/watched/AbstractQueryProcessor.js +155 -0
- package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
- package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
- package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
- package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
- package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
- package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
- package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
- package/lib/client/watched/WatchedQuery.d.ts +9 -0
- package/lib/client/watched/WatchedQuery.js +12 -0
- package/lib/client/watched/WatchedQuery.js.map +1 -0
- package/lib/constants.d.ts +5 -0
- package/lib/constants.js +6 -0
- package/lib/constants.js.map +1 -0
- package/lib/db/ConnectionClosedError.d.ts +12 -0
- package/lib/db/ConnectionClosedError.js +23 -0
- package/lib/db/ConnectionClosedError.js.map +1 -0
- package/lib/db/crud/SyncProgress.d.ts +10 -0
- package/lib/db/crud/SyncProgress.js +33 -0
- package/lib/db/crud/SyncProgress.js.map +1 -0
- package/lib/db/crud/SyncStatus.d.ts +48 -0
- package/lib/db/crud/SyncStatus.js +178 -0
- package/lib/db/crud/SyncStatus.js.map +1 -0
- package/lib/db/openDatabase.d.ts +7 -0
- package/lib/db/openDatabase.js +22 -0
- package/lib/db/openDatabase.js.map +1 -0
- package/lib/index.d.ts +22 -0
- package/lib/index.js +22 -0
- package/lib/index.js.map +1 -0
- package/lib/utils/AbortOperation.d.ts +11 -0
- package/lib/utils/AbortOperation.js +21 -0
- package/lib/utils/AbortOperation.js.map +1 -0
- package/lib/utils/ControlledExecutor.d.ts +31 -0
- package/lib/utils/ControlledExecutor.js +58 -0
- package/lib/utils/ControlledExecutor.js.map +1 -0
- package/lib/utils/MetaBaseObserver.d.ts +11 -0
- package/lib/utils/MetaBaseObserver.js +51 -0
- package/lib/utils/MetaBaseObserver.js.map +1 -0
- package/lib/utils/async.d.ts +46 -0
- package/lib/utils/async.js +147 -0
- package/lib/utils/async.js.map +1 -0
- package/lib/utils/compatibility.d.ts +8 -0
- package/lib/utils/compatibility.js +9 -0
- package/lib/utils/compatibility.js.map +1 -0
- package/lib/utils/mutex.d.ts +42 -0
- package/lib/utils/mutex.js +150 -0
- package/lib/utils/mutex.js.map +1 -0
- package/lib/utils/parseQuery.d.ts +12 -0
- package/lib/utils/parseQuery.js +20 -0
- package/lib/utils/parseQuery.js.map +1 -0
- package/lib/utils/queue.d.ts +16 -0
- package/lib/utils/queue.js +42 -0
- package/lib/utils/queue.js.map +1 -0
- package/lib/utils/stream_transform.d.ts +42 -0
- package/lib/utils/stream_transform.js +227 -0
- package/lib/utils/stream_transform.js.map +1 -0
- package/lib/version.d.ts +1 -0
- package/lib/version.js +4 -0
- package/lib/version.js.map +1 -0
- package/package.json +68 -0
- package/src/client/BasePowerSyncDatabase.ts +898 -0
- package/src/client/ConnectionManager.ts +441 -0
- package/src/client/CustomQuery.ts +60 -0
- package/src/client/sync/CheckpointRequestImpl.ts +54 -0
- package/src/client/sync/bucket/BucketStorageAdapter.ts +85 -0
- package/src/client/sync/bucket/CrudEntry.ts +116 -0
- package/src/client/sync/bucket/SqliteBucketStorage.ts +203 -0
- package/src/client/sync/options.ts +25 -0
- package/src/client/sync/stream/AbstractRemote.ts +388 -0
- package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +948 -0
- package/src/client/sync/stream/CheckpointState.ts +136 -0
- package/src/client/sync/stream/WebSocketSupport.ts +259 -0
- package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
- package/src/client/sync/stream/core-instruction.ts +85 -0
- package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
- package/src/client/triggers/TriggerManagerImpl.ts +538 -0
- package/src/client/watched/AbstractQueryProcessor.ts +231 -0
- package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
- package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
- package/src/client/watched/WatchedQuery.ts +14 -0
- package/src/constants.ts +6 -0
- package/src/db/ConnectionClosedError.ts +25 -0
- package/src/db/crud/SyncProgress.ts +39 -0
- package/src/db/crud/SyncStatus.ts +234 -0
- package/src/db/openDatabase.ts +23 -0
- package/src/index.ts +24 -0
- package/src/utils/AbortOperation.ts +19 -0
- package/src/utils/ControlledExecutor.ts +81 -0
- package/src/utils/MetaBaseObserver.ts +65 -0
- package/src/utils/async.ts +185 -0
- package/src/utils/compatibility.ts +9 -0
- package/src/utils/mutex.ts +186 -0
- package/src/utils/parseQuery.ts +31 -0
- package/src/utils/queue.ts +48 -0
- package/src/utils/stream_transform.ts +276 -0
- package/src/version.ts +3 -0
|
@@ -0,0 +1,948 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BaseObserverInterface,
|
|
3
|
+
BaseListener,
|
|
4
|
+
CrudEntry,
|
|
5
|
+
Disposable,
|
|
6
|
+
LogLevels,
|
|
7
|
+
PowerSyncLogger,
|
|
8
|
+
SyncStreamConnectionMethod,
|
|
9
|
+
SyncStatus,
|
|
10
|
+
BaseObserver
|
|
11
|
+
} from '@powersync/common';
|
|
12
|
+
|
|
13
|
+
import { AbortOperation } from '../../../utils/AbortOperation.js';
|
|
14
|
+
import { BucketStorageAdapter, PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';
|
|
15
|
+
import { AbstractRemote, SyncStreamOptions } from './AbstractRemote.js';
|
|
16
|
+
import {
|
|
17
|
+
CheckpointRequestPayload,
|
|
18
|
+
CoreSyncStatus,
|
|
19
|
+
Instruction,
|
|
20
|
+
NonInterruptingInstruction,
|
|
21
|
+
isInterruptingInstruction
|
|
22
|
+
} from './core-instruction.js';
|
|
23
|
+
import {
|
|
24
|
+
doneResult,
|
|
25
|
+
injectable,
|
|
26
|
+
InjectableIterator,
|
|
27
|
+
SimpleAsyncIterator,
|
|
28
|
+
valueResult
|
|
29
|
+
} from '../../../utils/stream_transform.js';
|
|
30
|
+
import { asyncNotifier } from '../../../utils/async.js';
|
|
31
|
+
import { JavaScriptSyncState, SyncStatusSnapshot } from '../../../db/crud/SyncStatus.js';
|
|
32
|
+
import { ResolvedSyncOptions } from '../options.js';
|
|
33
|
+
import { CheckpointStateSignals, isCheckpointRequestApplied } from './CheckpointState.js';
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @internal
|
|
37
|
+
*/
|
|
38
|
+
export enum LockType {
|
|
39
|
+
CRUD = 'crud',
|
|
40
|
+
SYNC = 'sync'
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Abstract Lock to be implemented by various JS environments
|
|
45
|
+
*
|
|
46
|
+
* @internal
|
|
47
|
+
*/
|
|
48
|
+
export interface LockOptions<T> {
|
|
49
|
+
callback: () => Promise<T>;
|
|
50
|
+
type: LockType;
|
|
51
|
+
signal?: AbortSignal;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @internal
|
|
56
|
+
*/
|
|
57
|
+
export interface AbstractStreamingSyncImplementationOptions {
|
|
58
|
+
adapter: BucketStorageAdapter;
|
|
59
|
+
subscriptions: SubscribedStream[];
|
|
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;
|
|
65
|
+
/**
|
|
66
|
+
* An identifier for which PowerSync DB this sync implementation is
|
|
67
|
+
* linked to. Most commonly DB name, but not restricted to DB name.
|
|
68
|
+
*/
|
|
69
|
+
identifier?: string;
|
|
70
|
+
logger: PowerSyncLogger;
|
|
71
|
+
remote: AbstractRemote;
|
|
72
|
+
/**
|
|
73
|
+
* The serialized schema - mainly used to forward information about raw tables to the sync client.
|
|
74
|
+
*/
|
|
75
|
+
serializedSchema: any;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @internal
|
|
80
|
+
*/
|
|
81
|
+
export interface StreamingSyncImplementationListener extends BaseListener {
|
|
82
|
+
/**
|
|
83
|
+
* Triggers whenever the status' members have changed in value
|
|
84
|
+
*/
|
|
85
|
+
statusChanged?: ((status: SyncStatusSnapshot) => void) | undefined;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @internal
|
|
90
|
+
*/
|
|
91
|
+
export interface StreamingSyncImplementation
|
|
92
|
+
extends BaseObserverInterface<StreamingSyncImplementationListener>, Disposable {
|
|
93
|
+
/**
|
|
94
|
+
* Connects to the sync service
|
|
95
|
+
*/
|
|
96
|
+
connect(options: ResolvedSyncOptions): Promise<void>;
|
|
97
|
+
/**
|
|
98
|
+
* Disconnects from the sync services.
|
|
99
|
+
* @throws if not connected or if abort is not controlled internally
|
|
100
|
+
*/
|
|
101
|
+
disconnect(): Promise<void>;
|
|
102
|
+
isConnected: boolean;
|
|
103
|
+
triggerCrudUpload: () => void;
|
|
104
|
+
waitForReady(): Promise<void>;
|
|
105
|
+
waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
|
|
106
|
+
updateSubscriptions(subscriptions: SubscribedStream[]): void;
|
|
107
|
+
markConnectionMayHaveChanged(): void;
|
|
108
|
+
|
|
109
|
+
requestCheckpoint(): Promise<bigint>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @internal
|
|
114
|
+
*/
|
|
115
|
+
export type SubscribedStream = {
|
|
116
|
+
name: string;
|
|
117
|
+
params: Record<string, any> | null;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* @internal
|
|
122
|
+
*/
|
|
123
|
+
export abstract class AbstractStreamingSyncImplementation
|
|
124
|
+
extends BaseObserver<StreamingSyncImplementationListener>
|
|
125
|
+
implements StreamingSyncImplementation
|
|
126
|
+
{
|
|
127
|
+
protected options: AbstractStreamingSyncImplementationOptions;
|
|
128
|
+
protected abortController: AbortController | null;
|
|
129
|
+
protected crudUpdateListener?: () => void;
|
|
130
|
+
protected streamingSyncPromise?: Promise<[void, void, void]>;
|
|
131
|
+
protected logger: PowerSyncLogger;
|
|
132
|
+
protected activeStreams: SubscribedStream[];
|
|
133
|
+
private connectionMayHaveChanged = false;
|
|
134
|
+
private crudUploadNotifier = asyncNotifier();
|
|
135
|
+
private checkpoints = new CheckpointStateSignals();
|
|
136
|
+
|
|
137
|
+
private notifyCompletedUploads?: () => void;
|
|
138
|
+
private handleActiveStreamsChange?: () => void;
|
|
139
|
+
|
|
140
|
+
syncStatus: SyncStatusSnapshot;
|
|
141
|
+
|
|
142
|
+
constructor(options: AbstractStreamingSyncImplementationOptions) {
|
|
143
|
+
super();
|
|
144
|
+
this.options = options;
|
|
145
|
+
this.activeStreams = options.subscriptions;
|
|
146
|
+
this.logger = options.logger;
|
|
147
|
+
|
|
148
|
+
this.syncStatus = new SyncStatusSnapshot(null, {});
|
|
149
|
+
this.abortController = null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
triggerCrudUpload() {
|
|
153
|
+
this.crudUploadNotifier.notify();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async waitForReady() {}
|
|
157
|
+
|
|
158
|
+
waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void> {
|
|
159
|
+
return new Promise((resolve) => {
|
|
160
|
+
if (predicate(this.syncStatus)) {
|
|
161
|
+
resolve();
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const l = this.registerListener({
|
|
166
|
+
statusChanged: () => {
|
|
167
|
+
if (predicate(this.syncStatus)) {
|
|
168
|
+
resolve();
|
|
169
|
+
l?.();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
get lastSyncedAt() {
|
|
177
|
+
const lastSynced = this.syncStatus.lastSyncedAt;
|
|
178
|
+
return lastSynced && new Date(lastSynced);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
get isConnected() {
|
|
182
|
+
return this.syncStatus.connected;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async dispose() {
|
|
186
|
+
super.dispose();
|
|
187
|
+
this.crudUpdateListener?.();
|
|
188
|
+
this.crudUpdateListener = undefined;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
|
|
192
|
+
|
|
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> {
|
|
224
|
+
const clientId = await this.options.adapter.getClientId();
|
|
225
|
+
let path = `/write-checkpoint2.json?client_id=${clientId}`;
|
|
226
|
+
const response = await this.options.remote.fetchAndDecodeJson({ path });
|
|
227
|
+
const checkpoint = response['data']['write_checkpoint'] as string;
|
|
228
|
+
this.logger.log({ level: LogLevels.debug, message: `Created write checkpoint: ${checkpoint}` });
|
|
229
|
+
return checkpoint;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
private async crudUploadLoop(signal: AbortSignal, options: ResolvedSyncOptions): Promise<void> {
|
|
233
|
+
while (!signal.aborted) {
|
|
234
|
+
await Promise.all([
|
|
235
|
+
// Start the initial CRUD upload on connect. Then, keep polling until we're done.
|
|
236
|
+
this._uploadAllCrud(signal, options),
|
|
237
|
+
this.delayRetry(signal, options.crudUploadThrottleMs)
|
|
238
|
+
]);
|
|
239
|
+
|
|
240
|
+
await this.crudUploadNotifier.waitForNotification(signal);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
private async _uploadAllCrud(signal: AbortSignal, options: ResolvedSyncOptions): Promise<void> {
|
|
245
|
+
return this.obtainLock({
|
|
246
|
+
type: LockType.CRUD,
|
|
247
|
+
signal,
|
|
248
|
+
callback: async () => {
|
|
249
|
+
/**
|
|
250
|
+
* Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
|
|
251
|
+
*/
|
|
252
|
+
let checkedCrudItem: CrudEntry | undefined;
|
|
253
|
+
|
|
254
|
+
while (!signal.aborted) {
|
|
255
|
+
try {
|
|
256
|
+
/**
|
|
257
|
+
* This is the first item in the FIFO CRUD queue.
|
|
258
|
+
*/
|
|
259
|
+
const nextCrudItem = await this.options.adapter.nextCrudItem();
|
|
260
|
+
if (nextCrudItem) {
|
|
261
|
+
this.updateJsSyncState({ uploading: true });
|
|
262
|
+
|
|
263
|
+
if (nextCrudItem.clientId == checkedCrudItem?.clientId) {
|
|
264
|
+
// This will force a higher log level than exceptions which are caught here.
|
|
265
|
+
this.logger.log({
|
|
266
|
+
level: LogLevels.warn,
|
|
267
|
+
message: `Potentially previously uploaded CRUD entries are still present in the upload queue.
|
|
268
|
+
Make sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.
|
|
269
|
+
The next upload iteration will be delayed.`
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
throw new Error('Delaying due to previously encountered CRUD item.');
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
checkedCrudItem = nextCrudItem;
|
|
276
|
+
await this.options.uploadCrud();
|
|
277
|
+
this.updateJsSyncState({ uploadError: undefined });
|
|
278
|
+
} else {
|
|
279
|
+
// Uploading is completed
|
|
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
|
+
});
|
|
287
|
+
if (neededUpdate) {
|
|
288
|
+
this.notifyCompletedUploads?.();
|
|
289
|
+
} else if (checkedCrudItem != null) {
|
|
290
|
+
// Only log this if there was something to upload
|
|
291
|
+
this.logger.log({ level: LogLevels.debug, message: 'Upload complete, no write checkpoint needed.' });
|
|
292
|
+
}
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
} catch (ex) {
|
|
296
|
+
checkedCrudItem = undefined;
|
|
297
|
+
this.updateJsSyncState({ uploading: false, uploadError: ex as Error });
|
|
298
|
+
await this.delayRetry(signal, options.retryDelayMs);
|
|
299
|
+
if (!this.isConnected) {
|
|
300
|
+
// Exit the upload loop if the sync stream is no longer connected
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
this.logger.log({
|
|
304
|
+
level: LogLevels.debug,
|
|
305
|
+
message: `Caught exception when uploading. Upload will retry after a delay.`,
|
|
306
|
+
error: ex
|
|
307
|
+
});
|
|
308
|
+
} finally {
|
|
309
|
+
this.updateJsSyncState({ uploading: false });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async connect(options: ResolvedSyncOptions) {
|
|
317
|
+
if (this.abortController) {
|
|
318
|
+
await this.disconnect();
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const controller = new AbortController();
|
|
322
|
+
this.abortController = controller;
|
|
323
|
+
this.streamingSyncPromise = Promise.all([
|
|
324
|
+
this.crudUploadLoop(controller.signal, options).catch((error) =>
|
|
325
|
+
this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error })
|
|
326
|
+
),
|
|
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
|
+
});
|
|
334
|
+
|
|
335
|
+
// Return a promise that resolves when the connection status is updated to indicate that we're connected. We do this
|
|
336
|
+
// by waiting for connecting to be true and then false again.
|
|
337
|
+
return new Promise<void>((resolve) => {
|
|
338
|
+
let sawStartOfConnection = false;
|
|
339
|
+
|
|
340
|
+
const disposer = this.registerListener({
|
|
341
|
+
statusChanged: (snapshot) => {
|
|
342
|
+
if (snapshot.connecting) {
|
|
343
|
+
sawStartOfConnection = true;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (snapshot.downloadError != null) {
|
|
347
|
+
this.logger.log({
|
|
348
|
+
level: LogLevels.warn,
|
|
349
|
+
message: 'Initial connect attempt did not successfully connect to server'
|
|
350
|
+
});
|
|
351
|
+
} else if (!sawStartOfConnection || snapshot.connecting) {
|
|
352
|
+
// Still connecting.
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
disposer();
|
|
357
|
+
resolve();
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async requestCheckpoint(): Promise<bigint> {
|
|
364
|
+
const neverAbort = new AbortController().signal;
|
|
365
|
+
return BigInt(await this.requestNextCheckpointFromService(neverAbort));
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async disconnect(): Promise<void> {
|
|
369
|
+
if (!this.abortController) {
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// This might be called multiple times
|
|
374
|
+
if (!this.abortController.signal.aborted) {
|
|
375
|
+
this.abortController.abort(new AbortOperation('Disconnect has been requested'));
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// Await any pending operations before completing the disconnect operation
|
|
379
|
+
try {
|
|
380
|
+
await this.streamingSyncPromise;
|
|
381
|
+
} catch (ex) {
|
|
382
|
+
// The operation might have failed, all we care about is if it has completed
|
|
383
|
+
this.logger.log({ level: LogLevels.warn, message: 'Error in sync while disconnecting', error: ex });
|
|
384
|
+
}
|
|
385
|
+
this.streamingSyncPromise = undefined;
|
|
386
|
+
|
|
387
|
+
this.abortController = null;
|
|
388
|
+
this.markAsDisconnected();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
private markAsDisconnected() {
|
|
392
|
+
const current = this.syncStatus.core;
|
|
393
|
+
if (current == null) {
|
|
394
|
+
// There's no connection attempt for which state could be cleared.
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
this.updateSyncStatus({
|
|
399
|
+
...current,
|
|
400
|
+
connected: false,
|
|
401
|
+
connecting: false,
|
|
402
|
+
downloading: null
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
private async streamingSync(signal: AbortSignal, options: ResolvedSyncOptions): Promise<void> {
|
|
407
|
+
/**
|
|
408
|
+
* Listen for CRUD updates and trigger upstream uploads
|
|
409
|
+
*/
|
|
410
|
+
this.crudUpdateListener = this.options.adapter.registerListener({
|
|
411
|
+
crudUpdate: () => this.triggerCrudUpload()
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Create a new abort controller which aborts items downstream.
|
|
416
|
+
* This is needed to close any previous connections on exception.
|
|
417
|
+
*/
|
|
418
|
+
let nestedAbortController = new AbortController();
|
|
419
|
+
|
|
420
|
+
signal.addEventListener('abort', () => {
|
|
421
|
+
/**
|
|
422
|
+
* A request for disconnect was received upstream. Relay the request
|
|
423
|
+
* to the nested abort controller.
|
|
424
|
+
*/
|
|
425
|
+
nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
|
|
426
|
+
this.crudUpdateListener?.();
|
|
427
|
+
this.crudUpdateListener = undefined;
|
|
428
|
+
this.markAsDisconnected();
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* This loops runs until [retry] is false or the abort signal is set to aborted.
|
|
433
|
+
* Aborting the nestedAbortController will:
|
|
434
|
+
* - Abort any pending fetch requests
|
|
435
|
+
* - Close any sync stream ReadableStreams (which will also close any established network requests)
|
|
436
|
+
*/
|
|
437
|
+
while (true) {
|
|
438
|
+
let shouldDelayRetry = true;
|
|
439
|
+
let result: RustIterationResult | null = null;
|
|
440
|
+
|
|
441
|
+
try {
|
|
442
|
+
if (signal?.aborted) {
|
|
443
|
+
break;
|
|
444
|
+
}
|
|
445
|
+
result = await this.streamingSyncIteration(nestedAbortController.signal, options);
|
|
446
|
+
// Continue immediately, streamingSyncIteration will wait before completing if necessary.
|
|
447
|
+
} catch (ex) {
|
|
448
|
+
/**
|
|
449
|
+
* Either:
|
|
450
|
+
* - A network request failed with a failed connection or not OKAY response code.
|
|
451
|
+
* - There was a sync processing error.
|
|
452
|
+
* - The connection was aborted.
|
|
453
|
+
* This loop will retry after a delay if the connection was not aborted.
|
|
454
|
+
* The nested abort controller will cleanup any open network requests and streams.
|
|
455
|
+
* The WebRemote should only abort pending fetch requests or close active Readable streams.
|
|
456
|
+
*/
|
|
457
|
+
|
|
458
|
+
if (ex instanceof AbortOperation) {
|
|
459
|
+
this.logger.log({ level: LogLevels.warn, message: 'Sync aborted', error: ex });
|
|
460
|
+
shouldDelayRetry = false;
|
|
461
|
+
// A disconnect was requested, we should not delay since there is no explicit retry
|
|
462
|
+
} else if (this.connectionMayHaveChanged && (ex as Error).message?.indexOf('No iteration is active') >= 0) {
|
|
463
|
+
this.connectionMayHaveChanged = false;
|
|
464
|
+
this.logger.log({
|
|
465
|
+
level: LogLevels.info,
|
|
466
|
+
message: 'Sync error after changed connection, retrying immediately'
|
|
467
|
+
});
|
|
468
|
+
shouldDelayRetry = false;
|
|
469
|
+
} else {
|
|
470
|
+
this.logger.log({ level: LogLevels.error, message: 'Sync error', error: ex });
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
this.updateJsSyncState({ downloadError: ex as Error });
|
|
474
|
+
} finally {
|
|
475
|
+
this.checkpoints.downloadIterationEnded();
|
|
476
|
+
this.notifyCompletedUploads = undefined;
|
|
477
|
+
|
|
478
|
+
if (!signal.aborted) {
|
|
479
|
+
nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));
|
|
480
|
+
nestedAbortController = new AbortController();
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
if (result?.immediateRestart != true) {
|
|
484
|
+
this.markAsDisconnected();
|
|
485
|
+
|
|
486
|
+
// On error, wait a little before retrying
|
|
487
|
+
if (shouldDelayRetry) {
|
|
488
|
+
await this.delayRetry(nestedAbortController.signal, options.retryDelayMs, true);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// Mark as disconnected if here
|
|
495
|
+
this.markAsDisconnected();
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
markConnectionMayHaveChanged() {
|
|
499
|
+
// By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
|
|
500
|
+
// an active sync iteration on the connection in use.
|
|
501
|
+
this.connectionMayHaveChanged = true;
|
|
502
|
+
|
|
503
|
+
// This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
|
|
504
|
+
// make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
|
|
505
|
+
// iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
|
|
506
|
+
this.handleActiveStreamsChange?.();
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Older versions of the JS SDK used to encode subkeys as JSON in `OplogEntry.toJSON`.
|
|
511
|
+
* Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
|
|
512
|
+
* While this is not a problem as long as it's done consistently, it causes issues when a database
|
|
513
|
+
* created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
|
|
514
|
+
* is enabled.
|
|
515
|
+
*
|
|
516
|
+
* So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
|
|
517
|
+
* migration is only triggered when necessary (for now). The function returns whether the new format
|
|
518
|
+
* should be used, so that the JS SDK is able to write to updated databases.
|
|
519
|
+
*
|
|
520
|
+
* @param requireFixedKeyFormat - Whether we require the new format or also support the old one.
|
|
521
|
+
* The Rust client requires the new subkey format.
|
|
522
|
+
* @returns Whether the database is now using the new, fixed subkey format.
|
|
523
|
+
*/
|
|
524
|
+
private async requireKeyFormat(requireFixedKeyFormat: boolean): Promise<boolean> {
|
|
525
|
+
const hasMigrated = await this.options.adapter.hasMigratedSubkeys();
|
|
526
|
+
if (requireFixedKeyFormat && !hasMigrated) {
|
|
527
|
+
await this.options.adapter.migrateToFixedSubkeys();
|
|
528
|
+
return true;
|
|
529
|
+
} else {
|
|
530
|
+
return hasMigrated;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
protected streamingSyncIteration(
|
|
535
|
+
signal: AbortSignal,
|
|
536
|
+
options: ResolvedSyncOptions
|
|
537
|
+
): Promise<RustIterationResult | null> {
|
|
538
|
+
return this.obtainLock({
|
|
539
|
+
type: LockType.SYNC,
|
|
540
|
+
signal,
|
|
541
|
+
callback: async () => {
|
|
542
|
+
// Validate app metadata
|
|
543
|
+
const invalidMetadata = Object.entries(options.appMetadata).filter(([_, value]) => typeof value != 'string');
|
|
544
|
+
if (invalidMetadata.length > 0) {
|
|
545
|
+
throw new Error(
|
|
546
|
+
`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
await this.requireKeyFormat(true);
|
|
551
|
+
return await this.rustSyncIteration(signal, options);
|
|
552
|
+
}
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
private receiveSyncLines(data: {
|
|
557
|
+
options: SyncStreamOptions;
|
|
558
|
+
connection: ResolvedSyncOptions;
|
|
559
|
+
}): SimpleAsyncIterator<EnqueuedCommand> {
|
|
560
|
+
const { options, connection } = data;
|
|
561
|
+
const remote = this.options.remote;
|
|
562
|
+
|
|
563
|
+
const openInner = async () => {
|
|
564
|
+
if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
|
|
565
|
+
return await remote.fetchStream(options);
|
|
566
|
+
} else {
|
|
567
|
+
return await this.options.remote.socketStreamRaw({
|
|
568
|
+
...options,
|
|
569
|
+
...{ fetchStrategy: connection.fetchStrategy }
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
let inner: SimpleAsyncIterator<string | Uint8Array> | undefined;
|
|
575
|
+
let done = false;
|
|
576
|
+
|
|
577
|
+
return {
|
|
578
|
+
async next(): Promise<IteratorResult<EnqueuedCommand>> {
|
|
579
|
+
if (done) {
|
|
580
|
+
return doneResult;
|
|
581
|
+
} else if (inner == null) {
|
|
582
|
+
inner = await openInner();
|
|
583
|
+
// We're connected here, so we can tell the core extension about it.
|
|
584
|
+
return valueResult<EnqueuedCommand>({
|
|
585
|
+
command: PowerSyncControlCommand.CONNECTION_STATE,
|
|
586
|
+
payload: 'established'
|
|
587
|
+
});
|
|
588
|
+
} else {
|
|
589
|
+
const event = await inner.next();
|
|
590
|
+
if (event.done) {
|
|
591
|
+
done = true;
|
|
592
|
+
return valueResult<EnqueuedCommand>({ command: PowerSyncControlCommand.CONNECTION_STATE, payload: 'end' });
|
|
593
|
+
} else {
|
|
594
|
+
return valueResult<EnqueuedCommand>({
|
|
595
|
+
command:
|
|
596
|
+
typeof event.value == 'string'
|
|
597
|
+
? PowerSyncControlCommand.PROCESS_TEXT_LINE
|
|
598
|
+
: PowerSyncControlCommand.PROCESS_BSON_LINE,
|
|
599
|
+
payload: event.value
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
}
|
|
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
|
+
|
|
667
|
+
private async rustSyncIteration(
|
|
668
|
+
signal: AbortSignal,
|
|
669
|
+
resolvedOptions: ResolvedSyncOptions
|
|
670
|
+
): Promise<RustIterationResult> {
|
|
671
|
+
const syncImplementation = this;
|
|
672
|
+
const adapter = this.options.adapter;
|
|
673
|
+
const remote = this.options.remote;
|
|
674
|
+
let hideDisconnectOnRestart = false;
|
|
675
|
+
let notifyTokenRefreshed: (() => void) | undefined;
|
|
676
|
+
|
|
677
|
+
if (signal.aborted) {
|
|
678
|
+
throw new AbortOperation('Connection request has been aborted');
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const serializedSchema = this.options.serializedSchema;
|
|
682
|
+
function startCommand() {
|
|
683
|
+
const options: any = {
|
|
684
|
+
parameters: resolvedOptions.params,
|
|
685
|
+
app_metadata: resolvedOptions.appMetadata,
|
|
686
|
+
active_streams: syncImplementation.activeStreams,
|
|
687
|
+
include_defaults: resolvedOptions.includeDefaultStreams,
|
|
688
|
+
checkpoint_mode: resolvedOptions.checkpointMode === 'legacy' ? 'legacy' : 'requests'
|
|
689
|
+
};
|
|
690
|
+
if (serializedSchema) {
|
|
691
|
+
options.schema = serializedSchema;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
return invokePowerSyncControl(PowerSyncControlCommand.START, JSON.stringify(options));
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
async function stop() {
|
|
698
|
+
const instructions = await invokePowerSyncControl(PowerSyncControlCommand.STOP);
|
|
699
|
+
for (const instruction of instructions) {
|
|
700
|
+
// We don't need to handle interrupting instructions since we're unconditionally ending the sync iteration at
|
|
701
|
+
// this point.
|
|
702
|
+
if (isInterruptingInstruction(instruction)) continue;
|
|
703
|
+
await handleInstruction(instruction);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
async function invokePowerSyncControl(
|
|
708
|
+
op: PowerSyncControlCommand,
|
|
709
|
+
payload?: Uint8Array | string
|
|
710
|
+
): Promise<Instruction[]> {
|
|
711
|
+
const rawResponse = await adapter.control(op, payload ?? null);
|
|
712
|
+
const payloadDesc = payload == null || typeof payload == 'string' ? payload : '<bytes>';
|
|
713
|
+
|
|
714
|
+
syncImplementation.logger.log({
|
|
715
|
+
level: LogLevels.trace,
|
|
716
|
+
message: `powersync_control(${op}, ${payloadDesc}) -> ${rawResponse}`
|
|
717
|
+
});
|
|
718
|
+
|
|
719
|
+
if (op != PowerSyncControlCommand.STOP) {
|
|
720
|
+
// Evidently we have a working connection here, otherwise powersync_control would have failed.
|
|
721
|
+
syncImplementation.connectionMayHaveChanged = false;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
return JSON.parse(rawResponse);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
async function handleInstruction(instruction: NonInterruptingInstruction) {
|
|
728
|
+
if ('LogLine' in instruction) {
|
|
729
|
+
const { severity, line } = instruction.LogLine;
|
|
730
|
+
|
|
731
|
+
switch (severity) {
|
|
732
|
+
case 'DEBUG':
|
|
733
|
+
syncImplementation.logger.log({
|
|
734
|
+
level: LogLevels.debug,
|
|
735
|
+
message: line
|
|
736
|
+
});
|
|
737
|
+
break;
|
|
738
|
+
case 'INFO':
|
|
739
|
+
syncImplementation.logger.log({
|
|
740
|
+
level: LogLevels.info,
|
|
741
|
+
message: line
|
|
742
|
+
});
|
|
743
|
+
break;
|
|
744
|
+
case 'WARNING':
|
|
745
|
+
syncImplementation.logger.log({
|
|
746
|
+
level: LogLevels.warn,
|
|
747
|
+
message: line
|
|
748
|
+
});
|
|
749
|
+
break;
|
|
750
|
+
}
|
|
751
|
+
} else if ('UpdateSyncStatus' in instruction) {
|
|
752
|
+
syncImplementation.updateSyncStatus(instruction.UpdateSyncStatus.status);
|
|
753
|
+
} else if ('FetchCredentials' in instruction) {
|
|
754
|
+
if (instruction.FetchCredentials.did_expire) {
|
|
755
|
+
remote.invalidateCredentials();
|
|
756
|
+
} else {
|
|
757
|
+
remote.invalidateCredentials();
|
|
758
|
+
|
|
759
|
+
// Restart iteration after the credentials have been refreshed.
|
|
760
|
+
remote.fetchCredentials().then(
|
|
761
|
+
(_) => {
|
|
762
|
+
notifyTokenRefreshed?.();
|
|
763
|
+
},
|
|
764
|
+
(err) => {
|
|
765
|
+
syncImplementation.logger.log({
|
|
766
|
+
level: LogLevels.warn,
|
|
767
|
+
message: 'Could not prefetch credentials',
|
|
768
|
+
error: err
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
);
|
|
772
|
+
}
|
|
773
|
+
} else if ('FlushFileSystem' in instruction) {
|
|
774
|
+
// Not necessary on JS platforms.
|
|
775
|
+
} else if ('DidCompleteSync' in instruction) {
|
|
776
|
+
syncImplementation.updateJsSyncState({ downloadError: undefined });
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
try {
|
|
781
|
+
const defaultResult = { immediateRestart: false };
|
|
782
|
+
// Pending sync lines received from the service, as well as local events that trigger a powersync_control
|
|
783
|
+
// invocation (local events include refreshed tokens and completed uploads).
|
|
784
|
+
// This is a single data stream so that we can handle all control calls from a single place.
|
|
785
|
+
let controlInvocations: InjectableIterator<EnqueuedCommand> | null = null;
|
|
786
|
+
|
|
787
|
+
for (const startInstruction of await startCommand()) {
|
|
788
|
+
if ('EstablishSyncStream' in startInstruction) {
|
|
789
|
+
const establish = startInstruction.EstablishSyncStream;
|
|
790
|
+
const syncOptions: SyncStreamOptions = {
|
|
791
|
+
path: '/sync/stream',
|
|
792
|
+
abortSignal: signal,
|
|
793
|
+
data: establish.request
|
|
794
|
+
};
|
|
795
|
+
|
|
796
|
+
controlInvocations = injectable(
|
|
797
|
+
syncImplementation.receiveSyncLines({
|
|
798
|
+
options: syncOptions,
|
|
799
|
+
connection: resolvedOptions
|
|
800
|
+
})
|
|
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
|
+
}
|
|
820
|
+
} else if ('CloseSyncStream' in startInstruction) {
|
|
821
|
+
return defaultResult;
|
|
822
|
+
} else {
|
|
823
|
+
await handleInstruction(startInstruction);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
if (controlInvocations == null) return defaultResult;
|
|
827
|
+
|
|
828
|
+
this.notifyCompletedUploads = () => {
|
|
829
|
+
controlInvocations.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
|
|
830
|
+
};
|
|
831
|
+
this.handleActiveStreamsChange = () => {
|
|
832
|
+
controlInvocations.inject({
|
|
833
|
+
command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
|
|
834
|
+
payload: JSON.stringify(this.activeStreams)
|
|
835
|
+
});
|
|
836
|
+
};
|
|
837
|
+
notifyTokenRefreshed = () => {
|
|
838
|
+
controlInvocations.inject({
|
|
839
|
+
command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED
|
|
840
|
+
});
|
|
841
|
+
};
|
|
842
|
+
|
|
843
|
+
let hadSyncLine = false;
|
|
844
|
+
loop: while (true) {
|
|
845
|
+
const { done, value } = await controlInvocations.next();
|
|
846
|
+
if (done) break;
|
|
847
|
+
|
|
848
|
+
if (!hadSyncLine) {
|
|
849
|
+
// Trigger a local CRUD upload when the first sync line has been received, this allows uploading local changes
|
|
850
|
+
// that have been made while offline or disconnected.
|
|
851
|
+
if (
|
|
852
|
+
value.command == PowerSyncControlCommand.PROCESS_TEXT_LINE ||
|
|
853
|
+
value.command == PowerSyncControlCommand.PROCESS_BSON_LINE
|
|
854
|
+
) {
|
|
855
|
+
hadSyncLine = true;
|
|
856
|
+
this.triggerCrudUpload?.();
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
const instructions = await invokePowerSyncControl(value.command, value.payload);
|
|
861
|
+
for (const instruction of instructions) {
|
|
862
|
+
if ('EstablishSyncStream' in instruction) {
|
|
863
|
+
throw new Error('Received EstablishSyncStream while already connected.');
|
|
864
|
+
} else if ('CloseSyncStream' in instruction) {
|
|
865
|
+
hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
|
|
866
|
+
break loop;
|
|
867
|
+
} else {
|
|
868
|
+
await handleInstruction(instruction);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
} finally {
|
|
873
|
+
this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
|
|
874
|
+
notifyTokenRefreshed = undefined;
|
|
875
|
+
await stop();
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
return { immediateRestart: hideDisconnectOnRestart };
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
protected updateSyncStatus(core: CoreSyncStatus | null, jsState?: JavaScriptSyncState) {
|
|
882
|
+
const updated = new SyncStatusSnapshot(core, {
|
|
883
|
+
...this.syncStatus.jsState,
|
|
884
|
+
...jsState
|
|
885
|
+
});
|
|
886
|
+
|
|
887
|
+
if (!this.syncStatus.isEqual(updated)) {
|
|
888
|
+
this.syncStatus = updated;
|
|
889
|
+
// Only trigger this is there was a change
|
|
890
|
+
this.iterateListeners((cb) => cb.statusChanged?.(updated));
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
protected updateJsSyncState(state: JavaScriptSyncState) {
|
|
895
|
+
this.updateSyncStatus(this.syncStatus.core, state);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
private async delayRetry(signal: AbortSignal, delay: number, resumeOnCheckpointRequest = false): Promise<void> {
|
|
899
|
+
return new Promise((resolve) => {
|
|
900
|
+
if (signal.aborted) {
|
|
901
|
+
// If the signal is already aborted, resolve immediately
|
|
902
|
+
resolve();
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
let nested: AbortController | null = null;
|
|
907
|
+
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
908
|
+
|
|
909
|
+
const endDelay = () => {
|
|
910
|
+
resolve();
|
|
911
|
+
if (timeoutId) {
|
|
912
|
+
clearTimeout(timeoutId);
|
|
913
|
+
timeoutId = undefined;
|
|
914
|
+
}
|
|
915
|
+
if (nested) {
|
|
916
|
+
nested.abort();
|
|
917
|
+
nested = null;
|
|
918
|
+
}
|
|
919
|
+
signal.removeEventListener('abort', endDelay);
|
|
920
|
+
};
|
|
921
|
+
|
|
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
|
+
}
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
updateSubscriptions(subscriptions: SubscribedStream[]): void {
|
|
936
|
+
this.activeStreams = subscriptions;
|
|
937
|
+
this.handleActiveStreamsChange?.();
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
interface EnqueuedCommand {
|
|
942
|
+
command: PowerSyncControlCommand;
|
|
943
|
+
payload?: Uint8Array | string;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
interface RustIterationResult {
|
|
947
|
+
immediateRestart: boolean;
|
|
948
|
+
}
|