I made a distributed lock that can be used by other services. It solves data-setting race issues. I mostly made it as an exercise in TDD.
yarn install
- yarn
- redis
yarn start
Configure by creating a .env file in the root directory with the following keys:
PORT
- port on which to launch this node app. Default is3000
HOST
- hostname. Default islocalhost
REDIS_PORT
- redis port. Default is6379
REDIS_HOST
- Redis host. Default islocalhost
DEFAULT_EXPIRY
- Default expiry time. Default is 1 second.
Alternatively, command line options can be specified:
-p --port <value> specify launch port
-H --host <value> specify launch host
-P --redis-port <value> specify redis port
-R --redis-host <string> specify redis host
-N --no-redis use in-memory key repository instead of redis
-E --default-expiry <ms> set default lock duration expiry time (ms)
The no redis option uses an in-memory repository instead of redis.
Program will keep track of locked keys identified by a uid string. Other services can access its API:
Method | Path | Input | Description | Output |
---|---|---|---|---|
POST | /lock |
uid: string - unique id of service making API callkeys: string | string[] - keys to lockexp?: number (optional) - length of lock (ms). Equals default if not specified. |
Service locks specified keys either until it is unlocked or after expiry. | response is JSON containing either:error or tokens:{ key ,version }[] |
POST | /unlock |
uid: string tokens: {key: string, version: number}[] - keys to lock - should use the tokens response of the lock object. |
Unlock the tokens by including the tokens received when they were locked. | unlocked : string - keys that have been unlocked. |
POST | /check |
keys: string | string [] |
Checks whether all specified keys are locked | locked: boolean - true if at least 1 key is locked |
Distributed under the GPLv3 License. See LICENSE
for more information.