-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathPowerSyncDatabase.ts
More file actions
225 lines (200 loc) · 7.38 KB
/
PowerSyncDatabase.ts
File metadata and controls
225 lines (200 loc) · 7.38 KB
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
import {
type BucketStorageAdapter,
type PowerSyncBackendConnector,
type PowerSyncCloseOptions,
type RequiredAdditionalConnectionOptions,
AbstractPowerSyncDatabase,
DBAdapter,
DEFAULT_POWERSYNC_CLOSE_OPTIONS,
isDBAdapter,
isSQLOpenFactory,
PowerSyncDatabaseOptions,
PowerSyncDatabaseOptionsWithDBAdapter,
PowerSyncDatabaseOptionsWithOpenFactory,
PowerSyncDatabaseOptionsWithSettings,
SqliteBucketStorage,
StreamingSyncImplementation
} from '@powersync/common';
import { Mutex } from 'async-mutex';
import { getNavigatorLocks } from '../shared/navigator';
import { WASQLiteOpenFactory } from './adapters/wa-sqlite/WASQLiteOpenFactory';
import {
DEFAULT_WEB_SQL_FLAGS,
ResolvedWebSQLOpenOptions,
resolveWebSQLFlags,
WebSQLFlags
} from './adapters/web-sql-flags';
import { WebDBAdapter } from './adapters/WebDBAdapter';
import { SharedWebStreamingSyncImplementation } from './sync/SharedWebStreamingSyncImplementation';
import { SSRStreamingSyncImplementation } from './sync/SSRWebStreamingSyncImplementation';
import { WebRemote } from './sync/WebRemote';
import {
WebStreamingSyncImplementation,
WebStreamingSyncImplementationOptions
} from './sync/WebStreamingSyncImplementation';
export interface WebPowerSyncFlags extends WebSQLFlags {
/**
* Externally unload open PowerSync database instances when the window closes.
* Setting this to `true` requires calling `close` on all open PowerSyncDatabase
* instances before the window unloads
*/
externallyUnload?: boolean;
}
type WithWebFlags<Base> = Base & { flags?: WebPowerSyncFlags };
export interface WebSyncOptions {
/**
* Allows you to override the default sync worker.
*
* You can either provide a path to the worker script
* or a factory method that returns a worker.
*/
worker?: string | URL | ((options: ResolvedWebSQLOpenOptions) => SharedWorker);
}
type WithWebSyncOptions<Base> = Base & {
sync?: WebSyncOptions;
};
export interface WebEncryptionOptions {
/**
* Encryption key for the database.
* If set, the database will be encrypted using Multiple Ciphers.
*/
encryptionKey?: string;
}
type WithWebEncryptionOptions<Base> = Base & WebEncryptionOptions;
export type WebPowerSyncDatabaseOptionsWithAdapter = WithWebSyncOptions<
WithWebFlags<PowerSyncDatabaseOptionsWithDBAdapter>
>;
export type WebPowerSyncDatabaseOptionsWithOpenFactory = WithWebSyncOptions<
WithWebFlags<PowerSyncDatabaseOptionsWithOpenFactory>
>;
export type WebPowerSyncDatabaseOptionsWithSettings = WithWebSyncOptions<
WithWebFlags<WithWebEncryptionOptions<PowerSyncDatabaseOptionsWithSettings>>
>;
export type WebPowerSyncDatabaseOptions = WithWebSyncOptions<WithWebFlags<PowerSyncDatabaseOptions>>;
export const DEFAULT_POWERSYNC_FLAGS: Required<WebPowerSyncFlags> = {
...DEFAULT_WEB_SQL_FLAGS,
externallyUnload: false
};
export const resolveWebPowerSyncFlags = (flags?: WebPowerSyncFlags): Required<WebPowerSyncFlags> => {
return {
...DEFAULT_POWERSYNC_FLAGS,
...flags,
...resolveWebSQLFlags(flags)
};
};
/**
* Asserts that the database options are valid for custom database constructors.
*/
function assertValidDatabaseOptions(options: WebPowerSyncDatabaseOptions): void {
if ('database' in options && 'encryptionKey' in options) {
const { database } = options;
if (isSQLOpenFactory(database) || isDBAdapter(database)) {
throw new Error(
`Invalid configuration: 'encryptionKey' should only be included inside the database object when using a custom ${isSQLOpenFactory(database) ? 'WASQLiteOpenFactory' : 'WASQLiteDBAdapter'} constructor.`
);
}
}
}
/**
* A PowerSync database which provides SQLite functionality
* which is automatically synced.
*
* @example
* ```typescript
* export const db = new PowerSyncDatabase({
* schema: AppSchema,
* database: {
* dbFilename: 'example.db'
* }
* });
* ```
*/
export class PowerSyncDatabase extends AbstractPowerSyncDatabase {
static SHARED_MUTEX = new Mutex();
protected unloadListener?: () => Promise<void>;
protected resolvedFlags: WebPowerSyncFlags;
constructor(options: WebPowerSyncDatabaseOptionsWithAdapter);
constructor(options: WebPowerSyncDatabaseOptionsWithOpenFactory);
constructor(options: WebPowerSyncDatabaseOptionsWithSettings);
constructor(options: WebPowerSyncDatabaseOptions);
constructor(protected options: WebPowerSyncDatabaseOptions) {
super(options);
assertValidDatabaseOptions(options);
this.resolvedFlags = resolveWebPowerSyncFlags(options.flags);
if (this.resolvedFlags.enableMultiTabs && !this.resolvedFlags.externallyUnload) {
this.unloadListener = () => this.close({ disconnect: false });
window.addEventListener('unload', this.unloadListener);
}
}
async _initialize(): Promise<void> {}
protected openDBAdapter(options: WebPowerSyncDatabaseOptionsWithSettings): DBAdapter {
const defaultFactory = new WASQLiteOpenFactory({
...options.database,
flags: resolveWebPowerSyncFlags(options.flags),
encryptionKey: options.encryptionKey
});
return defaultFactory.openDB();
}
/**
* Closes the database connection.
* By default the sync stream client is only disconnected if
* multiple tabs are not enabled.
*/
close(options: PowerSyncCloseOptions = DEFAULT_POWERSYNC_CLOSE_OPTIONS): Promise<void> {
if (this.unloadListener) {
window.removeEventListener('unload', this.unloadListener);
}
return super.close({
// Don't disconnect by default if multiple tabs are enabled
disconnect: options.disconnect ?? !this.resolvedFlags.enableMultiTabs
});
}
protected generateBucketStorageAdapter(): BucketStorageAdapter {
return new SqliteBucketStorage(this.database);
}
protected async runExclusive<T>(cb: () => Promise<T>) {
if (this.resolvedFlags.ssrMode) {
return PowerSyncDatabase.SHARED_MUTEX.runExclusive(cb);
}
return getNavigatorLocks().request(`lock-${this.database.name}`, cb);
}
protected generateSyncStreamImplementation(
connector: PowerSyncBackendConnector,
options: RequiredAdditionalConnectionOptions
): StreamingSyncImplementation {
const remote = new WebRemote(connector, this.logger);
const syncOptions: WebStreamingSyncImplementationOptions = {
...(this.options as {}),
retryDelayMs: options.retryDelayMs,
crudUploadThrottleMs: options.crudUploadThrottleMs,
flags: this.resolvedFlags,
adapter: this.bucketStorageAdapter,
remote,
uploadCrud: async () => {
await this.waitForReady();
await connector.uploadData(this);
},
identifier: this.database.name,
logger: this.logger
};
switch (true) {
case this.resolvedFlags.ssrMode:
return new SSRStreamingSyncImplementation(syncOptions);
case this.resolvedFlags.enableMultiTabs:
if (!this.resolvedFlags.broadcastLogs) {
const warning = `
Multiple tabs are enabled, but broadcasting of logs is disabled.
Logs for shared sync worker will only be available in the shared worker context
`;
const logger = this.options.logger;
logger ? logger.warn(warning) : console.warn(warning);
}
return new SharedWebStreamingSyncImplementation({
...syncOptions,
db: this.database as WebDBAdapter // This should always be the case
});
default:
return new WebStreamingSyncImplementation(syncOptions);
}
}
}