FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

fix(lockfile): scope exit hooks to owned locks by AmanVarshney01 · Pull Request #6 · alchemy-run/node-utils · GitHub

Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .ts  (3) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
51 changes: 36 additions & 15 deletions packages/node-utils/src/lockfile.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,32 @@ type AcquireCallback = (
) => void;

const locks: Record<string, InternalLock> = {};
const locksOwnedForExit = new Set<InternalLock>();
let removeExitHook: (() => void) | undefined;

function removeOwnedLocksOnExit(): void {
for (const lock of locksOwnedForExit) {
try {
lock.options.fs.rmdirSync(lock.lockfilePath);
} catch {
/* Empty */
}
}
}

function trackLockForExit(lock: InternalLock): void {
locksOwnedForExit.add(lock);
removeExitHook ??= exitHook(removeOwnedLocksOnExit);
}

function untrackLockForExit(lock: InternalLock): void {
locksOwnedForExit.delete(lock);

if (locksOwnedForExit.size === 0) {
removeExitHook?.();
removeExitHook = undefined;
}
}

function getLockFile(file: string, options: { lockfilePath?: string }): string {
return options.lockfilePath || `${file}.lock`;
Expand Down Expand Up @@ -302,6 +328,10 @@ function setLockAsCompromised(
lock: InternalLock,
err: Error,
): void {
if (lock.released) {
return;
}

lock.released = true;

// Cancel lock mtime update
Expand All @@ -314,6 +344,7 @@ function setLockAsCompromised(
delete locks[file];
}

untrackLockForExit(lock);
lock.options.onCompromised(err);
}

Expand Down Expand Up @@ -382,6 +413,7 @@ export function lock(
options: resolved,
lastUpdate: Date.now(),
});
trackLockForExit(internalLock);

// We must keep the lock fresh to avoid staleness
updateLock(file, resolved);
Expand Down Expand Up @@ -443,7 +475,10 @@ export function unlock(
lock.released = true;
delete locks[file];

removeLock(file, resolved, callback);
removeLock(file, resolved, (err) => {
untrackLockForExit(lock);
callback(err);
});
});
}

Expand Down Expand Up @@ -486,17 +521,3 @@ export function check(
export function getLocks(): Record<string, InternalLock> {
return locks;
}

// Remove acquired locks on exit
/* istanbul ignore next */
exitHook(() => {
for (const file in locks) {
const options = locks[file].options;

try {
options.fs.rmdirSync(getLockFile(file, options));
} catch (e) {
/* Empty */
}
}
});
68 changes: 68 additions & 0 deletions packages/node-utils/test/fixtures/lock-listeners.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

const listenerCounts = () => ({
exit: process.listenerCount("exit"),
SIGINT: process.listenerCount("SIGINT"),
SIGTERM: process.listenerCount("SIGTERM"),
});

const beforeImport = listenerCounts();
const lockfile = await import("../../src/index.ts");
const afterImport = listenerCounts();
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "node-utils-lockfile-"));

try {
const firstFile = path.join(tmpDir, "first");
const secondFile = path.join(tmpDir, "second");
fs.writeFileSync(firstFile, "");
fs.writeFileSync(secondFile, "");

const releaseFirst = await lockfile.lock(firstFile);
const afterFirstLock = listenerCounts();
const releaseSecond = await lockfile.lock(secondFile);
const afterSecondLock = listenerCounts();

await releaseFirst();
const afterFirstRelease = listenerCounts();
await releaseSecond();
const afterSecondRelease = listenerCounts();

const slowFile = path.join(tmpDir, "slow");
fs.writeFileSync(slowFile, "");
let finishRemoval: (() => void) | undefined;
const slowFs = {
...fs,
rmdir: (
lockPath: fs.PathLike,
callback: (err: NodeJS.ErrnoException | null) => void,
) => {
finishRemoval = () => fs.rmdir(lockPath, callback);
},
};
const releaseSlowLock = await lockfile.lock(slowFile, {
fs: slowFs,
realpath: false,
});
const slowRelease = releaseSlowLock();
const duringSlowRelease = listenerCounts();
finishRemoval?.();
await slowRelease;
const afterSlowRelease = listenerCounts();

console.log(
JSON.stringify({
beforeImport,
afterImport,
afterFirstLock,
afterSecondLock,
afterFirstRelease,
afterSecondRelease,
duringSlowRelease,
afterSlowRelease,
}),
);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
31 changes: 31 additions & 0 deletions packages/node-utils/test/misc.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ import { clearDir, ensureDir, removeDir } from "./util/tmp.ts";

const tmpDir = `${import.meta.dir}/tmp`;

interface ListenerCounts {
exit: number;
SIGINT: number;
SIGTERM: number;
}

beforeAll(() => ensureDir(tmpDir));

afterAll(() => removeDir(tmpDir));
Expand Down Expand Up @@ -40,6 +46,31 @@ it("should not hold the process if it has no more work to do", () => {
expect(result.status).toBe(0);
}, 10000);

it("should only register exit listeners while locks are owned", () => {
const result = spawnSync(
"bun",
[`${import.meta.dir}/fixtures/lock-listeners.ts`],
{ encoding: "utf8" },
);

expect(result.status).toBe(0);

const counts = JSON.parse(result.stdout) as Record<string, ListenerCounts>;
const withExitHook = {
exit: counts.beforeImport.exit + 1,
SIGINT: counts.beforeImport.SIGINT + 1,
SIGTERM: counts.beforeImport.SIGTERM + 1,
};

expect(counts.afterImport).toEqual(counts.beforeImport);
expect(counts.afterFirstLock).toEqual(withExitHook);
expect(counts.afterSecondLock).toEqual(withExitHook);
expect(counts.afterFirstRelease).toEqual(withExitHook);
expect(counts.afterSecondRelease).toEqual(counts.beforeImport);
expect(counts.duringSlowRelease).toEqual(withExitHook);
expect(counts.afterSlowRelease).toEqual(counts.beforeImport);
});

it("should work on stress conditions", () => {
const result = spawnSync("bun", [`${import.meta.dir}/fixtures/stress.ts`], {
encoding: "utf8",
Expand Down
Loading

Back | FazBrowse Home | New Git URL