UNPKG

@microfleet/ioredis-lock

Version:

Node distributed locking using redis with ioredis adapter

80 lines (79 loc) 2.96 kB
import type { Redis, Cluster, Result } from 'ioredis'; export interface Config { timeout: number; retries: number; delay: number; jitter: number; } declare module 'ioredis' { interface RedisCommander<Context> { delifequal(key: string, id: string): Result<string, Context>; pexpireifequal(key: string, id: string, seconds: number): Result<string, Context>; } } /** * @class Lock */ export declare class Lock { static _acquiredLocks: Set<Lock>; private readonly _id; private readonly _client; private _locked; private _key; readonly config: Config; /** * The constructor for a Lock object. Accepts both a redis client, as well as * an options object with the following properties: timeout, retries and delay. * Any options not supplied are subject to the current defaults. * @constructor * * @param {RedisClient} client The node_redis client to use * @param {object} options * * @property {int} timeout Time in milliseconds before which a lock expires * (default: 10000 ms) * @property {int} retries Maximum number of retries in acquiring a lock if the * first attempt failed (default: 0) * @property {int} delay Time in milliseconds to wait between each attempt * (default: 50 ms) */ constructor(client: Redis | Cluster, options?: Partial<Config>); /** * Attempts to acquire a lock, given a key, and an optional callback function. * If the initial lock fails, additional attempts will be made for the * configured number of retries, and padded by the delay. The callback is * invoked with an error on failure, and returns a promise if no callback is * supplied. If invoked in the context of a promise, it may throw a * LockAcquisitionError. * * @param key The redis key to use for the lock */ acquire(key: string): Promise<Lock>; /** * Attempts to extend the lock * @param expire in `timeout` seconds */ extend(time?: number): Promise<Lock>; /** * Attempts to release the lock, and accepts an optional callback function. * The callback is invoked with an error on failure, and returns a promise * if no callback is supplied. If invoked in the context of a promise, it may * throw a LockReleaseError. */ release(): Promise<Lock>; /** * @private */ private _setupClient; /** * Attempts to acquire the lock, and retries upon failure if the number of * remaining retries is greater than zero. Each attempt is padded by the * lock's configured retry delay. * * @param {string} key The redis key to use for the lock * @param {int} retries Number of remaining retries * * @returns {Promise} */ _attemptLock(key: string, retries: number): Promise<void>; }