UNPKG

@jsdsl/semaphore

Version:

A Promise-based semaphore implementation.

3 lines (2 loc) 1.6 kB
"use strict";var __awaiter=this&&this.__awaiter||function(t,e,o,r){return new(o||(o=Promise))((function(i,n){function s(t){try{c(r.next(t))}catch(t){n(t)}}function a(t){try{c(r.throw(t))}catch(t){n(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof o?e:new o((function(t){t(e)}))).then(s,a)}c((r=r.apply(t,e||[])).next())}))},__importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Semaphore=void 0,require("promise-any-polyfill");const crypto_1=__importDefault(require("crypto")),semaphore_lock_1=require("./semaphore-lock");class Semaphore{constructor(t=1){this.maxLockCount=t,this.outstandingLocks={}}getLockPromises(){return Object.values(this.outstandingLocks).map((t=>t.waitForRelease()))}getLock(){return __awaiter(this,void 0,void 0,(function*(){for(;this.getLockCount()>=this.getMaximumLockCount();)yield Promise.any(this.getLockPromises());let t;do{t=crypto_1.default.randomBytes(16).toString("hex")}while(this.outstandingLocks.hasOwnProperty(t));return this.outstandingLocks[t]=new semaphore_lock_1.SemaphoreLock(t),this.outstandingLocks[t].waitForRelease().then((()=>delete this.outstandingLocks[t])),this.outstandingLocks[t]}))}performLockedOperation(t){return __awaiter(this,void 0,void 0,(function*(){let e=yield this.getLock();try{return yield t()}catch(t){throw t}finally{e.release()}}))}getLockCount(){return Object.keys(this.outstandingLocks).length}getMaximumLockCount(){return this.maxLockCount}}exports.Semaphore=Semaphore; //# sourceMappingURL=semaphore.js.map