UNPKG

@sanity/util

Version:

Utilities shared across projects of Sanity

1 lines 1.87 kB
{"version":3,"file":"concurrency-limiter.mjs","sources":["../src/concurrency-limiter.ts"],"sourcesContent":["/**\n * ConcurrencyLimiter manages the number of concurrent operations that can be performed.\n * It ensures that the number of operations does not exceed a specified maximum limit.\n */\nexport class ConcurrencyLimiter {\n current = 0\n resolvers: Array<() => void> = []\n public max: number\n constructor(max: number) {\n this.max = max\n }\n\n /**\n * Indicates when a slot for a new operation is ready.\n * If under the limit, it resolves immediately; otherwise, it waits until a slot is free.\n */\n ready = (): Promise<void> => {\n if (this.max === Infinity) return Promise.resolve()\n\n if (this.current < this.max) {\n this.current++\n return Promise.resolve()\n }\n\n return new Promise<void>((resolve) => {\n this.resolvers.push(resolve)\n })\n }\n\n /**\n * Releases a slot, decrementing the current count of operations if nothing is in the queue.\n * If there are operations waiting, it allows the next one in the queue to proceed.\n */\n release = (): void => {\n if (this.max === Infinity) return\n\n const nextResolver = this.resolvers.shift()\n if (nextResolver) {\n nextResolver()\n return\n }\n\n this.current = Math.max(0, this.current - 1)\n }\n}\n"],"names":[],"mappings":"AAIO,MAAM,mBAAmB;AAAA,EAC9B,UAAU;AAAA,EACV,YAA+B,CAAA;AAAA,EACxB;AAAA,EACP,YAAY,KAAa;AACvB,SAAK,MAAM;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ,MACF,KAAK,QAAQ,QAAiB,QAAQ,QAAA,IAEtC,KAAK,UAAU,KAAK,OACtB,KAAK,WACE,QAAQ,aAGV,IAAI,QAAc,CAAC,YAAY;AACpC,SAAK,UAAU,KAAK,OAAO;AAAA,EAC7B,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA,EAOH,UAAU,MAAY;AACpB,QAAI,KAAK,QAAQ,MAAU;AAE3B,UAAM,eAAe,KAAK,UAAU,MAAA;AACpC,QAAI,cAAc;AAChB,mBAAA;AACA;AAAA,IACF;AAEA,SAAK,UAAU,KAAK,IAAI,GAAG,KAAK,UAAU,CAAC;AAAA,EAC7C;AACF;"}