@powersync/web 2.6.0 → 2.7.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/index.react_native_web.js +667 -140
- package/dist/index.react_native_web.js.map +1 -1
- package/dist/worker/{OPFSCoopSyncVFS-CDNBPKfy.js → OPFSCoopSyncVFS-Dujy2ZwX.js} +2 -2
- package/dist/worker/{OPFSCoopSyncVFS-CDNBPKfy.js.map → OPFSCoopSyncVFS-Dujy2ZwX.js.map} +1 -1
- package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js +2 -0
- package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js.map +1 -0
- package/dist/worker/worker.js +1 -1
- package/dist/worker/worker.js.map +1 -1
- package/lib/db/NavigatorTriggerClaimManager.js +1 -1
- package/lib/db/NavigatorTriggerClaimManager.js.map +1 -1
- package/lib/db/PowerSyncDatabase.js +1 -1
- package/lib/db/PowerSyncDatabase.js.map +1 -1
- package/lib/db/adapters/options.d.ts +25 -2
- package/lib/db/adapters/options.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -7
- package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js +130 -25
- package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/DatabaseClient.d.ts +13 -0
- package/lib/db/adapters/wa-sqlite/DatabaseClient.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +2 -1
- package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js +12 -6
- package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.d.ts +30 -0
- package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.js +210 -0
- package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.js.map +1 -0
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +1 -0
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +178 -75
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/vfs.d.ts +30 -4
- package/lib/db/adapters/wa-sqlite/vfs.js +53 -2
- package/lib/db/adapters/wa-sqlite/vfs.js.map +1 -1
- package/lib/db/sync/SharedWebStreamingSyncImplementation.js +1 -1
- package/lib/db/sync/SharedWebStreamingSyncImplementation.js.map +1 -1
- package/lib/db/sync/WebStreamingSyncImplementation.js +1 -1
- package/lib/db/sync/WebStreamingSyncImplementation.js.map +1 -1
- package/lib/shared/{tab_close_signal.d.ts → locks.d.ts} +13 -0
- package/lib/shared/locks.js +56 -0
- package/lib/shared/locks.js.map +1 -0
- package/lib/worker/db/MultiDatabaseServer.js +37 -12
- package/lib/worker/db/MultiDatabaseServer.js.map +1 -1
- package/lib/worker/sync/SharedSyncImplementation.js +1 -1
- package/lib/worker/sync/SharedSyncImplementation.js.map +1 -1
- package/lib/worker/sync/WorkerClient.js +1 -1
- package/lib/worker/sync/WorkerClient.js.map +1 -1
- package/lib/worker/worker.js +67 -1
- package/lib/worker/worker.js.map +1 -1
- package/package.json +3 -3
- package/src/db/NavigatorTriggerClaimManager.ts +1 -1
- package/src/db/PowerSyncDatabase.ts +1 -1
- package/src/db/adapters/options.ts +27 -2
- package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +148 -34
- package/src/db/adapters/wa-sqlite/DatabaseClient.ts +16 -0
- package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +16 -7
- package/src/db/adapters/wa-sqlite/SimpleOpfsFileSystem.ts +249 -0
- package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +236 -97
- package/src/db/adapters/wa-sqlite/vfs.ts +61 -7
- package/src/db/sync/SharedWebStreamingSyncImplementation.ts +1 -1
- package/src/db/sync/WebStreamingSyncImplementation.ts +1 -1
- package/src/shared/locks.ts +66 -0
- package/src/worker/db/MultiDatabaseServer.ts +46 -12
- package/src/worker/sync/SharedSyncImplementation.ts +1 -1
- package/src/worker/sync/WorkerClient.ts +1 -1
- package/src/worker/worker.ts +82 -3
- package/lib/shared/navigator.d.ts +0 -1
- package/lib/shared/navigator.js +0 -7
- package/lib/shared/navigator.js.map +0 -1
- package/lib/shared/tab_close_signal.js +0 -27
- package/lib/shared/tab_close_signal.js.map +0 -1
- package/src/shared/navigator.ts +0 -9
- package/src/shared/tab_close_signal.ts +0 -28
|
@@ -4,12 +4,12 @@ import { ResolvedWebSQLOpenOptions, WebSQLOpenOptions } from '../options.js';
|
|
|
4
4
|
import { SSRDBAdapter } from '../SSRDBAdapter.js';
|
|
5
5
|
import { vfsRequiresDedicatedWorkers, WASQLiteVFS } from './vfs.js';
|
|
6
6
|
import { MultiDatabaseServer } from '../../../worker/db/MultiDatabaseServer.js';
|
|
7
|
-
import { DatabaseClient, OpenWorkerConnection } from './DatabaseClient.js';
|
|
8
|
-
import { generateTabCloseSignal } from '../../../shared/
|
|
7
|
+
import { DatabaseClient, OpenWorkerConnection, SharedFeatureDetectionResult } from './DatabaseClient.js';
|
|
8
|
+
import { generateTabCloseSignal } from '../../../shared/locks.js';
|
|
9
9
|
import { AsyncDbAdapter, PoolConnection } from '../AsyncWebAdapter.js';
|
|
10
|
-
import { RawWaSqliteDatabaseOptions } from './RawSqliteConnection.js';
|
|
10
|
+
import { RawWaSqliteDatabaseOptions, SimpleOpfsMode } from './RawSqliteConnection.js';
|
|
11
11
|
import { maxPathNameLength, resolveAndValidateOptions } from '../resolveAndValidateOptions.js';
|
|
12
|
-
import { connectToExistingWorker, connectToWorker, WorkerConnection } from '../../../worker/client.js';
|
|
12
|
+
import { connectToExistingWorker, connectToWorker, isSharedWorker, WorkerConnection } from '../../../worker/client.js';
|
|
13
13
|
|
|
14
14
|
export interface WASQLiteOpenFactoryOptions {
|
|
15
15
|
open: WebSQLOpenOptions;
|
|
@@ -67,118 +67,257 @@ export class WASQLiteOpenFactory implements SQLOpenFactory {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
async openConnection(): Promise<PoolConnection> {
|
|
70
|
-
const {
|
|
71
|
-
enableMultiTabs,
|
|
72
|
-
useWebWorker,
|
|
73
|
-
vfs,
|
|
74
|
-
dbFilename,
|
|
75
|
-
encryptionKey,
|
|
76
|
-
temporaryStorage,
|
|
77
|
-
cacheSizeKb,
|
|
78
|
-
preparedStatementsCache,
|
|
79
|
-
additionalInitializationFunctions,
|
|
80
|
-
storageBucket
|
|
81
|
-
} = this.options;
|
|
70
|
+
const { enableMultiTabs, useWebWorker, vfs } = this.options;
|
|
82
71
|
|
|
83
72
|
if (!enableMultiTabs) {
|
|
84
73
|
this.logger.log({ level: LogLevels.warn, message: 'Multiple tabs are not enabled in this browser' });
|
|
85
74
|
}
|
|
86
75
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
let requiresPersistentTriggers = vfsRequiresDedicatedWorkers(vfs);
|
|
90
|
-
|
|
91
|
-
function resolveRawWaSqliteDatabaseOptions(readonly: boolean): RawWaSqliteDatabaseOptions {
|
|
92
|
-
return {
|
|
93
|
-
filename: dbFilename,
|
|
94
|
-
readonly,
|
|
95
|
-
vfs,
|
|
96
|
-
encryptionKey,
|
|
97
|
-
temporaryStorage,
|
|
98
|
-
cacheSizeKb,
|
|
99
|
-
// TODO: Enable prepared statement cache by default?
|
|
100
|
-
preparedStatementsCache: preparedStatementsCache ?? 0,
|
|
101
|
-
additionalInitializationFunctions,
|
|
102
|
-
storageBucket
|
|
103
|
-
};
|
|
76
|
+
if (!useWebWorker) {
|
|
77
|
+
return { writer: await this.#openInCurrentContext(), additionalReaders: [] };
|
|
104
78
|
}
|
|
105
79
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
80
|
+
switch (vfs) {
|
|
81
|
+
case 'auto':
|
|
82
|
+
return { writer: await this.#openSimpleOpfs(true), additionalReaders: [] };
|
|
83
|
+
case WASQLiteVFS.SimpleOpfsVFS:
|
|
84
|
+
return { writer: await this.#openSimpleOpfs(false), additionalReaders: [] };
|
|
85
|
+
case WASQLiteVFS.OPFSWriteAheadVFS: {
|
|
86
|
+
// This VFS supports concurrent reads, so we can open additional workers to host read-only connections for
|
|
87
|
+
// concurrent reads / writes.
|
|
88
|
+
const writer = await this.#openInWorker({ vfs, readonly: false });
|
|
89
|
+
const additionalReadersCount = this.options.additionalReaders ?? 1;
|
|
90
|
+
const additionalReaders = await Promise.all(
|
|
91
|
+
Array.from({ length: additionalReadersCount }, () => this.#openInWorker({ vfs, readonly: true }))
|
|
92
|
+
);
|
|
93
|
+
return { writer, additionalReaders };
|
|
94
|
+
}
|
|
95
|
+
default:
|
|
96
|
+
return { writer: await this.#openInWorker({ vfs, readonly: false }), additionalReaders: [] };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
126
99
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Opens a {@link WASQLiteVFS.SimpleOpfsVFS} database, or picks the best available storage for the `'auto'` VFS
|
|
102
|
+
* option if `fallbackToMemory` is set.
|
|
103
|
+
*
|
|
104
|
+
* This VFS has three different modes (shared workers, readwrite-unsafe, re-open fallback), see the doc comment on it.
|
|
105
|
+
* We start a feature detection to check what the current browser supports. In order of preference, we use:
|
|
106
|
+
*
|
|
107
|
+
* 1. {@link WASQLiteVFS.SimpleOpfsVFS} through a shared worker spawning a nested dedicated worker.
|
|
108
|
+
* 2. {@link WASQLiteVFS.SimpleOpfsVFS} in a dedicated worker.
|
|
109
|
+
* 3. {@link WASQLiteVFS.InMemoryVfs} in a shared worker (only with `fallbackToMemory`).
|
|
110
|
+
* 4. {@link WASQLiteVFS.InMemoryVfs} in a dedicated worker (only with `fallbackToMemory`).
|
|
111
|
+
*/
|
|
112
|
+
async #openSimpleOpfs(fallbackToMemory: boolean): Promise<DatabaseClient> {
|
|
113
|
+
const shared = this.options.enableMultiTabs ? await this.#openSharedWorker() : null;
|
|
114
|
+
let nested: Comlink.Remote<OpenWorkerConnection> | null = null;
|
|
115
|
+
let dedicated: OpenedWorker | null = null;
|
|
116
|
+
// The worker hosting the opened database, which is then owned by the returned client. We close all other workers.
|
|
117
|
+
let used: OpenedWorker | null = null;
|
|
118
|
+
|
|
119
|
+
const connect = async (worker: OpenedWorker, options: ResolvedDatabaseOptions) => {
|
|
120
|
+
const client = await this.#connect(worker, options);
|
|
121
|
+
used = worker;
|
|
122
|
+
return client;
|
|
123
|
+
};
|
|
124
|
+
const connectInMemory = (worker: OpenedWorker) => {
|
|
125
|
+
this.logger.log({ level: LogLevels.warn, message: 'Falling back to in-memory because OPFS is unavailable.' });
|
|
126
|
+
return connect(worker, { vfs: WASQLiteVFS.InMemoryVfs, readonly: false });
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
try {
|
|
130
|
+
if (shared) {
|
|
131
|
+
const features = await this.#detectNestedFeatures(shared);
|
|
132
|
+
if (features?.worker) {
|
|
133
|
+
if (features.worker.opfs) {
|
|
134
|
+
// Shared workers can open dedicated workers. Perfect, we'll have the shared worker spawn a nested worker
|
|
135
|
+
// and connect to that.
|
|
136
|
+
nested = Comlink.wrap<OpenWorkerConnection>(await shared.source.spawnNested());
|
|
137
|
+
return await connect(
|
|
138
|
+
{ source: nested, connection: shared.connection },
|
|
139
|
+
{ vfs: WASQLiteVFS.SimpleOpfsVFS, readonly: false, simpleMode: 'shared' }
|
|
140
|
+
);
|
|
141
|
+
} else if (fallbackToMemory) {
|
|
142
|
+
// The nested worker doesn't have OPFS access, so a dedicated worker started by us won't have that either.
|
|
143
|
+
return await connectInMemory(shared);
|
|
142
144
|
}
|
|
143
|
-
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
144
147
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
148
|
+
// We'll have to use a dedicated worker directly.
|
|
149
|
+
dedicated = this.#openWorker(false);
|
|
150
|
+
const features = await dedicated.source.dedicatedFeatureDetection();
|
|
151
|
+
if (features.opfs || !fallbackToMemory) {
|
|
152
|
+
// See if we can at least use readwrite-unsafe, as that is more efficient than the fallback of closing and
|
|
153
|
+
// re-opening files on contention.
|
|
154
|
+
const simpleMode =
|
|
155
|
+
(this.options.simpleMode as SimpleOpfsMode | undefined) ?? (features.openWithMode ? 'rw-unsafe' : 'fallback');
|
|
150
156
|
|
|
151
|
-
|
|
157
|
+
return await connect(dedicated, { vfs: WASQLiteVFS.SimpleOpfsVFS, readonly: false, simpleMode });
|
|
158
|
+
}
|
|
152
159
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
160
|
+
return await connectInMemory(shared ?? dedicated);
|
|
161
|
+
} finally {
|
|
162
|
+
const usedWorker = used as OpenedWorker | null;
|
|
163
|
+
if (nested && usedWorker?.source !== nested) nested[Comlink.releaseProxy]();
|
|
164
|
+
if (shared && usedWorker?.connection !== shared.connection) closeWorker(shared);
|
|
165
|
+
if (dedicated && usedWorker !== dedicated) closeWorker(dedicated);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
157
168
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
169
|
+
/** Asks a shared worker whether it can spawn nested workers with OPFS access, or returns null if that fails. */
|
|
170
|
+
async #detectNestedFeatures(shared: OpenedWorker): Promise<SharedFeatureDetectionResult | null> {
|
|
171
|
+
try {
|
|
172
|
+
return await shared.source.sharedFeatureDetection();
|
|
173
|
+
} catch (error) {
|
|
174
|
+
this.logger.log({ level: LogLevels.error, error, message: 'Could not detect features of shared worker' });
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Opens a database with a VFS that doesn't need feature detection, using a shared worker when the VFS and options
|
|
181
|
+
* allow that.
|
|
182
|
+
*/
|
|
183
|
+
async #openInWorker(options: ResolvedDatabaseOptions): Promise<DatabaseClient> {
|
|
184
|
+
const useShared = !vfsRequiresDedicatedWorkers(options.vfs) && this.options.enableMultiTabs;
|
|
185
|
+
return this.#connect(this.#openWorker(useShared), options);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Don't use a web worker. Instead, open the MultiDatabaseServer a worker would use locally.
|
|
190
|
+
*
|
|
191
|
+
* Without workers, the only storage the `'auto'` option can pick is an in-memory database.
|
|
192
|
+
*/
|
|
193
|
+
async #openInCurrentContext(): Promise<DatabaseClient> {
|
|
194
|
+
let vfs = this.options.vfs;
|
|
195
|
+
if (vfs == 'auto') {
|
|
196
|
+
this.logger.log({ level: LogLevels.warn, message: 'Using in-memory database because web workers are disabled.' });
|
|
197
|
+
vfs = WASQLiteVFS.InMemoryVfs;
|
|
198
|
+
}
|
|
199
|
+
const localServer = new MultiDatabaseServer(this.logger);
|
|
200
|
+
const connection = await localServer.openConnectionLocally(
|
|
201
|
+
this.logger,
|
|
202
|
+
this.#resolveRawWaSqliteDatabaseOptions({ vfs, readonly: false })
|
|
203
|
+
);
|
|
204
|
+
|
|
205
|
+
return new DatabaseClient(
|
|
206
|
+
{ connection, source: null, remoteCanCloseUnexpectedly: false },
|
|
207
|
+
{ ...this.options, vfs, requiresPersistentTriggers: true }
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async #connect(worker: OpenedWorker, options: ResolvedDatabaseOptions): Promise<DatabaseClient> {
|
|
212
|
+
const { source, connection: workerConnection } = worker;
|
|
213
|
+
const closeSignal = new AbortController();
|
|
214
|
+
const connection = await source.connect({
|
|
215
|
+
database: this.#resolveRawWaSqliteDatabaseOptions(options),
|
|
216
|
+
logLevel: this.options.databaseWorkerLogLevel,
|
|
217
|
+
lockName: await generateTabCloseSignal(closeSignal.signal)
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
return new DatabaseClient(
|
|
221
|
+
{
|
|
222
|
+
connection,
|
|
223
|
+
source,
|
|
224
|
+
// This tab owns the worker, so we're guaranteed to outlive it.
|
|
225
|
+
remoteCanCloseUnexpectedly: false,
|
|
226
|
+
onClose: () => {
|
|
227
|
+
closeSignal.abort();
|
|
228
|
+
workerConnection.close();
|
|
161
229
|
}
|
|
162
|
-
|
|
230
|
+
},
|
|
231
|
+
{
|
|
232
|
+
...this.options,
|
|
233
|
+
vfs: options.vfs,
|
|
234
|
+
requiresPersistentTriggers: vfsRequiresDedicatedWorkers(options.vfs)
|
|
163
235
|
}
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async #openSharedWorker(): Promise<OpenedWorker | null> {
|
|
240
|
+
const shared = this.#openWorker(true);
|
|
241
|
+
if (!isSharedWorker(shared.connection.worker)) {
|
|
242
|
+
// A custom worker factory might not respect the `shared` option, and dedicated workers can't share the
|
|
243
|
+
// database across tabs. Fall back to the modes relying on navigator locks.
|
|
244
|
+
closeWorker(shared);
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return shared;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
#openWorker(shared: boolean): OpenedWorker {
|
|
252
|
+
const optionsDbWorker = this.options.worker;
|
|
253
|
+
let connection: WorkerConnection;
|
|
254
|
+
|
|
255
|
+
if (typeof optionsDbWorker == 'function') {
|
|
256
|
+
const worker = optionsDbWorker({ ...this.options, shared });
|
|
257
|
+
connection = connectToExistingWorker(worker, this.logger, 'database');
|
|
164
258
|
} else {
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
{
|
|
173
|
-
...this.options,
|
|
174
|
-
requiresPersistentTriggers
|
|
175
|
-
}
|
|
176
|
-
);
|
|
259
|
+
connection = connectToWorker({
|
|
260
|
+
service: 'database',
|
|
261
|
+
databaseIdentifier: this.options.dbFilename,
|
|
262
|
+
shared: shared,
|
|
263
|
+
customWorker: optionsDbWorker,
|
|
264
|
+
loggerForErrors: this.logger
|
|
265
|
+
});
|
|
177
266
|
}
|
|
178
267
|
|
|
268
|
+
return { connection, source: Comlink.wrap<OpenWorkerConnection>(connection.endpoint) };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
#resolveRawWaSqliteDatabaseOptions({
|
|
272
|
+
vfs,
|
|
273
|
+
readonly,
|
|
274
|
+
simpleMode
|
|
275
|
+
}: ResolvedDatabaseOptions): RawWaSqliteDatabaseOptions {
|
|
276
|
+
const {
|
|
277
|
+
dbFilename,
|
|
278
|
+
encryptionKey,
|
|
279
|
+
temporaryStorage,
|
|
280
|
+
cacheSizeKb,
|
|
281
|
+
preparedStatementsCache,
|
|
282
|
+
additionalInitializationFunctions,
|
|
283
|
+
storageBucket
|
|
284
|
+
} = this.options;
|
|
285
|
+
|
|
179
286
|
return {
|
|
180
|
-
|
|
181
|
-
|
|
287
|
+
filename: dbFilename,
|
|
288
|
+
readonly,
|
|
289
|
+
vfs,
|
|
290
|
+
encryptionKey,
|
|
291
|
+
temporaryStorage,
|
|
292
|
+
cacheSizeKb,
|
|
293
|
+
// TODO: Enable prepared statement cache by default?
|
|
294
|
+
preparedStatementsCache: preparedStatementsCache ?? 0,
|
|
295
|
+
additionalInitializationFunctions,
|
|
296
|
+
storageBucket,
|
|
297
|
+
simpleMode
|
|
182
298
|
};
|
|
183
299
|
}
|
|
184
300
|
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Options for a database connection after the `'auto'` VFS option and the {@link SimpleOpfsMode} have been
|
|
304
|
+
* resolved.
|
|
305
|
+
*/
|
|
306
|
+
interface ResolvedDatabaseOptions {
|
|
307
|
+
vfs: WASQLiteVFS;
|
|
308
|
+
readonly: boolean;
|
|
309
|
+
simpleMode?: SimpleOpfsMode;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* A worker we're connected to, but haven't necessarily opened a database in yet.
|
|
314
|
+
*/
|
|
315
|
+
interface OpenedWorker {
|
|
316
|
+
connection: WorkerConnection;
|
|
317
|
+
source: Comlink.Remote<OpenWorkerConnection>;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function closeWorker(worker: OpenedWorker) {
|
|
321
|
+
worker.source[Comlink.releaseProxy]();
|
|
322
|
+
worker.connection.close();
|
|
323
|
+
}
|
|
@@ -26,20 +26,59 @@ export enum WASQLiteVFS {
|
|
|
26
26
|
* This VFS primarily intended for development, but it also useful for online-first deployments not syncing large
|
|
27
27
|
* amounts of data, as it is quicker to start up.
|
|
28
28
|
*/
|
|
29
|
-
InMemoryVfs = 'InMemoryVFS'
|
|
29
|
+
InMemoryVfs = 'InMemoryVFS',
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A simple OPFS-based virtual file system.
|
|
33
|
+
*
|
|
34
|
+
* This VFS uses a very simple internal design: Instead of opening files on demand (or with a prior pool), it uses the
|
|
35
|
+
* fact that that a SQLite database only consists of two files: The main database and a journal for recovery. These
|
|
36
|
+
* two file handles are pre-opened before the database is used, allowing all IO to be synchronous and to go directly
|
|
37
|
+
* to those files.
|
|
38
|
+
*
|
|
39
|
+
* It is worth noting that this design has fundamental drawbacks: It doesn't support `ATTACH`ing additional databases,
|
|
40
|
+
* and temporary data (e.g. for materialized CTEs) is always stored in memory. This is not relevant for most setups
|
|
41
|
+
* though, and not supporting this is what enables the simple design.
|
|
42
|
+
*
|
|
43
|
+
* Synchronous file handles in OPFS are only available in dedicated workers, and two tabs can't open the same file
|
|
44
|
+
* at the same time. To enable multi-tab support, this VFS comes in three possible configurations, the PowerSync SDK
|
|
45
|
+
* selects the best one based on browser features:
|
|
46
|
+
*
|
|
47
|
+
* 1. __Shared workers__: While we need dedicated workers to access files synchronously, the web standard allows
|
|
48
|
+
* shared workers to spawn their own dedicated workers. This is not supported by all browsers, but highly efficient
|
|
49
|
+
* option when available as we don't need to rely on navigator locks.
|
|
50
|
+
* 2. `readwrite-unsafe`: On Chromium browsers, this flag allows multiple tabs to access the same files (the PowerSync
|
|
51
|
+
* SDK additionally uses navigator locks to avoid corruption from concurrent writes).
|
|
52
|
+
* 3. Close and open fallback: On other browsers, file handles are kept open until another tab signals that it needs
|
|
53
|
+
* access to them. At that point, queued local transactions are awaited before closing the file handles. At the
|
|
54
|
+
* next database query, the same signal is sent to the other tab before re-opening files locally.
|
|
55
|
+
*/
|
|
56
|
+
SimpleOpfsVFS = 'SimpleOpfsVFS'
|
|
30
57
|
}
|
|
31
58
|
|
|
32
|
-
export function vfsRequiresDedicatedWorkers(vfs: WASQLiteVFS) {
|
|
59
|
+
export function vfsRequiresDedicatedWorkers(vfs: WASQLiteVFS | 'auto') {
|
|
60
|
+
if (vfs === 'auto') {
|
|
61
|
+
// Falls back to an in-memory database when workers aren't available.
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
|
|
33
65
|
return vfs != WASQLiteVFS.IDBBatchAtomicVFS && vfs != WASQLiteVFS.InMemoryVfs;
|
|
34
66
|
}
|
|
35
67
|
|
|
36
68
|
/**
|
|
37
69
|
* Whether the VFS can keep its files in a Storage Bucket, see {@link WebSpecificOpenOptions.storageBucket}.
|
|
38
70
|
*/
|
|
39
|
-
export function vfsSupportsStorageBuckets(vfs: WASQLiteVFS) {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
71
|
+
export function vfsSupportsStorageBuckets(vfs: WASQLiteVFS | 'auto') {
|
|
72
|
+
switch (vfs) {
|
|
73
|
+
case WASQLiteVFS.OPFSCoopSyncVFS:
|
|
74
|
+
case WASQLiteVFS.OPFSWriteAheadVFS:
|
|
75
|
+
case WASQLiteVFS.AccessHandlePoolVFS:
|
|
76
|
+
case WASQLiteVFS.SimpleOpfsVFS:
|
|
77
|
+
case 'auto': // auto mode can resolve to opfs, in which case it supports storage buckets
|
|
78
|
+
return true;
|
|
79
|
+
default:
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
43
82
|
}
|
|
44
83
|
|
|
45
84
|
/**
|
|
@@ -115,7 +154,8 @@ export async function loadModuleAndVfs({
|
|
|
115
154
|
vfs,
|
|
116
155
|
filename,
|
|
117
156
|
encryptionKey,
|
|
118
|
-
storageBucket
|
|
157
|
+
storageBucket,
|
|
158
|
+
simpleMode
|
|
119
159
|
}: RawWaSqliteDatabaseOptions): Promise<{ module: SQLiteModule; vfs: SQLiteVFS }> {
|
|
120
160
|
let moduleFactory = syncModuleFactory;
|
|
121
161
|
let resolveVfs: (module: any) => Promise<SQLiteVFS>;
|
|
@@ -148,6 +188,20 @@ export async function loadModuleAndVfs({
|
|
|
148
188
|
resolveVfs = (module) => OPFSWriteAheadVFS.create(filename, module, vfsOptionsForStorageBucket(storageBucket));
|
|
149
189
|
break;
|
|
150
190
|
}
|
|
191
|
+
case WASQLiteVFS.SimpleOpfsVFS: {
|
|
192
|
+
const { SimpleOpfsFileSystem } = await import('./SimpleOpfsFileSystem.js');
|
|
193
|
+
|
|
194
|
+
const getRoot = vfsOptionsForStorageBucket(storageBucket).getRoot;
|
|
195
|
+
const resolver = SimpleOpfsFileSystem.directoryResolver(filename, simpleMode === 'rw-unsafe', getRoot);
|
|
196
|
+
|
|
197
|
+
// @ts-expect-error It conforms to SQLiteVFS, but an intermediate type is missing so tsc can't know
|
|
198
|
+
resolveVfs = async (module) => {
|
|
199
|
+
const vfs = new SimpleOpfsFileSystem(filename, module, resolver);
|
|
200
|
+
await vfs.open();
|
|
201
|
+
return vfs;
|
|
202
|
+
};
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
151
205
|
case WASQLiteVFS.InMemoryVfs: {
|
|
152
206
|
const { MemoryVFS } = await import('@journeyapps/wa-sqlite/src/examples/MemoryVFS.js');
|
|
153
207
|
// @ts-expect-error The types for this static method are missing upstream
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
WebStreamingSyncImplementation,
|
|
9
9
|
WebStreamingSyncImplementationOptions
|
|
10
10
|
} from './WebStreamingSyncImplementation.js';
|
|
11
|
-
import { generateTabCloseSignal } from '../../shared/
|
|
11
|
+
import { generateTabCloseSignal } from '../../shared/locks.js';
|
|
12
12
|
import {
|
|
13
13
|
SubscribedStream,
|
|
14
14
|
SyncStatusJson,
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
LockOptions,
|
|
7
7
|
LockType
|
|
8
8
|
} from '@powersync/shared-internals';
|
|
9
|
-
import { getNavigatorLocks } from '../../shared/
|
|
9
|
+
import { getNavigatorLocks } from '../../shared/locks.js';
|
|
10
10
|
|
|
11
11
|
export interface WebStreamingSyncImplementationOptions extends AbstractStreamingSyncImplementationOptions {
|
|
12
12
|
sync?: {
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { UnlockFn } from '@powersync/shared-internals';
|
|
2
|
+
|
|
3
|
+
export const getNavigatorLocks = (): LockManager => {
|
|
4
|
+
if ('locks' in navigator && navigator.locks) {
|
|
5
|
+
return navigator.locks;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
throw new Error(
|
|
9
|
+
'Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.'
|
|
10
|
+
);
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Requests a random lock that will be released once the optional signal is aborted (or, if no signal is given, when the
|
|
15
|
+
* tab is closed).
|
|
16
|
+
*
|
|
17
|
+
* This allows sending the name of the lock to another context (e.g. a shared worker), which will also attempt to
|
|
18
|
+
* acquire it. Since the lock is returned when the tab is closed, this allows the shared worker to free resources
|
|
19
|
+
* assocatiated with this tab.
|
|
20
|
+
*
|
|
21
|
+
* We take hold of this lock as soon-as-possible in order to cater for potentially closed tabs.
|
|
22
|
+
*/
|
|
23
|
+
export async function generateTabCloseSignal(abort?: AbortSignal): Promise<string> {
|
|
24
|
+
const name = `tab-close-signal-${crypto.randomUUID()}`;
|
|
25
|
+
const releaseLock = await requestNavigatorLock(name, { signal: abort });
|
|
26
|
+
|
|
27
|
+
abort?.addEventListener('abort', releaseLock);
|
|
28
|
+
return name;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Requests a navigator lock, resolving once it has been granted.
|
|
33
|
+
*
|
|
34
|
+
* The lock is held until the returned function is called, or until another context steals it (in which case `onStolen`
|
|
35
|
+
* is invoked).
|
|
36
|
+
*/
|
|
37
|
+
export function requestNavigatorLock(
|
|
38
|
+
name: string,
|
|
39
|
+
{ signal, steal, onStolen }: { signal?: AbortSignal; steal?: boolean; onStolen?: () => void } = {}
|
|
40
|
+
): Promise<UnlockFn> {
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
let granted: { released: boolean } | null = null;
|
|
43
|
+
|
|
44
|
+
getNavigatorLocks()
|
|
45
|
+
.request(name, { signal, steal }, (_) => {
|
|
46
|
+
return new Promise<void>((returnLock) => {
|
|
47
|
+
const state = { released: false };
|
|
48
|
+
granted = state;
|
|
49
|
+
resolve(() => {
|
|
50
|
+
state.released = true;
|
|
51
|
+
returnLock();
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
})
|
|
55
|
+
.catch((e) => {
|
|
56
|
+
if (granted == null) {
|
|
57
|
+
// Failed to obtain the lock (e.g. because the request was aborted).
|
|
58
|
+
reject(e);
|
|
59
|
+
} else if (!granted.released) {
|
|
60
|
+
// The callback was invoked, but the lock hasn't been released yet. That can only mean that the lock has been
|
|
61
|
+
// stolen from another context.
|
|
62
|
+
onStolen?.();
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
}
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { LogLevels, PowerSyncLogger } from '@powersync/common';
|
|
2
2
|
import * as Comlink from 'comlink';
|
|
3
3
|
import { ClientConnectionView, DatabaseServer } from '../../db/adapters/wa-sqlite/DatabaseServer.js';
|
|
4
|
-
import { getNavigatorLocks } from '../../shared/
|
|
4
|
+
import { getNavigatorLocks } from '../../shared/locks.js';
|
|
5
5
|
import { RawSqliteConnection, RawWaSqliteDatabaseOptions } from '../../db/adapters/wa-sqlite/RawSqliteConnection.js';
|
|
6
|
-
import {
|
|
7
|
-
|
|
6
|
+
import {
|
|
7
|
+
ConcurrentSqliteConnection,
|
|
8
|
+
ConnectionMutex,
|
|
9
|
+
LazyNavigatorMutex,
|
|
10
|
+
NavigatorMutex
|
|
11
|
+
} from '../../db/adapters/wa-sqlite/ConcurrentConnection.js';
|
|
12
|
+
import { loadModuleAndVfs, WASQLiteVFS } from '../../db/adapters/wa-sqlite/vfs.js';
|
|
8
13
|
import { Mutex } from '@powersync/shared-internals';
|
|
14
|
+
import type { SimpleOpfsFileSystem } from '../../db/adapters/wa-sqlite/SimpleOpfsFileSystem.js';
|
|
9
15
|
|
|
10
16
|
const OPEN_DB_LOCK = 'open-wasqlite-db';
|
|
11
17
|
|
|
@@ -75,28 +81,56 @@ export class MultiDatabaseServer {
|
|
|
75
81
|
|
|
76
82
|
async #databaseOpenAttempt(logger: PowerSyncLogger, options: RawWaSqliteDatabaseOptions): Promise<DatabaseServer> {
|
|
77
83
|
const { filename, readonly, vfs } = options;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
84
|
+
|
|
85
|
+
let locks: ConnectionMutex;
|
|
86
|
+
let needsNavigatorLocks;
|
|
87
|
+
if (
|
|
88
|
+
isSharedWorker ||
|
|
89
|
+
readonly ||
|
|
90
|
+
vfs == WASQLiteVFS.InMemoryVfs ||
|
|
91
|
+
(vfs == WASQLiteVFS.SimpleOpfsVFS && options.simpleMode == 'shared')
|
|
92
|
+
) {
|
|
93
|
+
// We don't need navigator locks for shared workers because all queries run in this shared worker exclusively.
|
|
94
|
+
// For read-only connections, we use a VFS that supports concurrent reads (so a single lock on the connection is
|
|
95
|
+
// fine). In-memory databases either run in a shared worker or aren't shared across tabs at all, so the internal
|
|
96
|
+
// lock is enough.
|
|
97
|
+
locks = new Mutex();
|
|
98
|
+
needsNavigatorLocks = false;
|
|
99
|
+
} else if (vfs == WASQLiteVFS.SimpleOpfsVFS && options.simpleMode != 'rw-unsafe') {
|
|
100
|
+
// Use navigator locks that also release sync access handles when there's contention.
|
|
101
|
+
locks = new LazyNavigatorMutex(`db-lock-${options.filename}`);
|
|
102
|
+
needsNavigatorLocks = true;
|
|
103
|
+
} else {
|
|
104
|
+
// We need navigator locks, but these don't need to coordinate with the file system.
|
|
105
|
+
locks = new NavigatorMutex(`db-lock-${options.filename}`);
|
|
106
|
+
needsNavigatorLocks = true;
|
|
107
|
+
}
|
|
108
|
+
|
|
83
109
|
const activeDatabases = this.#activeDatabases;
|
|
84
110
|
|
|
85
111
|
async function openDatabase() {
|
|
86
112
|
let server: DatabaseServer | undefined = activeDatabases.get(filename);
|
|
87
113
|
if (server == null) {
|
|
88
114
|
const connection = new RawSqliteConnection(options);
|
|
89
|
-
const withSafeConcurrency = new ConcurrentSqliteConnection(connection,
|
|
115
|
+
const withSafeConcurrency = new ConcurrentSqliteConnection(connection, locks);
|
|
90
116
|
|
|
91
117
|
// Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want
|
|
92
118
|
// to do that in an exclusive lock. Note that OPEN_DB_LOCK is not enough for that, as another tab might have
|
|
93
119
|
// already created a connection (and is thus outside of OPEN_DB_LOCK) while currently writing to it.
|
|
94
120
|
const returnLease = await withSafeConcurrency.acquireMutex();
|
|
95
121
|
try {
|
|
96
|
-
await
|
|
122
|
+
const { module, vfs } = await loadModuleAndVfs(options);
|
|
123
|
+
if (options.vfs == WASQLiteVFS.SimpleOpfsVFS) {
|
|
124
|
+
withSafeConcurrency.simpleOpfsVfs = vfs as unknown as SimpleOpfsFileSystem;
|
|
125
|
+
if (locks instanceof LazyNavigatorMutex) {
|
|
126
|
+
locks.linkedVfs = withSafeConcurrency.simpleOpfsVfs;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
await connection.initWithModule(module, vfs);
|
|
97
131
|
} catch (e) {
|
|
98
|
-
|
|
99
|
-
await
|
|
132
|
+
// Close the connection and its file handles while we still have exclusive access.
|
|
133
|
+
await withSafeConcurrency.close(returnLease);
|
|
100
134
|
throw e;
|
|
101
135
|
}
|
|
102
136
|
returnLease();
|
|
@@ -30,7 +30,7 @@ import {
|
|
|
30
30
|
import { AbstractSharedSyncClientProvider } from './AbstractSharedSyncClientProvider.js';
|
|
31
31
|
import { BroadcastLogger } from './BroadcastLogger.js';
|
|
32
32
|
import { DatabaseClient, OpenWorkerConnection } from '../../db/adapters/wa-sqlite/DatabaseClient.js';
|
|
33
|
-
import { generateTabCloseSignal } from '../../shared/
|
|
33
|
+
import { generateTabCloseSignal } from '../../shared/locks.js';
|
|
34
34
|
import { ResolvedWebSQLOpenOptions } from '../../db/adapters/options.js';
|
|
35
35
|
|
|
36
36
|
/**
|