UNPKG

redis-semaphore

Version:

Distributed mutex and semaphore based on Redis

86 lines 3.39 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Lock = void 0; const debug_1 = __importDefault(require("debug")); const uuid_1 = require("uuid"); const LostLockError_1 = __importDefault(require("./errors/LostLockError")); const TimeoutError_1 = __importDefault(require("./errors/TimeoutError")); const misc_1 = require("./misc"); const REFRESH_INTERVAL_COEF = 0.8; const debug = (0, debug_1.default)('redis-semaphore:instance'); class Lock { constructor({ lockTimeout = misc_1.defaultTimeoutOptions.lockTimeout, acquireTimeout = misc_1.defaultTimeoutOptions.acquireTimeout, retryInterval = misc_1.defaultTimeoutOptions.retryInterval, refreshInterval = Math.round(lockTimeout * REFRESH_INTERVAL_COEF), onLockLost = misc_1.defaultOnLockLost } = misc_1.defaultTimeoutOptions) { this._refreshing = false; this._acquired = false; this._identifier = (0, uuid_1.v4)(); this._acquireOptions = { lockTimeout, acquireTimeout, retryInterval, identifier: this._identifier }; this._refreshTimeInterval = refreshInterval; this._processRefresh = this._processRefresh.bind(this); this._onLockLost = onLockLost; } get identifier() { return this._identifier; } get isAcquired() { return this._acquired; } _startRefresh() { this._refreshInterval = setInterval(this._processRefresh, this._refreshTimeInterval); this._refreshInterval.unref(); } _stopRefresh() { if (this._refreshInterval) { debug(`clear refresh interval ${this._kind} (key: ${this._key}, identifier: ${this._identifier})`); clearInterval(this._refreshInterval); } } async _processRefresh() { if (this._refreshing) { debug(`already refreshing ${this._kind} (key: ${this._key}, identifier: ${this._identifier}) (skip)`); return; } this._refreshing = true; try { debug(`refresh ${this._kind} (key: ${this._key}, identifier: ${this._identifier})`); const refreshed = await this._refresh(); if (!refreshed) { this._acquired = false; this._stopRefresh(); const lockLostError = new LostLockError_1.default(`Lost ${this._kind} for key ${this._key}`); this._onLockLost(lockLostError); } } finally { this._refreshing = false; } } async acquire() { debug(`acquire ${this._kind} (key: ${this._key})`); const acquired = await this._acquire(); if (!acquired) { throw new TimeoutError_1.default(`Acquire ${this._kind} ${this._key} timeout`); } this._acquired = true; if (this._refreshTimeInterval > 0) { this._startRefresh(); } } async release() { debug(`release ${this._kind} (key: ${this._key}, identifier: ${this._identifier})`); if (this._refreshTimeInterval > 0) { this._stopRefresh(); } await this._release(); this._acquired = false; } } exports.Lock = Lock; //# sourceMappingURL=Lock.js.map