import { getRuntimeStateJson, setRuntimeStateJson, withImmediateTransaction, } from "./sdk-runtime-state-db.js"; const DATABASE_LOCK_KEY = "databaseLock"; interface DatabaseLock { isLocked: boolean; lockedBy: string; lockedAt: string | null; } const defaultLock = (): DatabaseLock => ({ isLocked: false, lockedBy: "", lockedAt: null, }); function readLock(): DatabaseLock { return getRuntimeStateJson(DATABASE_LOCK_KEY) ?? defaultLock(); } /** * Gets the current database lock state * @returns The current database lock state */ export const getDatabaseLock = (): DatabaseLock => { return readLock(); }; /** * Attempts to acquire the database lock * @param processName Name of the process requesting the lock * @returns true if lock was acquired, false if database is already locked */ export const acquireDatabaseLock = (processName: string): boolean => { return withImmediateTransaction(() => { const currentLock = readLock(); if (currentLock.isLocked) { return false; } setRuntimeStateJson(DATABASE_LOCK_KEY, { isLocked: true, lockedBy: processName, lockedAt: new Date().toISOString(), }); return true; }); }; /** * Releases the database lock * @param processName Name of the process releasing the lock * @returns true if lock was released, false if process doesn't own the lock */ export const releaseDatabaseLock = (processName: string): boolean => { return withImmediateTransaction(() => { const currentLock = readLock(); if (!currentLock.isLocked || currentLock.lockedBy !== processName) { return false; } setRuntimeStateJson(DATABASE_LOCK_KEY, defaultLock()); return true; }); }; /** * Checks if the database is available for use * @returns true if database is available, false if locked */ export const isDatabaseAvailable = (): boolean => { return !readLock().isLocked; };