@maximai/maxim-js
Version:
Maxim AI JS SDK. Visit https://getmaxim.ai for more info.
50 lines • 1.59 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Semaphore = void 0;
const crypto_1 = __importDefault(require("crypto"));
class Semaphore {
constructor(key, maxLocks) {
this.key = Semaphore.hash(key);
this.maxLocks = maxLocks;
this.currentLocks = 0;
this.queue = [];
Semaphore.semaphores.set(this.key, this);
}
static hash(key) {
return crypto_1.default.createHash("md5").update(key).digest("hex");
}
async acquire() {
if (this.currentLocks < this.maxLocks) {
this.currentLocks++;
return Promise.resolve();
}
return new Promise((resolve) => {
this.queue.push(resolve);
});
}
release() {
if (this.currentLocks > 0) {
this.currentLocks--;
if (this.queue.length > 0) {
const nextResolver = this.queue.shift();
if (nextResolver) {
this.currentLocks++;
nextResolver();
}
}
}
}
static get(key, maxLocks) {
const hashedKey = Semaphore.hash(key);
if (!Semaphore.semaphores.has(hashedKey)) {
return new Semaphore(key, maxLocks);
}
return Semaphore.semaphores.get(hashedKey);
}
}
exports.Semaphore = Semaphore;
Semaphore.semaphores = new Map();
//# sourceMappingURL=semaphore.js.map