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 = {
count: number;
handle: fs.FileHandle;
lockPath: string;
};
@ -34,13 +33,6 @@ function isAlive(pid: number): boolean {
*/
function releaseAllLocksSync(): void {
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 {
fsSync.rmSync(held.lockPath, { force: true });
} catch {
@ -131,7 +123,6 @@ export async function acquireSessionWriteLock(params: {
current.count -= 1;
if (current.count > 0) return;
HELD_LOCKS.delete(normalizedSessionFile);
await current.handle.close();
await fs.rm(current.lockPath, { force: true });
},
};
@ -143,11 +134,15 @@ export async function acquireSessionWriteLock(params: {
attempt += 1;
try {
const handle = await fs.open(lockPath, "wx");
await handle.writeFile(
JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }, null, 2),
"utf8",
);
HELD_LOCKS.set(normalizedSessionFile, { count: 1, handle, lockPath });
try {
await handle.writeFile(
JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }, null, 2),
"utf8",
);
} finally {
await handle.close();
}
HELD_LOCKS.set(normalizedSessionFile, { count: 1, lockPath });
return {
release: async () => {
const current = HELD_LOCKS.get(normalizedSessionFile);
@ -155,7 +150,6 @@ export async function acquireSessionWriteLock(params: {
current.count -= 1;
if (current.count > 0) return;
HELD_LOCKS.delete(normalizedSessionFile);
await current.handle.close();
await fs.rm(current.lockPath, { force: true });
},
};