fix: resolve EBADF errors in session-write-lock

This commit is contained in:
Nathan Hangen 2026-01-28 22:47:09 -05:00
parent 5932f40bd2
commit d56a112e39

View File

@ -9,7 +9,6 @@ type LockFilePayload = {
type HeldLock = { type HeldLock = {
count: number; count: number;
handle: fs.FileHandle;
lockPath: string; lockPath: string;
}; };
@ -34,13 +33,6 @@ function isAlive(pid: number): boolean {
*/ */
function releaseAllLocksSync(): void { function releaseAllLocksSync(): void {
for (const [sessionFile, held] of HELD_LOCKS) { for (const [sessionFile, held] of HELD_LOCKS) {
try {
if (typeof held.handle.fd === "number") {
fsSync.closeSync(held.handle.fd);
}
} catch {
// Ignore errors during cleanup - best effort
}
try { try {
fsSync.rmSync(held.lockPath, { force: true }); fsSync.rmSync(held.lockPath, { force: true });
} catch { } catch {
@ -131,7 +123,6 @@ export async function acquireSessionWriteLock(params: {
current.count -= 1; current.count -= 1;
if (current.count > 0) return; if (current.count > 0) return;
HELD_LOCKS.delete(normalizedSessionFile); HELD_LOCKS.delete(normalizedSessionFile);
await current.handle.close();
await fs.rm(current.lockPath, { force: true }); await fs.rm(current.lockPath, { force: true });
}, },
}; };
@ -143,11 +134,15 @@ export async function acquireSessionWriteLock(params: {
attempt += 1; attempt += 1;
try { try {
const handle = await fs.open(lockPath, "wx"); const handle = await fs.open(lockPath, "wx");
await handle.writeFile( try {
JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }, null, 2), await handle.writeFile(
"utf8", JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }, null, 2),
); "utf8",
HELD_LOCKS.set(normalizedSessionFile, { count: 1, handle, lockPath }); );
} finally {
await handle.close();
}
HELD_LOCKS.set(normalizedSessionFile, { count: 1, lockPath });
return { return {
release: async () => { release: async () => {
const current = HELD_LOCKS.get(normalizedSessionFile); const current = HELD_LOCKS.get(normalizedSessionFile);
@ -155,7 +150,6 @@ export async function acquireSessionWriteLock(params: {
current.count -= 1; current.count -= 1;
if (current.count > 0) return; if (current.count > 0) return;
HELD_LOCKS.delete(normalizedSessionFile); HELD_LOCKS.delete(normalizedSessionFile);
await current.handle.close();
await fs.rm(current.lockPath, { force: true }); await fs.rm(current.lockPath, { force: true });
}, },
}; };