A Redis Locker that can be used as both:

  • a Read Write Locker that uses a (single) Redis server to store the locks and counts.
  • a Resource Locker that uses a (single) Redis server to store the lock. This solution should be process-safe. The only references to locks are string keys derived from identifier paths.

The Read Write algorithm roughly goes as follows:

  • Acquire a read lock: allowed as long as there is no write lock. On acquiring the read counter goes up.
  • Acquire a write lock: allowed as long as there is no other write lock AND the read counter is 0.
  • Release a read lock: decreases the read counter with 1
  • Release a write lock: unlocks the write lock

The Resource locking algorithm uses a single mutex/lock.

All operations, such as checking for a write lock AND read count, are executed in a single Lua script. These scripts are used by Redis as a single new command. Redis executes its operations in a single thread, as such, each such operation can be considered atomic.

The operation to (un)lock will always resolve with either 1/OK/true if succeeded or 0/false if not succeeded. Rejection with errors will be happen on actual failures. Retrying the (un)lock operations will be done by making use of the LockUtils' retryFunctionUntil function.

Implements

Constructors

  • Creates a new RedisClient

    Parameters

    • redisClient: string = '127.0.0.1:6379'

      Redis connection string of a standalone Redis node

    • attemptSettings: AttemptSettings = {}

      Override default AttemptSettings

    • OptionalredisSettings: RedisSettings

      Addition settings used to create the Redis client or to interact with the Redis server

    Returns RedisLocker

Properties

logger: Logger = ...

Methods

  • Releases a lock on the requested identifier. The promise will resolve when the lock has been released. If there is no lock on the resource, an error should be thrown.

    Parameters

    Returns Promise<void>

  • Run the given function while the resource is locked. The lock will be released when the (async) input function resolves. This function should be used for operations that only require reading the resource.

    Type Parameters

    • T

    Parameters

    Returns Promise<T>

    A promise resolving when the lock is released.

  • Run the given function while the resource is locked. The lock will be released when the (async) input function resolves. This function should be used for operations that could modify the resource.

    Type Parameters

    • T

    Parameters

    Returns Promise<T>

    A promise resolving when the lock is released.