Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: consider locks acquired in the future to be stale #109

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/lockfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ function acquireLock(file, options, callback) {
}

function isLockStale(stat, options) {
return stat.mtime.getTime() < Date.now() - options.stale;
// On some systems it can happen that the time is rewinded after a hard reboot
// This would leave us with a lock that seems to be held at a future time.
return Math.abs(Date.now() - stat.mtime.getTime()) > options.stale;
}

function removeLock(file, options, callback) {
Expand Down
13 changes: 13 additions & 0 deletions test/lock.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,19 @@ it('should remove and acquire over stale locks', async () => {
expect(fs.statSync(`${tmpDir}/foo.lock`).mtime.getTime()).toBeGreaterThan(Date.now() - 3000);
});

it('should remove and acquire locks from the future', async () => {
const mtime = new Date(Date.now() + 60000);

fs.writeFileSync(`${tmpDir}/foo`, '');
fs.mkdirSync(`${tmpDir}/foo.lock`);
fs.utimesSync(`${tmpDir}/foo.lock`, mtime, mtime);

await lockfile.lock(`${tmpDir}/foo`);

expect(fs.statSync(`${tmpDir}/foo.lock`).mtime.getTime()).toBeGreaterThan(Date.now() - 3000);
expect(fs.statSync(`${tmpDir}/foo.lock`).mtime.getTime()).toBeLessThan(Date.now() + 3000);
});

it('should retry if the lockfile was removed when verifying staleness', async () => {
const mtime = new Date(Date.now() - 60000);
let count = 0;
Expand Down