sqliteWebOpener function

OpenDatabase sqliteWebOpener({
  1. required Uri sqlite3Wasm,
  2. Uri? opfsWorker,
  3. String storagePrefix = 'cloud_firestore_dart',
  4. Duration lockTimeout = const Duration(seconds: 2),
  5. bool acceptIndexedDbWriteLoss = false,
})

Returns an OpenDatabase that keeps each database in IndexedDB, or in the origin private file system (OPFS) when opfsWorker is given and the browser supports it.

sqlite3Wasm is the URL of the sqlite3.wasm file of the sqlite3 package version in use; it is fetched on the first open. storagePrefix names the IndexedDB databases and OPFS directories (<prefix>/<database name>) and the Web Locks. lockTimeout is how long an open waits for a database that is open elsewhere before it fails: long enough for the page that was just reloaded to be gone, short for a second tab.

opfsWorker is the URL of sqlite_opfs_worker.dart compiled to JavaScript (dart run cloud_firestore_dart_sqlite:setup_web compiles it). With it the database is a file in OPFS that SQLite reads from as it needs, in that dedicated worker, instead of a copy of the whole database in memory (SqliteOpfsDatabase). In a browser without synchronous OPFS access in workers the opener uses IndexedDB as without it (SqliteWebDatabase). The first OPFS open of a cache that exists in IndexedDB only moves it to OPFS, pending writes included.

Before the first IndexedDB open of the page the opener checks that the resolved sqlite3 package can store what a write acknowledged: with 3.4.0 to 3.5.2 it can not, and the open fails with a SqliteWebSetupException (SqliteWebSetupProblem.unsafeSqlite3) unless acceptIndexedDbWriteLoss is true. A sqlite3Wasm that is missing, or the build of another sqlite3 version, fails the open with a SqliteWebSetupException that says so.

Implementation

OpenDatabase sqliteWebOpener({
  required Uri sqlite3Wasm,
  Uri? opfsWorker,
  String storagePrefix = 'cloud_firestore_dart',
  Duration lockTimeout = const Duration(seconds: 2),
  bool acceptIndexedDbWriteLoss = false,
}) {
  Future<sqlite.WasmSqlite3>? loading;

  return (
    String name, {
    int? version,
    OnConfigure? onConfigure,
    OnCreate? onCreate,
    OnVersionChange? onUpgrade,
    OnVersionChange? onDowngrade,
    OnOpen? onOpen,
  }) async {
    final String storageName = '$storagePrefix/$name';

    // `close()` cannot be awaited by its caller. A database of this page that
    // is still being closed (`terminate()` followed by a new instance) is
    // waited for instead of being reported as open.
    await _closing[storageName];

    // One open database per name, in this tab and in every other.
    final Future<void> Function()? releaseLock = await _tryLock(
      storageName,
      lockTimeout,
    );
    if (releaseLock == null) {
      throw FirestoreException(
        message:
            'The offline cache "$name" is already open in another tab (or in this '
            'one). It can only be used by one tab at a time: use a memory cache '
            'in this tab.',
        errorCode: FirestoreErrorCode.failedPrecondition,
      );
    }

    if (opfsWorker != null) {
      final SqliteOpfsDatabase? opened;
      try {
        opened = await _openOpfs(
          worker: Uri.base.resolveUri(opfsWorker),
          sqlite3Wasm: Uri.base.resolveUri(sqlite3Wasm),
          storageName: storageName,
          releaseLock: releaseLock,
          // The Web Lock keeps other tabs out, so files that are still busy
          // belong to the worker of a page that is gone: the browser ends it
          // a moment later, usually well within a second, rarely after more
          // than two (seen in test/browser/web_persistence_crash_test.dart).
          handleTimeout: _opfsHandleTimeout,
          version: version,
          onConfigure: onConfigure,
          onCreate: onCreate,
          onUpgrade: onUpgrade,
          onDowngrade: onDowngrade,
          onOpen: onOpen,
        );
      } catch (_) {
        await releaseLock();
        rethrow;
      }
      if (opened != null) {
        return opened;
      }
      // No synchronous OPFS access in this browser: IndexedDB, as without a
      // worker. The lock is still held.
    }

    sqlite.IndexedDbFileSystem? fileSystem;
    sqlite.VirtualFileSystem? registered;
    sqlite.WasmSqlite3? sqlite3;
    SqliteWebDatabase? db;
    try {
      // A failed download is tried again on the next open.
      sqlite3 = await (loading ??= sqlite.WasmSqlite3.loadFromUrl(sqlite3Wasm)
          .onError<Object>((Object error, StackTrace stackTrace) async {
            loading = null;
            final SqliteWebSetupException? explained = await explainWasmFailure(
              Uri.base.resolveUri(sqlite3Wasm),
              error,
            );
            Error.throwWithStackTrace(explained ?? error, stackTrace);
          }));

      // sqlite3 3.4.0 to 3.5.2 can not keep what was acknowledged.
      if (!acceptIndexedDbWriteLoss) {
        await checkIndexedDbFlush(storagePrefix: storagePrefix);
      }

      // Reads the database into memory. A file system of its own per open
      // database, registered under a name of its own.
      fileSystem = await sqlite.IndexedDbFileSystem.open(
        dbName: storageName,
        vfsName: 'indexeddb-${_fileSystems++}',
      );
      registered = _ReadCopyFileSystem(fileSystem);
      sqlite3.registerVirtualFileSystem(registered);

      const String file = '/database';
      db = SqliteWebDatabase._(
        sqlite3.open(file, vfs: registered.name),
        sqlite3,
        fileSystem,
        registered,
        storageName,
        releaseLock,
      );

      // Keep every changed page in memory until its transaction commits.
      // SQLite would otherwise write pages of a large transaction to the
      // database file early, and the IndexedDB file system may store such a
      // page before the journal record that can undo it (it merges queued
      // writes to the same file), which a tab that dies at that moment could
      // not recover from.
      db._database.execute('PRAGMA cache_spill = OFF');

      // The callbacks run Firestore's schema setup and migrations. They must
      // be called in this order and awaited before the database is returned.
      await onConfigure?.call(db);

      // The setup and the schema version it leads to are one transaction (as
      // in Android's SQLiteOpenHelper): a tab that is closed while a new
      // cache is being created, or upgraded, leaves the old state behind and
      // the next open starts over, instead of finding half of the tables. A
      // database without any table is new, whatever was stored of it.
      final int wanted = version ?? 1;
      db._database.execute('BEGIN IMMEDIATE');
      try {
        final int current = db._database.userVersion;
        final bool isNew =
            current == 0 &&
            db._database.select('SELECT 1 FROM sqlite_master LIMIT 1').isEmpty;
        if (isNew) {
          await onCreate?.call(db, wanted);
        } else if (current < wanted) {
          await onUpgrade?.call(db, current, wanted);
        } else if (current > wanted) {
          await onDowngrade?.call(db, current, wanted);
        }
        // The schema version is kept in `PRAGMA user_version`.
        db._database.userVersion = wanted;
        db._database.execute('COMMIT');
      } catch (_) {
        if (!db._database.autocommit) {
          db._database.execute('ROLLBACK');
        }
        rethrow;
      }
      await flushAll(fileSystem);

      await onOpen?.call(db);
      return db;
    } catch (_) {
      if (db != null) {
        db.close();
      } else {
        if (registered != null) {
          sqlite3?.unregisterVirtualFileSystem(registered);
        }
        await fileSystem?.close();
        await releaseLock();
      }
      rethrow;
    }
  };
}