moxystudio / node-proper-lockfile

An inter-process and inter-machine lockfile utility that works on a local or network file system.
MIT License
235 stars 38 forks source link

It doesn't work in Windows, or I don't understand it's logic #115

Open jsonslim opened 1 year ago

jsonslim commented 1 year ago

I'm able to write to a file despite the library is working. Here is my "locking" code:


const file = './file.txt';

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// === main logic ===
lockfile.lock(file)
.then(async (release) => {

    await delay(10000);

    return release();
})
.catch((e) => {
    console.error(e)
});

It locks the file.txt for 10 seconds, and during this time I shouldn't be able to write the file from other processes(if I understand it correctly), but I can open the file in windows "notepad" and change the text.

Here is the code I run in parallel, and it also does rewrite the file.txt :


(() => {
    try {
        const fd = fs.openSync('./file.txt', 'a+');
        fs.writeFileSync(fd, 'some nasty text')
    } catch (e) {
        console.error(e);
    }
})();

So, what does the lib do? Thanks!

agustin-golmar commented 1 year ago

Hi @SpacewormSera!

I was searching for a solution of AWS EFS advisory locking mechanism inside Node.js and just find this library.

As I understand the mechanics of the library, every thread, process, application or machine must access the shared file-system with this library, because it uses mkdir and mtime system functions to provide the locking behaviour. These guarantee atomicity of operations. If you lock a file with proper-lockfile, but then access the same file directly (even using Node.js), then you are not using the locking behaviour, you're just "jumping over it". This is because it works like an advisory lock in PostgreSQL, that is, it works if every party respects the mechanism, but is not enforced by the system.

See Understanding Node.js file locking (A. Evans, 2022).