mutex-common.js
1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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];
};