perf(plugins): cache runtime mirror file decisions

This commit is contained in:
Peter Steinberger
2026-04-28 23:36:59 +01:00
parent 6ce1058296
commit 75df09b9ec
5 changed files with 103 additions and 9 deletions

View File

@@ -1,7 +1,7 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
acquireFileLock,
drainFileLockStateForTest,
@@ -55,4 +55,28 @@ describe("acquireFileLock", () => {
return true;
});
}, 5_000);
it("closes an opened lock handle when writing the owner payload fails", async () => {
const filePath = path.join(tempDir, "write-fails");
const writeError = new Error("owner write failed");
const close = vi.fn().mockResolvedValue(undefined);
vi.spyOn(fs, "open").mockResolvedValue({
close,
writeFile: vi.fn().mockRejectedValue(writeError),
} as unknown as Awaited<ReturnType<typeof fs.open>>);
await expect(
acquireFileLock(filePath, {
retries: {
retries: 0,
factor: 1,
minTimeout: 1,
maxTimeout: 1,
},
stale: 100,
}),
).rejects.toThrow(writeError);
expect(close).toHaveBeenCalledTimes(1);
});
});

View File

@@ -183,10 +183,16 @@ export async function acquireFileLock(
for (let attempt = 0; attempt <= options.retries.retries; 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",
);
try {
await handle.writeFile(
JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }, null, 2),
"utf8",
);
} catch (writeError) {
await handle.close().catch(() => undefined);
await fs.rm(lockPath, { force: true }).catch(() => undefined);
throw writeError;
}
HELD_LOCKS.set(normalizedFile, { count: 1, handle, lockPath });
return {
lockPath,