All files / kernel-store/src/sqlite wasm.ts

97.97% Statements 145/148
89.47% Branches 34/38
100% Functions 24/24
97.95% Lines 144/147

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408                                                          43x     43x 42x     42x   1x 1x     43x 43x 43x   43x                     43x   43x                   4x 4x 2x 2x 1x 1x 1x     3x 3x 1x   2x     43x                     3x 3x 2x 2x 1x 1x 1x     2x 2x     43x                 1x 1x 1x 1x     43x               1x 1x 1x 1x     43x 3x   1x                                         43x   43x 43x   43x   43x 43x 43x 43x 43x 43x 43x 43x 43x               13x 5x   8x 8x 8x 8x             4x 4x 4x 4x               2x 2x 2x 2x 2x                   3x 3x 3x 3x 1x                           1x 1x 1x 1x 1x                   4x 4x 4x 4x 4x 4x 4x 8x 8x 7x     4x     4x   3x                                 2x 2x 2x 2x 3x 3x 3x     2x   2x                   3x 2x 3x 3x 3x   2x 2x 2x 2x         7x                       4x 4x 4x                       10x 10x 10x 10x 10x                 5x 5x 5x 1x   4x 4x 4x 4x 2x                   5x 5x 5x 1x   4x 4x 4x 4x 3x       43x                 1x      
import { Logger } from '@metamask/logger';
import type { Database as SqliteDatabase } from '@sqlite.org/sqlite-wasm';
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
 
import {
  DEFAULT_DB_FILENAME,
  assertSafeIdentifier,
  SQL_QUERIES,
} from './common.ts';
import { getDBFolder } from './env.ts';
import type { KVStore, VatStore, KernelDatabase } from '../types.ts';
 
export type Database = SqliteDatabase & {
  _inTx: boolean;
  // stack of active savepoint names
  _spStack: string[];
};
 
/**
 * Ensure that SQLite is initialized.
 *
 * @param dbFilename - The filename of the database to use.
 * @param logger - The logger to use, if any.
 * @returns The SQLite database object.
 */
export async function initDB(
  dbFilename: string,
  logger?: Logger,
): Promise<Database> {
  const sqlite3 = await sqlite3InitModule();
  let db: SqliteDatabase;
 
  if (sqlite3.oo1.OpfsDb) {
    const dbName = dbFilename.startsWith(':')
      ? dbFilename
      : ['ocap', getDBFolder(), dbFilename].filter(Boolean).join('-');
    db = new sqlite3.oo1.OpfsDb(dbName, 'cw');
  } else {
    logger?.warn(`OPFS not enabled, database will be ephemeral`);
    db = new sqlite3.oo1.DB(`:memory:`, 'cw');
  }
 
  const dbWithTx = db as Database;
  dbWithTx._inTx = false;
  dbWithTx._spStack = [];
 
  return dbWithTx;
}
 
/**
 * Makes a {@link KVStore} on top of a SQLite database
 *
 * @param db - The (open) database to use.
 * @param logger - A logger object for recording activity.
 * @returns A key/value store using the given database.
 */
function makeKVStore(db: Database, logger?: Logger): KVStore {
  db.exec(SQL_QUERIES.CREATE_TABLE);
 
  const sqlKVGet = db.prepare(SQL_QUERIES.GET);
 
  /**
   * Read a key's value from the database.
   *
   * @param key - A key to fetch.
   * @param required - True if it is an error for the entry not to be there.
   * @returns The value at that key.
   */
  function kvGet(key: string, required: boolean): string | undefined {
    sqlKVGet.bind([key]);
    if (sqlKVGet.step()) {
      const result = sqlKVGet.getString(0);
      if (result) {
        sqlKVGet.reset();
        logger?.debug(`kv get '${key}' as '${result}'`);
        return result;
      }
    }
    sqlKVGet.reset();
    if (required) {
      throw Error(`no record matching key '${key}'`);
    }
    return undefined;
  }
 
  const sqlKVGetNextKey = db.prepare(SQL_QUERIES.GET_NEXT);
 
  /**
   * Get the lexicographically next key in the KV store after a given key.
   *
   * @param previousKey - The key you want to know the key after.
   *
   * @returns The key after `previousKey`, or undefined if `previousKey` is the
   *   last key in the store.
   */
  function kvGetNextKey(previousKey: string): string | undefined {
    sqlKVGetNextKey.bind([previousKey]);
    if (sqlKVGetNextKey.step()) {
      const result = sqlKVGetNextKey.getString(0);
      if (result) {
        sqlKVGetNextKey.reset();
        logger?.debug(`kv getNextKey '${previousKey}' as '${result}'`);
        return result;
      }
    }
    sqlKVGetNextKey.reset();
    return undefined;
  }
 
  const sqlKVSet = db.prepare(SQL_QUERIES.SET);
 
  /**
   * Set the value associated with a key in the database.
   *
   * @param key - A key to assign.
   * @param value - The value to assign to it.
   */
  function kvSet(key: string, value: string): void {
    logger?.debug(`kv set '${key}' to '${value}'`);
    sqlKVSet.bind([key, value]);
    sqlKVSet.step();
    sqlKVSet.reset();
  }
 
  const sqlKVDelete = db.prepare(SQL_QUERIES.DELETE);
 
  /**
   * Delete a key from the database.
   *
   * @param key - The key to remove.
   */
  function kvDelete(key: string): void {
    logger?.debug(`kv delete '${key}'`);
    sqlKVDelete.bind([key]);
    sqlKVDelete.step();
    sqlKVDelete.reset();
  }
 
  return {
    get: (key) => kvGet(key, false),
    getNextKey: kvGetNextKey,
    getRequired: (key) => kvGet(key, true) as string,
    set: kvSet,
    delete: kvDelete,
  };
}
 
