-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathSharedSyncImplementation.ts
401 lines (349 loc) · 12 KB
/
SharedSyncImplementation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import {
type AbstractStreamingSyncImplementation,
type ILogger,
type LockOptions,
type PowerSyncConnectionOptions,
type StreamingSyncImplementation,
type StreamingSyncImplementationListener,
type SyncStatusOptions,
AbortOperation,
BaseObserver,
createLogger,
DBAdapter,
SqliteBucketStorage,
SyncStatus
} from '@powersync/common';
import { Mutex } from 'async-mutex';
import * as Comlink from 'comlink';
import { WebRemote } from '../../db/sync/WebRemote';
import {
WebStreamingSyncImplementation,
WebStreamingSyncImplementationOptions
} from '../../db/sync/WebStreamingSyncImplementation';
import { OpenAsyncDatabaseConnection } from '../../db/adapters/AsyncDatabaseConnection';
import { LockedAsyncDatabaseAdapter } from '../../db/adapters/LockedAsyncDatabaseAdapter';
import { ResolvedWebSQLOpenOptions } from '../../db/adapters/web-sql-flags';
import { WorkerWrappedAsyncDatabaseConnection } from '../../db/adapters/WorkerWrappedAsyncDatabaseConnection';
import { getNavigatorLocks } from '../../shared/navigator';
import { AbstractSharedSyncClientProvider } from './AbstractSharedSyncClientProvider';
import { BroadcastLogger } from './BroadcastLogger';
/**
* Manual message events for shared sync clients
*/
export enum SharedSyncClientEvent {
/**
* This client requests the shared sync manager should
* close it's connection to the client.
*/
CLOSE_CLIENT = 'close-client'
}
export type ManualSharedSyncPayload = {
event: SharedSyncClientEvent;
data: any; // TODO update in future
};
/**
* @internal
*/
export type SharedSyncInitOptions = {
streamOptions: Omit<WebStreamingSyncImplementationOptions, 'adapter' | 'uploadCrud' | 'remote'>;
dbParams: ResolvedWebSQLOpenOptions;
};
/**
* @internal
*/
export interface SharedSyncImplementationListener extends StreamingSyncImplementationListener {
initialized: () => void;
}
/**
* @internal
*/
export type WrappedSyncPort = {
port: MessagePort;
clientProvider: Comlink.Remote<AbstractSharedSyncClientProvider>;
db?: DBAdapter;
};
/**
* @internal
*/
export type RemoteOperationAbortController = {
controller: AbortController;
activePort: WrappedSyncPort;
};
/**
* @internal
* Shared sync implementation which runs inside a shared webworker
*/
export class SharedSyncImplementation
extends BaseObserver<SharedSyncImplementationListener>
implements StreamingSyncImplementation
{
protected ports: WrappedSyncPort[];
protected syncStreamClient: AbstractStreamingSyncImplementation | null;
protected isInitialized: Promise<void>;
protected statusListener?: () => void;
protected fetchCredentialsController?: RemoteOperationAbortController;
protected uploadDataController?: RemoteOperationAbortController;
protected dbAdapter: DBAdapter | null;
protected syncParams: SharedSyncInitOptions | null;
protected logger: ILogger;
protected lastConnectOptions: PowerSyncConnectionOptions | undefined;
syncStatus: SyncStatus;
broadCastLogger: ILogger;
constructor() {
super();
this.ports = [];
this.dbAdapter = null;
this.syncParams = null;
this.syncStreamClient = null;
this.logger = createLogger('shared-sync');
this.lastConnectOptions = undefined;
this.isInitialized = new Promise((resolve) => {
const callback = this.registerListener({
initialized: () => {
resolve();
callback?.();
}
});
});
this.syncStatus = new SyncStatus({});
this.broadCastLogger = new BroadcastLogger(this.ports);
}
async waitForStatus(status: SyncStatusOptions): Promise<void> {
await this.waitForReady();
return this.syncStreamClient!.waitForStatus(status);
}
async waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void> {
await this.waitForReady();
return this.syncStreamClient!.waitUntilStatusMatches(predicate);
}
get lastSyncedAt(): Date | undefined {
return this.syncStreamClient?.lastSyncedAt;
}
get isConnected(): boolean {
return this.syncStreamClient?.isConnected ?? false;
}
async waitForReady() {
return this.isInitialized;
}
/**
* Configures the DBAdapter connection and a streaming sync client.
*/
async setParams(params: SharedSyncInitOptions) {
if (this.syncParams) {
// Cannot modify already existing sync implementation
return;
}
this.syncParams = params;
if (params.streamOptions?.flags?.broadcastLogs) {
this.logger = this.broadCastLogger;
}
self.onerror = (event) => {
// Share any uncaught events on the broadcast logger
this.logger.error('Uncaught exception in PowerSync shared sync worker', event);
};
await this.openInternalDB();
this.iterateListeners((l) => l.initialized?.());
}
async dispose() {
await this.waitForReady();
this.statusListener?.();
return this.syncStreamClient?.dispose();
}
/**
* Connects to the PowerSync backend instance.
* Multiple tabs can safely call this in their initialization.
* The connection will simply be reconnected whenever a new tab
* connects.
*/
async connect(options?: PowerSyncConnectionOptions) {
await this.waitForReady();
// This effectively queues connect and disconnect calls. Ensuring multiple tabs' requests are synchronized
return getNavigatorLocks().request('shared-sync-connect', async () => {
if (!this.dbAdapter) {
await this.openInternalDB();
}
this.syncStreamClient = this.generateStreamingImplementation();
this.lastConnectOptions = options;
this.syncStreamClient.registerListener({
statusChanged: (status) => {
this.updateAllStatuses(status.toJSON());
}
});
await this.syncStreamClient.connect(options);
});
}
async disconnect() {
await this.waitForReady();
// This effectively queues connect and disconnect calls. Ensuring multiple tabs' requests are synchronized
return getNavigatorLocks().request('shared-sync-connect', async () => {
await this.syncStreamClient?.disconnect();
await this.syncStreamClient?.dispose();
this.syncStreamClient = null;
});
}
/**
* Adds a new client tab's message port to the list of connected ports
*/
addPort(port: MessagePort) {
const portProvider = {
port,
clientProvider: Comlink.wrap<AbstractSharedSyncClientProvider>(port)
};
this.ports.push(portProvider);
// Give the newly connected client the latest status
const status = this.syncStreamClient?.syncStatus;
if (status) {
portProvider.clientProvider.statusChanged(status.toJSON());
}
}
/**
* Removes a message port client from this manager's managed
* clients.
*/
async removePort(port: MessagePort) {
const index = this.ports.findIndex((p) => p.port == port);
if (index < 0) {
console.warn(`Could not remove port ${port} since it is not present in active ports.`);
return;
}
const trackedPort = this.ports[index];
// Remove from the list of active ports
this.ports.splice(index, 1);
/**
* The port might currently be in use. Any active functions might
* not resolve. Abort them here.
*/
[this.fetchCredentialsController, this.uploadDataController].forEach((abortController) => {
if (abortController?.activePort.port == port) {
abortController!.controller.abort(new AbortOperation('Closing pending requests after client port is removed'));
}
});
const shouldReconnect = !!this.syncStreamClient;
if (this.dbAdapter && this.dbAdapter == trackedPort.db) {
if (shouldReconnect) {
await this.disconnect();
}
// Clearing the adapter will result in a new one being opened in connect
this.dbAdapter = null;
if (shouldReconnect) {
await this.connect(this.lastConnectOptions);
}
}
if (trackedPort.db) {
trackedPort.db.close();
}
// Release proxy
trackedPort.clientProvider[Comlink.releaseProxy]();
}
triggerCrudUpload() {
this.waitForReady().then(() => this.syncStreamClient?.triggerCrudUpload());
}
async obtainLock<T>(lockOptions: LockOptions<T>): Promise<T> {
await this.waitForReady();
return this.syncStreamClient!.obtainLock(lockOptions);
}
async hasCompletedSync(): Promise<boolean> {
await this.waitForReady();
return this.syncStreamClient!.hasCompletedSync();
}
async getWriteCheckpoint(): Promise<string> {
await this.waitForReady();
return this.syncStreamClient!.getWriteCheckpoint();
}
protected generateStreamingImplementation() {
// This should only be called after initialization has completed
const syncParams = this.syncParams!;
// Create a new StreamingSyncImplementation for each connect call. This is usually done is all SDKs.
return new WebStreamingSyncImplementation({
adapter: new SqliteBucketStorage(this.dbAdapter!, new Mutex(), this.logger),
remote: new WebRemote({
fetchCredentials: async () => {
const lastPort = this.ports[this.ports.length - 1];
return new Promise(async (resolve, reject) => {
const abortController = new AbortController();
this.fetchCredentialsController = {
controller: abortController,
activePort: lastPort
};
abortController.signal.onabort = reject;
try {
console.log('calling the last port client provider for credentials');
resolve(await lastPort.clientProvider.fetchCredentials());
} catch (ex) {
reject(ex);
} finally {
this.fetchCredentialsController = undefined;
}
});
}
}),
uploadCrud: async () => {
const lastPort = this.ports[this.ports.length - 1];
return new Promise(async (resolve, reject) => {
const abortController = new AbortController();
this.uploadDataController = {
controller: abortController,
activePort: lastPort
};
// Resolving will make it retry
abortController.signal.onabort = () => resolve();
try {
resolve(await lastPort.clientProvider.uploadCrud());
} catch (ex) {
reject(ex);
} finally {
this.uploadDataController = undefined;
}
});
},
...syncParams.streamOptions,
// Logger cannot be transferred just yet
logger: this.logger
});
}
protected async openInternalDB() {
const lastClient = this.ports[this.ports.length - 1];
if (!lastClient) {
// Should not really happen in practice
throw new Error(`Could not open DB connection since no client is connected.`);
}
const workerPort = await lastClient.clientProvider.getDBWorkerPort();
const remote = Comlink.wrap<OpenAsyncDatabaseConnection>(workerPort);
const identifier = this.syncParams!.dbParams.dbFilename;
const db = await remote(this.syncParams!.dbParams);
const locked = new LockedAsyncDatabaseAdapter({
name: identifier,
openConnection: async () => {
return new WorkerWrappedAsyncDatabaseConnection({
remote,
baseConnection: db,
identifier
});
},
logger: this.logger
});
await locked.init();
this.dbAdapter = lastClient.db = locked;
}
/**
* A method to update the all shared statuses for each
* client.
*/
private updateAllStatuses(status: SyncStatusOptions) {
this.syncStatus = new SyncStatus(status);
this.ports.forEach((p) => p.clientProvider.statusChanged(status));
}
/**
* A function only used for unit tests which updates the internal
* sync stream client and all tab client's sync status
*/
private _testUpdateAllStatuses(status: SyncStatusOptions) {
if (!this.syncStreamClient) {
// This is just for testing purposes
this.syncStreamClient = this.generateStreamingImplementation();
}
// Only assigning, don't call listeners for this test
this.syncStreamClient!.syncStatus = new SyncStatus(status);
this.updateAllStatuses(status);
}
}