@apiratorjs/locking
Version:
A lightweight library providing both local and distributed locking primitives (mutexes and semaphores) for managing concurrency in Node.js.
70 lines • 2.42 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemoryDistributedSemaphore = void 0;
const node_crypto_1 = __importDefault(require("node:crypto"));
const semaphore_1 = require("../semaphore");
class InMemoryDistributedSemaphore {
constructor(props, _registry, _type = "semaphore") {
this._registry = _registry;
this._type = _type;
this._isDestroyed = false;
this.implementation = "in-memory";
this.maxCount = props.maxCount;
this.name = `${_type}:${props.name}`;
if (!this._registry.has(this.name)) {
this._registry.set(this.name, new semaphore_1.Semaphore(this.maxCount));
}
}
get isDestroyed() {
return this._isDestroyed;
}
async runExclusive(...args) {
let callback;
let params;
if (args.length === 1) {
callback = args[0];
}
else {
params = args[0];
callback = args[1];
}
const releaser = await this.acquire(params);
try {
return await callback();
}
finally {
await releaser.release();
}
}
async destroy(message) {
const semaphore = this.getSemaphoreOrException();
this._isDestroyed = true;
this._registry.delete(this.name);
await semaphore.cancelAll(message ?? "Semaphore destroyed");
}
async freeCount() {
return this.getSemaphoreOrException().freeCount();
}
async acquire(params, acquireToken) {
const token = `${this.name}:${node_crypto_1.default.randomUUID()}`;
return this.getSemaphoreOrException().acquire(params, acquireToken ?? token);
}
async cancelAll(errMessage) {
return this.getSemaphoreOrException().cancelAll(errMessage);
}
async isLocked() {
return this.getSemaphoreOrException().isLocked();
}
getSemaphoreOrException() {
const semaphore = this._registry.get(this.name);
if (!semaphore) {
throw new Error(`${this._type} '${this.name}' does not exist`);
}
return semaphore;
}
}
exports.InMemoryDistributedSemaphore = InMemoryDistributedSemaphore;
//# sourceMappingURL=in-memory-distributed-semaphore.js.map