advisory-lock
Distributed locking using PostgreSQL advisory locks.
Some use cases:
- You run an Express based web app and want to post a message to Slack
every 30 mins containing some stats (new registrations in last 30 mins
for example). You might have 10 web server processes running but don't
want to get X messages in Slack (only one is enough). You can use this
library to elect a "master" process which sends the messages.
- etc.
Install
npm install --save advisory-lock
Usage
advisoryLock(connectionString)(lockName)
connectionString
must be a Postgres connection stringlockName
must be a unique identifier for the lock
Returns a mutex object containing the following Promise returning
functions:
withLock(fn)
fn
Promise returning function or regular function to be executed once the lock is acquired
Like lock()
but automatically release the lock after fn()
resolves.
Returns a promise which resolves to the value fn
resolves to.
Throws an error if the Postgres connection closes unexpectedly.
tryLock()
Returns a promise which resolves to true
if the lock is free and
false
if the lock is taken. Doesn't "block".
lock()
Wait until we get exclusive lock.
unlock()
Release the exclusive lock.
tryLockShared()
Like tryLock()
but for shared lock.
lockShared()
While held, this blocks any attempt to obtain an exclusive lock. (e.g.: calls to .lock()
or .withLock()
)
unlockShared()
Release shared lock.
withLockShared(fn)
Same as withLock()
but using a shared lock.
Example
import advisoryLock from 'advisory-lock'
const mutex = advisoryLock('postgres://user:pass@localhost:3475/dbname')('some-lock-name')
const doSomething = () => {
return Promise.resolve()
}
mutex
.withLock(doSomething)
.catch((err) => {
})
.then(() => {
})
mutex.tryLock().then((obtainedLock) => {
if (obtainedLock) {
return doSomething().then(() => mutex.release())
} else {
throw new Error('failed to obtain lock')
}
})
See ./test for more usage examples.