import { closeSync, existsSync, mkdirSync, openSync, rmSync, statSync, unlinkSync } from "node:fs"; import { dirname } from "node:path"; const LOCK_TIMEOUT_MS = 30_000; const STALE_LOCK_MS = 120_000; const RETRY_DELAY_MS = 100; export async function withFileLock(lockPath: string, run: () => Promise): Promise { mkdirSync(dirname(lockPath), { recursive: true }); const descriptor = await acquireLock(lockPath); try { return await run(); } finally { closeSync(descriptor); unlinkSync(lockPath); } } // SQLite is local and single-user here, so a small file lock is enough to // serialize the write-heavy search/bootstrap path across Bun processes. export async function withDatabaseLock( lockPath: string, run: () => Promise, ): Promise { return await withFileLock(lockPath, run); } async function acquireLock(lockPath: string): Promise { const deadline = Date.now() + LOCK_TIMEOUT_MS; while (Date.now() < deadline) { try { return openSync(lockPath, "wx"); } catch (error) { if (!isAlreadyExists(error)) { throw error; } clearStaleLock(lockPath); await Bun.sleep(RETRY_DELAY_MS); } } throw new Error("timed out waiting for the local database lock"); } function clearStaleLock(lockPath: string): void { if (!existsSync(lockPath)) { return; } try { const ageMs = Date.now() - statSync(lockPath).mtimeMs; if (ageMs > STALE_LOCK_MS) { rmSync(lockPath, { force: true }); } } catch { // Another process may have released or replaced the lock while we checked. } } function isAlreadyExists(error: unknown): boolean { return error instanceof Error && "code" in error && error.code === "EEXIST"; }