mutex.js 2.11 KB
'use strict';

const DEBUGMODE = process.env.NODE_ENV !== 'production';

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

const mutexWaitForOK = locks.createMutex();
const mutexCommand = locks.createMutex();

const mutexSubCommand = locks.createMutex();

function setLockWaitForOK() {
    if (DEBUGMODE) logger.verbose('Entering MUTEX OK');
    return new Promise((resolve) => {
        mutexWaitForOK.lock(() => {
            if (DEBUGMODE) logger.verbose('MUTEX OK entered');
            resolve(true);
        });
    });
}

function releaseLockWaitForOK() {
    try {
        if (DEBUGMODE) logger.verbose('Leaving MUTEX OK');
        mutexWaitForOK.unlock();
    } catch (e) {
        //
    }
}

function setLockWaitForCommand() {
    if (DEBUGMODE) logger.verbose('Entering MUTEX Command');
    return new Promise((resolve) => {
        mutexCommand.lock(() => {
            if (DEBUGMODE) logger.verbose('MUTEX Command entered');
            resolve(true);
        });
    });
}

function tryLockWaitForCommand() {
    return mutexCommand.tryLock();
}


function releaseLockWaitForCommand() {
    try {
        if (DEBUGMODE) logger.verbose('Leaving MUTEX Command');
        mutexCommand.unlock();
    } catch (e) {
        //
    }
}

function setLockWaitForSubCommand() {
    if (DEBUGMODE) logger.verbose('Entering MUTEX SUBCOMMAND');
    return new Promise((resolve) => {
        mutexSubCommand.lock(() => {
            if (DEBUGMODE) logger.verbose('MUTEX SUBCOMMAND entered');
            resolve(true);
        });
    });
}

function releaseLockWaitForSubCommand() {
    try {
        if (DEBUGMODE) logger.verbose('Leaving MUTEX SUBCOMMAND');
        mutexSubCommand.unlock();
    } catch (e) {
        //
    }
}

exports.setLockWaitForOK = setLockWaitForOK;
exports.releaseLockWaitForOK = releaseLockWaitForOK;

exports.setLockWaitForCommand = setLockWaitForCommand;
exports.releaseLockWaitForCommand = releaseLockWaitForCommand;
exports.tryLockWaitForCommand = tryLockWaitForCommand;

exports.setLockWaitForSubCommand = setLockWaitForSubCommand;
exports.releaseLockWaitForSubCommand = releaseLockWaitForSubCommand;