@evolu/web 3.4.1 → 3.5.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/src/Sqlite.ts CHANGED
@@ -1,175 +1,155 @@
1
- import type { CreateSqliteDriver, SqliteRow } from "@evolu/common";
1
+ /**
2
+ * The SQLite driver of Evolu for the web, on `@evolu/sqlite-wasm`.
3
+ *
4
+ * @module
5
+ */
6
+
2
7
  import {
3
- bytesToHex,
4
8
  createPreparedStatementsCache,
9
+ err,
5
10
  exhaustiveCheck,
6
11
  ok,
7
- performanceDurationBetween,
8
- PositiveMillis,
9
- sleep,
10
- tryAsync,
12
+ type CreateSqliteDriver,
13
+ type DatabaseHeldError,
14
+ type Name,
15
+ type Result,
16
+ type SqliteDriver,
17
+ type Task,
18
+ type Typed,
19
+ type TypeName,
11
20
  } from "@evolu/common";
12
- import sqlite3InitModule, {
13
- type Database,
14
- type PreparedStatement,
15
- type SAHPoolUtil,
21
+ import type { WaitForDatabaseRelease } from "@evolu/common/local-first";
22
+ import {
23
+ createEncryptedSqliteDatabase,
24
+ createSqliteDatabase,
25
+ createSqliteWasm,
26
+ OpfsName,
27
+ openSahPool,
28
+ sqliteWasmUrl,
29
+ SqliteVfsPath,
30
+ type deriveLegacySqliteKey,
31
+ type OpfsRootDep,
32
+ type SahPool,
33
+ type SahPoolError,
34
+ type SahPoolOptions,
35
+ type SqliteDatabase,
36
+ type SqliteError,
37
+ type SqliteStatement,
38
+ type SqliteWasm,
39
+ type SqliteWasmDep,
40
+ type SqliteWasmError,
41
+ type SubtleCryptoDep,
16
42
  } from "@evolu/sqlite-wasm";
17
43
 
18
- // @ts-expect-error Missing types.
19
- globalThis.sqlite3ApiConfig = {
20
- warn: (arg: unknown) => {
21
- // Ignore irrelevant warning.
22
- // https://github.com/sqlite/sqlite-wasm/issues/62
23
- if (
24
- typeof arg === "string" &&
25
- arg.startsWith("Ignoring inability to install OPFS sqlite3_vfs")
26
- )
27
- return;
28
- // oxlint-disable-next-line eslint/no-console
29
- console.warn(arg);
30
- },
31
- };
32
-
33
- // Init ASAP.
34
- const sqlite3Promise = sqlite3InitModule();
35
-
36
- const fileName = "evolu1.db";
37
-
38
- export const createWasmSqliteDriver: CreateSqliteDriver =
39
- (name, options) => async (run) => {
40
- const sqlite3 = await sqlite3Promise;
41
-
42
- using disposer = new DisposableStack();
43
- const useDatabase = (database: Database): Database =>
44
- disposer.adopt(database, (database) => {
45
- database.close();
46
- });
44
+ /**
45
+ * Loads SQLite from the {@link sqliteWasmUrl} of `@evolu/sqlite-wasm` for
46
+ * {@link createWasmSqliteDriver}. It passes the fetch to
47
+ * {@link createSqliteWasm}, which compiles the binary while it downloads when
48
+ * the server sends it as `application/wasm`, and from its bytes otherwise.
49
+ *
50
+ * Start it in the worker's composition root, so SQLite loads while the worker
51
+ * waits for its database.
52
+ */
53
+ export const loadSqliteWasm: Task<SqliteWasm, SqliteWasmError> = (run) =>
54
+ run(createSqliteWasm(run.deps.nativeFetch(sqliteWasmUrl)), run.deps);
55
+
56
+ /**
57
+ * Creates the {@link CreateSqliteDriver} of Evolu for the web.
58
+ *
59
+ * A database is the file `/evolu1.db` in a pool of OPFS sync access handles in
60
+ * the directory `.<name>`, in the format of SQLite's opfs-sahpool, and the pool
61
+ * encrypts it in the `encrypted` mode. So the databases `@evolu/web` 3 created
62
+ * with `@evolu/sqlite-wasm` 2.2.4 open unchanged, an encrypted one with the key
63
+ * 2.2.4 derived from the encryption key, which is never rekeyed. 2.2.4 derived
64
+ * it because of a bug in SQLite3 Multiple Ciphers: it took the encryption key,
65
+ * passed in SQLCipher's notation for a raw key, as a passphrase
66
+ * (https://github.com/utelle/SQLite3MultipleCiphers/issues/218), as
67
+ * {@link deriveLegacySqliteKey} of `@evolu/sqlite-wasm` describes. A new
68
+ * encrypted database is encrypted with the encryption key itself, so
69
+ * `@evolu/web` 3.4.1 and earlier cannot open it. A database in the `memory`
70
+ * mode uses no OPFS.
71
+ *
72
+ * In WebKit on macOS, such as Safari, whose file system ignores case by
73
+ * default, names that differ only in case share the directory, and both can
74
+ * hold it at once, so make database names differ in more than case.
75
+ *
76
+ * The pool is opened once, so the driver throws while another context holds a
77
+ * file of it. A DbWorker waits for the files with
78
+ * {@link createWaitForDatabaseRelease} first.
79
+ *
80
+ * The {@link SqliteDriver} contract has no error channel, so every error, such
81
+ * as a query's {@link SqliteError}, is thrown as the cause of an `Error` whose
82
+ * message is SQLite's message, or the error's type for an error without one.
83
+ */
84
+ export const createWasmSqliteDriver =
85
+ (deps: WasmSqliteDriverDeps): CreateSqliteDriver =>
86
+ (name, options) =>
87
+ async (run) => {
88
+ const sqliteWasm = getOrThrowWithMessage(await deps.sqliteWasmLoad);
89
+ const databaseDeps = { ...deps, sqliteWasm };
47
90
 
48
91
  let deleteDatabaseFile = false;
49
- const createOpfsSAHPoolVfs = async (
50
- options: Parameters<typeof sqlite3.installOpfsSAHPoolVfs>[0],
51
- ): Promise<SAHPoolUtil> => {
52
- // Evolu opens a database only while it holds the database lock, but a
53
- // DbWorker that ended without closing it, because its tab closed,
54
- // crashed or navigated away, can hold pool files after the lock has
55
- // passed on: WebKit releases a terminated worker's locks and its files
56
- // separately, in no set order
57
- // (https://bugs.webkit.org/show_bug.cgi?id=301520). sqlite-wasm cannot
58
- // set up a pool with a held file, and it then deletes the pool
59
- // directory, which the held file usually but not always prevents. Only
60
- // a worker that has ended can hold
61
- // the files, and it can only release them, so the pool is set up once
62
- // every file opens.
63
- const canOpenPoolFiles = async (): Promise<boolean> => {
64
- const root = await navigator.storage.getDirectory();
65
- // sqlite-wasm keeps the pool in `.${name}/.opaque` in both OPFS modes.
66
- const poolDirectory = await tryAsync(() =>
67
- root.getDirectoryHandle(`.${name}`),
68
- );
69
- if (!poolDirectory.ok) return true;
70
- const opaqueDirectory = await tryAsync(() =>
71
- poolDirectory.value.getDirectoryHandle(".opaque"),
72
- );
73
- if (!opaqueDirectory.ok) return true;
74
- for await (const handle of opaqueDirectory.value.values()) {
75
- if (handle.kind !== "file") continue;
76
- const accessHandle = await tryAsync(() =>
77
- handle.createSyncAccessHandle(),
78
- );
79
- if (!accessHandle.ok) {
80
- // WebKit rejects a held file with InvalidStateError, other
81
- // engines with NoModificationAllowedError, as the spec says
82
- // (https://bugs.webkit.org/show_bug.cgi?id=326135).
83
- // WebKit also uses InvalidStateError for a closed or invalid
84
- // handle and a stopped context. A retry opens fresh handles from
85
- // a new listing, and a stopped context ends the loop with its
86
- // worker, so retrying those is harmless.
87
- if (
88
- accessHandle.error instanceof DOMException &&
89
- (accessHandle.error.name === "InvalidStateError" ||
90
- accessHandle.error.name === "NoModificationAllowedError")
91
- )
92
- return false;
93
- throw accessHandle.error;
94
- }
95
- accessHandle.value.close();
96
- }
97
- return true;
98
- };
99
-
100
- const waitStart = run.deps.time.performance.now();
101
- let retryDelay = 50;
102
- let isWaitReported = false;
103
- while (!(await canOpenPoolFiles())) {
104
- const waited = performanceDurationBetween(
105
- waitStart,
106
- run.deps.time.performance.now(),
107
- );
108
- if (!isWaitReported && waited >= 5000) {
109
- isWaitReported = true;
110
- run.deps.console.warn(
111
- `Waiting for an ended DbWorker to release the files of database ${name}.`,
112
- );
113
- }
114
- await run.ok(sleep(PositiveMillis.orThrow(retryDelay)));
115
- retryDelay = Math.min(retryDelay * 2, 1000);
116
- }
92
+ using disposer = new DisposableStack();
117
93
 
118
- const pool = await sqlite3.installOpfsSAHPoolVfs(options);
119
- if (pool.isPaused()) await pool.unpauseVfs();
94
+ const openPool = async (): Promise<SahPool> => {
95
+ const pool = disposer.use(
96
+ getOrThrowWithMessage(await run(openDatabasePool(name), databaseDeps)),
97
+ );
120
98
  disposer.defer(() => {
121
- if (deleteDatabaseFile) pool.unlink(`/${fileName}`);
122
- pool.pauseVfs();
99
+ if (deleteDatabaseFile)
100
+ getOrThrowWithMessage(pool.unlink(databasePath));
123
101
  });
124
102
  return pool;
125
103
  };
126
104
 
127
- let db: Database;
105
+ let database: SqliteDatabase;
128
106
 
129
107
  switch (options?.mode) {
130
108
  case "memory":
131
- // oxlint-disable-next-line react/rules-of-hooks -- useDatabase registers disposal and is not a React Hook.
132
- db = useDatabase(new sqlite3.oo1.DB(":memory:"));
109
+ database = disposer.use(
110
+ getOrThrowWithMessage(
111
+ createSqliteDatabase(databaseDeps)({ type: "Memory" }),
112
+ ),
113
+ );
133
114
  break;
134
115
 
135
116
  case "encrypted": {
136
- // MultipleCiphers encryption requires its VFS wrapper for OPFS SAH-pool.
137
- // @ts-expect-error Missing types (update @evolu/sqlite-wasm types)
138
- // oxlint-disable-next-line typescript/no-unsafe-call
139
- sqlite3.capi.sqlite3mc_vfs_create("opfs", 1);
140
- const pool = await createOpfsSAHPoolVfs({
141
- directory: `.${name}`,
142
- });
143
- // oxlint-disable-next-line react/rules-of-hooks -- useDatabase registers disposal and is not a React Hook.
144
- db = useDatabase(
145
- new pool.OpfsSAHPoolDb(
146
- // SQLite normalizes this URI filename to SAH-pool path "/evolu1.db".
147
- `file:${fileName}?vfs=multipleciphers-opfs-sahpool`,
117
+ const encrypted = getOrThrowWithMessage(
118
+ await run(
119
+ createEncryptedSqliteDatabase({
120
+ type: "EncryptedFile",
121
+ vfs: await openPool(),
122
+ path: databasePath,
123
+ key: options.encryptionKey,
124
+ }),
125
+ databaseDeps,
148
126
  ),
149
127
  );
150
- db.exec(`
151
- PRAGMA cipher = 'sqlcipher';
152
- PRAGMA key = "x'${bytesToHex(options.encryptionKey)}'";
153
- `);
128
+ database = disposer.use(encrypted.database);
154
129
  break;
155
130
  }
156
131
 
157
- case undefined: {
158
- const pool = await createOpfsSAHPoolVfs({ name });
159
- // oxlint-disable-next-line react/rules-of-hooks -- useDatabase registers disposal and is not a React Hook.
160
- db = useDatabase(new pool.OpfsSAHPoolDb(`file:${fileName}`));
132
+ case undefined:
133
+ database = disposer.use(
134
+ getOrThrowWithMessage(
135
+ createSqliteDatabase(databaseDeps)({
136
+ type: "File",
137
+ vfs: await openPool(),
138
+ path: databasePath,
139
+ }),
140
+ ),
141
+ );
161
142
  break;
162
- }
163
143
 
164
144
  default:
165
145
  exhaustiveCheck(options);
166
146
  }
167
147
 
168
148
  const cache = disposer.use(
169
- createPreparedStatementsCache<PreparedStatement>(
170
- (sql) => db.prepare(sql),
149
+ createPreparedStatementsCache<SqliteStatement>(
150
+ (sql) => getOrThrowWithMessage(database.prepare(sql)),
171
151
  (statement) => {
172
- statement.finalize();
152
+ statement[Symbol.dispose]();
173
153
  },
174
154
  ),
175
155
  );
@@ -178,41 +158,15 @@ export const createWasmSqliteDriver: CreateSqliteDriver =
178
158
 
179
159
  return ok({
180
160
  exec: (query) => {
181
- const prepared = cache.get(query);
182
-
183
- if (prepared) {
184
- try {
185
- if (query.parameters.length > 0) prepared.bind(query.parameters);
186
-
187
- const rows = [];
188
- while (prepared.step()) {
189
- rows.push(prepared.get({}));
190
- }
191
-
192
- return {
193
- rows: rows as ReadonlyArray<SqliteRow>,
194
- changes: db.changes(),
195
- };
196
- } finally {
197
- // SQLite refuses to bind a statement whose step failed until it is
198
- // reset. That reset returns the step's error again, which
199
- // PreparedStatement.reset would throw over the original one.
200
- sqlite3.capi.sqlite3_reset(prepared);
201
- }
202
- }
203
-
204
- const rows = db.exec(query.sql, {
205
- returnValue: "resultRows",
206
- rowMode: "object",
207
- bind: query.parameters,
208
- }) as ReadonlyArray<SqliteRow>;
209
-
210
- const changes = db.changes();
211
-
212
- return { rows, changes };
161
+ const statement = cache.get(query);
162
+ return getOrThrowWithMessage(
163
+ statement
164
+ ? statement.run(query.parameters)
165
+ : database.run(query.sql, query.parameters),
166
+ );
213
167
  },
214
168
 
215
- export: () => sqlite3.capi.sqlite3_js_db_export(db),
169
+ export: () => getOrThrowWithMessage(database.export()),
216
170
 
217
171
  deleteDatabase: () => {
218
172
  deleteDatabaseFile = true;
@@ -224,3 +178,73 @@ export const createWasmSqliteDriver: CreateSqliteDriver =
224
178
  },
225
179
  });
226
180
  };
181
+
182
+ /** Dependencies of {@link createWasmSqliteDriver}. */
183
+ export type WasmSqliteDriverDeps = OpfsRootDep &
184
+ SqliteWasmLoadDep &
185
+ SubtleCryptoDep;
186
+
187
+ /** Dependency wrapper for SQLite as {@link loadSqliteWasm} loads it. */
188
+ export interface SqliteWasmLoadDep {
189
+ /**
190
+ * SQLite, as {@link loadSqliteWasm} loads it, still loading or loaded. A
191
+ * failed load throws when a database is opened.
192
+ */
193
+ readonly sqliteWasmLoad: PromiseLike<Result<SqliteWasm, SqliteWasmError>>;
194
+ }
195
+
196
+ /**
197
+ * Creates the {@link WaitForDatabaseRelease} of Evolu for the web. It opens the
198
+ * pool {@link createWasmSqliteDriver} opens for the database, and disposes it
199
+ * once it opens.
200
+ *
201
+ * When another context holds a file of the pool, the pool is opened again after
202
+ * 50 ms, then after twice the previous delay, up to a second, with the
203
+ * `heldTimeout` option of {@link openSahPool}, and the wait fails with
204
+ * {@link DatabaseHeldError} when it is still held 10 seconds after the first
205
+ * attempt started. Evolu then refuses to start the database, and the app
206
+ * receives the error as its `evoluError`. Every other error is thrown, as the
207
+ * driver throws it.
208
+ */
209
+ export const createWaitForDatabaseRelease =
210
+ (deps: OpfsRootDep & SqliteWasmLoadDep): WaitForDatabaseRelease =>
211
+ (name) =>
212
+ async (run) => {
213
+ const sqliteWasm = getOrThrowWithMessage(await deps.sqliteWasmLoad);
214
+ const opened = await run(
215
+ // Longer than the two seconds Chromium gives a terminated worker.
216
+ openDatabasePool(name, { heldTimeout: "10s" }),
217
+ { ...deps, sqliteWasm },
218
+ );
219
+ if (!opened.ok && opened.error.type === "SahPoolHeldError")
220
+ return err({ type: "DatabaseHeldError", name });
221
+ using _pool = getOrThrowWithMessage(opened);
222
+ return ok();
223
+ };
224
+
225
+ // The pool of a database's file is in the directory `.<name>`, as in
226
+ // @evolu/web 3.
227
+ const openDatabasePool = (
228
+ name: Name,
229
+ options?: Pick<SahPoolOptions, "heldTimeout">,
230
+ ): Task<SahPool, SahPoolError, OpfsRootDep & SqliteWasmDep> =>
231
+ // A Name is non-empty and URL-safe, so `.<name>` always passes.
232
+ openSahPool({ ...options, directory: [OpfsName.orThrow(`.${name}`)] });
233
+
234
+ // The path SQLite's opfs-sahpool gave `file:evolu1.db`, which @evolu/web 3
235
+ // opened.
236
+ const databasePath = /*#__PURE__*/ SqliteVfsPath.orThrow("/evolu1.db");
237
+
238
+ // The SqliteDriver contract has no error channel, and the WaitForDatabaseRelease
239
+ // contract only DatabaseHeldError, so any other error is thrown as the cause of
240
+ // an Error, with SQLite's message when it has one.
241
+ const getOrThrowWithMessage = <T>(result: Result<T, Typed<TypeName>>): T => {
242
+ if (result.ok) return result.value;
243
+ const { error } = result;
244
+ throw new Error(
245
+ "message" in error && typeof error.message === "string"
246
+ ? error.message
247
+ : error.type,
248
+ { cause: error },
249
+ );
250
+ };
@@ -6,15 +6,29 @@ installPolyfills();
6
6
 
7
7
  import { createRandomBytes } from "@evolu/common";
8
8
  import { startDbWorker } from "@evolu/common/local-first";
9
- import { createWasmSqliteDriver } from "../Sqlite.ts";
9
+ import {
10
+ createWaitForDatabaseRelease,
11
+ createWasmSqliteDriver,
12
+ loadSqliteWasm,
13
+ } from "../Sqlite.ts";
10
14
  import { createRun } from "../Task.ts";
11
15
  import { createWorkerDeps, createWorkerSelf } from "../Worker.ts";
12
16
 
13
17
  const run = createRun({
14
18
  ...createWorkerDeps(),
15
- createSqliteDriver: createWasmSqliteDriver,
16
19
  lockManager: navigator.locks,
17
20
  randomBytes: createRandomBytes(),
18
21
  });
19
22
 
20
- void run(startDbWorker(createWorkerSelf(self)));
23
+ const sqliteDeps = {
24
+ opfsRoot: navigator.storage,
25
+ // SQLite loads while the DbWorker waits for its database.
26
+ sqliteWasmLoad: run(loadSqliteWasm),
27
+ subtleCrypto: crypto.subtle,
28
+ };
29
+
30
+ void run(startDbWorker(createWorkerSelf(self)), {
31
+ ...run.deps,
32
+ createSqliteDriver: createWasmSqliteDriver(sqliteDeps),
33
+ waitForDatabaseRelease: createWaitForDatabaseRelease(sqliteDeps),
34
+ });