/** * Better Auth on the project's SQLite file in `cloudhal studio` (#342). Node-only: imported by * `auth-node.ts` alone. * * Better Auth and the store hold two connections to `data.db`. Better Auth's transactions span * awaits: a sign-up reads, hashes the password, then writes. Two things went wrong when the store * wrote meanwhile: the transaction's snapshot went stale and its first write failed at once * (`SQLITE_BUSY_SNAPSHOT`, "database is locked", the sign-up answered 422); or, once it had * written, the store's write waited for the lock synchronously, blocking the event loop the * transaction needed in order to commit, until SQLite's busy timeout made it fail. * * So every Better Auth transaction runs inside the file's `SqliteFileLock`, the lock the store's * driver takes for each statement: from `BEGIN` to `COMMIT` no statement of the process's other * connections runs, and code inside the transaction passes straight through (the lock is * re-entrant). Inside the lock the transaction begins with `BEGIN IMMEDIATE`: it takes the write * lock up front, so a writer in another process (another `cloudhal` command) is waited for by the * busy timeout, instead of leaving a stale snapshot behind. * * Why not `BEGIN IMMEDIATE` alone: it would hold the write lock through the password hash, and * every store write in that window would then wait synchronously, the freeze above. Why not a * retry on `SQLITE_BUSY`: it covers the stale snapshot but not the freeze, and it would run a * sign-up's work twice. */ import type { SqliteFileLock } from "@cloudhal/storage/sqlite"; import type Database from "better-sqlite3"; import { CompiledQuery, type DatabaseConnection, Kysely, type KyselyConfig, SqliteDialect, type SqliteDialectConfig, SqliteDriver, } from "kysely"; /** Kysely's SQLite driver, with transactions that take the write lock when they begin. */ class ImmediateSqliteDriver extends SqliteDriver { override async beginTransaction(connection: DatabaseConnection): Promise { await connection.executeQuery(CompiledQuery.raw("begin immediate")); } } class ImmediateSqliteDialect extends SqliteDialect { readonly #config: SqliteDialectConfig; constructor(config: SqliteDialectConfig) { super(config); this.#config = config; } override createDriver(): SqliteDriver { return new ImmediateSqliteDriver(this.#config); } } type Builder = { execute(fn: (trx: unknown) => Promise): Promise }; /** A transaction builder whose `execute` runs inside `lock`; builders it returns are wrapped too. */ function lockedBuilder(builder: B, lock: SqliteFileLock): B { return new Proxy(builder, { get(target, key) { const value = Reflect.get(target, key, target); if (key === "execute") return (fn: (trx: unknown) => Promise) => lock.run(() => (value as Builder["execute"]).call(target, fn)); if (typeof value !== "function") return value; return (...args: unknown[]) => { const out = (value as (...a: unknown[]) => unknown).apply(target, args); return out && typeof (out as Builder).execute === "function" ? lockedBuilder(out as Builder, lock) : out; }; }, }); } /** Kysely whose transactions run inside the file's lock (only `transaction()` differs). */ class LockedKysely extends Kysely { readonly #lock: SqliteFileLock; constructor(config: KyselyConfig, lock: SqliteFileLock) { super(config); this.#lock = lock; } override transaction() { return lockedBuilder( super.transaction() as unknown as Builder, this.#lock, ) as unknown as ReturnType["transaction"]>; } } /** * `AuthOptions.database` for Better Auth on `database`, with its transactions in `lock` and * opened with `BEGIN IMMEDIATE` (Better Auth's Kysely adapter, `{ db, type, transaction }`). */ export function lockedAuthDatabase(database: Database.Database, lock: SqliteFileLock) { const db = new LockedKysely({ dialect: new ImmediateSqliteDialect({ database }) }, lock); return { db, type: "sqlite" as const, transaction: true }; }