Distributed lock client backed by mongo.
#> npm install --save mongo-lock-node
;;// connect to mongoconst db = await MongoClient;const collection = db;await collection;// create a clientconst lockID = "lock_1"; // must be unique per lockconst clientID = "client_1"; // must be unique per clientconst lock = collection lockID clientID;// acquire the write locktryawait lock;catch err// other try/catch blocks omitted for brevityconsole; // => "error acquiring lock lock_1: connection interrupted"throw err;// no other clients acquire a read or write lock while you have the write lockconsole;// release the write lockawait lock;// acquire the read lockawait lock;// other clients can also acquire a read lock, no clients can acquire the write lockconsole;// release the read lockawait lock;
The current implementation is limited in a few ways. We may address these issues in the future but right now you should be aware of them before using this library:
- Re-enterable locks. RWMutex treats a clientID already existing on the lock in the db as a lock that this client owns. It re-enters the lock and proceeds as if you have the lock.
- No heartbeat. Our current requirements for this project do not include heartbeats, so any client that does not call unlock will remain on the lock forever.
- Manual setup. This library does not currently support setup. The collection you pass to the
constructor must have a unique index on the
Building for local use