/** * #342: `SqliteFileLock` puts the process's connections to one SQLite file in turn. A transaction * that spans awaits on one connection holds it; the driver's statements on another connection wait * for it (asynchronously) instead of blocking the event loop on SQLite's lock; code inside the * transaction passes straight through. */ import { mkdtemp, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import Database from "better-sqlite3"; import { afterEach, describe, expect, it } from "vitest"; import { BetterSqlite3Driver, SqliteFileLock, sqliteFileLock } from "../src/sql/better-sqlite3.ts"; const tick = () => new Promise((r) => setImmediate(r)); describe("SqliteFileLock (#342)", () => { let dir: string | undefined; afterEach(async () => { if (dir) await rm(dir, { recursive: true, force: true }); dir = undefined; }); const file = async () => { dir = await mkdtemp(path.join(os.tmpdir(), "cloudhal-sqlite-lock-")); return path.join(dir, "data.db"); }; it("is one lock per file, shared by every driver the process opens to it", async () => { const f = await file(); expect(sqliteFileLock(f)).toBe(sqliteFileLock(path.join(path.dirname(f), ".", "data.db"))); expect(sqliteFileLock(f)).not.toBe(sqliteFileLock(`${f}-other`)); }); it("runs holders in turn, first come first served, and lets a holder's own calls through", async () => { const lock = new SqliteFileLock(); const order: string[] = []; const a = lock.run(async () => { order.push("a:start"); await tick(); // re-entrant: no deadlock on the lock it holds await lock.run(() => order.push("a:inner")); order.push("a:end"); }); const b = lock.run(() => order.push("b")); expect(lock.held()).toBe(false); await Promise.all([a, b]); expect(order).toEqual(["a:start", "a:inner", "a:end", "b"]); // a holder that throws releases the lock await expect( lock.run(() => { throw new Error("boom"); }), ).rejects.toThrow("boom"); await expect(lock.run(() => "free")).resolves.toBe("free"); }); it("makes a store write wait for another connection's open transaction instead of failing", async () => { const f = await file(); const store = await BetterSqlite3Driver.open(f); await store.exec("CREATE TABLE t (n INTEGER)"); // Better Auth's side: its own connection, a transaction that writes, then awaits const auth = new Database(f, { timeout: 100 }); auth.pragma("journal_mode = WAL"); const lock = sqliteFileLock(f); const transaction = lock.run(async () => { auth.exec("BEGIN IMMEDIATE"); auth.prepare("INSERT INTO t VALUES (1)").run(); await new Promise((r) => setTimeout(r, 50)); // a call from inside the transaction to the store's driver goes straight through expect(await store.get<{ n: number }>("SELECT count(*) AS n FROM t")).toEqual({ n: 0 }); auth.exec("COMMIT"); }); await tick(); const started = performance.now(); await store.run("INSERT INTO t VALUES (2)"); expect(performance.now() - started).toBeLessThan(1_000); await transaction; expect(await store.all("SELECT n FROM t ORDER BY n")).toEqual([{ n: 1 }, { n: 2 }]); // the same write on a connection outside the lock: SQLite's busy wait, then a failure const outside = new Database(f, { timeout: 100 }); const held = lock.run(async () => { auth.exec("BEGIN IMMEDIATE"); auth.prepare("INSERT INTO t VALUES (3)").run(); await new Promise((r) => setTimeout(r, 50)); auth.exec("COMMIT"); }); await tick(); expect(() => outside.prepare("INSERT INTO t VALUES (4)").run()).toThrow(/database is locked/); await held; outside.close(); auth.close(); await store.close(); }); it("gives an in-memory database no lock, and takes none when told not to", async () => { const memory = await BetterSqlite3Driver.open(":memory:"); const lock = new SqliteFileLock(); let inside = false; // without a lock the driver never waits for one await lock.run(async () => { await memory.exec("CREATE TABLE t (n INTEGER)"); inside = true; }); expect(inside).toBe(true); const f = await file(); const unlocked = await BetterSqlite3Driver.open(f, { lock: false }); let released = false; const blocked = sqliteFileLock(f).run(async () => { await new Promise((r) => setTimeout(r, 30)); released = true; }); await tick(); await unlocked.exec("CREATE TABLE t (n INTEGER)"); expect(released).toBe(false); // it did not wait for the holder await blocked; await unlocked.close(); await memory.close(); }); });