├── .gitignore ├── .npmignore ├── .travis.yml ├── README.md ├── index.js ├── package.json └── test └── test.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | package-lock.json 3 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - 8.8 5 | 6 | services: 7 | - redis 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | redis-lock 2 | ========== 3 | 4 | [![Build Status](https://travis-ci.org/errorception/redis-lock.svg)](https://travis-ci.org/errorception/redis-lock) 5 | 6 | Implements a locking primitive using redis in node.js. 7 | 8 | Fully non-blocking and asynchronous, and uses the algorithm described in the [redis docs](https://redis.io/commands/setnx). 9 | 10 | Useful for concurrency control. For example, when updating a database record you might want to ensure that no other part of your code is updating the same record at that time. 11 | 12 | Used heavily at [errorception](http://errorception.com/). 13 | 14 | Requires v4 of [node-redis](https://github.com/redis/node-redis) 15 | For previous versions use [v0.1.4](https://www.npmjs.com/package/redis-lock/v/0.1.4) 16 | 17 | ## Example 18 | 19 | ```javascript 20 | const client = require("redis").createClient(), 21 | lock = require("redis-lock")(client); 22 | 23 | await client.connect(); // node-redis v4 needs to connect before sending commands 24 | 25 | const done = await lock("myLock") 26 | // No one else will be able to get a lock on 'myLock' until you call done() 27 | await done(); 28 | 29 | ``` 30 | 31 | Slightly more descriptive example: 32 | ```javascript 33 | const client = require("redis").createClient(), 34 | lock = require("redis-lock")(client); 35 | 36 | await client.connect(); 37 | 38 | const done1 = await lock("myLock") 39 | // Simulate a 1 second long operation 40 | setTimeout(done1, 1000); 41 | 42 | const done2 = await lock("myLock") 43 | // Even though this function has been scheduled at the same time 44 | // as the function above, this callback will not be executed till 45 | // the function above has called done(). Hence, this will have to 46 | // wait for at least 1 second. 47 | await done2(); 48 | ``` 49 | 50 | ## Installation 51 | 52 | $ npm install redis-lock 53 | 54 | 55 | ## Usage 56 | 57 | ``redis-lock`` is really simple to use - It's just a function! 58 | 59 | ### Initialization 60 | 61 | To initialize redis-lock, simply call it by passing in a redis client instance, created by calling ``.createClient()`` on the excellent [node-redis](https://github.com/redis/node_redis). This is taken in as a parameter because you might want to configure the client to suit your environment (host, port, etc.), and to enable you to reuse the client from your app if you want to. 62 | 63 | You can also provide a second (optional) parameter: `retryDelay`. If due to any reason a lock couldn't be acquired, lock acquisition is retried after waiting for a little bit of time. `retryDelay` lets you control this delay time. Default: 50ms. 64 | 65 | ```javascript 66 | const lock = require("redis-lock")(require("redis").createClient(), 10); 67 | ``` 68 | 69 | This will return a function called (say) ``lock``, described below: 70 | 71 | ### lock(lockName, [timeout = 5000]): done 72 | 73 | * ``lockName``: Any name for a lock. Must follow redis's key naming rules. Make this as granular as you can. For example, to get a lock when editing record 1 in the database, call the lock ``record1`` rather than ``database``, so that other records in the database can be modified even as you are holding this lock. 74 | * ``timeout``: (Optional) The maximum time (in ms) to hold the lock for. If this time is exceeded, the lock is automatically released to prevent deadlocks. Default: 5000 ms (5 seconds). 75 | 76 | Returns a ``done`` async function which releases the lock (or do nothing if timeout has already released it) 77 | 78 | Full example, with ``console.log`` calls to illustrate the flow: 79 | ```javascript 80 | const client = require("redis").createClient(), 81 | lock = require("redis-lock")(client); 82 | 83 | await client.connect(); 84 | 85 | console.log("Asking for lock"); 86 | const done = await lock("myLock") 87 | console.log("Lock acquired"); 88 | await someTask() // Some async task 89 | console.log("Releasing lock now"); 90 | await done() 91 | console.log("Lock has been released, and is available for others to use"); 92 | ``` 93 | 94 | ## Details 95 | 96 | * It's guaranteed that only one function will be called at a time for the same lock. 97 | * This module doesn't block the event loop. All operations are completely asynchronous and non-blocking. 98 | * If two functions happen to ask for a lock simultaneously, the execution of the second function is deferred until the first function has released its lock or has timed out. 99 | * It's not possible for two functions to acquire the same lock at any point in time, except if the timeout is breached. 100 | * If the timeout is breached, the lock is released, and the next function coming along and asking for a lock acquires the lock. 101 | * Since it's asynchronous, different functions could be holding different locks simultaneously. This is awesome! 102 | * If redis is down for any reason, none of the functions are given locks, and none of the locks are released. The code will keep polling to check if redis is available again to acquire the lock. 103 | 104 | ## License 105 | 106 | (The MIT License) 107 | 108 | Copyright (c) 2012 Rakesh Pai 109 | 110 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 111 | 112 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 113 | 114 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 115 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const DEFAULT_TIMEOUT = 5000; 4 | const DEFAULT_RETRY_DELAY = 50; 5 | 6 | async function acquireLock (client, lockName, timeout, retryDelay, onLockAcquired) { 7 | function retry () { 8 | setTimeout(() => { 9 | acquireLock(client, lockName, timeout, retryDelay, onLockAcquired); 10 | }, retryDelay); 11 | } 12 | 13 | const lockTimeoutValue = Date.now() + timeout + 1; 14 | try { 15 | const result = await client.set(lockName, lockTimeoutValue, { 16 | PX: timeout, 17 | NX: true 18 | }); 19 | if (result === null) { 20 | throw new Error("Lock failed"); 21 | } 22 | onLockAcquired(lockTimeoutValue); 23 | } catch (err) { 24 | retry(); 25 | } 26 | } 27 | 28 | function redisLock (client, retryDelay = DEFAULT_RETRY_DELAY) { 29 | if(!(client && client.set && "v4" in client)) { 30 | throw new Error("You must specify a v4 client instance of https://github.com/redis/node-redis"); 31 | } 32 | async function lock (lockName, timeout = DEFAULT_TIMEOUT) { 33 | return new Promise(resolve => { 34 | if (!lockName) { 35 | throw new Error("You must specify a lock string. It is on the redis key `lock.[string]` that the lock is acquired."); 36 | } 37 | 38 | lockName = `lock.${ lockName}`; 39 | 40 | acquireLock(client, lockName, timeout, retryDelay, lockTimeoutValue => { 41 | resolve(async () => { 42 | if (lockTimeoutValue > Date.now()) { 43 | return client.del(lockName); 44 | } 45 | }); 46 | }); 47 | }); 48 | } 49 | return lock; 50 | } 51 | 52 | module.exports = redisLock; 53 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Rakesh Pai (http://errorception.com/)", 3 | "name": "redis-lock", 4 | "description": "A locking primitive using redis.", 5 | "version": "1.0.0", 6 | "repository": { 7 | "type": "git", 8 | "url": "git://github.com/errorception/redis-lock.git" 9 | }, 10 | "main": "index.js", 11 | "engines": { 12 | "node": ">=12" 13 | }, 14 | "dependencies": {}, 15 | "devDependencies": { 16 | "mocha": "4.x", 17 | "redis": "4.x", 18 | "should": "^13.x" 19 | }, 20 | "scripts": { 21 | "test": "mocha" 22 | }, 23 | "optionalDependencies": {}, 24 | "homepage": "https://github.com/errorception/redis-lock", 25 | "keywords": [ 26 | "locks", 27 | "concurrency", 28 | "redis", 29 | "distributed" 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | const should = require("should"), 2 | redisClient = require("redis").createClient(), 3 | lock = require("../index")(redisClient) 4 | 5 | const delay = (fn, ms) => new Promise( 6 | res => setTimeout(async () => { 7 | const val = await fn(); 8 | res(val); 9 | }, ms) 10 | ); 11 | 12 | describe("redis-lock", function() { 13 | before(async () => { 14 | await redisClient.connect(); 15 | }) 16 | 17 | after(async () => { 18 | await redisClient.disconnect(); 19 | }); 20 | 21 | it("should aquire a lock and call the callback", async () => { 22 | const completed = await lock("testLock"); 23 | const timeStamp = await redisClient.get("lock.testLock"); 24 | parseFloat(timeStamp).should.be.above(Date.now()); 25 | await completed(); 26 | const lockValue = await redisClient.get("lock.testLock"); 27 | should.not.exist(lockValue); 28 | }); 29 | 30 | it("should defer second operation if first has lock", async () => { 31 | const completed1 = await lock("testLock") 32 | const p1 = delay(async () => { 33 | await completed1(); 34 | return 1; 35 | }, 500); // Longer, started first 36 | 37 | const completed2 = await lock("testLock") 38 | const p2 = delay(async () => { 39 | await completed2(); 40 | return 2; 41 | }, 200); // Shorter, started later 42 | 43 | const first = await Promise.race([p1, p2]); 44 | first.should.equal(1) 45 | }); 46 | 47 | it("shouldn't create a deadlock if the first operation doesn't release the lock within ", async () => { 48 | var start = new Date(); 49 | await lock("testLock", 300); 50 | // Not signalling completion 51 | 52 | const completed = await lock("testLock"); 53 | // This should be called after 300 ms 54 | (new Date() - start).should.be.above(300); 55 | await completed(); 56 | }); 57 | }); 58 | --------------------------------------------------------------------------------