olalonde / advisory-lock

advisory-lock
13 stars 1 forks source link

advisory-lock

Build
Status

Distributed* locking using PostgreSQL advisory locks.

Some use cases:

* Your PostgreSQL database being a central point of failure. For a high available distributed lock, have a look at ZooKeeper.

Install

npm install --save advisory-lock

Example

import advisoryLock from "advisory-lock";
const mutex = advisoryLock("postgres://user:pass@localhost:3475/dbname")(
  "some-lock-name"
);

// waits and blocks indefinitely for the lock before executing the function
await mutex.withLock(async () => {
  // do something exclusive
  // releases lock when promise resolves or rejects
});

// doesn't "block", just tells us if the lock is available
const unlock = await mutex.tryLock();
if (unlock) {
  // we are now responsible for manually releasing the lock
  // do something...
  await unlock();
} else {
  throw new Error("could not acquire lock");
}

See ./test for more usage examples.

CLI Usage

A withlock command line utility is provided to make to facilitate the common use case of ensuring only one instance of a process is running at any time.

withlock demo

withlock <lockName> [--db <connectionString>] -- <command>

Where <lockName> is the name of the lock, <command> (everything after --) is the command to run exclusively, once the lock is acquired. --db <connectionString> is optional and if not specified, the PG_CONNECTION_STRING environment variable will be used.

Example:

export PG_CONNECTION_STRING="postgres://postgres@127.0.0.1/mydb"
withlock dbmigration -- npm run knex migrate:latest

Usage

advisoryLock(connectionString)

Returns a createMutex function.

createMutex(lockName)

Returns a mutex object containing the functions listed below. All object methods are really just functions attached to the object and are not bound to this so they can be safely destructured, e.g. const { withLock } = createMutext(lockName).

For a better understanding of what each functions does, see PosgtreSQL's manual.

mutex.withLock(fn)

Like lock() but automatically release the lock after fn() is executed.

Returns the value returned by fn().

mutex.tryLock(): UnlockFunction

Returns an unlock() function if the lock was acquired and undefined otherwise.

mutex.lock(): UnlockFunction

Blocks and waits for lock acquisition and returns an unlock() function.