@powersync/web 2.5.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 +741 -155
- package/dist/index.react_native_web.js.map +1 -1
- package/dist/worker/AccessHandlePoolVFS-Do8lc5Ck.js +2 -0
- package/dist/worker/AccessHandlePoolVFS-Do8lc5Ck.js.map +1 -0
- package/dist/worker/FacadeVFS-d1ZDvud7.js.map +1 -1
- package/dist/worker/IDBBatchAtomicVFS-CDb4d4wN.js +2 -0
- package/dist/worker/IDBBatchAtomicVFS-CDb4d4wN.js.map +1 -0
- package/dist/worker/MemoryVFS-DVJL5F8j.js.map +1 -1
- package/dist/worker/OPFSCoopSyncVFS-Dujy2ZwX.js +2 -0
- package/dist/worker/OPFSCoopSyncVFS-Dujy2ZwX.js.map +1 -0
- package/dist/worker/OPFSWriteAheadVFS-V9yBrLWl.js +2 -0
- package/dist/worker/OPFSWriteAheadVFS-V9yBrLWl.js.map +1 -0
- package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js +2 -0
- package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js.map +1 -0
- package/dist/worker/assets/mc-wa-sqlite-Cq3AePIW.wasm +0 -0
- package/dist/worker/assets/{mc-wa-sqlite-async-DdlQmAUV.wasm → mc-wa-sqlite-async-aRcIGeKj.wasm} +0 -0
- package/dist/worker/assets/wa-sqlite-CePoIZt_.wasm +0 -0
- package/dist/worker/assets/wa-sqlite-async-B3FiUnt1.wasm +0 -0
- package/dist/worker/{mc-wa-sqlite-PubB6u8c.js → mc-wa-sqlite-DRR2R_uj.js} +2 -2
- package/dist/worker/mc-wa-sqlite-DRR2R_uj.js.map +1 -0
- package/dist/worker/{mc-wa-sqlite-async-DJG_ANKO.js → mc-wa-sqlite-async-C40l6kIz.js} +2 -2
- package/dist/worker/mc-wa-sqlite-async-C40l6kIz.js.map +1 -0
- package/dist/worker/{wa-sqlite-D1_4mGs8.js → wa-sqlite-_a9CU4MM.js} +2 -2
- package/dist/worker/wa-sqlite-_a9CU4MM.js.map +1 -0
- package/dist/worker/wa-sqlite-async-Da0d0GJg.js +2 -0
- package/dist/worker/wa-sqlite-async-Da0d0GJg.js.map +1 -0
- package/dist/worker/{websockets-Q8W_lerF.js → websockets-Dx9ExO-W.js} +2 -2
- package/dist/worker/{websockets-Q8W_lerF.js.map → websockets-Dx9ExO-W.js.map} +1 -1
- 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.d.ts +4 -3
- package/lib/db/PowerSyncDatabase.js +4 -1
- package/lib/db/PowerSyncDatabase.js.map +1 -1
- package/lib/db/adapters/options.d.ts +55 -2
- package/lib/db/adapters/options.js.map +1 -1
- package/lib/db/adapters/resolveAndValidateOptions.js +6 -1
- package/lib/db/adapters/resolveAndValidateOptions.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 +7 -1
- package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js +19 -8
- 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 -73
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/vfs.d.ts +52 -3
- package/lib/db/adapters/wa-sqlite/vfs.js +84 -4
- package/lib/db/adapters/wa-sqlite/vfs.js.map +1 -1
- package/lib/db/sync/SharedWebStreamingSyncImplementation.d.ts +1 -0
- package/lib/db/sync/SharedWebStreamingSyncImplementation.js +29 -12
- package/lib/db/sync/SharedWebStreamingSyncImplementation.js.map +1 -1
- package/lib/db/sync/WebRemote.d.ts +2 -3
- package/lib/db/sync/WebRemote.js +0 -2
- package/lib/db/sync/WebRemote.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.d.ts +9 -2
- package/lib/worker/sync/SharedSyncImplementation.js +67 -38
- package/lib/worker/sync/SharedSyncImplementation.js.map +1 -1
- package/lib/worker/sync/WorkerClient.d.ts +3 -3
- package/lib/worker/sync/WorkerClient.js +4 -4
- 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 +6 -6
- package/src/db/NavigatorTriggerClaimManager.ts +1 -1
- package/src/db/PowerSyncDatabase.ts +7 -4
- package/src/db/adapters/options.ts +59 -2
- package/src/db/adapters/resolveAndValidateOptions.ts +9 -1
- 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 +28 -9
- package/src/db/adapters/wa-sqlite/SimpleOpfsFileSystem.ts +249 -0
- package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +236 -93
- package/src/db/adapters/wa-sqlite/vfs.ts +107 -6
- package/src/db/sync/SharedWebStreamingSyncImplementation.ts +35 -16
- package/src/db/sync/WebRemote.ts +2 -5
- 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 +90 -49
- package/src/worker/sync/WorkerClient.ts +5 -4
- package/src/worker/worker.ts +82 -3
- package/dist/worker/AccessHandlePoolVFS-B9CKqcQ3.js +0 -2
- package/dist/worker/AccessHandlePoolVFS-B9CKqcQ3.js.map +0 -1
- package/dist/worker/IDBBatchAtomicVFS-BfRzbRoV.js +0 -2
- package/dist/worker/IDBBatchAtomicVFS-BfRzbRoV.js.map +0 -1
- package/dist/worker/OPFSCoopSyncVFS-BxXAVpVQ.js +0 -2
- package/dist/worker/OPFSCoopSyncVFS-BxXAVpVQ.js.map +0 -1
- package/dist/worker/OPFSWriteAheadVFS-DuqXaOct.js +0 -2
- package/dist/worker/OPFSWriteAheadVFS-DuqXaOct.js.map +0 -1
- package/dist/worker/assets/mc-wa-sqlite-BHScYYZw.wasm +0 -0
- package/dist/worker/assets/wa-sqlite-CIxTmRHQ.wasm +0 -0
- package/dist/worker/assets/wa-sqlite-async-zc68fxQq.wasm +0 -0
- package/dist/worker/mc-wa-sqlite-PubB6u8c.js.map +0 -1
- package/dist/worker/mc-wa-sqlite-async-DJG_ANKO.js.map +0 -1
- package/dist/worker/wa-sqlite-D1_4mGs8.js.map +0 -1
- package/dist/worker/wa-sqlite-async-BxkwNY-2.js +0 -2
- package/dist/worker/wa-sqlite-async-BxkwNY-2.js.map +0 -1
- 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
|
@@ -3,6 +3,9 @@ export * from '@powersync/common';
|
|
|
3
3
|
import * as Comlink from 'comlink';
|
|
4
4
|
import { Mutex, ConnectionClosedError, Semaphore, LockType, AbstractRemote, AbstractStreamingSyncImplementation, serializeErrorForRelay, BasePowerSyncDatabase, openDatabase } from '@powersync/shared-internals';
|
|
5
5
|
import { Factory, SQLITE_ROW } from '@journeyapps/wa-sqlite';
|
|
6
|
+
import { FacadeVFS } from '@journeyapps/wa-sqlite/src/FacadeVFS.js';
|
|
7
|
+
import { MemoryVFS } from '@journeyapps/wa-sqlite/src/examples/MemoryVFS.js';
|
|
8
|
+
import * as VFS from '@journeyapps/wa-sqlite/src/VFS.js';
|
|
6
9
|
|
|
7
10
|
/**
|
|
8
11
|
* IndexDBFileSystemStorageAdapter implements LocalStorageAdapter using IndexedDB.
|
|
@@ -135,10 +138,78 @@ var WASQLiteVFS;
|
|
|
135
138
|
* amounts of data, as it is quicker to start up.
|
|
136
139
|
*/
|
|
137
140
|
WASQLiteVFS["InMemoryVfs"] = "InMemoryVFS";
|
|
141
|
+
/**
|
|
142
|
+
* A simple OPFS-based virtual file system.
|
|
143
|
+
*
|
|
144
|
+
* This VFS uses a very simple internal design: Instead of opening files on demand (or with a prior pool), it uses the
|
|
145
|
+
* fact that that a SQLite database only consists of two files: The main database and a journal for recovery. These
|
|
146
|
+
* two file handles are pre-opened before the database is used, allowing all IO to be synchronous and to go directly
|
|
147
|
+
* to those files.
|
|
148
|
+
*
|
|
149
|
+
* It is worth noting that this design has fundamental drawbacks: It doesn't support `ATTACH`ing additional databases,
|
|
150
|
+
* and temporary data (e.g. for materialized CTEs) is always stored in memory. This is not relevant for most setups
|
|
151
|
+
* though, and not supporting this is what enables the simple design.
|
|
152
|
+
*
|
|
153
|
+
* Synchronous file handles in OPFS are only available in dedicated workers, and two tabs can't open the same file
|
|
154
|
+
* at the same time. To enable multi-tab support, this VFS comes in three possible configurations, the PowerSync SDK
|
|
155
|
+
* selects the best one based on browser features:
|
|
156
|
+
*
|
|
157
|
+
* 1. __Shared workers__: While we need dedicated workers to access files synchronously, the web standard allows
|
|
158
|
+
* shared workers to spawn their own dedicated workers. This is not supported by all browsers, but highly efficient
|
|
159
|
+
* option when available as we don't need to rely on navigator locks.
|
|
160
|
+
* 2. `readwrite-unsafe`: On Chromium browsers, this flag allows multiple tabs to access the same files (the PowerSync
|
|
161
|
+
* SDK additionally uses navigator locks to avoid corruption from concurrent writes).
|
|
162
|
+
* 3. Close and open fallback: On other browsers, file handles are kept open until another tab signals that it needs
|
|
163
|
+
* access to them. At that point, queued local transactions are awaited before closing the file handles. At the
|
|
164
|
+
* next database query, the same signal is sent to the other tab before re-opening files locally.
|
|
165
|
+
*/
|
|
166
|
+
WASQLiteVFS["SimpleOpfsVFS"] = "SimpleOpfsVFS";
|
|
138
167
|
})(WASQLiteVFS || (WASQLiteVFS = {}));
|
|
139
168
|
function vfsRequiresDedicatedWorkers(vfs) {
|
|
169
|
+
if (vfs === 'auto') {
|
|
170
|
+
// Falls back to an in-memory database when workers aren't available.
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
140
173
|
return vfs != WASQLiteVFS.IDBBatchAtomicVFS && vfs != WASQLiteVFS.InMemoryVfs;
|
|
141
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* Whether the VFS can keep its files in a Storage Bucket, see {@link WebSpecificOpenOptions.storageBucket}.
|
|
177
|
+
*/
|
|
178
|
+
function vfsSupportsStorageBuckets(vfs) {
|
|
179
|
+
switch (vfs) {
|
|
180
|
+
case WASQLiteVFS.OPFSCoopSyncVFS:
|
|
181
|
+
case WASQLiteVFS.OPFSWriteAheadVFS:
|
|
182
|
+
case WASQLiteVFS.AccessHandlePoolVFS:
|
|
183
|
+
case WASQLiteVFS.SimpleOpfsVFS:
|
|
184
|
+
case 'auto': // auto mode can resolve to opfs, in which case it supports storage buckets
|
|
185
|
+
return true;
|
|
186
|
+
default:
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Options for an OPFS-based VFS that keep its files in the named Storage Bucket, see
|
|
192
|
+
* {@link WebSpecificOpenOptions.storageBucket}. Without a bucket name, no options: the VFS uses the root of the
|
|
193
|
+
* origin private file system.
|
|
194
|
+
*
|
|
195
|
+
* @internal
|
|
196
|
+
*/
|
|
197
|
+
function vfsOptionsForStorageBucket(storageBucket, storageBuckets = navigator.storageBuckets) {
|
|
198
|
+
if (storageBucket == null) {
|
|
199
|
+
return {};
|
|
200
|
+
}
|
|
201
|
+
if (storageBuckets == null) {
|
|
202
|
+
throw new Error(`The 'storageBucket' option needs the Storage Buckets API (navigator.storageBuckets), which this browser does not have. Check for it before setting the option.`);
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
// Called by the VFS each time it needs its root directory. Opening the bucket again creates it when the
|
|
206
|
+
// browser deleted it with the rest of the site's data.
|
|
207
|
+
getRoot: () => storageBuckets.open(storageBucket).then((bucket) => bucket.getDirectory()),
|
|
208
|
+
// Keeps the locks and channels of a file apart from those of a file of the same name in another bucket.
|
|
209
|
+
// Bucket names cannot contain ':', so the names of two buckets never overlap.
|
|
210
|
+
prefix: `${storageBucket}:`
|
|
211
|
+
};
|
|
212
|
+
}
|
|
142
213
|
async function asyncModuleFactory(encryptionKey) {
|
|
143
214
|
if (encryptionKey) {
|
|
144
215
|
const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs');
|
|
@@ -162,7 +233,7 @@ async function syncModuleFactory(encryptionKey) {
|
|
|
162
233
|
/**
|
|
163
234
|
* @internal
|
|
164
235
|
*/
|
|
165
|
-
async function loadModuleAndVfs({ vfs, filename, encryptionKey }) {
|
|
236
|
+
async function loadModuleAndVfs({ vfs, filename, encryptionKey, storageBucket, simpleMode }) {
|
|
166
237
|
let moduleFactory = syncModuleFactory;
|
|
167
238
|
let resolveVfs;
|
|
168
239
|
switch (vfs) {
|
|
@@ -178,19 +249,31 @@ async function loadModuleAndVfs({ vfs, filename, encryptionKey }) {
|
|
|
178
249
|
case WASQLiteVFS.AccessHandlePoolVFS: {
|
|
179
250
|
// @ts-expect-error The types for this import are missing upstream
|
|
180
251
|
const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');
|
|
181
|
-
resolveVfs = (module) => AccessHandlePoolVFS.create(filename, module);
|
|
252
|
+
resolveVfs = (module) => AccessHandlePoolVFS.create(filename, module, vfsOptionsForStorageBucket(storageBucket));
|
|
182
253
|
break;
|
|
183
254
|
}
|
|
184
255
|
case WASQLiteVFS.OPFSCoopSyncVFS: {
|
|
185
256
|
// @ts-expect-error The types for this import are missing upstream
|
|
186
257
|
const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');
|
|
187
|
-
resolveVfs = (module) => OPFSCoopSyncVFS.create(filename, module);
|
|
258
|
+
resolveVfs = (module) => OPFSCoopSyncVFS.create(filename, module, vfsOptionsForStorageBucket(storageBucket));
|
|
188
259
|
break;
|
|
189
260
|
}
|
|
190
261
|
case WASQLiteVFS.OPFSWriteAheadVFS: {
|
|
191
262
|
// @ts-expect-error The types for this import are missing upstream
|
|
192
263
|
const { OPFSWriteAheadVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSWriteAheadVFS.js');
|
|
193
|
-
resolveVfs = (module) => OPFSWriteAheadVFS.create(filename, module,
|
|
264
|
+
resolveVfs = (module) => OPFSWriteAheadVFS.create(filename, module, vfsOptionsForStorageBucket(storageBucket));
|
|
265
|
+
break;
|
|
266
|
+
}
|
|
267
|
+
case WASQLiteVFS.SimpleOpfsVFS: {
|
|
268
|
+
const { SimpleOpfsFileSystem } = await Promise.resolve().then(function () { return SimpleOpfsFileSystem$1; });
|
|
269
|
+
const getRoot = vfsOptionsForStorageBucket(storageBucket).getRoot;
|
|
270
|
+
const resolver = SimpleOpfsFileSystem.directoryResolver(filename, simpleMode === 'rw-unsafe', getRoot);
|
|
271
|
+
// @ts-expect-error It conforms to SQLiteVFS, but an intermediate type is missing so tsc can't know
|
|
272
|
+
resolveVfs = async (module) => {
|
|
273
|
+
const vfs = new SimpleOpfsFileSystem(filename, module, resolver);
|
|
274
|
+
await vfs.open();
|
|
275
|
+
return vfs;
|
|
276
|
+
};
|
|
194
277
|
break;
|
|
195
278
|
}
|
|
196
279
|
case WASQLiteVFS.InMemoryVfs: {
|
|
@@ -397,6 +480,55 @@ const getNavigatorLocks = () => {
|
|
|
397
480
|
}
|
|
398
481
|
throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');
|
|
399
482
|
};
|
|
483
|
+
/**
|
|
484
|
+
* Requests a random lock that will be released once the optional signal is aborted (or, if no signal is given, when the
|
|
485
|
+
* tab is closed).
|
|
486
|
+
*
|
|
487
|
+
* This allows sending the name of the lock to another context (e.g. a shared worker), which will also attempt to
|
|
488
|
+
* acquire it. Since the lock is returned when the tab is closed, this allows the shared worker to free resources
|
|
489
|
+
* assocatiated with this tab.
|
|
490
|
+
*
|
|
491
|
+
* We take hold of this lock as soon-as-possible in order to cater for potentially closed tabs.
|
|
492
|
+
*/
|
|
493
|
+
async function generateTabCloseSignal(abort) {
|
|
494
|
+
const name = `tab-close-signal-${crypto.randomUUID()}`;
|
|
495
|
+
const releaseLock = await requestNavigatorLock(name, { signal: abort });
|
|
496
|
+
abort?.addEventListener('abort', releaseLock);
|
|
497
|
+
return name;
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Requests a navigator lock, resolving once it has been granted.
|
|
501
|
+
*
|
|
502
|
+
* The lock is held until the returned function is called, or until another context steals it (in which case `onStolen`
|
|
503
|
+
* is invoked).
|
|
504
|
+
*/
|
|
505
|
+
function requestNavigatorLock(name, { signal, steal, onStolen } = {}) {
|
|
506
|
+
return new Promise((resolve, reject) => {
|
|
507
|
+
let granted = null;
|
|
508
|
+
getNavigatorLocks()
|
|
509
|
+
.request(name, { signal, steal }, (_) => {
|
|
510
|
+
return new Promise((returnLock) => {
|
|
511
|
+
const state = { released: false };
|
|
512
|
+
granted = state;
|
|
513
|
+
resolve(() => {
|
|
514
|
+
state.released = true;
|
|
515
|
+
returnLock();
|
|
516
|
+
});
|
|
517
|
+
});
|
|
518
|
+
})
|
|
519
|
+
.catch((e) => {
|
|
520
|
+
if (granted == null) {
|
|
521
|
+
// Failed to obtain the lock (e.g. because the request was aborted).
|
|
522
|
+
reject(e);
|
|
523
|
+
}
|
|
524
|
+
else if (!granted.released) {
|
|
525
|
+
// The callback was invoked, but the lock hasn't been released yet. That can only mean that the lock has been
|
|
526
|
+
// stolen from another context.
|
|
527
|
+
onStolen?.();
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
});
|
|
531
|
+
}
|
|
400
532
|
|
|
401
533
|
var TemporaryStorageOption;
|
|
402
534
|
(function (TemporaryStorageOption) {
|
|
@@ -439,6 +571,11 @@ function resolveAndValidateOptions(options) {
|
|
|
439
571
|
if (vfsRequiresDedicatedWorkers(resolved.vfs) && !resolved.useWebWorker) {
|
|
440
572
|
throw new Error(`Invalid configuration: The 'useWebWorker' flag must be true when using an OPFS-based VFS (${resolved.vfs}).`);
|
|
441
573
|
}
|
|
574
|
+
if (resolved.storageBucket != null) {
|
|
575
|
+
if (!vfsSupportsStorageBuckets(resolved.vfs)) {
|
|
576
|
+
throw new Error(`Invalid configuration: The 'storageBucket' option needs an OPFS-based VFS, which ${resolved.vfs} is not.`);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
442
579
|
return resolved;
|
|
443
580
|
}
|
|
444
581
|
|
|
@@ -509,19 +646,25 @@ class RawSqliteConnection {
|
|
|
509
646
|
get isOpen() {
|
|
510
647
|
return this.db != 0;
|
|
511
648
|
}
|
|
512
|
-
async init() {
|
|
513
|
-
const { module, vfs } = await loadModuleAndVfs(this.options);
|
|
514
|
-
await this.initWithModule(module, vfs);
|
|
515
|
-
}
|
|
516
649
|
async initWithModule(module, vfs) {
|
|
517
650
|
const api = (this._sqliteAPI = await this.openSQLiteAPI(module, vfs));
|
|
518
|
-
|
|
651
|
+
let fileName = this.options.filename;
|
|
652
|
+
const isSimpleOpfsVfs = this.options.vfs == WASQLiteVFS.SimpleOpfsVFS;
|
|
653
|
+
if (isSimpleOpfsVfs) {
|
|
654
|
+
// The simple VFS doesn't support flexible file names, we use a nested OPFS directory instead.
|
|
655
|
+
fileName = '/database';
|
|
656
|
+
}
|
|
657
|
+
this.db = await api.open_v2(fileName, this.options.readonly ? 1 /* SQLITE_OPEN_READONLY */ : 6 /* SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE */);
|
|
519
658
|
await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
|
|
520
659
|
if (this.options.encryptionKey) {
|
|
521
660
|
const escapedKey = this.options.encryptionKey.replaceAll("'", "''");
|
|
522
661
|
await this.executeRaw(`PRAGMA key = '${escapedKey}';`);
|
|
523
662
|
}
|
|
524
663
|
await this.executeRaw(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
|
|
664
|
+
if (isSimpleOpfsVfs) {
|
|
665
|
+
// This VFS does not support deleting files, so we use the TRUNCATE journaling mode instead.
|
|
666
|
+
await this.executeRaw(`PRAGMA journal_mode = TRUNCATE`);
|
|
667
|
+
}
|
|
525
668
|
await this.executeRaw(`SELECT powersync_update_hooks('install');`);
|
|
526
669
|
}
|
|
527
670
|
async openSQLiteAPI(module, vfs) {
|
|
@@ -530,9 +673,14 @@ class RawSqliteConnection {
|
|
|
530
673
|
const sqlite3 = Factory(module);
|
|
531
674
|
sqlite3.vfs_register(vfs, true);
|
|
532
675
|
/**
|
|
533
|
-
* Register the PowerSync core
|
|
676
|
+
* Register the PowerSync core and additional statically linked extensions
|
|
534
677
|
*/
|
|
535
|
-
|
|
678
|
+
for (const name of ['powersync_init_static', ...(this.options.additionalInitializationFunctions ?? [])]) {
|
|
679
|
+
const result = module.ccall(name, 'int', []);
|
|
680
|
+
if (result !== 0) {
|
|
681
|
+
throw new Error(`SQLite extension initializer ${name} failed with code ${result}`);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
536
684
|
/**
|
|
537
685
|
* Create the multiple cipher vfs if an encryption key is provided
|
|
538
686
|
*/
|
|
@@ -690,42 +838,29 @@ class RawSqliteConnection {
|
|
|
690
838
|
*/
|
|
691
839
|
class ConcurrentSqliteConnection {
|
|
692
840
|
inner;
|
|
841
|
+
mutex;
|
|
693
842
|
/**
|
|
694
|
-
*
|
|
695
|
-
*
|
|
696
|
-
* If null, we'll use navigator locks instead.
|
|
843
|
+
* The {@link SimpleOpfsFileSystem} used by the inner connection, if any. SQLite closing its files doesn't close the
|
|
844
|
+
* sync access handles of that file system, so we do that after closing the connection.
|
|
697
845
|
*/
|
|
698
|
-
|
|
846
|
+
simpleOpfsVfs = null;
|
|
847
|
+
constructor(inner,
|
|
699
848
|
/**
|
|
700
|
-
*
|
|
849
|
+
* A mutex ensuring at most one {@link ConnectionLeaseToken} can exist for this connection at a time.
|
|
701
850
|
*
|
|
702
851
|
* While {@link ConcurrentSqliteConnection} prevents concurrent access to a database _connection_, it's possible we
|
|
703
852
|
* might have multiple connections to the same physical database (e.g. if multiple tabs use dedicated workers).
|
|
704
|
-
* In those setups, we use navigator locks instead of an internal mutex to guard access
|
|
853
|
+
* In those setups, we use navigator locks instead of an internal mutex to guard access.
|
|
705
854
|
*/
|
|
706
|
-
|
|
855
|
+
mutex) {
|
|
707
856
|
this.inner = inner;
|
|
708
|
-
this.
|
|
857
|
+
this.mutex = mutex;
|
|
709
858
|
}
|
|
710
859
|
get options() {
|
|
711
860
|
return this.inner.options;
|
|
712
861
|
}
|
|
713
862
|
acquireMutex(abort) {
|
|
714
|
-
|
|
715
|
-
return this.leaseMutex.acquire(abort);
|
|
716
|
-
}
|
|
717
|
-
return new Promise((resolve, reject) => {
|
|
718
|
-
const options = { signal: abort };
|
|
719
|
-
navigator.locks
|
|
720
|
-
.request(`db-lock-${this.options.filename}`, options, (_) => {
|
|
721
|
-
return new Promise((returnLock) => {
|
|
722
|
-
return resolve(() => {
|
|
723
|
-
returnLock();
|
|
724
|
-
});
|
|
725
|
-
});
|
|
726
|
-
})
|
|
727
|
-
.catch(reject);
|
|
728
|
-
});
|
|
863
|
+
return this.mutex.acquire(abort);
|
|
729
864
|
}
|
|
730
865
|
// Unsafe, unguarded access to the SQLite connection.
|
|
731
866
|
unsafeUseInner() {
|
|
@@ -753,14 +888,22 @@ class ConcurrentSqliteConnection {
|
|
|
753
888
|
}
|
|
754
889
|
return token;
|
|
755
890
|
}
|
|
756
|
-
|
|
757
|
-
|
|
891
|
+
/**
|
|
892
|
+
* @param returnMutex If the caller already holds the mutex (from {@link acquireMutex}), the function returning it.
|
|
893
|
+
*/
|
|
894
|
+
async close(returnMutex) {
|
|
895
|
+
returnMutex ??= await this.acquireMutex();
|
|
758
896
|
try {
|
|
759
897
|
await this.inner.close();
|
|
760
898
|
}
|
|
761
899
|
finally {
|
|
900
|
+
this.simpleOpfsVfs?.close();
|
|
762
901
|
returnMutex();
|
|
763
902
|
}
|
|
903
|
+
if (this.mutex instanceof LazyNavigatorMutex) {
|
|
904
|
+
// We won't use this connection again, so don't wait for another tab to steal the navigator locks.
|
|
905
|
+
await this.mutex.releaseNavigatorLocks();
|
|
906
|
+
}
|
|
764
907
|
}
|
|
765
908
|
}
|
|
766
909
|
/**
|
|
@@ -799,6 +942,115 @@ class ConnectionLeaseToken {
|
|
|
799
942
|
});
|
|
800
943
|
}
|
|
801
944
|
}
|
|
945
|
+
class NavigatorMutex {
|
|
946
|
+
name;
|
|
947
|
+
constructor(name) {
|
|
948
|
+
this.name = name;
|
|
949
|
+
}
|
|
950
|
+
acquire(signal) {
|
|
951
|
+
return requestNavigatorLock(this.name, { signal });
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* A protocol that only gives up navigator locks when another tab requests them.
|
|
956
|
+
*
|
|
957
|
+
* This is mainly relevant for a {@link SimpleOpfsFileSystem} used without shared workers and without
|
|
958
|
+
* `readwrite-unsafe`, as we have to close sync access handles when another tab wants to use the database. The protocol
|
|
959
|
+
* here works like this:
|
|
960
|
+
*
|
|
961
|
+
* 1. Acquire a temporary lock (to avoid contention, not needed for correctness).
|
|
962
|
+
* 2. Obtain an outer lock, stealing it if necessary.
|
|
963
|
+
* 3. Obtain the inner lock.
|
|
964
|
+
* 4. Release the temporary lock.
|
|
965
|
+
* 5. Run the exclusive operation.
|
|
966
|
+
* 6. Wait for another tab to steal the outer lock from us (as its second step).
|
|
967
|
+
* 7. Close the VFS once we're done with it, and return the inner lock.
|
|
968
|
+
*/
|
|
969
|
+
class LazyNavigatorMutex {
|
|
970
|
+
name;
|
|
971
|
+
/**
|
|
972
|
+
* A file system to open after acquiring navigator locks and to close before returning them.
|
|
973
|
+
*/
|
|
974
|
+
linkedVfs = null;
|
|
975
|
+
#outerLockName;
|
|
976
|
+
#temporaryLockName;
|
|
977
|
+
/**
|
|
978
|
+
* A local mutex guarding access within this context. Requesting it first is cheap, and allows the navigator lock
|
|
979
|
+
* logic to assume exclusive access to {@link LazyNavigatorMutex.#heldNavigatorLocks}.
|
|
980
|
+
*/
|
|
981
|
+
#localMutex = new Mutex();
|
|
982
|
+
#heldNavigatorLocks = null;
|
|
983
|
+
constructor(name) {
|
|
984
|
+
this.name = name;
|
|
985
|
+
this.#outerLockName = `${name}-outer`;
|
|
986
|
+
this.#temporaryLockName = `${name}-tmp`;
|
|
987
|
+
}
|
|
988
|
+
async #acquireNavigatorLocks(signal) {
|
|
989
|
+
console.assert(this.#heldNavigatorLocks == null);
|
|
990
|
+
let temporary;
|
|
991
|
+
let outer;
|
|
992
|
+
let inner;
|
|
993
|
+
try {
|
|
994
|
+
// 1. Acquire the temporary lock, so that we don't have multiple tabs stealing the outer lock from each other.
|
|
995
|
+
temporary = await requestNavigatorLock(this.#temporaryLockName, { signal });
|
|
996
|
+
// 2. Request the outer lock, stealing it from another tab if necessary. Abort signals can't be combined with
|
|
997
|
+
// steal, so we don't pass one here.
|
|
998
|
+
outer = await requestNavigatorLock(this.#outerLockName, {
|
|
999
|
+
steal: true,
|
|
1000
|
+
onStolen: () => this.#handleOuterLockStolen()
|
|
1001
|
+
});
|
|
1002
|
+
// 3. Obtain the inner lock. The tab we've stolen the outer lock from will return it once it's done.
|
|
1003
|
+
inner = await requestNavigatorLock(this.name, { signal });
|
|
1004
|
+
await this.linkedVfs?.open();
|
|
1005
|
+
this.#heldNavigatorLocks = { outer, inner };
|
|
1006
|
+
}
|
|
1007
|
+
catch (e) {
|
|
1008
|
+
// Failed to acquire some locks, ensure they're all released.
|
|
1009
|
+
outer?.();
|
|
1010
|
+
inner?.();
|
|
1011
|
+
throw e;
|
|
1012
|
+
}
|
|
1013
|
+
finally {
|
|
1014
|
+
// 4. Release the temporary lock.
|
|
1015
|
+
temporary?.();
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
#handleOuterLockStolen() {
|
|
1019
|
+
// Steps 6 and 7.
|
|
1020
|
+
this.releaseNavigatorLocks();
|
|
1021
|
+
}
|
|
1022
|
+
async acquire(signal) {
|
|
1023
|
+
const returnLocalMutex = await this.#localMutex.acquire(signal);
|
|
1024
|
+
if (this.#heldNavigatorLocks != null) {
|
|
1025
|
+
// We already hold the navigator locks, so we can use the database directly.
|
|
1026
|
+
return returnLocalMutex;
|
|
1027
|
+
}
|
|
1028
|
+
try {
|
|
1029
|
+
await this.#acquireNavigatorLocks(signal);
|
|
1030
|
+
}
|
|
1031
|
+
catch (e) {
|
|
1032
|
+
returnLocalMutex();
|
|
1033
|
+
throw e;
|
|
1034
|
+
}
|
|
1035
|
+
// Step 5: Run the exclusive operation. Steps 6 and 7 run when the outer lock gets stolen from us, a callback
|
|
1036
|
+
// reacting to that has been installed at this point.
|
|
1037
|
+
return returnLocalMutex;
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Closes the linked VFS (if any) and returns navigator locks, if they're currently held.
|
|
1041
|
+
*/
|
|
1042
|
+
async releaseNavigatorLocks() {
|
|
1043
|
+
await this.#localMutex.runExclusive(() => {
|
|
1044
|
+
const held = this.#heldNavigatorLocks;
|
|
1045
|
+
if (held != null) {
|
|
1046
|
+
this.linkedVfs?.close();
|
|
1047
|
+
held.outer();
|
|
1048
|
+
held.inner();
|
|
1049
|
+
this.#heldNavigatorLocks = null;
|
|
1050
|
+
}
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
802
1054
|
|
|
803
1055
|
const OPEN_DB_LOCK = 'open-wasqlite-db';
|
|
804
1056
|
/**
|
|
@@ -853,27 +1105,52 @@ class MultiDatabaseServer {
|
|
|
853
1105
|
}
|
|
854
1106
|
async #databaseOpenAttempt(logger, options) {
|
|
855
1107
|
const { filename, readonly, vfs } = options;
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
1108
|
+
let locks;
|
|
1109
|
+
let needsNavigatorLocks;
|
|
1110
|
+
if (isSharedWorker$1 ||
|
|
1111
|
+
readonly ||
|
|
1112
|
+
vfs == WASQLiteVFS.InMemoryVfs ||
|
|
1113
|
+
(vfs == WASQLiteVFS.SimpleOpfsVFS && options.simpleMode == 'shared')) {
|
|
1114
|
+
// We don't need navigator locks for shared workers because all queries run in this shared worker exclusively.
|
|
1115
|
+
// For read-only connections, we use a VFS that supports concurrent reads (so a single lock on the connection is
|
|
1116
|
+
// fine). In-memory databases either run in a shared worker or aren't shared across tabs at all, so the internal
|
|
1117
|
+
// lock is enough.
|
|
1118
|
+
locks = new Mutex();
|
|
1119
|
+
needsNavigatorLocks = false;
|
|
1120
|
+
}
|
|
1121
|
+
else if (vfs == WASQLiteVFS.SimpleOpfsVFS && options.simpleMode != 'rw-unsafe') {
|
|
1122
|
+
// Use navigator locks that also release sync access handles when there's contention.
|
|
1123
|
+
locks = new LazyNavigatorMutex(`db-lock-${options.filename}`);
|
|
1124
|
+
needsNavigatorLocks = true;
|
|
1125
|
+
}
|
|
1126
|
+
else {
|
|
1127
|
+
// We need navigator locks, but these don't need to coordinate with the file system.
|
|
1128
|
+
locks = new NavigatorMutex(`db-lock-${options.filename}`);
|
|
1129
|
+
needsNavigatorLocks = true;
|
|
1130
|
+
}
|
|
861
1131
|
const activeDatabases = this.#activeDatabases;
|
|
862
1132
|
async function openDatabase() {
|
|
863
1133
|
let server = activeDatabases.get(filename);
|
|
864
1134
|
if (server == null) {
|
|
865
1135
|
const connection = new RawSqliteConnection(options);
|
|
866
|
-
const withSafeConcurrency = new ConcurrentSqliteConnection(connection,
|
|
1136
|
+
const withSafeConcurrency = new ConcurrentSqliteConnection(connection, locks);
|
|
867
1137
|
// Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want
|
|
868
1138
|
// to do that in an exclusive lock. Note that OPEN_DB_LOCK is not enough for that, as another tab might have
|
|
869
1139
|
// already created a connection (and is thus outside of OPEN_DB_LOCK) while currently writing to it.
|
|
870
1140
|
const returnLease = await withSafeConcurrency.acquireMutex();
|
|
871
1141
|
try {
|
|
872
|
-
await
|
|
1142
|
+
const { module, vfs } = await loadModuleAndVfs(options);
|
|
1143
|
+
if (options.vfs == WASQLiteVFS.SimpleOpfsVFS) {
|
|
1144
|
+
withSafeConcurrency.simpleOpfsVfs = vfs;
|
|
1145
|
+
if (locks instanceof LazyNavigatorMutex) {
|
|
1146
|
+
locks.linkedVfs = withSafeConcurrency.simpleOpfsVfs;
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
await connection.initWithModule(module, vfs);
|
|
873
1150
|
}
|
|
874
1151
|
catch (e) {
|
|
875
|
-
|
|
876
|
-
await
|
|
1152
|
+
// Close the connection and its file handles while we still have exclusive access.
|
|
1153
|
+
await withSafeConcurrency.close(returnLease);
|
|
877
1154
|
throw e;
|
|
878
1155
|
}
|
|
879
1156
|
returnLease();
|
|
@@ -1104,32 +1381,6 @@ async function useConnectionState(state, workerPromise, fireActionOnAbort = fals
|
|
|
1104
1381
|
}
|
|
1105
1382
|
}
|
|
1106
1383
|
|
|
1107
|
-
/**
|
|
1108
|
-
* Requests a random lock that will be released once the optional signal is aborted (or, if no signal is given, when the
|
|
1109
|
-
* tab is closed).
|
|
1110
|
-
*
|
|
1111
|
-
* This allows sending the name of the lock to another context (e.g. a shared worker), which will also attempt to
|
|
1112
|
-
* acquire it. Since the lock is returned when the tab is closed, this allows the shared worker to free resources
|
|
1113
|
-
* assocatiated with this tab.
|
|
1114
|
-
*
|
|
1115
|
-
* We take hold of this lock as soon-as-possible in order to cater for potentially closed tabs.
|
|
1116
|
-
*/
|
|
1117
|
-
function generateTabCloseSignal(abort) {
|
|
1118
|
-
return new Promise((resolve, reject) => {
|
|
1119
|
-
const options = { signal: abort };
|
|
1120
|
-
getNavigatorLocks()
|
|
1121
|
-
.request(`tab-close-signal-${crypto.randomUUID()}`, options, (lock) => {
|
|
1122
|
-
resolve(lock.name);
|
|
1123
|
-
return new Promise((resolve) => {
|
|
1124
|
-
if (abort) {
|
|
1125
|
-
abort.addEventListener('abort', () => resolve());
|
|
1126
|
-
}
|
|
1127
|
-
});
|
|
1128
|
-
})
|
|
1129
|
-
.catch(reject);
|
|
1130
|
-
});
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
1384
|
/**
|
|
1134
1385
|
* Internal helper function to acquire a connection from a pool that has a designated writer, additional readers, and
|
|
1135
1386
|
* also allows dispatching reads to the writer.
|
|
@@ -1421,94 +1672,199 @@ class WASQLiteOpenFactory {
|
|
|
1421
1672
|
return this.openAdapter();
|
|
1422
1673
|
}
|
|
1423
1674
|
async openConnection() {
|
|
1424
|
-
const { enableMultiTabs, useWebWorker, vfs
|
|
1675
|
+
const { enableMultiTabs, useWebWorker, vfs } = this.options;
|
|
1425
1676
|
if (!enableMultiTabs) {
|
|
1426
1677
|
this.logger.log({ level: LogLevels.warn, message: 'Multiple tabs are not enabled in this browser' });
|
|
1427
1678
|
}
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
let requiresPersistentTriggers = vfsRequiresDedicatedWorkers(vfs);
|
|
1431
|
-
function resolveRawWaSqliteDatabaseOptions(readonly) {
|
|
1432
|
-
return {
|
|
1433
|
-
filename: dbFilename,
|
|
1434
|
-
readonly,
|
|
1435
|
-
vfs,
|
|
1436
|
-
encryptionKey,
|
|
1437
|
-
temporaryStorage,
|
|
1438
|
-
cacheSizeKb,
|
|
1439
|
-
// TODO: Enable prepared statement cache by default?
|
|
1440
|
-
preparedStatementsCache: preparedStatementsCache ?? 0
|
|
1441
|
-
};
|
|
1679
|
+
if (!useWebWorker) {
|
|
1680
|
+
return { writer: await this.#openInCurrentContext(), additionalReaders: [] };
|
|
1442
1681
|
}
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
workerConnection = connectToExistingWorker(worker, this.logger, 'database');
|
|
1450
|
-
}
|
|
1451
|
-
else {
|
|
1452
|
-
const needsDedicated = vfsRequiresDedicatedWorkers(vfs);
|
|
1453
|
-
const useShared = !needsDedicated && enableMultiTabs;
|
|
1454
|
-
workerConnection = connectToWorker({
|
|
1455
|
-
service: 'database',
|
|
1456
|
-
databaseIdentifier: this.options.dbFilename,
|
|
1457
|
-
shared: useShared,
|
|
1458
|
-
customWorker: optionsDbWorker,
|
|
1459
|
-
loggerForErrors: this.logger
|
|
1460
|
-
});
|
|
1461
|
-
}
|
|
1462
|
-
const source = Comlink.wrap(workerConnection.endpoint);
|
|
1463
|
-
const closeSignal = new AbortController();
|
|
1464
|
-
const connection = await source.connect({
|
|
1465
|
-
database: resolveRawWaSqliteDatabaseOptions(readonly),
|
|
1466
|
-
logLevel: this.options.databaseWorkerLogLevel,
|
|
1467
|
-
lockName: await generateTabCloseSignal(closeSignal.signal)
|
|
1468
|
-
});
|
|
1469
|
-
const clientOptions = {
|
|
1470
|
-
connection,
|
|
1471
|
-
source,
|
|
1472
|
-
// This tab owns the worker, so we're guaranteed to outlive it.
|
|
1473
|
-
remoteCanCloseUnexpectedly: false,
|
|
1474
|
-
onClose: () => {
|
|
1475
|
-
closeSignal.abort();
|
|
1476
|
-
workerConnection.close();
|
|
1477
|
-
}
|
|
1478
|
-
};
|
|
1479
|
-
return new DatabaseClient(clientOptions, {
|
|
1480
|
-
...this.options,
|
|
1481
|
-
requiresPersistentTriggers
|
|
1482
|
-
});
|
|
1483
|
-
};
|
|
1484
|
-
client = await openDatabaseWorker(false);
|
|
1485
|
-
if (vfs == WASQLiteVFS.OPFSWriteAheadVFS) {
|
|
1682
|
+
switch (vfs) {
|
|
1683
|
+
case 'auto':
|
|
1684
|
+
return { writer: await this.#openSimpleOpfs(true), additionalReaders: [] };
|
|
1685
|
+
case WASQLiteVFS.SimpleOpfsVFS:
|
|
1686
|
+
return { writer: await this.#openSimpleOpfs(false), additionalReaders: [] };
|
|
1687
|
+
case WASQLiteVFS.OPFSWriteAheadVFS: {
|
|
1486
1688
|
// This VFS supports concurrent reads, so we can open additional workers to host read-only connections for
|
|
1487
1689
|
// concurrent reads / writes.
|
|
1690
|
+
const writer = await this.#openInWorker({ vfs, readonly: false });
|
|
1488
1691
|
const additionalReadersCount = this.options.additionalReaders ?? 1;
|
|
1489
|
-
const
|
|
1490
|
-
|
|
1491
|
-
|
|
1692
|
+
const additionalReaders = await Promise.all(Array.from({ length: additionalReadersCount }, () => this.#openInWorker({ vfs, readonly: true })));
|
|
1693
|
+
return { writer, additionalReaders };
|
|
1694
|
+
}
|
|
1695
|
+
default:
|
|
1696
|
+
return { writer: await this.#openInWorker({ vfs, readonly: false }), additionalReaders: [] };
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
/**
|
|
1700
|
+
* Opens a {@link WASQLiteVFS.SimpleOpfsVFS} database, or picks the best available storage for the `'auto'` VFS
|
|
1701
|
+
* option if `fallbackToMemory` is set.
|
|
1702
|
+
*
|
|
1703
|
+
* This VFS has three different modes (shared workers, readwrite-unsafe, re-open fallback), see the doc comment on it.
|
|
1704
|
+
* We start a feature detection to check what the current browser supports. In order of preference, we use:
|
|
1705
|
+
*
|
|
1706
|
+
* 1. {@link WASQLiteVFS.SimpleOpfsVFS} through a shared worker spawning a nested dedicated worker.
|
|
1707
|
+
* 2. {@link WASQLiteVFS.SimpleOpfsVFS} in a dedicated worker.
|
|
1708
|
+
* 3. {@link WASQLiteVFS.InMemoryVfs} in a shared worker (only with `fallbackToMemory`).
|
|
1709
|
+
* 4. {@link WASQLiteVFS.InMemoryVfs} in a dedicated worker (only with `fallbackToMemory`).
|
|
1710
|
+
*/
|
|
1711
|
+
async #openSimpleOpfs(fallbackToMemory) {
|
|
1712
|
+
const shared = this.options.enableMultiTabs ? await this.#openSharedWorker() : null;
|
|
1713
|
+
let nested = null;
|
|
1714
|
+
let dedicated = null;
|
|
1715
|
+
// The worker hosting the opened database, which is then owned by the returned client. We close all other workers.
|
|
1716
|
+
let used = null;
|
|
1717
|
+
const connect = async (worker, options) => {
|
|
1718
|
+
const client = await this.#connect(worker, options);
|
|
1719
|
+
used = worker;
|
|
1720
|
+
return client;
|
|
1721
|
+
};
|
|
1722
|
+
const connectInMemory = (worker) => {
|
|
1723
|
+
this.logger.log({ level: LogLevels.warn, message: 'Falling back to in-memory because OPFS is unavailable.' });
|
|
1724
|
+
return connect(worker, { vfs: WASQLiteVFS.InMemoryVfs, readonly: false });
|
|
1725
|
+
};
|
|
1726
|
+
try {
|
|
1727
|
+
if (shared) {
|
|
1728
|
+
const features = await this.#detectNestedFeatures(shared);
|
|
1729
|
+
if (features?.worker) {
|
|
1730
|
+
if (features.worker.opfs) {
|
|
1731
|
+
// Shared workers can open dedicated workers. Perfect, we'll have the shared worker spawn a nested worker
|
|
1732
|
+
// and connect to that.
|
|
1733
|
+
nested = Comlink.wrap(await shared.source.spawnNested());
|
|
1734
|
+
return await connect({ source: nested, connection: shared.connection }, { vfs: WASQLiteVFS.SimpleOpfsVFS, readonly: false, simpleMode: 'shared' });
|
|
1735
|
+
}
|
|
1736
|
+
else if (fallbackToMemory) {
|
|
1737
|
+
// The nested worker doesn't have OPFS access, so a dedicated worker started by us won't have that either.
|
|
1738
|
+
return await connectInMemory(shared);
|
|
1739
|
+
}
|
|
1492
1740
|
}
|
|
1493
|
-
additionalReaders.push(...(await Promise.all(additionalReaderPromises)));
|
|
1494
1741
|
}
|
|
1742
|
+
// We'll have to use a dedicated worker directly.
|
|
1743
|
+
dedicated = this.#openWorker(false);
|
|
1744
|
+
const features = await dedicated.source.dedicatedFeatureDetection();
|
|
1745
|
+
if (features.opfs || !fallbackToMemory) {
|
|
1746
|
+
// See if we can at least use readwrite-unsafe, as that is more efficient than the fallback of closing and
|
|
1747
|
+
// re-opening files on contention.
|
|
1748
|
+
const simpleMode = this.options.simpleMode ?? (features.openWithMode ? 'rw-unsafe' : 'fallback');
|
|
1749
|
+
return await connect(dedicated, { vfs: WASQLiteVFS.SimpleOpfsVFS, readonly: false, simpleMode });
|
|
1750
|
+
}
|
|
1751
|
+
return await connectInMemory(shared ?? dedicated);
|
|
1752
|
+
}
|
|
1753
|
+
finally {
|
|
1754
|
+
const usedWorker = used;
|
|
1755
|
+
if (nested && usedWorker?.source !== nested)
|
|
1756
|
+
nested[Comlink.releaseProxy]();
|
|
1757
|
+
if (shared && usedWorker?.connection !== shared.connection)
|
|
1758
|
+
closeWorker(shared);
|
|
1759
|
+
if (dedicated && usedWorker !== dedicated)
|
|
1760
|
+
closeWorker(dedicated);
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
/** Asks a shared worker whether it can spawn nested workers with OPFS access, or returns null if that fails. */
|
|
1764
|
+
async #detectNestedFeatures(shared) {
|
|
1765
|
+
try {
|
|
1766
|
+
return await shared.source.sharedFeatureDetection();
|
|
1767
|
+
}
|
|
1768
|
+
catch (error) {
|
|
1769
|
+
this.logger.log({ level: LogLevels.error, error, message: 'Could not detect features of shared worker' });
|
|
1770
|
+
return null;
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
/**
|
|
1774
|
+
* Opens a database with a VFS that doesn't need feature detection, using a shared worker when the VFS and options
|
|
1775
|
+
* allow that.
|
|
1776
|
+
*/
|
|
1777
|
+
async #openInWorker(options) {
|
|
1778
|
+
const useShared = !vfsRequiresDedicatedWorkers(options.vfs) && this.options.enableMultiTabs;
|
|
1779
|
+
return this.#connect(this.#openWorker(useShared), options);
|
|
1780
|
+
}
|
|
1781
|
+
/**
|
|
1782
|
+
* Don't use a web worker. Instead, open the MultiDatabaseServer a worker would use locally.
|
|
1783
|
+
*
|
|
1784
|
+
* Without workers, the only storage the `'auto'` option can pick is an in-memory database.
|
|
1785
|
+
*/
|
|
1786
|
+
async #openInCurrentContext() {
|
|
1787
|
+
let vfs = this.options.vfs;
|
|
1788
|
+
if (vfs == 'auto') {
|
|
1789
|
+
this.logger.log({ level: LogLevels.warn, message: 'Using in-memory database because web workers are disabled.' });
|
|
1790
|
+
vfs = WASQLiteVFS.InMemoryVfs;
|
|
1791
|
+
}
|
|
1792
|
+
const localServer = new MultiDatabaseServer(this.logger);
|
|
1793
|
+
const connection = await localServer.openConnectionLocally(this.logger, this.#resolveRawWaSqliteDatabaseOptions({ vfs, readonly: false }));
|
|
1794
|
+
return new DatabaseClient({ connection, source: null, remoteCanCloseUnexpectedly: false }, { ...this.options, vfs, requiresPersistentTriggers: true });
|
|
1795
|
+
}
|
|
1796
|
+
async #connect(worker, options) {
|
|
1797
|
+
const { source, connection: workerConnection } = worker;
|
|
1798
|
+
const closeSignal = new AbortController();
|
|
1799
|
+
const connection = await source.connect({
|
|
1800
|
+
database: this.#resolveRawWaSqliteDatabaseOptions(options),
|
|
1801
|
+
logLevel: this.options.databaseWorkerLogLevel,
|
|
1802
|
+
lockName: await generateTabCloseSignal(closeSignal.signal)
|
|
1803
|
+
});
|
|
1804
|
+
return new DatabaseClient({
|
|
1805
|
+
connection,
|
|
1806
|
+
source,
|
|
1807
|
+
// This tab owns the worker, so we're guaranteed to outlive it.
|
|
1808
|
+
remoteCanCloseUnexpectedly: false,
|
|
1809
|
+
onClose: () => {
|
|
1810
|
+
closeSignal.abort();
|
|
1811
|
+
workerConnection.close();
|
|
1812
|
+
}
|
|
1813
|
+
}, {
|
|
1814
|
+
...this.options,
|
|
1815
|
+
vfs: options.vfs,
|
|
1816
|
+
requiresPersistentTriggers: vfsRequiresDedicatedWorkers(options.vfs)
|
|
1817
|
+
});
|
|
1818
|
+
}
|
|
1819
|
+
async #openSharedWorker() {
|
|
1820
|
+
const shared = this.#openWorker(true);
|
|
1821
|
+
if (!isSharedWorker(shared.connection.worker)) {
|
|
1822
|
+
// A custom worker factory might not respect the `shared` option, and dedicated workers can't share the
|
|
1823
|
+
// database across tabs. Fall back to the modes relying on navigator locks.
|
|
1824
|
+
closeWorker(shared);
|
|
1825
|
+
return null;
|
|
1826
|
+
}
|
|
1827
|
+
return shared;
|
|
1828
|
+
}
|
|
1829
|
+
#openWorker(shared) {
|
|
1830
|
+
const optionsDbWorker = this.options.worker;
|
|
1831
|
+
let connection;
|
|
1832
|
+
if (typeof optionsDbWorker == 'function') {
|
|
1833
|
+
const worker = optionsDbWorker({ ...this.options, shared });
|
|
1834
|
+
connection = connectToExistingWorker(worker, this.logger, 'database');
|
|
1495
1835
|
}
|
|
1496
1836
|
else {
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
requiresPersistentTriggers
|
|
1837
|
+
connection = connectToWorker({
|
|
1838
|
+
service: 'database',
|
|
1839
|
+
databaseIdentifier: this.options.dbFilename,
|
|
1840
|
+
shared: shared,
|
|
1841
|
+
customWorker: optionsDbWorker,
|
|
1842
|
+
loggerForErrors: this.logger
|
|
1504
1843
|
});
|
|
1505
1844
|
}
|
|
1845
|
+
return { connection, source: Comlink.wrap(connection.endpoint) };
|
|
1846
|
+
}
|
|
1847
|
+
#resolveRawWaSqliteDatabaseOptions({ vfs, readonly, simpleMode }) {
|
|
1848
|
+
const { dbFilename, encryptionKey, temporaryStorage, cacheSizeKb, preparedStatementsCache, additionalInitializationFunctions, storageBucket } = this.options;
|
|
1506
1849
|
return {
|
|
1507
|
-
|
|
1508
|
-
|
|
1850
|
+
filename: dbFilename,
|
|
1851
|
+
readonly,
|
|
1852
|
+
vfs,
|
|
1853
|
+
encryptionKey,
|
|
1854
|
+
temporaryStorage,
|
|
1855
|
+
cacheSizeKb,
|
|
1856
|
+
// TODO: Enable prepared statement cache by default?
|
|
1857
|
+
preparedStatementsCache: preparedStatementsCache ?? 0,
|
|
1858
|
+
additionalInitializationFunctions,
|
|
1859
|
+
storageBucket,
|
|
1860
|
+
simpleMode
|
|
1509
1861
|
};
|
|
1510
1862
|
}
|
|
1511
1863
|
}
|
|
1864
|
+
function closeWorker(worker) {
|
|
1865
|
+
worker.source[Comlink.releaseProxy]();
|
|
1866
|
+
worker.connection.close();
|
|
1867
|
+
}
|
|
1512
1868
|
|
|
1513
1869
|
/**
|
|
1514
1870
|
* @internal
|
|
@@ -1653,10 +2009,8 @@ function getOsInfo(nav) {
|
|
|
1653
2009
|
}
|
|
1654
2010
|
|
|
1655
2011
|
class WebRemote extends AbstractRemote {
|
|
1656
|
-
connector;
|
|
1657
2012
|
constructor(connector, logger) {
|
|
1658
2013
|
super(connector, logger);
|
|
1659
|
-
this.connector = connector;
|
|
1660
2014
|
}
|
|
1661
2015
|
fetch({ resource, request }) {
|
|
1662
2016
|
return fetch(resource, request);
|
|
@@ -1782,10 +2136,10 @@ class SharedSyncClientProvider extends AbstractSharedSyncClientProvider {
|
|
|
1782
2136
|
* Don't return anything here, just incase something which is not
|
|
1783
2137
|
* serializable is returned from the `uploadCrud` function.
|
|
1784
2138
|
*/
|
|
1785
|
-
await this.#relay(() => this.options.uploadCrud());
|
|
2139
|
+
await this.#relay(() => this.options.connector.uploadCrud());
|
|
1786
2140
|
}
|
|
1787
2141
|
async postCheckpointRequest(clientId, requestId) {
|
|
1788
|
-
return await this.#relay(async () => (await this.options.postCheckpointRequest(clientId, requestId)) ?? null);
|
|
2142
|
+
return await this.#relay(async () => (await this.options.connector.postCheckpointRequest(clientId, requestId)) ?? null);
|
|
1789
2143
|
}
|
|
1790
2144
|
get logger() {
|
|
1791
2145
|
return this.options.logger;
|
|
@@ -1862,9 +2216,13 @@ class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplementatio
|
|
|
1862
2216
|
* - The client sends the params to the shared worker after locks have been registered.
|
|
1863
2217
|
*/
|
|
1864
2218
|
const closeSignal = await generateTabCloseSignal(this.abortOnClose.signal);
|
|
2219
|
+
const { identifier, connector } = this.options;
|
|
1865
2220
|
// Awaiting here ensures the worker is waiting for the lock
|
|
1866
|
-
await this.syncManager.
|
|
1867
|
-
|
|
2221
|
+
await this.syncManager.initialize(closeSignal, {
|
|
2222
|
+
hasFetchCredentials: !!connector.fetchCredentials,
|
|
2223
|
+
hasPostCheckpointRequest: !!connector.postCheckpointRequest,
|
|
2224
|
+
hasUploadCrud: !!connector.uploadCrud
|
|
2225
|
+
});
|
|
1868
2226
|
await this.syncManager.setParams({
|
|
1869
2227
|
dbParams: this.dbAdapter.getConfiguration(),
|
|
1870
2228
|
streamOptions: {
|
|
@@ -1887,8 +2245,26 @@ class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplementatio
|
|
|
1887
2245
|
return this.syncManager.disconnect();
|
|
1888
2246
|
}
|
|
1889
2247
|
async dispose() {
|
|
1890
|
-
|
|
1891
|
-
|
|
2248
|
+
let registeredWithWorker = true;
|
|
2249
|
+
try {
|
|
2250
|
+
await this.waitForReady();
|
|
2251
|
+
}
|
|
2252
|
+
catch {
|
|
2253
|
+
// The worker rejected this client (e.g. because it connects in a mode incompatible with other tabs), so it won't
|
|
2254
|
+
// acknowledge a close request either.
|
|
2255
|
+
registeredWithWorker = false;
|
|
2256
|
+
}
|
|
2257
|
+
if (registeredWithWorker) {
|
|
2258
|
+
await this.#closeWorkerClient();
|
|
2259
|
+
}
|
|
2260
|
+
await super.dispose();
|
|
2261
|
+
this.abortOnClose.abort();
|
|
2262
|
+
// Release the proxy
|
|
2263
|
+
this.syncManager[Comlink.releaseProxy]();
|
|
2264
|
+
this.worker.close();
|
|
2265
|
+
}
|
|
2266
|
+
#closeWorkerClient() {
|
|
2267
|
+
return new Promise((resolve) => {
|
|
1892
2268
|
// This will always be a message port since we use shared workers.
|
|
1893
2269
|
const messagePort = this.worker.endpoint;
|
|
1894
2270
|
// Listen for the close acknowledgment from the worker
|
|
@@ -1905,11 +2281,6 @@ class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplementatio
|
|
|
1905
2281
|
};
|
|
1906
2282
|
messagePort.postMessage(closeMessagePayload);
|
|
1907
2283
|
});
|
|
1908
|
-
await super.dispose();
|
|
1909
|
-
this.abortOnClose.abort();
|
|
1910
|
-
// Release the proxy
|
|
1911
|
-
this.syncManager[Comlink.releaseProxy]();
|
|
1912
|
-
this.worker.close();
|
|
1913
2284
|
}
|
|
1914
2285
|
async waitForReady() {
|
|
1915
2286
|
return this.isInitialized;
|
|
@@ -2033,6 +2404,9 @@ class WebPowerSyncDatabase extends BasePowerSyncDatabase {
|
|
|
2033
2404
|
// Lets development tooling in this page find the live databases.
|
|
2034
2405
|
registerDatabase(this);
|
|
2035
2406
|
}
|
|
2407
|
+
get sdkName() {
|
|
2408
|
+
return '@powersync/web';
|
|
2409
|
+
}
|
|
2036
2410
|
async _initialize() {
|
|
2037
2411
|
if (this.database instanceof AsyncDbAdapter) {
|
|
2038
2412
|
/**
|
|
@@ -2149,5 +2523,217 @@ class WebPowerSyncDatabase extends BasePowerSyncDatabase {
|
|
|
2149
2523
|
// Typed constructor to avoid leaking AbstractPowerSyncDatabase into the public interface
|
|
2150
2524
|
const PowerSyncDatabase = WebPowerSyncDatabase;
|
|
2151
2525
|
|
|
2526
|
+
// @ts-expect-error
|
|
2527
|
+
class SimpleOpfsFileSystem extends FacadeVFS {
|
|
2528
|
+
#files = null;
|
|
2529
|
+
#memory;
|
|
2530
|
+
#openedFiles = new Map();
|
|
2531
|
+
#openRoot;
|
|
2532
|
+
constructor(name, module, openRoot) {
|
|
2533
|
+
super(name, module);
|
|
2534
|
+
this.#memory = new MemoryVFS(`${name}-memory`, module);
|
|
2535
|
+
this.#openRoot = openRoot;
|
|
2536
|
+
}
|
|
2537
|
+
#requireFiles() {
|
|
2538
|
+
if (this.#files == null) {
|
|
2539
|
+
throw new Error(`Called OPFS method while closed.`);
|
|
2540
|
+
}
|
|
2541
|
+
return this.#files;
|
|
2542
|
+
}
|
|
2543
|
+
#requireFile(file) {
|
|
2544
|
+
return this.#requireFiles().files[file.index];
|
|
2545
|
+
}
|
|
2546
|
+
#useFile(options) {
|
|
2547
|
+
const opened = this.#openedFiles.get(options.fileId);
|
|
2548
|
+
if (opened != null) {
|
|
2549
|
+
try {
|
|
2550
|
+
return options.opfs(this.#requireFile(opened));
|
|
2551
|
+
}
|
|
2552
|
+
catch (e) {
|
|
2553
|
+
console.error('OPFS VFS error', e);
|
|
2554
|
+
return VFS.SQLITE_IOERR;
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
else {
|
|
2558
|
+
return options.memory(this.#memory);
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
jOpen(zName, fileId, flags, pOutFlags) {
|
|
2562
|
+
if (flags & VFS.SQLITE_OPEN_MAIN_DB) {
|
|
2563
|
+
if (zName != '/database') {
|
|
2564
|
+
return VFS.SQLITE_CANTOPEN;
|
|
2565
|
+
}
|
|
2566
|
+
this.#openedFiles.set(fileId, database);
|
|
2567
|
+
return VFS.SQLITE_OK;
|
|
2568
|
+
}
|
|
2569
|
+
else if (flags & VFS.SQLITE_OPEN_MAIN_JOURNAL) {
|
|
2570
|
+
if (zName != '/database-journal') {
|
|
2571
|
+
return VFS.SQLITE_CANTOPEN;
|
|
2572
|
+
}
|
|
2573
|
+
this.#openedFiles.set(fileId, databaseJournal);
|
|
2574
|
+
return VFS.SQLITE_OK;
|
|
2575
|
+
}
|
|
2576
|
+
else {
|
|
2577
|
+
// We don't care about other files (like those for materialized views). Back them by the in-memory VFS.
|
|
2578
|
+
return this.#memory.jOpen(zName, fileId, flags, pOutFlags);
|
|
2579
|
+
}
|
|
2580
|
+
}
|
|
2581
|
+
jDelete(name, syncDir) {
|
|
2582
|
+
switch (name) {
|
|
2583
|
+
case '/database':
|
|
2584
|
+
case '/database-journal':
|
|
2585
|
+
// We don't support deleting files in this VFS, and use a journal mode where that is not necessary.
|
|
2586
|
+
return VFS.SQLITE_IOERR_DELETE;
|
|
2587
|
+
default:
|
|
2588
|
+
return this.#memory.jDelete(name, syncDir);
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
jAccess(zName, flags, pResOut) {
|
|
2592
|
+
switch (zName) {
|
|
2593
|
+
case '/database':
|
|
2594
|
+
case '/database-journal':
|
|
2595
|
+
// These always exist
|
|
2596
|
+
pResOut.setInt32(0, 1, true);
|
|
2597
|
+
return VFS.SQLITE_OK;
|
|
2598
|
+
default:
|
|
2599
|
+
return this.#memory.jAccess(zName, flags, pResOut);
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
jClose(fileId) {
|
|
2603
|
+
return this.#useFile({
|
|
2604
|
+
fileId,
|
|
2605
|
+
opfs: () => {
|
|
2606
|
+
this.#openedFiles.delete(fileId);
|
|
2607
|
+
return VFS.SQLITE_OK;
|
|
2608
|
+
},
|
|
2609
|
+
memory: (m) => m.jClose(fileId)
|
|
2610
|
+
});
|
|
2611
|
+
}
|
|
2612
|
+
jRead(fileId, data, iOffset) {
|
|
2613
|
+
return this.#useFile({
|
|
2614
|
+
fileId,
|
|
2615
|
+
opfs: (file) => {
|
|
2616
|
+
const bytesRead = file.read(data.subarray(), { at: iOffset });
|
|
2617
|
+
if (bytesRead < data.byteLength) {
|
|
2618
|
+
data.fill(0, bytesRead);
|
|
2619
|
+
return VFS.SQLITE_IOERR_SHORT_READ;
|
|
2620
|
+
}
|
|
2621
|
+
return VFS.SQLITE_OK;
|
|
2622
|
+
},
|
|
2623
|
+
memory: (m) => m.jRead(fileId, data, iOffset)
|
|
2624
|
+
});
|
|
2625
|
+
}
|
|
2626
|
+
jWrite(fileId, data, iOffset) {
|
|
2627
|
+
return this.#useFile({
|
|
2628
|
+
fileId,
|
|
2629
|
+
opfs: (file) => {
|
|
2630
|
+
const nBytes = file.write(data.subarray(), { at: iOffset });
|
|
2631
|
+
if (nBytes !== data.byteLength)
|
|
2632
|
+
throw new Error('short write');
|
|
2633
|
+
return VFS.SQLITE_OK;
|
|
2634
|
+
},
|
|
2635
|
+
memory: (m) => m.jWrite(fileId, data, iOffset)
|
|
2636
|
+
});
|
|
2637
|
+
}
|
|
2638
|
+
jTruncate(fileId, iSize) {
|
|
2639
|
+
return this.#useFile({
|
|
2640
|
+
fileId,
|
|
2641
|
+
opfs: (file) => {
|
|
2642
|
+
file.truncate(iSize);
|
|
2643
|
+
return VFS.SQLITE_OK;
|
|
2644
|
+
},
|
|
2645
|
+
memory: (m) => m.jTruncate(fileId, iSize)
|
|
2646
|
+
});
|
|
2647
|
+
}
|
|
2648
|
+
jSync(fileId, flags) {
|
|
2649
|
+
return this.#useFile({
|
|
2650
|
+
fileId,
|
|
2651
|
+
opfs: (file) => {
|
|
2652
|
+
file.flush();
|
|
2653
|
+
return VFS.SQLITE_OK;
|
|
2654
|
+
},
|
|
2655
|
+
memory: (m) => m.jSync(fileId, flags)
|
|
2656
|
+
});
|
|
2657
|
+
}
|
|
2658
|
+
jFileSize(fileId, pSize64) {
|
|
2659
|
+
return this.#useFile({
|
|
2660
|
+
fileId,
|
|
2661
|
+
opfs: (file) => {
|
|
2662
|
+
pSize64.setBigInt64(0, BigInt(file.getSize()), true);
|
|
2663
|
+
return VFS.SQLITE_OK;
|
|
2664
|
+
},
|
|
2665
|
+
memory: (m) => m.jFileSize(fileId, pSize64)
|
|
2666
|
+
});
|
|
2667
|
+
}
|
|
2668
|
+
/**
|
|
2669
|
+
* Re-opens a file system previously closed with {@link SimpleOpfsFileSystem.close}.
|
|
2670
|
+
*/
|
|
2671
|
+
async open() {
|
|
2672
|
+
console.assert(this.#files == null);
|
|
2673
|
+
const { dir, readWriteUnsafe } = await this.#openRoot();
|
|
2674
|
+
this.#files = await OpfsFiles.open(dir, readWriteUnsafe);
|
|
2675
|
+
}
|
|
2676
|
+
/**
|
|
2677
|
+
* Closes the synchronous access handles kept open while this file system is active.
|
|
2678
|
+
*
|
|
2679
|
+
* This file system can be re-opened afterwards with {@link SimpleOpfsFileSystem.open}.
|
|
2680
|
+
*/
|
|
2681
|
+
close() {
|
|
2682
|
+
this.#files?.close();
|
|
2683
|
+
this.#files = null;
|
|
2684
|
+
}
|
|
2685
|
+
static directoryResolver(name, readWriteUnsafe, getRoot) {
|
|
2686
|
+
const url = new URL(name, 'file://');
|
|
2687
|
+
return async () => {
|
|
2688
|
+
let dir = await (getRoot ? getRoot() : navigator.storage.getDirectory());
|
|
2689
|
+
for (const segment of ['powersync', ...url.pathname.split('/')]) {
|
|
2690
|
+
if (!segment.length)
|
|
2691
|
+
continue; // Skip initial / and empty directory names
|
|
2692
|
+
dir = await dir.getDirectoryHandle(segment, { create: true });
|
|
2693
|
+
}
|
|
2694
|
+
return { dir, readWriteUnsafe };
|
|
2695
|
+
};
|
|
2696
|
+
}
|
|
2697
|
+
}
|
|
2698
|
+
class OpfsFiles {
|
|
2699
|
+
files;
|
|
2700
|
+
constructor(database, journal) {
|
|
2701
|
+
this.files = [database, journal];
|
|
2702
|
+
}
|
|
2703
|
+
close() {
|
|
2704
|
+
for (const file of this.files) {
|
|
2705
|
+
file.close();
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
static async open(root, readWriteUnsafe) {
|
|
2709
|
+
async function open(name) {
|
|
2710
|
+
const handle = await root.getFileHandle(name, { create: true });
|
|
2711
|
+
return await (readWriteUnsafe
|
|
2712
|
+
? // @ts-expect-error
|
|
2713
|
+
handle.createSyncAccessHandle({ mode: 'readwrite-unsafe' })
|
|
2714
|
+
: handle.createSyncAccessHandle());
|
|
2715
|
+
}
|
|
2716
|
+
const [database, journal] = await Promise.allSettled([open('database'), open('journal')]);
|
|
2717
|
+
if (database.status === 'fulfilled' && journal.status === 'fulfilled') {
|
|
2718
|
+
return new OpfsFiles(database.value, journal.value);
|
|
2719
|
+
}
|
|
2720
|
+
if (database.status === 'fulfilled') {
|
|
2721
|
+
database.value.close();
|
|
2722
|
+
throw journal.reason;
|
|
2723
|
+
}
|
|
2724
|
+
else if (journal.status === 'fulfilled') {
|
|
2725
|
+
journal.value.close();
|
|
2726
|
+
}
|
|
2727
|
+
throw database.reason;
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
const database = Object.freeze({ index: 0, name: '/database' });
|
|
2731
|
+
const databaseJournal = Object.freeze({ index: 1, name: '/database-journal' });
|
|
2732
|
+
|
|
2733
|
+
var SimpleOpfsFileSystem$1 = /*#__PURE__*/Object.freeze({
|
|
2734
|
+
__proto__: null,
|
|
2735
|
+
SimpleOpfsFileSystem: SimpleOpfsFileSystem
|
|
2736
|
+
});
|
|
2737
|
+
|
|
2152
2738
|
export { IndexDBFileSystemStorageAdapter, PowerSyncDatabase, SharedWebStreamingSyncImplementation, TemporaryStorageOption, WASQLiteOpenFactory, WASQLiteVFS, WebPowerSyncDatabase, WebRemote, WebStreamingSyncImplementation };
|
|
2153
2739
|
//# sourceMappingURL=index.react_native_web.js.map
|