|
| 1 | +/* |
| 2 | + * Created by Trevor Sears <trevor@trevorsears.com> (https://trevorsears.com/). |
| 3 | + * 3:09 PM -- September 09, 2021. |
| 4 | + * Project: @jsdsl/semaphore |
| 5 | + */ |
| 6 | + |
| 7 | +import "promise-any-polyfill"; |
| 8 | +import crypto from "crypto"; |
| 9 | +import { SemaphoreLock } from "./semaphore-lock"; |
| 10 | + |
| 11 | +type OutstandingLockMap = { |
| 12 | + |
| 13 | +[id: string]: Promise<string> |
| 14 | + |
| 15 | +} |
| 16 | + |
| 17 | +export class Semaphore { |
| 18 | + |
| 19 | +protected readonly maxLockCount: number; |
| 20 | + |
| 21 | +protected outstandingLocks: OutstandingLockMap; |
| 22 | + |
| 23 | +public constructor(maxLockCount: number) { |
| 24 | + |
| 25 | +this.maxLockCount = maxLockCount; |
| 26 | +this.outstandingLocks = {}; |
| 27 | + |
| 28 | +} |
| 29 | + |
| 30 | +public async getLock(): Promise<SemaphoreLock> { |
| 31 | + |
| 32 | +// While we are at or (hopefully not) above capacity... |
| 33 | +while (this.getLockCount() >= this.getMaximumLockCount()) { |
| 34 | + |
| 35 | +console.log(`Waiting to remove promise...`); |
| 36 | + |
| 37 | +let resolution: any = await Promise.any(Object.values(this.outstandingLocks)) |
| 38 | + |
| 39 | +console.log(`resolution: ${resolution}`); |
| 40 | + |
| 41 | +// Remove the first resolved promise that we find. |
| 42 | +delete this.outstandingLocks[resolution]; |
| 43 | + |
| 44 | +console.log(`...found promise to remove!`); |
| 45 | + |
| 46 | +} |
| 47 | + |
| 48 | +console.log(`Generating new lock.`); |
| 49 | + |
| 50 | +let id: string = crypto.randomBytes(16).toString("hex"); |
| 51 | + |
| 52 | +let lock: SemaphoreLock = new SemaphoreLock(id); |
| 53 | + |
| 54 | +this.outstandingLocks[id] = lock.onRelinquish(); |
| 55 | + |
| 56 | +return lock; |
| 57 | + |
| 58 | +} |
| 59 | + |
| 60 | +public getLockCount(): number { |
| 61 | + |
| 62 | +return Object.keys(this.outstandingLocks).length; |
| 63 | + |
| 64 | +} |
| 65 | + |
| 66 | +public getMaximumLockCount(): number { |
| 67 | + |
| 68 | +return this.maxLockCount; |
| 69 | + |
| 70 | +} |
| 71 | + |
| 72 | +} |
0 commit comments