@szegedsw/lib-node
Version:
A little framework published by Szeged Software Zrt. in order to enhance api endpoint security and create reuseable code. Email module, Logging system, and much more. Further improvements are expected.
55 lines • 2.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultiProcessLock = void 0;
const logger_1 = require("../logger/logger");
let MultiProcessLock = /** @class */ (() => {
class MultiProcessLock {
static addLocks(key, quantity = 2) {
if (!this.multiLocks[key]) {
this.multiLocks[key] = { quantity, locked: 0, waiting: 0 };
// times(quantity)((i) => (this.multiLocks[key][i] = false));
}
}
static async lock(key, locks = 1) {
// starting lock process
logger_1.Logger.trace(`Locking ${locks} process type(s) of '${key}'...`);
if (!this.multiLocks[key]) {
logger_1.Logger.error(`Process lock ${key} is not initialized!`);
return;
}
if (this.multiLocks[key].quantity < locks) {
logger_1.Logger.warning(`Process locks will never be created, because maximum locks number is ${this.multiLocks[key].quantity} and requested locks number is ${locks}`);
return;
}
this.multiLocks[key].waiting += locks;
while (this.multiLocks[key].quantity - this.multiLocks[key].locked < locks) {
await (async () => null).sleep(1);
}
this.multiLocks[key].locked += locks;
this.multiLocks[key].waiting -= locks;
logger_1.Logger.trace(`Successfully locked ${locks} process type(s) of '${key}'! (Waiting: ${this.multiLocks[key].waiting})`);
}
static unlock(key, unlocks = 1) {
logger_1.Logger.trace(`Unlocking ${unlocks} process type(s) of '${key}'...`);
if (!this.multiLocks[key]) {
logger_1.Logger.error(`Process lock ${key} is not initialized!`);
return;
}
if (this.multiLocks[key].locked < unlocks) {
logger_1.Logger.warning(`Process locks will not be unlocked, because current locks number is ${this.multiLocks[key].locked} and requested unlocks number is ${unlocks}`);
return;
}
this.multiLocks[key].locked -= unlocks;
logger_1.Logger.trace(`Successfully unlocked ${unlocks} process type(s) of '${key}'! (Remaining: ${this.multiLocks[key].locked})`);
}
}
Object.defineProperty(MultiProcessLock, "multiLocks", {
enumerable: true,
configurable: true,
writable: true,
value: {}
});
return MultiProcessLock;
})();
exports.MultiProcessLock = MultiProcessLock;
//# sourceMappingURL=multi-process-lock.js.map