@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
|
@@ -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,15 +138,54 @@ 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
|
}
|
|
142
175
|
/**
|
|
143
176
|
* Whether the VFS can keep its files in a Storage Bucket, see {@link WebSpecificOpenOptions.storageBucket}.
|
|
144
177
|
*/
|
|
145
178
|
function vfsSupportsStorageBuckets(vfs) {
|
|
146
|
-
|
|
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
|
+
}
|
|
147
189
|
}
|
|
148
190
|
/**
|
|
149
191
|
* Options for an OPFS-based VFS that keep its files in the named Storage Bucket, see
|
|
@@ -191,7 +233,7 @@ async function syncModuleFactory(encryptionKey) {
|
|
|
191
233
|
/**
|
|
192
234
|
* @internal
|
|
193
235
|
*/
|
|
194
|
-
async function loadModuleAndVfs({ vfs, filename, encryptionKey, storageBucket }) {
|
|
236
|
+
async function loadModuleAndVfs({ vfs, filename, encryptionKey, storageBucket, simpleMode }) {
|
|
195
237
|
let moduleFactory = syncModuleFactory;
|
|
196
238
|
let resolveVfs;
|
|
197
239
|
switch (vfs) {
|
|
@@ -222,6 +264,18 @@ async function loadModuleAndVfs({ vfs, filename, encryptionKey, storageBucket })
|
|
|
222
264
|
resolveVfs = (module) => OPFSWriteAheadVFS.create(filename, module, vfsOptionsForStorageBucket(storageBucket));
|
|
223
265
|
break;
|
|
224
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
|
+
};
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
225
279
|
case WASQLiteVFS.InMemoryVfs: {
|
|
226
280
|
const { MemoryVFS } = await import('@journeyapps/wa-sqlite/src/examples/MemoryVFS.js');
|
|
227
281
|
// @ts-expect-error The types for this static method are missing upstream
|
|
@@ -426,6 +480,55 @@ const getNavigatorLocks = () => {
|
|
|
426
480
|
}
|
|
427
481
|
throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');
|
|
428
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
|
+
}
|
|
429
532
|
|
|
430
533
|
var TemporaryStorageOption;
|
|
431
534
|
(function (TemporaryStorageOption) {
|
|
@@ -543,19 +646,25 @@ class RawSqliteConnection {
|
|
|
543
646
|
get isOpen() {
|
|
544
647
|
return this.db != 0;
|
|
545
648
|
}
|
|
546
|
-
async init() {
|
|
547
|
-
const { module, vfs } = await loadModuleAndVfs(this.options);
|
|
548
|
-
await this.initWithModule(module, vfs);
|
|
549
|
-
}
|
|
550
649
|
async initWithModule(module, vfs) {
|
|
551
650
|
const api = (this._sqliteAPI = await this.openSQLiteAPI(module, vfs));
|
|
552
|
-
|
|
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 */);
|
|
553
658
|
await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
|
|
554
659
|
if (this.options.encryptionKey) {
|
|
555
660
|
const escapedKey = this.options.encryptionKey.replaceAll("'", "''");
|
|
556
661
|
await this.executeRaw(`PRAGMA key = '${escapedKey}';`);
|
|
557
662
|
}
|
|
558
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
|
+
}
|
|
559
668
|
await this.executeRaw(`SELECT powersync_update_hooks('install');`);
|
|
560
669
|
}
|
|
561
670
|
async openSQLiteAPI(module, vfs) {
|
|
@@ -729,42 +838,29 @@ class RawSqliteConnection {
|
|
|
729
838
|
*/
|
|
730
839
|
class ConcurrentSqliteConnection {
|
|
731
840
|
inner;
|
|
841
|
+
mutex;
|
|
732
842
|
/**
|
|
733
|
-
*
|
|
734
|
-
*
|
|
735
|
-
* 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.
|
|
736
845
|
*/
|
|
737
|
-
|
|
846
|
+
simpleOpfsVfs = null;
|
|
847
|
+
constructor(inner,
|
|
738
848
|
/**
|
|
739
|
-
*
|
|
849
|
+
* A mutex ensuring at most one {@link ConnectionLeaseToken} can exist for this connection at a time.
|
|
740
850
|
*
|
|
741
851
|
* While {@link ConcurrentSqliteConnection} prevents concurrent access to a database _connection_, it's possible we
|
|
742
852
|
* might have multiple connections to the same physical database (e.g. if multiple tabs use dedicated workers).
|
|
743
|
-
* 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.
|
|
744
854
|
*/
|
|
745
|
-
|
|
855
|
+
mutex) {
|
|
746
856
|
this.inner = inner;
|
|
747
|
-
this.
|
|
857
|
+
this.mutex = mutex;
|
|
748
858
|
}
|
|
749
859
|
get options() {
|
|
750
860
|
return this.inner.options;
|
|
751
861
|
}
|
|
752
862
|
acquireMutex(abort) {
|
|
753
|
-
|
|
754
|
-
return this.leaseMutex.acquire(abort);
|
|
755
|
-
}
|
|
756
|
-
return new Promise((resolve, reject) => {
|
|
757
|
-
const options = { signal: abort };
|
|
758
|
-
navigator.locks
|
|
759
|
-
.request(`db-lock-${this.options.filename}`, options, (_) => {
|
|
760
|
-
return new Promise((returnLock) => {
|
|
761
|
-
return resolve(() => {
|
|
762
|
-
returnLock();
|
|
763
|
-
});
|
|
764
|
-
});
|
|
765
|
-
})
|
|
766
|
-
.catch(reject);
|
|
767
|
-
});
|
|
863
|
+
return this.mutex.acquire(abort);
|
|
768
864
|
}
|
|
769
865
|
// Unsafe, unguarded access to the SQLite connection.
|
|
770
866
|
unsafeUseInner() {
|
|
@@ -792,14 +888,22 @@ class ConcurrentSqliteConnection {
|
|
|
792
888
|
}
|
|
793
889
|
return token;
|
|
794
890
|
}
|
|
795
|
-
|
|
796
|
-
|
|
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();
|
|
797
896
|
try {
|
|
798
897
|
await this.inner.close();
|
|
799
898
|
}
|
|
800
899
|
finally {
|
|
900
|
+
this.simpleOpfsVfs?.close();
|
|
801
901
|
returnMutex();
|
|
802
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
|
+
}
|
|
803
907
|
}
|
|
804
908
|
}
|
|
805
909
|
/**
|
|
@@ -838,6 +942,115 @@ class ConnectionLeaseToken {
|
|
|
838
942
|
});
|
|
839
943
|
}
|
|
840
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
|
+
}
|
|
841
1054
|
|
|
842
1055
|
const OPEN_DB_LOCK = 'open-wasqlite-db';
|
|
843
1056
|
/**
|
|
@@ -892,27 +1105,52 @@ class MultiDatabaseServer {
|
|
|
892
1105
|
}
|
|
893
1106
|
async #databaseOpenAttempt(logger, options) {
|
|
894
1107
|
const { filename, readonly, vfs } = options;
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
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
|
+
}
|
|
900
1131
|
const activeDatabases = this.#activeDatabases;
|
|
901
1132
|
async function openDatabase() {
|
|
902
1133
|
let server = activeDatabases.get(filename);
|
|
903
1134
|
if (server == null) {
|
|
904
1135
|
const connection = new RawSqliteConnection(options);
|
|
905
|
-
const withSafeConcurrency = new ConcurrentSqliteConnection(connection,
|
|
1136
|
+
const withSafeConcurrency = new ConcurrentSqliteConnection(connection, locks);
|
|
906
1137
|
// Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want
|
|
907
1138
|
// to do that in an exclusive lock. Note that OPEN_DB_LOCK is not enough for that, as another tab might have
|
|
908
1139
|
// already created a connection (and is thus outside of OPEN_DB_LOCK) while currently writing to it.
|
|
909
1140
|
const returnLease = await withSafeConcurrency.acquireMutex();
|
|
910
1141
|
try {
|
|
911
|
-
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);
|
|
912
1150
|
}
|
|
913
1151
|
catch (e) {
|
|
914
|
-
|
|
915
|
-
await
|
|
1152
|
+
// Close the connection and its file handles while we still have exclusive access.
|
|
1153
|
+
await withSafeConcurrency.close(returnLease);
|
|
916
1154
|
throw e;
|
|
917
1155
|
}
|
|
918
1156
|
returnLease();
|
|
@@ -1143,32 +1381,6 @@ async function useConnectionState(state, workerPromise, fireActionOnAbort = fals
|
|
|
1143
1381
|
}
|
|
1144
1382
|
}
|
|
1145
1383
|
|
|
1146
|
-
/**
|
|
1147
|
-
* Requests a random lock that will be released once the optional signal is aborted (or, if no signal is given, when the
|
|
1148
|
-
* tab is closed).
|
|
1149
|
-
*
|
|
1150
|
-
* This allows sending the name of the lock to another context (e.g. a shared worker), which will also attempt to
|
|
1151
|
-
* acquire it. Since the lock is returned when the tab is closed, this allows the shared worker to free resources
|
|
1152
|
-
* assocatiated with this tab.
|
|
1153
|
-
*
|
|
1154
|
-
* We take hold of this lock as soon-as-possible in order to cater for potentially closed tabs.
|
|
1155
|
-
*/
|
|
1156
|
-
function generateTabCloseSignal(abort) {
|
|
1157
|
-
return new Promise((resolve, reject) => {
|
|
1158
|
-
const options = { signal: abort };
|
|
1159
|
-
getNavigatorLocks()
|
|
1160
|
-
.request(`tab-close-signal-${crypto.randomUUID()}`, options, (lock) => {
|
|
1161
|
-
resolve(lock.name);
|
|
1162
|
-
return new Promise((resolve) => {
|
|
1163
|
-
if (abort) {
|
|
1164
|
-
abort.addEventListener('abort', () => resolve());
|
|
1165
|
-
}
|
|
1166
|
-
});
|
|
1167
|
-
})
|
|
1168
|
-
.catch(reject);
|
|
1169
|
-
});
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
1384
|
/**
|
|
1173
1385
|
* Internal helper function to acquire a connection from a pool that has a designated writer, additional readers, and
|
|
1174
1386
|
* also allows dispatching reads to the writer.
|
|
@@ -1460,96 +1672,199 @@ class WASQLiteOpenFactory {
|
|
|
1460
1672
|
return this.openAdapter();
|
|
1461
1673
|
}
|
|
1462
1674
|
async openConnection() {
|
|
1463
|
-
const { enableMultiTabs, useWebWorker, vfs
|
|
1675
|
+
const { enableMultiTabs, useWebWorker, vfs } = this.options;
|
|
1464
1676
|
if (!enableMultiTabs) {
|
|
1465
1677
|
this.logger.log({ level: LogLevels.warn, message: 'Multiple tabs are not enabled in this browser' });
|
|
1466
1678
|
}
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
let requiresPersistentTriggers = vfsRequiresDedicatedWorkers(vfs);
|
|
1470
|
-
function resolveRawWaSqliteDatabaseOptions(readonly) {
|
|
1471
|
-
return {
|
|
1472
|
-
filename: dbFilename,
|
|
1473
|
-
readonly,
|
|
1474
|
-
vfs,
|
|
1475
|
-
encryptionKey,
|
|
1476
|
-
temporaryStorage,
|
|
1477
|
-
cacheSizeKb,
|
|
1478
|
-
// TODO: Enable prepared statement cache by default?
|
|
1479
|
-
preparedStatementsCache: preparedStatementsCache ?? 0,
|
|
1480
|
-
additionalInitializationFunctions,
|
|
1481
|
-
storageBucket
|
|
1482
|
-
};
|
|
1679
|
+
if (!useWebWorker) {
|
|
1680
|
+
return { writer: await this.#openInCurrentContext(), additionalReaders: [] };
|
|
1483
1681
|
}
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
workerConnection = connectToExistingWorker(worker, this.logger, 'database');
|
|
1491
|
-
}
|
|
1492
|
-
else {
|
|
1493
|
-
const needsDedicated = vfsRequiresDedicatedWorkers(vfs);
|
|
1494
|
-
const useShared = !needsDedicated && enableMultiTabs;
|
|
1495
|
-
workerConnection = connectToWorker({
|
|
1496
|
-
service: 'database',
|
|
1497
|
-
databaseIdentifier: this.options.dbFilename,
|
|
1498
|
-
shared: useShared,
|
|
1499
|
-
customWorker: optionsDbWorker,
|
|
1500
|
-
loggerForErrors: this.logger
|
|
1501
|
-
});
|
|
1502
|
-
}
|
|
1503
|
-
const source = Comlink.wrap(workerConnection.endpoint);
|
|
1504
|
-
const closeSignal = new AbortController();
|
|
1505
|
-
const connection = await source.connect({
|
|
1506
|
-
database: resolveRawWaSqliteDatabaseOptions(readonly),
|
|
1507
|
-
logLevel: this.options.databaseWorkerLogLevel,
|
|
1508
|
-
lockName: await generateTabCloseSignal(closeSignal.signal)
|
|
1509
|
-
});
|
|
1510
|
-
const clientOptions = {
|
|
1511
|
-
connection,
|
|
1512
|
-
source,
|
|
1513
|
-
// This tab owns the worker, so we're guaranteed to outlive it.
|
|
1514
|
-
remoteCanCloseUnexpectedly: false,
|
|
1515
|
-
onClose: () => {
|
|
1516
|
-
closeSignal.abort();
|
|
1517
|
-
workerConnection.close();
|
|
1518
|
-
}
|
|
1519
|
-
};
|
|
1520
|
-
return new DatabaseClient(clientOptions, {
|
|
1521
|
-
...this.options,
|
|
1522
|
-
requiresPersistentTriggers
|
|
1523
|
-
});
|
|
1524
|
-
};
|
|
1525
|
-
client = await openDatabaseWorker(false);
|
|
1526
|
-
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: {
|
|
1527
1688
|
// This VFS supports concurrent reads, so we can open additional workers to host read-only connections for
|
|
1528
1689
|
// concurrent reads / writes.
|
|
1690
|
+
const writer = await this.#openInWorker({ vfs, readonly: false });
|
|
1529
1691
|
const additionalReadersCount = this.options.additionalReaders ?? 1;
|
|
1530
|
-
const
|
|
1531
|
-
|
|
1532
|
-
|
|
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
|
+
}
|
|
1533
1740
|
}
|
|
1534
|
-
additionalReaders.push(...(await Promise.all(additionalReaderPromises)));
|
|
1535
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');
|
|
1536
1835
|
}
|
|
1537
1836
|
else {
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
requiresPersistentTriggers
|
|
1837
|
+
connection = connectToWorker({
|
|
1838
|
+
service: 'database',
|
|
1839
|
+
databaseIdentifier: this.options.dbFilename,
|
|
1840
|
+
shared: shared,
|
|
1841
|
+
customWorker: optionsDbWorker,
|
|
1842
|
+
loggerForErrors: this.logger
|
|
1545
1843
|
});
|
|
1546
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;
|
|
1547
1849
|
return {
|
|
1548
|
-
|
|
1549
|
-
|
|
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
|
|
1550
1861
|
};
|
|
1551
1862
|
}
|
|
1552
1863
|
}
|
|
1864
|
+
function closeWorker(worker) {
|
|
1865
|
+
worker.source[Comlink.releaseProxy]();
|
|
1866
|
+
worker.connection.close();
|
|
1867
|
+
}
|
|
1553
1868
|
|
|
1554
1869
|
/**
|
|
1555
1870
|
* @internal
|
|
@@ -2208,5 +2523,217 @@ class WebPowerSyncDatabase extends BasePowerSyncDatabase {
|
|
|
2208
2523
|
// Typed constructor to avoid leaking AbstractPowerSyncDatabase into the public interface
|
|
2209
2524
|
const PowerSyncDatabase = WebPowerSyncDatabase;
|
|
2210
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
|
+
|
|
2211
2738
|
export { IndexDBFileSystemStorageAdapter, PowerSyncDatabase, SharedWebStreamingSyncImplementation, TemporaryStorageOption, WASQLiteOpenFactory, WASQLiteVFS, WebPowerSyncDatabase, WebRemote, WebStreamingSyncImplementation };
|
|
2212
2739
|
//# sourceMappingURL=index.react_native_web.js.map
|