{"id":20767014,"url":"https://github.com/binded/advisory-lock","last_synced_at":"2025-05-11T08:34:05.363Z","repository":{"id":47727048,"uuid":"58603325","full_name":"binded/advisory-lock","owner":"binded","description":"Distributed locking using PostgreSQL advisory locks (Node.js)","archived":true,"fork":false,"pushed_at":"2022-08-11T18:36:22.000Z","size":134,"stargazers_count":53,"open_issues_count":4,"forks_count":12,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-04-27T12:02:16.879Z","etag":null,"topics":["lock","nodejs","postgresql","postgresql-advisory-locks","promise","withlock"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/binded.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-05-12T03:12:01.000Z","updated_at":"2025-03-11T07:58:49.000Z","dependencies_parsed_at":"2022-09-26T19:53:35.280Z","dependency_job_id":null,"html_url":"https://github.com/binded/advisory-lock","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binded%2Fadvisory-lock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binded%2Fadvisory-lock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binded%2Fadvisory-lock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binded%2Fadvisory-lock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/binded","download_url":"https://codeload.github.com/binded/advisory-lock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253540462,"owners_count":21924522,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["lock","nodejs","postgresql","postgresql-advisory-locks","promise","withlock"],"created_at":"2024-11-17T11:27:16.653Z","updated_at":"2025-05-11T08:34:05.089Z","avatar_url":"https://github.com/binded.png","language":"JavaScript","readme":"# advisory-lock\n\n[![Build Status](https://travis-ci.org/blockai/advisory-lock.svg?branch=master)](https://travis-ci.org/blockai/advisory-lock)\n\nDistributed* locking using [PostgreSQL advisory locks](http://www.postgresql.org/docs/current/static/explicit-locking.html#ADVISORY-LOCKS).\n\nSome use cases:\n\n- You have a [clock process](https://devcenter.heroku.com/articles/scheduled-jobs-custom-clock-processes)\n    and want to make absolutely sure there will never be more than one\n    process active at any given time.\n\n    This sort of situation can otherwise arise if the clock process is\n    scaled up by accident or during a deployment which keeps the old\n    version running until the new version responds to a health check.\n\n- Running a database migration at server startup. If your app is scaled,\n    multiple processes will simultaneously try to run the database\n    migration which can lead to problems.\n\n- Leader election. Let's say you have a web app and want to post a\n    message to Slack every 30 mins containing some statistic (e.g. new\n    registrations in the last 30 mins). You might have 10 processes\n    running but don't want to get 10 identical messages in Slack.\n    You can use this library to elect a \"master\" process which\n    is responsible for sending the message.\n\n- [etc.](https://www.google.com/?q=distributed+lock#newwindow=1\u0026q=distributed+lock)\n\n\\* Your PostgreSQL database being a central point of failure. For\n    a high available distributed lock, have a look at\n    [ZooKeeper](https://zookeeper.apache.org).\n\n## Install\n\n```\nnpm install --save advisory-lock\n```\n\n## CLI Usage\n\nA `withlock` command line utility is provided to make to facilitate the\ncommon use case of ensuring only one instance of a process is running at any\ntime.\n\n![withlock demo](./withlock-demo.gif)\n\n```bash\nwithlock \u003clockName\u003e [--db \u003cconnectionString\u003e] -- \u003ccommand\u003e\n```\n\nWhere `\u003clockName\u003e` is the name of the lock, `\u003ccommand\u003e` (everything after\n`--`) is the command to run exclusively, once the lock is acquired.\n`--db \u003cconnectionString\u003e` is optional and if not specified, the\n`PG_CONNECTION_STRING` environment variable will be used.\n\nExample:\n\n```bash\nexport PG_CONNECTION_STRING=\"postgres://postgres@127.0.0.1/mydb\"\nwithlock dbmigration -- npm run knex migrate:latest\n```\n\n## Usage\n\n### advisoryLock(connectionString)\n\n- `connectionString` must be a Postgres connection string\n\nReturns a `createMutex` function.\n\nThe `createMutex` function also exposes a `client` property\nthat can be used to terminate the database connection if necessary.\n\nPS: Each call to `advisoryLock(connectionString)` creates a new PostgreSQL\nconnection which is not automatically terminated, so if that is an\n[issue for you](https://github.com/blockai/advisory-lock/issues/1), you\ncan use `createMutex.client.end()` to end the connection when\nappropriate (e.g.  after releasing a lock). This is however typically\nnot needed since usually, `advisoryLock()` only needs to be called once.\n\n### createMutex(lockName)\n\n- `lockName` must be a unique identifier for the lock\n\nReturns a **mutex** object containing the functions listed below. All\n**object** methods are really just functions attached to the object and\nare not bound to *this* so they can be safely destructured,\ne.g. `const { withLock } = createMutext(lockName)`.\n\nFor a better understanding of what each functions does,\nsee [PosgtreSQL's manual](http://www.postgresql.org/docs/current/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS).\n\n#### mutex.withLock(fn)\n\n- `fn` Promise returning function or regular function to be executed once the lock is acquired\n\nLike `lock()` but automatically release the lock after `fn()` resolves.\n\nReturns a promise which resolves to the value `fn` resolves to.\n\nThrows an error if the Postgres connection closes unexpectedly.\n\n#### mutex.tryLock()\n\nReturns a promise which resolves to `true` if the lock is free and\n`false` if the lock is taken. Doesn't \"block\".\n\n#### mutex.lock()\n\nWait until we get exclusive lock.\n\n#### mutex.unlock()\n\nRelease the exclusive lock.\n\n#### mutex.tryLockShared()\n\nLike `tryLock()` but for shared lock.\n\n#### mutex.lockShared()\n\nWhile held, this blocks any attempt to obtain an exclusive lock. (e.g.: calls to `.lock()` or `.withLock()`)\n\n#### mutex.unlockShared()\n\nRelease shared lock.\n\n#### mutex.withLockShared(fn)\n\nSame as `withLock()` but using a shared lock.\n\n## Example\n\n```javascript\nimport advisoryLock from 'advisory-lock'\nconst mutex = advisoryLock('postgres://user:pass@localhost:3475/dbname')('some-lock-name')\n\nconst doSomething = () =\u003e {\n  // doSomething\n  return Promise.resolve()\n}\n\nmutex\n  .withLock(doSomething) // \"blocks\" until lock is free\n  .catch((err) =\u003e {\n    // this gets executed if the postgres connection closes unexpectedly, etc.\n  })\n  .then(() =\u003e {\n    // lock is released now...\n  })\n\n// doesn't \"block\"\nmutex.tryLock().then((obtainedLock) =\u003e {\n  if (obtainedLock) {\n    return doSomething().then(() =\u003e mutex.unlock())\n  } else {\n    throw new Error('failed to obtain lock')\n  }\n})\n\n```\n\nSee [./test](./test) for more usage examples.\n\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinded%2Fadvisory-lock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbinded%2Fadvisory-lock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinded%2Fadvisory-lock/lists"}