/** * One SQLite file, several connections in one Node process (#342): `cloudhal studio` opens the * project's `data.db` for the store and again for Better Auth. better-sqlite3 runs each statement * synchronously, so the store never holds a lock across an `await`, but Better Auth's * transactions do (a sign-up reads, awaits the password hash, then writes). A store write inside * that window either made the transaction's snapshot stale (`SQLITE_BUSY_SNAPSHOT`, the sign-up * failed) or, after its first write, waited for SQLite's lock synchronously, blocking the event * loop the transaction needed to commit. * * `SqliteFileLock` puts them in turn: a transaction that spans awaits holds the file's lock from * `BEGIN` to `COMMIT`, and every statement on another connection to the file takes it for its * (synchronous) run. It is re-entrant through `AsyncLocalStorage`, so code running inside the * transaction (a hook that reads or writes) goes straight through instead of deadlocking. Other * processes are SQLite's own business: `SQLITE_BUSY_TIMEOUT_MS` and `BEGIN IMMEDIATE`. * * Node-only (`@cloudhal/storage/sqlite`). */ import { AsyncLocalStorage } from "node:async_hooks"; import path from "node:path"; /** How long a connection waits for another process's write lock (better-sqlite3's `timeout`). */ export const SQLITE_BUSY_TIMEOUT_MS = 5_000; export class SqliteFileLock { readonly #held = new AsyncLocalStorage(); #tail: Promise = Promise.resolve(); /** Runs `fn` alone among this file's lock holders; inside a holder, at once. */ async run(fn: () => T | Promise): Promise { if (this.#held.getStore()) return fn(); const previous = this.#tail; let release!: () => void; this.#tail = new Promise((resolve) => { release = resolve; }); await previous; try { return await this.#held.run(true, fn); } finally { release(); } } /** Whether the caller runs inside this lock (tests). */ held(): boolean { return this.#held.getStore() === true; } } const locks = new Map(); /** The lock of a database file, shared by every connection this process opens to it. */ export function sqliteFileLock(filename: string): SqliteFileLock { const key = path.resolve(filename); let lock = locks.get(key); if (!lock) { lock = new SqliteFileLock(); locks.set(key, lock); } return lock; }