/**
 * Makes a {@link KernelDatabase} for low-level persistent storage.
 *
 * @param options - The options for the database.
 * @param options.dbFilename - The filename of the database to use. Defaults to {@link DEFAULT_DB_FILENAME}.
 * @param options.logger - A logger to use.
 * @returns A key/value store to base higher level stores on.
 */
export async function makeSQLKernelDatabase({
  dbFilename,
  logger,
}: {
  dbFilename?: string | undefined;
  logger?: Logger;
}): Promise<KernelDatabase> {
  const db = await initDB(dbFilename ?? DEFAULT_DB_FILENAME, logger);
 
  logger?.debug('Initializing kernel store');
  const kvStore = makeKVStore(db, logger?.subLogger({ tags: ['kv'] }));
 
  db.exec(SQL_QUERIES.CREATE_TABLE_VS);
 
  const sqlKVClear = db.prepare(SQL_QUERIES.CLEAR);
  const sqlKVClearVS = db.prepare(SQL_QUERIES.CLEAR_VS);
  const sqlVatstoreGetAll = db.prepare(SQL_QUERIES.GET_ALL_VS);
  const sqlVatstoreSet = db.prepare(SQL_QUERIES.SET_VS);
  const sqlVatstoreDelete = db.prepare(SQL_QUERIES.DELETE_VS);
  const sqlVatstoreDeleteAll = db.prepare(SQL_QUERIES.DELETE_VS_ALL);
  const sqlBeginTransaction = db.prepare(SQL_QUERIES.BEGIN_TRANSACTION);
  const sqlCommitTransaction = db.prepare(SQL_QUERIES.COMMIT_TRANSACTION);
  const sqlAbortTransaction = db.prepare(SQL_QUERIES.ABORT_TRANSACTION);
 
  /**
   * Begin a transaction if not already in one
   *
   * @returns True if a new transaction was started, false if already in one
   */
  function beginIfNeeded(): boolean {
    if (db._inTx) {
      return false;
    }
    sqlBeginTransaction.step();
    sqlBeginTransaction.reset();
    db._inTx = true;
    return true;
  }
 
  /**
   * Commit a transaction if one is active and no savepoints remain
   */
  function commitIfNeeded(): void {
    Eif (db._inTx && db._spStack.length === 0) {
      sqlCommitTransaction.step();
      sqlCommitTransaction.reset();
      db._inTx = false;
    }
  }
 
  /**
   * Rollback a transaction
   */
  function rollbackIfNeeded(): void {
    Eif (db._inTx) {
      sqlAbortTransaction.step();
      sqlAbortTransaction.reset();
      db._inTx = false;
      db._spStack.length = 0;
    }
  }
 
  /**
   * Safely mutate the database with proper transaction management
   *
   * @param mutator - Function that performs the database mutations
   */
  function safeMutate(mutator: () => void): void {
    const startedTx = beginIfNeeded();
    try {
      mutator();
      if (startedTx) {
        commitIfNeeded();
      }
    } catch (error) {
      if (startedTx) {
        rollbackIfNeeded();
      }
      throw error;
    }
  }
 
  /**
   * Delete everything from the database.
   */
  function kvClear(): void {
    logger?.debug('clearing all kernel state');
    sqlKVClear.step();
    sqlKVClear.reset();
    sqlKVClearVS.step();
    sqlKVClearVS.reset();
  }
 
  /**
   * Execute a SQL query.
   *
   * @param sql - The SQL query to execute.
   * @returns An array of results.
   */
  function executeQuery(sql: string): Record<string, string>[] {
    const stmt = db.prepare(sql);
    const results: Record<string, string>[] = [];
    try {
      const { columnCount } = stmt;
      while (stmt.step()) {
        const row: Record<string, string> = {};
        for (let i = 0; i < columnCount; i++) {
          const columnName = stmt.getColumnName(i);
          if (columnName) {
            row[columnName] = String(stmt.get(i) as string);
          }
        }
        results.push(row);
      }
    } finally {
      stmt.reset();
    }
    return results;
  }
 
  /**
   * Create a new VatStore for a vat.
   *
   * @param vatID - The vat for which this is being done.
   *
   * @returns a a VatStore object for the given vat.
   */
  function makeVatStore(vatID: string): VatStore {
    /**
     * Fetch all the data in the vatstore.
     *
     * @returns the vatstore contents as a key-value Map.
     */
    function getKVData(): [string, string][] {
      const result: [string, string][] = [];
      sqlVatstoreGetAll.bind([vatID]);
      try {
        while (sqlVatstoreGetAll.step()) {
          const key = sqlVatstoreGetAll.getString(0) as string;
          const value = sqlVatstoreGetAll.getString(1) as string;
          result.push([key, value]);
        }
      } finally {
        sqlVatstoreGetAll.reset();
      }
      return result;
    }
 
    /**
     * Update the state of the vatstore
     *
     * @param sets - A map of key values that have been changed.
     * @param deletes - A set of keys that have been deleted.
     */
    function updateKVData(sets: [string, string][], deletes: string[]): void {
      safeMutate(() => {
        for (const [key, value] of sets) {
          sqlVatstoreSet.bind([vatID, key, value]);
          sqlVatstoreSet.step();
          sqlVatstoreSet.reset();
        }
        for (const value of deletes) {
          sqlVatstoreDelete.bind([vatID, value]);
          sqlVatstoreDelete.step();
          sqlVatstoreDelete.reset();
        }
      });
    }
 
    return {
      getKVData,
      updateKVData,
    };
  }
 
  /**
   * Delete an entire VatStore.
   *
   * @param vatId - The vat whose store is to be deleted.
   */
  function deleteVatStore(vatId: string): void {
    sqlVatstoreDeleteAll.bind([vatId]);
    sqlVatstoreDeleteAll.step();
    sqlVatstoreDeleteAll.reset();
  }
 
  /**
   * Create a savepoint in the database.
   *
   * @param name - The name of the savepoint.
   */
  function createSavepoint(name: string): void {
    // We must be in a transaction when creating the savepoint or releasing it
    // later will cause an autocommit.
    // See https://github.com/Agoric/agoric-sdk/issues/8423
    beginIfNeeded();
    assertSafeIdentifier(name);
    const query = SQL_QUERIES.CREATE_SAVEPOINT.replace('%NAME%', name);
    db.exec(query);
    db._spStack.push(name);
  }
 
  /**
   * Rollback to a savepoint in the database.
   *
   * @param name - The name of the savepoint.
   */
  function rollbackSavepoint(name: string): void {
    assertSafeIdentifier(name);
    const idx = db._spStack.lastIndexOf(name);
    if (idx < 0) {
      throw new Error(`No such savepoint: ${name}`);
    }
    const query = SQL_QUERIES.ROLLBACK_SAVEPOINT.replace('%NAME%', name);
    db.exec(query);
    db._spStack.splice(idx);
    if (db._spStack.length === 0) {
      rollbackIfNeeded();
    }
  }
 
  /**
   * Release a savepoint in the database.
   *
   * @param name - The name of the savepoint.
   */
  function releaseSavepoint(name: string): void {
    assertSafeIdentifier(name);
    const idx = db._spStack.lastIndexOf(name);
    if (idx < 0) {
      throw new Error(`No such savepoint: ${name}`);
    }
    const query = SQL_QUERIES.RELEASE_SAVEPOINT.replace('%NAME%', name);
    db.exec(query);
    db._spStack.splice(idx);
    if (db._spStack.length === 0) {
      commitIfNeeded();
    }
  }
 
  return {
    kernelKVStore: kvStore,
    clear: kvClear,
    executeQuery,
    makeVatStore,
    deleteVatStore,
    createSavepoint,
    rollbackSavepoint,
    releaseSavepoint,
    close: () => db.close(),
  };
}