UNPKG

@maximai/maxim-js

Version:

Maxim AI JS SDK. Visit https://getmaxim.ai for more info.

52 lines 1.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Semaphore = void 0; const platform_1 = require("../platform"); class Semaphore { constructor(key, maxLocks) { this.key = Semaphore.hash(key); this.maxLocks = maxLocks; this.currentLocks = 0; this.queue = []; // Store the semaphore instance in the static map Semaphore.semaphores.set(this.key, this); } static hash(key) { return platform_1.platform.crypto.createHash("md5").update(key).digest("hex"); } async acquire() { // If there are available locks, acquire immediately if (this.currentLocks < this.maxLocks) { this.currentLocks++; return Promise.resolve(); } // Otherwise, add to the queue and wait return new Promise((resolve) => { this.queue.push(resolve); }); } release() { if (this.currentLocks > 0) { this.currentLocks--; // If there are waiting processes in the queue, resolve the next one if (this.queue.length > 0) { const nextResolver = this.queue.shift(); if (nextResolver) { this.currentLocks++; nextResolver(); } } } } // Static method to get or create a Semaphore instance 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