@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
|
@@ -4,12 +4,12 @@ import { ResolvedWebSQLOpenOptions, WebSQLOpenOptions } from '../options.js';
|
|
|
4
4
|
import { SSRDBAdapter } from '../SSRDBAdapter.js';
|
|
5
5
|
import { vfsRequiresDedicatedWorkers, WASQLiteVFS } from './vfs.js';
|
|
6
6
|
import { MultiDatabaseServer } from '../../../worker/db/MultiDatabaseServer.js';
|
|
7
|
-
import { DatabaseClient, OpenWorkerConnection } from './DatabaseClient.js';
|
|
8
|
-
import { generateTabCloseSignal } from '../../../shared/
|
|
7
|
+
import { DatabaseClient, OpenWorkerConnection, SharedFeatureDetectionResult } from './DatabaseClient.js';
|
|
8
|
+
import { generateTabCloseSignal } from '../../../shared/locks.js';
|
|
9
9
|
import { AsyncDbAdapter, PoolConnection } from '../AsyncWebAdapter.js';
|
|
10
|
-
import { RawWaSqliteDatabaseOptions } from './RawSqliteConnection.js';
|
|
10
|
+
import { RawWaSqliteDatabaseOptions, SimpleOpfsMode } from './RawSqliteConnection.js';
|
|
11
11
|
import { maxPathNameLength, resolveAndValidateOptions } from '../resolveAndValidateOptions.js';
|
|
12
|
-
import { connectToExistingWorker, connectToWorker, WorkerConnection } from '../../../worker/client.js';
|
|
12
|
+
import { connectToExistingWorker, connectToWorker, isSharedWorker, WorkerConnection } from '../../../worker/client.js';
|
|
13
13
|
|
|
14
14
|
export interface WASQLiteOpenFactoryOptions {
|
|
15
15
|
open: WebSQLOpenOptions;
|
|
@@ -67,114 +67,257 @@ export class WASQLiteOpenFactory implements SQLOpenFactory {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
async openConnection(): Promise<PoolConnection> {
|
|
70
|
-
const {
|
|
71
|
-
enableMultiTabs,
|
|
72
|
-
useWebWorker,
|
|
73
|
-
vfs,
|
|
74
|
-
dbFilename,
|
|
75
|
-
encryptionKey,
|
|
76
|
-
temporaryStorage,
|
|
77
|
-
cacheSizeKb,
|
|
78
|
-
preparedStatementsCache
|
|
79
|
-
} = this.options;
|
|
70
|
+
const { enableMultiTabs, useWebWorker, vfs } = this.options;
|
|
80
71
|
|
|
81
72
|
if (!enableMultiTabs) {
|
|
82
73
|
this.logger.log({ level: LogLevels.warn, message: 'Multiple tabs are not enabled in this browser' });
|
|
83
74
|
}
|
|
84
75
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
let requiresPersistentTriggers = vfsRequiresDedicatedWorkers(vfs);
|
|
88
|
-
|
|
89
|
-
function resolveRawWaSqliteDatabaseOptions(readonly: boolean): RawWaSqliteDatabaseOptions {
|
|
90
|
-
return {
|
|
91
|
-
filename: dbFilename,
|
|
92
|
-
readonly,
|
|
93
|
-
vfs,
|
|
94
|
-
encryptionKey,
|
|
95
|
-
temporaryStorage,
|
|
96
|
-
cacheSizeKb,
|
|
97
|
-
// TODO: Enable prepared statement cache by default?
|
|
98
|
-
preparedStatementsCache: preparedStatementsCache ?? 0
|
|
99
|
-
};
|
|
76
|
+
if (!useWebWorker) {
|
|
77
|
+
return { writer: await this.#openInCurrentContext(), additionalReaders: [] };
|
|
100
78
|
}
|
|
101
79
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
}
|
|
80
|
+
switch (vfs) {
|
|
81
|
+
case 'auto':
|
|
82
|
+
return { writer: await this.#openSimpleOpfs(true), additionalReaders: [] };
|
|
83
|
+
case WASQLiteVFS.SimpleOpfsVFS:
|
|
84
|
+
return { writer: await this.#openSimpleOpfs(false), additionalReaders: [] };
|
|
85
|
+
case WASQLiteVFS.OPFSWriteAheadVFS: {
|
|
86
|
+
// This VFS supports concurrent reads, so we can open additional workers to host read-only connections for
|
|
87
|
+
// concurrent reads / writes.
|
|
88
|
+
const writer = await this.#openInWorker({ vfs, readonly: false });
|
|
89
|
+
const additionalReadersCount = this.options.additionalReaders ?? 1;
|
|
90
|
+
const additionalReaders = await Promise.all(
|
|
91
|
+
Array.from({ length: additionalReadersCount }, () => this.#openInWorker({ vfs, readonly: true }))
|
|
92
|
+
);
|
|
93
|
+
return { writer, additionalReaders };
|
|
94
|
+
}
|
|
95
|
+
default:
|
|
96
|
+
return { writer: await this.#openInWorker({ vfs, readonly: false }), additionalReaders: [] };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
122
99
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Opens a {@link WASQLiteVFS.SimpleOpfsVFS} database, or picks the best available storage for the `'auto'` VFS
|
|
102
|
+
* option if `fallbackToMemory` is set.
|
|
103
|
+
*
|
|
104
|
+
* This VFS has three different modes (shared workers, readwrite-unsafe, re-open fallback), see the doc comment on it.
|
|
105
|
+
* We start a feature detection to check what the current browser supports. In order of preference, we use:
|
|
106
|
+
*
|
|
107
|
+
* 1. {@link WASQLiteVFS.SimpleOpfsVFS} through a shared worker spawning a nested dedicated worker.
|
|
108
|
+
* 2. {@link WASQLiteVFS.SimpleOpfsVFS} in a dedicated worker.
|
|
109
|
+
* 3. {@link WASQLiteVFS.InMemoryVfs} in a shared worker (only with `fallbackToMemory`).
|
|
110
|
+
* 4. {@link WASQLiteVFS.InMemoryVfs} in a dedicated worker (only with `fallbackToMemory`).
|
|
111
|
+
*/
|
|
112
|
+
async #openSimpleOpfs(fallbackToMemory: boolean): Promise<DatabaseClient> {
|
|
113
|
+
const shared = this.options.enableMultiTabs ? await this.#openSharedWorker() : null;
|
|
114
|
+
let nested: Comlink.Remote<OpenWorkerConnection> | null = null;
|
|
115
|
+
let dedicated: OpenedWorker | null = null;
|
|
116
|
+
// The worker hosting the opened database, which is then owned by the returned client. We close all other workers.
|
|
117
|
+
let used: OpenedWorker | null = null;
|
|
118
|
+
|
|
119
|
+
const connect = async (worker: OpenedWorker, options: ResolvedDatabaseOptions) => {
|
|
120
|
+
const client = await this.#connect(worker, options);
|
|
121
|
+
used = worker;
|
|
122
|
+
return client;
|
|
123
|
+
};
|
|
124
|
+
const connectInMemory = (worker: OpenedWorker) => {
|
|
125
|
+
this.logger.log({ level: LogLevels.warn, message: 'Falling back to in-memory because OPFS is unavailable.' });
|
|
126
|
+
return connect(worker, { vfs: WASQLiteVFS.InMemoryVfs, readonly: false });
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
try {
|
|
130
|
+
if (shared) {
|
|
131
|
+
const features = await this.#detectNestedFeatures(shared);
|
|
132
|
+
if (features?.worker) {
|
|
133
|
+
if (features.worker.opfs) {
|
|
134
|
+
// Shared workers can open dedicated workers. Perfect, we'll have the shared worker spawn a nested worker
|
|
135
|
+
// and connect to that.
|
|
136
|
+
nested = Comlink.wrap<OpenWorkerConnection>(await shared.source.spawnNested());
|
|
137
|
+
return await connect(
|
|
138
|
+
{ source: nested, connection: shared.connection },
|
|
139
|
+
{ vfs: WASQLiteVFS.SimpleOpfsVFS, readonly: false, simpleMode: 'shared' }
|
|
140
|
+
);
|
|
141
|
+
} else if (fallbackToMemory) {
|
|
142
|
+
// The nested worker doesn't have OPFS access, so a dedicated worker started by us won't have that either.
|
|
143
|
+
return await connectInMemory(shared);
|
|
138
144
|
}
|
|
139
|
-
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
140
147
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
148
|
+
// We'll have to use a dedicated worker directly.
|
|
149
|
+
dedicated = this.#openWorker(false);
|
|
150
|
+
const features = await dedicated.source.dedicatedFeatureDetection();
|
|
151
|
+
if (features.opfs || !fallbackToMemory) {
|
|
152
|
+
// See if we can at least use readwrite-unsafe, as that is more efficient than the fallback of closing and
|
|
153
|
+
// re-opening files on contention.
|
|
154
|
+
const simpleMode =
|
|
155
|
+
(this.options.simpleMode as SimpleOpfsMode | undefined) ?? (features.openWithMode ? 'rw-unsafe' : 'fallback');
|
|
146
156
|
|
|
147
|
-
|
|
157
|
+
return await connect(dedicated, { vfs: WASQLiteVFS.SimpleOpfsVFS, readonly: false, simpleMode });
|
|
158
|
+
}
|
|
148
159
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
160
|
+
return await connectInMemory(shared ?? dedicated);
|
|
161
|
+
} finally {
|
|
162
|
+
const usedWorker = used as OpenedWorker | null;
|
|
163
|
+
if (nested && usedWorker?.source !== nested) nested[Comlink.releaseProxy]();
|
|
164
|
+
if (shared && usedWorker?.connection !== shared.connection) closeWorker(shared);
|
|
165
|
+
if (dedicated && usedWorker !== dedicated) closeWorker(dedicated);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Asks a shared worker whether it can spawn nested workers with OPFS access, or returns null if that fails. */
|
|
170
|
+
async #detectNestedFeatures(shared: OpenedWorker): Promise<SharedFeatureDetectionResult | null> {
|
|
171
|
+
try {
|
|
172
|
+
return await shared.source.sharedFeatureDetection();
|
|
173
|
+
} catch (error) {
|
|
174
|
+
this.logger.log({ level: LogLevels.error, error, message: 'Could not detect features of shared worker' });
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Opens a database with a VFS that doesn't need feature detection, using a shared worker when the VFS and options
|
|
181
|
+
* allow that.
|
|
182
|
+
*/
|
|
183
|
+
async #openInWorker(options: ResolvedDatabaseOptions): Promise<DatabaseClient> {
|
|
184
|
+
const useShared = !vfsRequiresDedicatedWorkers(options.vfs) && this.options.enableMultiTabs;
|
|
185
|
+
return this.#connect(this.#openWorker(useShared), options);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Don't use a web worker. Instead, open the MultiDatabaseServer a worker would use locally.
|
|
190
|
+
*
|
|
191
|
+
* Without workers, the only storage the `'auto'` option can pick is an in-memory database.
|
|
192
|
+
*/
|
|
193
|
+
async #openInCurrentContext(): Promise<DatabaseClient> {
|
|
194
|
+
let vfs = this.options.vfs;
|
|
195
|
+
if (vfs == 'auto') {
|
|
196
|
+
this.logger.log({ level: LogLevels.warn, message: 'Using in-memory database because web workers are disabled.' });
|
|
197
|
+
vfs = WASQLiteVFS.InMemoryVfs;
|
|
198
|
+
}
|
|
199
|
+
const localServer = new MultiDatabaseServer(this.logger);
|
|
200
|
+
const connection = await localServer.openConnectionLocally(
|
|
201
|
+
this.logger,
|
|
202
|
+
this.#resolveRawWaSqliteDatabaseOptions({ vfs, readonly: false })
|
|
203
|
+
);
|
|
153
204
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
205
|
+
return new DatabaseClient(
|
|
206
|
+
{ connection, source: null, remoteCanCloseUnexpectedly: false },
|
|
207
|
+
{ ...this.options, vfs, requiresPersistentTriggers: true }
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async #connect(worker: OpenedWorker, options: ResolvedDatabaseOptions): Promise<DatabaseClient> {
|
|
212
|
+
const { source, connection: workerConnection } = worker;
|
|
213
|
+
const closeSignal = new AbortController();
|
|
214
|
+
const connection = await source.connect({
|
|
215
|
+
database: this.#resolveRawWaSqliteDatabaseOptions(options),
|
|
216
|
+
logLevel: this.options.databaseWorkerLogLevel,
|
|
217
|
+
lockName: await generateTabCloseSignal(closeSignal.signal)
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
return new DatabaseClient(
|
|
221
|
+
{
|
|
222
|
+
connection,
|
|
223
|
+
source,
|
|
224
|
+
// This tab owns the worker, so we're guaranteed to outlive it.
|
|
225
|
+
remoteCanCloseUnexpectedly: false,
|
|
226
|
+
onClose: () => {
|
|
227
|
+
closeSignal.abort();
|
|
228
|
+
workerConnection.close();
|
|
157
229
|
}
|
|
158
|
-
|
|
230
|
+
},
|
|
231
|
+
{
|
|
232
|
+
...this.options,
|
|
233
|
+
vfs: options.vfs,
|
|
234
|
+
requiresPersistentTriggers: vfsRequiresDedicatedWorkers(options.vfs)
|
|
159
235
|
}
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async #openSharedWorker(): Promise<OpenedWorker | null> {
|
|
240
|
+
const shared = this.#openWorker(true);
|
|
241
|
+
if (!isSharedWorker(shared.connection.worker)) {
|
|
242
|
+
// A custom worker factory might not respect the `shared` option, and dedicated workers can't share the
|
|
243
|
+
// database across tabs. Fall back to the modes relying on navigator locks.
|
|
244
|
+
closeWorker(shared);
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return shared;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
#openWorker(shared: boolean): OpenedWorker {
|
|
252
|
+
const optionsDbWorker = this.options.worker;
|
|
253
|
+
let connection: WorkerConnection;
|
|
254
|
+
|
|
255
|
+
if (typeof optionsDbWorker == 'function') {
|
|
256
|
+
const worker = optionsDbWorker({ ...this.options, shared });
|
|
257
|
+
connection = connectToExistingWorker(worker, this.logger, 'database');
|
|
160
258
|
} else {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
{
|
|
169
|
-
...this.options,
|
|
170
|
-
requiresPersistentTriggers
|
|
171
|
-
}
|
|
172
|
-
);
|
|
259
|
+
connection = connectToWorker({
|
|
260
|
+
service: 'database',
|
|
261
|
+
databaseIdentifier: this.options.dbFilename,
|
|
262
|
+
shared: shared,
|
|
263
|
+
customWorker: optionsDbWorker,
|
|
264
|
+
loggerForErrors: this.logger
|
|
265
|
+
});
|
|
173
266
|
}
|
|
174
267
|
|
|
268
|
+
return { connection, source: Comlink.wrap<OpenWorkerConnection>(connection.endpoint) };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
#resolveRawWaSqliteDatabaseOptions({
|
|
272
|
+
vfs,
|
|
273
|
+
readonly,
|
|
274
|
+
simpleMode
|
|
275
|
+
}: ResolvedDatabaseOptions): RawWaSqliteDatabaseOptions {
|
|
276
|
+
const {
|
|
277
|
+
dbFilename,
|
|
278
|
+
encryptionKey,
|
|
279
|
+
temporaryStorage,
|
|
280
|
+
cacheSizeKb,
|
|
281
|
+
preparedStatementsCache,
|
|
282
|
+
additionalInitializationFunctions,
|
|
283
|
+
storageBucket
|
|
284
|
+
} = this.options;
|
|
285
|
+
|
|
175
286
|
return {
|
|
176
|
-
|
|
177
|
-
|
|
287
|
+
filename: dbFilename,
|
|
288
|
+
readonly,
|
|
289
|
+
vfs,
|
|
290
|
+
encryptionKey,
|
|
291
|
+
temporaryStorage,
|
|
292
|
+
cacheSizeKb,
|
|
293
|
+
// TODO: Enable prepared statement cache by default?
|
|
294
|
+
preparedStatementsCache: preparedStatementsCache ?? 0,
|
|
295
|
+
additionalInitializationFunctions,
|
|
296
|
+
storageBucket,
|
|
297
|
+
simpleMode
|
|
178
298
|
};
|
|
179
299
|
}
|
|
180
300
|
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Options for a database connection after the `'auto'` VFS option and the {@link SimpleOpfsMode} have been
|
|
304
|
+
* resolved.
|
|
305
|
+
*/
|
|
306
|
+
interface ResolvedDatabaseOptions {
|
|
307
|
+
vfs: WASQLiteVFS;
|
|
308
|
+
readonly: boolean;
|
|
309
|
+
simpleMode?: SimpleOpfsMode;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* A worker we're connected to, but haven't necessarily opened a database in yet.
|
|
314
|
+
*/
|
|
315
|
+
interface OpenedWorker {
|
|
316
|
+
connection: WorkerConnection;
|
|
317
|
+
source: Comlink.Remote<OpenWorkerConnection>;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function closeWorker(worker: OpenedWorker) {
|
|
321
|
+
worker.source[Comlink.releaseProxy]();
|
|
322
|
+
worker.connection.close();
|
|
323
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type * as SQLite from '@journeyapps/wa-sqlite';
|
|
2
2
|
import { RawWaSqliteDatabaseOptions } from './RawSqliteConnection.js';
|
|
3
|
+
import type { WebSpecificOpenOptions } from '../options.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* List of currently tested virtual filesystems
|
|
@@ -25,13 +26,97 @@ export enum WASQLiteVFS {
|
|
|
25
26
|
* This VFS primarily intended for development, but it also useful for online-first deployments not syncing large
|
|
26
27
|
* amounts of data, as it is quicker to start up.
|
|
27
28
|
*/
|
|
28
|
-
InMemoryVfs = 'InMemoryVFS'
|
|
29
|
+
InMemoryVfs = 'InMemoryVFS',
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A simple OPFS-based virtual file system.
|
|
33
|
+
*
|
|
34
|
+
* This VFS uses a very simple internal design: Instead of opening files on demand (or with a prior pool), it uses the
|
|
35
|
+
* fact that that a SQLite database only consists of two files: The main database and a journal for recovery. These
|
|
36
|
+
* two file handles are pre-opened before the database is used, allowing all IO to be synchronous and to go directly
|
|
37
|
+
* to those files.
|
|
38
|
+
*
|
|
39
|
+
* It is worth noting that this design has fundamental drawbacks: It doesn't support `ATTACH`ing additional databases,
|
|
40
|
+
* and temporary data (e.g. for materialized CTEs) is always stored in memory. This is not relevant for most setups
|
|
41
|
+
* though, and not supporting this is what enables the simple design.
|
|
42
|
+
*
|
|
43
|
+
* Synchronous file handles in OPFS are only available in dedicated workers, and two tabs can't open the same file
|
|
44
|
+
* at the same time. To enable multi-tab support, this VFS comes in three possible configurations, the PowerSync SDK
|
|
45
|
+
* selects the best one based on browser features:
|
|
46
|
+
*
|
|
47
|
+
* 1. __Shared workers__: While we need dedicated workers to access files synchronously, the web standard allows
|
|
48
|
+
* shared workers to spawn their own dedicated workers. This is not supported by all browsers, but highly efficient
|
|
49
|
+
* option when available as we don't need to rely on navigator locks.
|
|
50
|
+
* 2. `readwrite-unsafe`: On Chromium browsers, this flag allows multiple tabs to access the same files (the PowerSync
|
|
51
|
+
* SDK additionally uses navigator locks to avoid corruption from concurrent writes).
|
|
52
|
+
* 3. Close and open fallback: On other browsers, file handles are kept open until another tab signals that it needs
|
|
53
|
+
* access to them. At that point, queued local transactions are awaited before closing the file handles. At the
|
|
54
|
+
* next database query, the same signal is sent to the other tab before re-opening files locally.
|
|
55
|
+
*/
|
|
56
|
+
SimpleOpfsVFS = 'SimpleOpfsVFS'
|
|
29
57
|
}
|
|
30
58
|
|
|
31
|
-
export function vfsRequiresDedicatedWorkers(vfs: WASQLiteVFS) {
|
|
59
|
+
export function vfsRequiresDedicatedWorkers(vfs: WASQLiteVFS | 'auto') {
|
|
60
|
+
if (vfs === 'auto') {
|
|
61
|
+
// Falls back to an in-memory database when workers aren't available.
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
|
|
32
65
|
return vfs != WASQLiteVFS.IDBBatchAtomicVFS && vfs != WASQLiteVFS.InMemoryVfs;
|
|
33
66
|
}
|
|
34
67
|
|
|
68
|
+
/**
|
|
69
|
+
* Whether the VFS can keep its files in a Storage Bucket, see {@link WebSpecificOpenOptions.storageBucket}.
|
|
70
|
+
*/
|
|
71
|
+
export function vfsSupportsStorageBuckets(vfs: WASQLiteVFS | 'auto') {
|
|
72
|
+
switch (vfs) {
|
|
73
|
+
case WASQLiteVFS.OPFSCoopSyncVFS:
|
|
74
|
+
case WASQLiteVFS.OPFSWriteAheadVFS:
|
|
75
|
+
case WASQLiteVFS.AccessHandlePoolVFS:
|
|
76
|
+
case WASQLiteVFS.SimpleOpfsVFS:
|
|
77
|
+
case 'auto': // auto mode can resolve to opfs, in which case it supports storage buckets
|
|
78
|
+
return true;
|
|
79
|
+
default:
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The part of the Storage Buckets API this module uses. The API is not in the TypeScript DOM library yet.
|
|
86
|
+
*/
|
|
87
|
+
export interface StorageBucketManagerLike {
|
|
88
|
+
open(name: string): Promise<{ getDirectory(): Promise<FileSystemDirectoryHandle> }>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Options for an OPFS-based VFS that keep its files in the named Storage Bucket, see
|
|
93
|
+
* {@link WebSpecificOpenOptions.storageBucket}. Without a bucket name, no options: the VFS uses the root of the
|
|
94
|
+
* origin private file system.
|
|
95
|
+
*
|
|
96
|
+
* @internal
|
|
97
|
+
*/
|
|
98
|
+
export function vfsOptionsForStorageBucket(
|
|
99
|
+
storageBucket: string | undefined,
|
|
100
|
+
storageBuckets: StorageBucketManagerLike | null | undefined = (navigator as any).storageBuckets
|
|
101
|
+
): { getRoot?: () => Promise<FileSystemDirectoryHandle>; prefix?: string } {
|
|
102
|
+
if (storageBucket == null) {
|
|
103
|
+
return {};
|
|
104
|
+
}
|
|
105
|
+
if (storageBuckets == null) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
`The 'storageBucket' option needs the Storage Buckets API (navigator.storageBuckets), which this browser does not have. Check for it before setting the option.`
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
// Called by the VFS each time it needs its root directory. Opening the bucket again creates it when the
|
|
112
|
+
// browser deleted it with the rest of the site's data.
|
|
113
|
+
getRoot: () => storageBuckets.open(storageBucket).then((bucket) => bucket.getDirectory()),
|
|
114
|
+
// Keeps the locks and channels of a file apart from those of a file of the same name in another bucket.
|
|
115
|
+
// Bucket names cannot contain ':', so the names of two buckets never overlap.
|
|
116
|
+
prefix: `${storageBucket}:`
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
35
120
|
/**
|
|
36
121
|
* @internal
|
|
37
122
|
*/
|
|
@@ -68,7 +153,9 @@ async function syncModuleFactory(encryptionKey: string | undefined): Promise<SQL
|
|
|
68
153
|
export async function loadModuleAndVfs({
|
|
69
154
|
vfs,
|
|
70
155
|
filename,
|
|
71
|
-
encryptionKey
|
|
156
|
+
encryptionKey,
|
|
157
|
+
storageBucket,
|
|
158
|
+
simpleMode
|
|
72
159
|
}: RawWaSqliteDatabaseOptions): Promise<{ module: SQLiteModule; vfs: SQLiteVFS }> {
|
|
73
160
|
let moduleFactory = syncModuleFactory;
|
|
74
161
|
let resolveVfs: (module: any) => Promise<SQLiteVFS>;
|
|
@@ -86,19 +173,33 @@ export async function loadModuleAndVfs({
|
|
|
86
173
|
case WASQLiteVFS.AccessHandlePoolVFS: {
|
|
87
174
|
// @ts-expect-error The types for this import are missing upstream
|
|
88
175
|
const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');
|
|
89
|
-
resolveVfs = (module) => AccessHandlePoolVFS.create(filename, module);
|
|
176
|
+
resolveVfs = (module) => AccessHandlePoolVFS.create(filename, module, vfsOptionsForStorageBucket(storageBucket));
|
|
90
177
|
break;
|
|
91
178
|
}
|
|
92
179
|
case WASQLiteVFS.OPFSCoopSyncVFS: {
|
|
93
180
|
// @ts-expect-error The types for this import are missing upstream
|
|
94
181
|
const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');
|
|
95
|
-
resolveVfs = (module) => OPFSCoopSyncVFS.create(filename, module);
|
|
182
|
+
resolveVfs = (module) => OPFSCoopSyncVFS.create(filename, module, vfsOptionsForStorageBucket(storageBucket));
|
|
96
183
|
break;
|
|
97
184
|
}
|
|
98
185
|
case WASQLiteVFS.OPFSWriteAheadVFS: {
|
|
99
186
|
// @ts-expect-error The types for this import are missing upstream
|
|
100
187
|
const { OPFSWriteAheadVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSWriteAheadVFS.js');
|
|
101
|
-
resolveVfs = (module) => OPFSWriteAheadVFS.create(filename, module,
|
|
188
|
+
resolveVfs = (module) => OPFSWriteAheadVFS.create(filename, module, vfsOptionsForStorageBucket(storageBucket));
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
case WASQLiteVFS.SimpleOpfsVFS: {
|
|
192
|
+
const { SimpleOpfsFileSystem } = await import('./SimpleOpfsFileSystem.js');
|
|
193
|
+
|
|
194
|
+
const getRoot = vfsOptionsForStorageBucket(storageBucket).getRoot;
|
|
195
|
+
const resolver = SimpleOpfsFileSystem.directoryResolver(filename, simpleMode === 'rw-unsafe', getRoot);
|
|
196
|
+
|
|
197
|
+
// @ts-expect-error It conforms to SQLiteVFS, but an intermediate type is missing so tsc can't know
|
|
198
|
+
resolveVfs = async (module) => {
|
|
199
|
+
const vfs = new SimpleOpfsFileSystem(filename, module, resolver);
|
|
200
|
+
await vfs.open();
|
|
201
|
+
return vfs;
|
|
202
|
+
};
|
|
102
203
|
break;
|
|
103
204
|
}
|
|
104
205
|
case WASQLiteVFS.InMemoryVfs: {
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
WebStreamingSyncImplementation,
|
|
9
9
|
WebStreamingSyncImplementationOptions
|
|
10
10
|
} from './WebStreamingSyncImplementation.js';
|
|
11
|
-
import { generateTabCloseSignal } from '../../shared/
|
|
11
|
+
import { generateTabCloseSignal } from '../../shared/locks.js';
|
|
12
12
|
import {
|
|
13
13
|
SubscribedStream,
|
|
14
14
|
SyncStatusJson,
|
|
@@ -74,11 +74,13 @@ class SharedSyncClientProvider extends AbstractSharedSyncClientProvider {
|
|
|
74
74
|
* Don't return anything here, just incase something which is not
|
|
75
75
|
* serializable is returned from the `uploadCrud` function.
|
|
76
76
|
*/
|
|
77
|
-
await this.#relay(() => this.options.uploadCrud());
|
|
77
|
+
await this.#relay(() => this.options.connector.uploadCrud!());
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
override async postCheckpointRequest(clientId: string, requestId: string): Promise<string | null> {
|
|
81
|
-
return await this.#relay(
|
|
81
|
+
return await this.#relay(
|
|
82
|
+
async () => (await this.options.connector.postCheckpointRequest!(clientId, requestId)) ?? null
|
|
83
|
+
);
|
|
82
84
|
}
|
|
83
85
|
|
|
84
86
|
get logger() {
|
|
@@ -177,10 +179,14 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
|
|
|
177
179
|
* - The client sends the params to the shared worker after locks have been registered.
|
|
178
180
|
*/
|
|
179
181
|
const closeSignal = await generateTabCloseSignal(this.abortOnClose.signal);
|
|
180
|
-
|
|
181
|
-
await this.syncManager.addLockBasedCloseSignal(closeSignal);
|
|
182
|
+
const { identifier, connector } = this.options;
|
|
182
183
|
|
|
183
|
-
|
|
184
|
+
// Awaiting here ensures the worker is waiting for the lock
|
|
185
|
+
await this.syncManager.initialize(closeSignal, {
|
|
186
|
+
hasFetchCredentials: !!connector.fetchCredentials,
|
|
187
|
+
hasPostCheckpointRequest: !!connector.postCheckpointRequest,
|
|
188
|
+
hasUploadCrud: !!connector.uploadCrud
|
|
189
|
+
});
|
|
184
190
|
|
|
185
191
|
await this.syncManager.setParams(
|
|
186
192
|
{
|
|
@@ -210,9 +216,30 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
|
|
|
210
216
|
}
|
|
211
217
|
|
|
212
218
|
async dispose(): Promise<void> {
|
|
213
|
-
|
|
219
|
+
let registeredWithWorker = true;
|
|
220
|
+
try {
|
|
221
|
+
await this.waitForReady();
|
|
222
|
+
} catch {
|
|
223
|
+
// The worker rejected this client (e.g. because it connects in a mode incompatible with other tabs), so it won't
|
|
224
|
+
// acknowledge a close request either.
|
|
225
|
+
registeredWithWorker = false;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (registeredWithWorker) {
|
|
229
|
+
await this.#closeWorkerClient();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
await super.dispose();
|
|
233
|
+
|
|
234
|
+
this.abortOnClose.abort();
|
|
214
235
|
|
|
215
|
-
|
|
236
|
+
// Release the proxy
|
|
237
|
+
this.syncManager[Comlink.releaseProxy]();
|
|
238
|
+
this.worker.close();
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
#closeWorkerClient() {
|
|
242
|
+
return new Promise<void>((resolve) => {
|
|
216
243
|
// This will always be a message port since we use shared workers.
|
|
217
244
|
const messagePort = this.worker.endpoint as MessagePort;
|
|
218
245
|
|
|
@@ -231,14 +258,6 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
|
|
|
231
258
|
};
|
|
232
259
|
messagePort.postMessage(closeMessagePayload);
|
|
233
260
|
});
|
|
234
|
-
|
|
235
|
-
await super.dispose();
|
|
236
|
-
|
|
237
|
-
this.abortOnClose.abort();
|
|
238
|
-
|
|
239
|
-
// Release the proxy
|
|
240
|
-
this.syncManager[Comlink.releaseProxy]();
|
|
241
|
-
this.worker.close();
|
|
242
261
|
}
|
|
243
262
|
|
|
244
263
|
async waitForReady() {
|
package/src/db/sync/WebRemote.ts
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
import { LogLevels, PowerSyncLogger } from '@powersync/common';
|
|
2
|
-
import { AbstractRemote, FetchOptions,
|
|
2
|
+
import { AbstractRemote, FetchOptions, InternalConnector } from '@powersync/shared-internals';
|
|
3
3
|
|
|
4
4
|
import { getUserAgentInfo } from './userAgent.js';
|
|
5
5
|
import type { WebSocketSyncStreamPlatform, WebSocketSupport } from '@powersync/shared-internals/websockets';
|
|
6
6
|
|
|
7
7
|
export class WebRemote extends AbstractRemote {
|
|
8
|
-
constructor(
|
|
9
|
-
protected connector: RemoteConnector,
|
|
10
|
-
logger: PowerSyncLogger
|
|
11
|
-
) {
|
|
8
|
+
constructor(connector: InternalConnector, logger: PowerSyncLogger) {
|
|
12
9
|
super(connector, logger);
|
|
13
10
|
}
|
|
14
11
|
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
LockOptions,
|
|
7
7
|
LockType
|
|
8
8
|
} from '@powersync/shared-internals';
|
|
9
|
-
import { getNavigatorLocks } from '../../shared/
|
|
9
|
+
import { getNavigatorLocks } from '../../shared/locks.js';
|
|
10
10
|
|
|
11
11
|
export interface WebStreamingSyncImplementationOptions extends AbstractStreamingSyncImplementationOptions {
|
|
12
12
|
sync?: {
|