mutex-common.js 1.79 KB
const DEBUGMODE = (process.env.NODE_ENV !== 'production') || process.env.DEBUG_MUTEX;

const locks = require('locks');
const logger = require('komodo-sdk/logger');

const locksList = {};
const lockBy = {};

exports.lock = function lock(lockName, label, cb) {
    if (DEBUGMODE) logger.verbose('Locking MUTEX', { lockName, label });
    return new Promise((resolve) => {
        if (!locksList[lockName]) {
            locksList[lockName] = locks.createMutex();
        }

        locksList[lockName].lock(() => {
            lockBy[lockName] = label;
            if (DEBUGMODE) logger.verbose('MUTEX locked', { lockName, label });
            resolve(true);
            if (typeof cb === 'function') cb();
        });
    });
};

exports.tryLock = function tryLock(lockName, label) {
    if (DEBUGMODE) logger.verbose('Trying to enter MUTEX if not locked', { lockName, label });

    if (!locksList[lockName]) {
        locksList[lockName] = locks.createMutex();
    }

    const result = locksList[lockName].tryLock();
    if (DEBUGMODE && result) logger.verbose('MUTEX entered', { lockName, label });
    if (DEBUGMODE && !result) logger.verbose('MUTEX not entered', { lockName, label });
    return result;
};


exports.unlock = function unlock(lockName, label) {
    if (DEBUGMODE) logger.verbose('Unlocking MUTEX', { lockName, label });

    if (!locksList[lockName]) {
        logger.warn('Try to unlock undefined MUTEX', { lockName, label });
        return;
    }

    try {
        if (locksList[lockName]) locksList[lockName].unlock();
        if (DEBUGMODE) logger.verbose('MUTEX unlocked', { lockName, label });
    } catch (e) {
        logger.warn('Exception on unlocking MUTEX. MUTEX not locked before?', { lockName, label, e });
    }
};

exports.getLockBy = function getLockBy(lockName) {
    return lockBy[lockName];
};