@grouparoo/core
Version:
The Grouparoo Core
66 lines (65 loc) • 2.7 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLock = exports.waitForLock = void 0;
const actionhero_1 = require("actionhero");
const uuid = __importStar(require("uuid"));
const RETRY_SLEEP = 100;
const MAX_ATTEMPTS = 300;
const LOCK_DURATION_MS = RETRY_SLEEP * MAX_ATTEMPTS + 1; //30 seconds
async function waitForLock(key, requestId = uuid.v4(), ttl = LOCK_DURATION_MS, attempts = 0, sleepTime = RETRY_SLEEP) {
const client = actionhero_1.api.redis.clients.client;
const lockKey = `grouparoo:lock:${key}`;
attempts++;
if (attempts > MAX_ATTEMPTS) {
throw new Error(`could not obtain a lock for ${lockKey} after ${MAX_ATTEMPTS} attempts`);
}
const set = await client.setnx(lockKey, requestId);
const checkValue = await client.get(lockKey);
if (!set || checkValue !== requestId) {
await actionhero_1.utils.sleep(sleepTime);
return waitForLock(key, requestId, ttl, attempts, sleepTime);
}
await client.expire(lockKey, Math.ceil(ttl / 1000));
async function releaseLock() {
await client.del(lockKey);
}
return { releaseLock, attempts };
}
exports.waitForLock = waitForLock;
async function getLock(key, ttl = LOCK_DURATION_MS) {
const client = actionhero_1.api.redis.clients.client;
const lockKey = `grouparoo:lock:${key}`;
let releaseLock = null;
const set = await client.setnx(lockKey, new Date().getTime());
if (set) {
await client.expire(lockKey, Math.ceil(ttl / 1000));
releaseLock = async () => {
return client.del(lockKey);
};
}
return releaseLock;
}
exports.getLock = getLock;