@chriscdn/promise-semaphore 2.0.12 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -11
- package/__tests__/semaphore.test.ts +1 -24
- package/lib/index.d.ts +0 -8
- package/lib/promise-semaphore.cjs +1 -1
- package/lib/promise-semaphore.cjs.map +1 -1
- package/lib/promise-semaphore.modern.js +1 -1
- package/lib/promise-semaphore.modern.js.map +1 -1
- package/lib/promise-semaphore.module.js +1 -1
- package/lib/promise-semaphore.module.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +3 -35
package/README.md
CHANGED
|
@@ -16,12 +16,26 @@ Using yarn:
|
|
|
16
16
|
yarn add @chriscdn/promise-semaphore
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
+
## Upgrade to v3
|
|
20
|
+
|
|
21
|
+
Change
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import Semaphore from "@chriscdn/promise-semaphore";
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
to
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { Semaphore } from "@chriscdn/promise-semaphore";
|
|
31
|
+
```
|
|
32
|
+
|
|
19
33
|
## API
|
|
20
34
|
|
|
21
35
|
### Create an instance
|
|
22
36
|
|
|
23
37
|
```js
|
|
24
|
-
import Semaphore from "@chriscdn/promise-semaphore";
|
|
38
|
+
import { Semaphore } from "@chriscdn/promise-semaphore";
|
|
25
39
|
const semaphore = new Semaphore([maxConcurrent]);
|
|
26
40
|
```
|
|
27
41
|
|
|
@@ -59,14 +73,6 @@ semaphore.count([key]);
|
|
|
59
73
|
|
|
60
74
|
This synchronous function returns the current number of locks.
|
|
61
75
|
|
|
62
|
-
### `wait` method
|
|
63
|
-
|
|
64
|
-
```js
|
|
65
|
-
semaphore.wait([key]);
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
This asynchronous function resolves immediately if `count` is 0; otherwise, it resolves once `count` reaches 0.
|
|
69
|
-
|
|
70
76
|
### `request` method
|
|
71
77
|
|
|
72
78
|
```js
|
|
@@ -103,7 +109,7 @@ This is useful in scenarios where only one instance of a function block should r
|
|
|
103
109
|
## Example 1
|
|
104
110
|
|
|
105
111
|
```js
|
|
106
|
-
import Semaphore from "@chriscdn/promise-semaphore";
|
|
112
|
+
import { Semaphore } from "@chriscdn/promise-semaphore";
|
|
107
113
|
const semaphore = new Semaphore();
|
|
108
114
|
|
|
109
115
|
// Using promises
|
|
@@ -158,7 +164,7 @@ This approach works as expected until `downloadAndSave()` is called multiple tim
|
|
|
158
164
|
This issue can be resolved by using a `Semaphore` with the `key` parameter:
|
|
159
165
|
|
|
160
166
|
```js
|
|
161
|
-
import Semaphore from "@chriscdn/promise-semaphore";
|
|
167
|
+
import { Semaphore } from "@chriscdn/promise-semaphore";
|
|
162
168
|
const semaphore = new Semaphore();
|
|
163
169
|
|
|
164
170
|
const downloadAndSave = async (url) => {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
2
|
|
|
3
|
-
import Semaphore from "../src/index";
|
|
3
|
+
import { Semaphore } from "../src/index";
|
|
4
4
|
|
|
5
5
|
const pause = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
6
6
|
|
|
@@ -145,26 +145,3 @@ describe("All test", () => {
|
|
|
145
145
|
});
|
|
146
146
|
});
|
|
147
147
|
});
|
|
148
|
-
|
|
149
|
-
describe("Wait TEST", () => {
|
|
150
|
-
const semaphore = new Semaphore(2);
|
|
151
|
-
|
|
152
|
-
it("Acquire & Release Basic", async () => {
|
|
153
|
-
let tester = 0;
|
|
154
|
-
|
|
155
|
-
semaphore
|
|
156
|
-
.acquire()
|
|
157
|
-
.then(() => pause(1000))
|
|
158
|
-
.then(() => (tester = 20))
|
|
159
|
-
.finally(() => semaphore.release());
|
|
160
|
-
|
|
161
|
-
semaphore
|
|
162
|
-
.acquire()
|
|
163
|
-
.then(() => pause(500))
|
|
164
|
-
.then(() => (tester = 10))
|
|
165
|
-
.finally(() => semaphore.release());
|
|
166
|
-
|
|
167
|
-
await semaphore.wait(); // WAIT for all tasks to finish
|
|
168
|
-
expect(tester).toBe(20);
|
|
169
|
-
});
|
|
170
|
-
});
|
package/lib/index.d.ts
CHANGED
|
@@ -53,13 +53,5 @@ declare class Semaphore {
|
|
|
53
53
|
* @returns {Promise<T>}
|
|
54
54
|
*/
|
|
55
55
|
requestIfAvailable<T>(fn: Function, key?: string | number): Promise<T | null>;
|
|
56
|
-
/**
|
|
57
|
-
* Wait until the count on `key` is 0 and then resolve.
|
|
58
|
-
*
|
|
59
|
-
* @param key
|
|
60
|
-
* @returns
|
|
61
|
-
*/
|
|
62
|
-
wait(key?: string | number): Promise<void>;
|
|
63
56
|
}
|
|
64
|
-
export default Semaphore;
|
|
65
57
|
export { Semaphore };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var t=/*#__PURE__*/function(){function t(e){this.queue=void 0,this.
|
|
1
|
+
function e(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var t=/*#__PURE__*/function(){function t(e){this.queue=void 0,this.maxConcurrent=void 0,this.count=void 0,this.queue=[],this.maxConcurrent=e,this.count=0}var n,r,i=t.prototype;return i.incrementCount=function(){this.count++},i.decrementCount=function(){this.count--},i.acquire=function(){var e=this;return this.canAcquire?(this.incrementCount(),Promise.resolve()):new Promise(function(t){return e.queue.push(t)})},i.release=function(){var e=this.queue.shift();e?setTimeout(e,0):this.decrementCount()},n=t,(r=[{key:"canAcquire",get:function(){return this.count<this.maxConcurrent}}])&&function(t,n){for(var r=0;r<n.length;r++){var i=n[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,e(i.key),i)}}(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n}(),n="_default";exports.Semaphore=/*#__PURE__*/function(){function e(e){void 0===e&&(e=1),this.semaphoreInstances=void 0,this.maxConcurrent=void 0,this.semaphoreInstances={},this.maxConcurrent=e}var r=e.prototype;return r.hasSemaphoreInstance=function(e){return void 0===e&&(e=n),Boolean(this.semaphoreInstances[e])},r.getSemaphoreInstance=function(e){return void 0===e&&(e=n),this.hasSemaphoreInstance(e)||(this.semaphoreInstances[e]=new t(this.maxConcurrent)),this.semaphoreInstances[e]},r.tidy=function(e){void 0===e&&(e=n),this.hasSemaphoreInstance(e)&&0===this.getSemaphoreInstance(e).count&&delete this.semaphoreInstances[e]},r.canAcquire=function(e){return void 0===e&&(e=n),!this.hasSemaphoreInstance(e)||this.getSemaphoreInstance(e).canAcquire},r.acquire=function(e){return void 0===e&&(e=n),this.getSemaphoreInstance(e).acquire()},r.release=function(e){void 0===e&&(e=n),this.getSemaphoreInstance(e).release(),this.tidy(e)},r.count=function(e){return void 0===e&&(e=n),this.hasSemaphoreInstance(e)?this.getSemaphoreInstance(e).count:0},r.hasTasks=function(e){return void 0===e&&(e=n),this.count(e)>0},r.request=function(e,t){void 0===t&&(t=n);try{var r=this;return Promise.resolve(function(n,i){try{var o=Promise.resolve(r.acquire(t)).then(function(){return Promise.resolve(e())})}catch(e){return i(!0,e)}return o&&o.then?o.then(i.bind(null,!1),i.bind(null,!0)):i(!1,o)}(0,function(e,n){if(r.release(t),e)throw n;return n}))}catch(e){return Promise.reject(e)}},r.requestIfAvailable=function(e,t){void 0===t&&(t=n);try{return this.canAcquire(t)?Promise.resolve(this.request(e,t)):Promise.resolve(null)}catch(e){return Promise.reject(e)}},e}();
|
|
2
2
|
//# sourceMappingURL=promise-semaphore.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"promise-semaphore.cjs","sources":["../src/index.ts"],"sourcesContent":["class SemaphoreItem {\n private queue:
|
|
1
|
+
{"version":3,"file":"promise-semaphore.cjs","sources":["../src/index.ts"],"sourcesContent":["class SemaphoreItem {\n private queue: Function[];\n private maxConcurrent: number;\n\n /**\n * The number of locks.\n */\n public count: number;\n\n constructor(maxConcurrent: number) {\n this.queue = [];\n this.maxConcurrent = maxConcurrent;\n this.count = 0;\n }\n\n get canAcquire(): boolean {\n return this.count < this.maxConcurrent;\n }\n\n private incrementCount() {\n this.count++;\n }\n\n private decrementCount() {\n this.count--;\n }\n\n acquire(): Promise<void> {\n if (this.canAcquire) {\n this.incrementCount();\n return Promise.resolve();\n } else {\n return new Promise((resolve) => this.queue.push(resolve));\n }\n }\n\n release(): void {\n const resolveFunc = this.queue.shift();\n\n if (resolveFunc) {\n // Give the micro task queue a small break instead of calling resolveFunc() directly\n setTimeout(resolveFunc, 0);\n } else {\n this.decrementCount();\n }\n }\n}\n\nconst defaultKey = \"_default\";\n\nclass Semaphore {\n private semaphoreInstances: Record<string | number, SemaphoreItem>;\n private maxConcurrent: number;\n\n /**\n * @param {number} [maxConcurrent] The maximum number of concurrent locks.\n */\n constructor(maxConcurrent: number = 1) {\n this.semaphoreInstances = {};\n this.maxConcurrent = maxConcurrent;\n }\n\n private hasSemaphoreInstance(key: string | number = defaultKey) {\n return Boolean(this.semaphoreInstances[key]);\n }\n\n private getSemaphoreInstance(key: string | number = defaultKey) {\n if (!this.hasSemaphoreInstance(key)) {\n this.semaphoreInstances[key] = new SemaphoreItem(this.maxConcurrent);\n }\n return this.semaphoreInstances[key];\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n private tidy(key: string | number = defaultKey): void {\n if (\n this.hasSemaphoreInstance(key) &&\n this.getSemaphoreInstance(key).count === 0\n ) {\n delete this.semaphoreInstances[key];\n }\n }\n\n /**\n * A synchronous function to determine whether a lock can be acquired.\n *\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {boolean} Returns true if the lock on `key` can be acquired, false\n * otherwise.\n */\n canAcquire(key: string | number = defaultKey): boolean {\n return !this.hasSemaphoreInstance(key) ||\n this.getSemaphoreInstance(key).canAcquire;\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n acquire(key: string | number = defaultKey) {\n return this.getSemaphoreInstance(key).acquire();\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n release(key: string | number = defaultKey): void {\n this.getSemaphoreInstance(key).release();\n this.tidy(key);\n }\n\n /**\n * The number of active locks. Will always be less or equal to `max`.\n *\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n count(key: string | number = defaultKey): number {\n if (this.hasSemaphoreInstance(key)) {\n return this.getSemaphoreInstance(key).count;\n } else {\n return 0;\n }\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {boolean} True if the semaphore and key has locks, false otherwise.\n */\n hasTasks(key: string | number = defaultKey): boolean {\n return this.count(key) > 0;\n }\n\n /**\n * @param {Function<T>} fn The function to execute.\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {Promise<T>}\n */\n async request<T>(\n fn: Function,\n key: string | number = defaultKey,\n ): Promise<T> {\n try {\n await this.acquire(key);\n return await fn();\n } finally {\n this.release(key);\n }\n }\n\n /**\n * Asynchronously executes `fn` if a lock can be immediately acquired.\n * Otherwise, returns null.\n *\n * @param {Function<T>} fn The function to execute.\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {Promise<T>}\n */\n async requestIfAvailable<T>(\n fn: Function,\n key: string | number = defaultKey,\n ): Promise<T | null> {\n if (this.canAcquire(key)) {\n return this.request(fn, key);\n } else {\n return null;\n }\n }\n}\n\nexport { Semaphore };\n"],"names":["SemaphoreItem","maxConcurrent","queue","this","count","_proto","prototype","incrementCount","decrementCount","acquire","_this","canAcquire","Promise","resolve","push","release","resolveFunc","shift","setTimeout","key","get","defaultKey","Semaphore","semaphoreInstances","_proto2","hasSemaphoreInstance","Boolean","getSemaphoreInstance","tidy","hasTasks","request","fn","_this2","then","_finallyRethrows","_wasThrown","_result","e","reject","requestIfAvailable"],"mappings":"mSAAMA,eAAa,WASjB,SAAAA,EAAYC,GARJC,KAAAA,kBACAD,mBAAa,EAAAE,KAKdC,WAGL,EAAAD,KAAKD,MAAQ,GACbC,KAAKF,cAAgBA,EACrBE,KAAKC,MAAQ,CACf,CAAC,QAAAC,EAAAL,EAAAM,iBAAAD,EAMOE,eAAA,WACNJ,KAAKC,OACP,EAACC,EAEOG,eAAA,WACNL,KAAKC,OACP,EAACC,EAEDI,QAAA,WAAOC,IAAAA,OACL,OAAIP,KAAKQ,YACPR,KAAKI,iBACEK,QAAQC,eAEJD,QAAQ,SAACC,UAAYH,EAAKR,MAAMY,KAAKD,EAAQ,EAE5D,EAACR,EAEDU,QAAA,WACE,IAAMC,EAAcb,KAAKD,MAAMe,QAE3BD,EAEFE,WAAWF,EAAa,GAExBb,KAAKK,gBAET,IAACR,KAAAmB,CAAAA,CAAAA,iBAAAC,IA9BD,WACE,OAAOjB,KAAKC,MAAQD,KAAKF,aAC3B,iPA+BF,CAhDmB,GAgDboB,EAAa,0CAEJ,WAOb,SAAAC,EAAYrB,YAAAA,IAAAA,EAAwB,GAACE,KAN7BoB,wBACAtB,EAAAA,KAAAA,qBAMNE,KAAKoB,mBAAqB,CAAA,EAC1BpB,KAAKF,cAAgBA,CACvB,CAAC,IAAAuB,EAAAF,EAAAhB,iBAAAkB,EAEOC,qBAAA,SAAqBN,GAC3B,gBAD2BA,IAAAA,EAAuBE,GAC3CK,QAAQvB,KAAKoB,mBAAmBJ,GACzC,EAACK,EAEOG,qBAAA,SAAqBR,GAI3B,gBAJ2BA,IAAAA,EAAuBE,GAC7ClB,KAAKsB,qBAAqBN,KAC7BhB,KAAKoB,mBAAmBJ,GAAO,IAAInB,EAAcG,KAAKF,gBAEjDE,KAAK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UAAAzB,QAAA0B,OAAAD,KAAAf,CAAA,CArHY"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class e{constructor(e){this.queue=void 0,this.
|
|
1
|
+
class e{constructor(e){this.queue=void 0,this.maxConcurrent=void 0,this.count=void 0,this.queue=[],this.maxConcurrent=e,this.count=0}get canAcquire(){return this.count<this.maxConcurrent}incrementCount(){this.count++}decrementCount(){this.count--}acquire(){return this.canAcquire?(this.incrementCount(),Promise.resolve()):new Promise(e=>this.queue.push(e))}release(){const e=this.queue.shift();e?setTimeout(e,0):this.decrementCount()}}const t="_default";class s{constructor(e=1){this.semaphoreInstances=void 0,this.maxConcurrent=void 0,this.semaphoreInstances={},this.maxConcurrent=e}hasSemaphoreInstance(e=t){return Boolean(this.semaphoreInstances[e])}getSemaphoreInstance(s=t){return this.hasSemaphoreInstance(s)||(this.semaphoreInstances[s]=new e(this.maxConcurrent)),this.semaphoreInstances[s]}tidy(e=t){this.hasSemaphoreInstance(e)&&0===this.getSemaphoreInstance(e).count&&delete this.semaphoreInstances[e]}canAcquire(e=t){return!this.hasSemaphoreInstance(e)||this.getSemaphoreInstance(e).canAcquire}acquire(e=t){return this.getSemaphoreInstance(e).acquire()}release(e=t){this.getSemaphoreInstance(e).release(),this.tidy(e)}count(e=t){return this.hasSemaphoreInstance(e)?this.getSemaphoreInstance(e).count:0}hasTasks(e=t){return this.count(e)>0}async request(e,s=t){try{return await this.acquire(s),await e()}finally{this.release(s)}}async requestIfAvailable(e,s=t){return this.canAcquire(s)?this.request(e,s):null}}export{s as Semaphore};
|
|
2
2
|
//# sourceMappingURL=promise-semaphore.modern.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"promise-semaphore.modern.js","sources":["../src/index.ts"],"sourcesContent":["class SemaphoreItem {\n private queue:
|
|
1
|
+
{"version":3,"file":"promise-semaphore.modern.js","sources":["../src/index.ts"],"sourcesContent":["class SemaphoreItem {\n private queue: Function[];\n private maxConcurrent: number;\n\n /**\n * The number of locks.\n */\n public count: number;\n\n constructor(maxConcurrent: number) {\n this.queue = [];\n this.maxConcurrent = maxConcurrent;\n this.count = 0;\n }\n\n get canAcquire(): boolean {\n return this.count < this.maxConcurrent;\n }\n\n private incrementCount() {\n this.count++;\n }\n\n private decrementCount() {\n this.count--;\n }\n\n acquire(): Promise<void> {\n if (this.canAcquire) {\n this.incrementCount();\n return Promise.resolve();\n } else {\n return new Promise((resolve) => this.queue.push(resolve));\n }\n }\n\n release(): void {\n const resolveFunc = this.queue.shift();\n\n if (resolveFunc) {\n // Give the micro task queue a small break instead of calling resolveFunc() directly\n setTimeout(resolveFunc, 0);\n } else {\n this.decrementCount();\n }\n }\n}\n\nconst defaultKey = \"_default\";\n\nclass Semaphore {\n private semaphoreInstances: Record<string | number, SemaphoreItem>;\n private maxConcurrent: number;\n\n /**\n * @param {number} [maxConcurrent] The maximum number of concurrent locks.\n */\n constructor(maxConcurrent: number = 1) {\n this.semaphoreInstances = {};\n this.maxConcurrent = maxConcurrent;\n }\n\n private hasSemaphoreInstance(key: string | number = defaultKey) {\n return Boolean(this.semaphoreInstances[key]);\n }\n\n private getSemaphoreInstance(key: string | number = defaultKey) {\n if (!this.hasSemaphoreInstance(key)) {\n this.semaphoreInstances[key] = new SemaphoreItem(this.maxConcurrent);\n }\n return this.semaphoreInstances[key];\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n private tidy(key: string | number = defaultKey): void {\n if (\n this.hasSemaphoreInstance(key) &&\n this.getSemaphoreInstance(key).count === 0\n ) {\n delete this.semaphoreInstances[key];\n }\n }\n\n /**\n * A synchronous function to determine whether a lock can be acquired.\n *\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {boolean} Returns true if the lock on `key` can be acquired, false\n * otherwise.\n */\n canAcquire(key: string | number = defaultKey): boolean {\n return !this.hasSemaphoreInstance(key) ||\n this.getSemaphoreInstance(key).canAcquire;\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n acquire(key: string | number = defaultKey) {\n return this.getSemaphoreInstance(key).acquire();\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n release(key: string | number = defaultKey): void {\n this.getSemaphoreInstance(key).release();\n this.tidy(key);\n }\n\n /**\n * The number of active locks. Will always be less or equal to `max`.\n *\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n count(key: string | number = defaultKey): number {\n if (this.hasSemaphoreInstance(key)) {\n return this.getSemaphoreInstance(key).count;\n } else {\n return 0;\n }\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {boolean} True if the semaphore and key has locks, false otherwise.\n */\n hasTasks(key: string | number = defaultKey): boolean {\n return this.count(key) > 0;\n }\n\n /**\n * @param {Function<T>} fn The function to execute.\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {Promise<T>}\n */\n async request<T>(\n fn: Function,\n key: string | number = defaultKey,\n ): Promise<T> {\n try {\n await this.acquire(key);\n return await fn();\n } finally {\n this.release(key);\n }\n }\n\n /**\n * Asynchronously executes `fn` if a lock can be immediately acquired.\n * Otherwise, returns null.\n *\n * @param {Function<T>} fn The function to execute.\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {Promise<T>}\n */\n async requestIfAvailable<T>(\n fn: Function,\n key: string | number = defaultKey,\n ): Promise<T | null> {\n if (this.canAcquire(key)) {\n return this.request(fn, key);\n } else {\n return null;\n }\n }\n}\n\nexport { Semaphore };\n"],"names":["SemaphoreItem","constructor","maxConcurrent","this","queue","count","canAcquire","incrementCount","decrementCount","acquire","Promise","resolve","push","release","resolveFunc","shift","setTimeout","defaultKey","Semaphore","semaphoreInstances","hasSemaphoreInstance","key","Boolean","getSemaphoreInstance","tidy","hasTasks","request","fn","requestIfAvailable"],"mappings":"AAAA,MAAMA,EASJC,WAAAA,CAAYC,GAAqBC,KARzBC,WAAK,EAAAD,KACLD,mBAAa,EAAAC,KAKdE,WAGL,EAAAF,KAAKC,MAAQ,GACbD,KAAKD,cAAgBA,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AqBC,GACrBlB,KAAKoB,qBAAqBF,GAAKhB,MAGvC,CACH,CAMAoB,QAAAA,CAASJ,EAAuBJ,GAC9B,OAAWd,KAACE,MAAMgB,GAAO,CAC3B,CAOA,aAAMK,CACJC,EACAN,EAAuBJ,GAEvB,IAEE,aADUd,KAACM,QAAQY,SACNM,GACd,CAAA,QACCxB,KAAKU,QAAQQ,EACd,CACH,CAUA,wBAAMO,CACJD,EACAN,EAAuBJ,GAEvB,OAAId,KAAKG,WAAWe,GACPlB,KAACuB,QAAQC,EAAIN,GAEjB,IAEX"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var t=/*#__PURE__*/function(){function t(e){this.queue=void 0,this.
|
|
1
|
+
function e(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var t=/*#__PURE__*/function(){function t(e){this.queue=void 0,this.maxConcurrent=void 0,this.count=void 0,this.queue=[],this.maxConcurrent=e,this.count=0}var n,r,i=t.prototype;return i.incrementCount=function(){this.count++},i.decrementCount=function(){this.count--},i.acquire=function(){var e=this;return this.canAcquire?(this.incrementCount(),Promise.resolve()):new Promise(function(t){return e.queue.push(t)})},i.release=function(){var e=this.queue.shift();e?setTimeout(e,0):this.decrementCount()},n=t,(r=[{key:"canAcquire",get:function(){return this.count<this.maxConcurrent}}])&&function(t,n){for(var r=0;r<n.length;r++){var i=n[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,e(i.key),i)}}(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),n}(),n="_default",r=/*#__PURE__*/function(){function e(e){void 0===e&&(e=1),this.semaphoreInstances=void 0,this.maxConcurrent=void 0,this.semaphoreInstances={},this.maxConcurrent=e}var r=e.prototype;return r.hasSemaphoreInstance=function(e){return void 0===e&&(e=n),Boolean(this.semaphoreInstances[e])},r.getSemaphoreInstance=function(e){return void 0===e&&(e=n),this.hasSemaphoreInstance(e)||(this.semaphoreInstances[e]=new t(this.maxConcurrent)),this.semaphoreInstances[e]},r.tidy=function(e){void 0===e&&(e=n),this.hasSemaphoreInstance(e)&&0===this.getSemaphoreInstance(e).count&&delete this.semaphoreInstances[e]},r.canAcquire=function(e){return void 0===e&&(e=n),!this.hasSemaphoreInstance(e)||this.getSemaphoreInstance(e).canAcquire},r.acquire=function(e){return void 0===e&&(e=n),this.getSemaphoreInstance(e).acquire()},r.release=function(e){void 0===e&&(e=n),this.getSemaphoreInstance(e).release(),this.tidy(e)},r.count=function(e){return void 0===e&&(e=n),this.hasSemaphoreInstance(e)?this.getSemaphoreInstance(e).count:0},r.hasTasks=function(e){return void 0===e&&(e=n),this.count(e)>0},r.request=function(e,t){void 0===t&&(t=n);try{var r=this;return Promise.resolve(function(n,i){try{var o=Promise.resolve(r.acquire(t)).then(function(){return Promise.resolve(e())})}catch(e){return i(!0,e)}return o&&o.then?o.then(i.bind(null,!1),i.bind(null,!0)):i(!1,o)}(0,function(e,n){if(r.release(t),e)throw n;return n}))}catch(e){return Promise.reject(e)}},r.requestIfAvailable=function(e,t){void 0===t&&(t=n);try{return this.canAcquire(t)?Promise.resolve(this.request(e,t)):Promise.resolve(null)}catch(e){return Promise.reject(e)}},e}();export{r as Semaphore};
|
|
2
2
|
//# sourceMappingURL=promise-semaphore.module.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"promise-semaphore.module.js","sources":["../src/index.ts"],"sourcesContent":["class SemaphoreItem {\n private queue:
|
|
1
|
+
{"version":3,"file":"promise-semaphore.module.js","sources":["../src/index.ts"],"sourcesContent":["class SemaphoreItem {\n private queue: Function[];\n private maxConcurrent: number;\n\n /**\n * The number of locks.\n */\n public count: number;\n\n constructor(maxConcurrent: number) {\n this.queue = [];\n this.maxConcurrent = maxConcurrent;\n this.count = 0;\n }\n\n get canAcquire(): boolean {\n return this.count < this.maxConcurrent;\n }\n\n private incrementCount() {\n this.count++;\n }\n\n private decrementCount() {\n this.count--;\n }\n\n acquire(): Promise<void> {\n if (this.canAcquire) {\n this.incrementCount();\n return Promise.resolve();\n } else {\n return new Promise((resolve) => this.queue.push(resolve));\n }\n }\n\n release(): void {\n const resolveFunc = this.queue.shift();\n\n if (resolveFunc) {\n // Give the micro task queue a small break instead of calling resolveFunc() directly\n setTimeout(resolveFunc, 0);\n } else {\n this.decrementCount();\n }\n }\n}\n\nconst defaultKey = \"_default\";\n\nclass Semaphore {\n private semaphoreInstances: Record<string | number, SemaphoreItem>;\n private maxConcurrent: number;\n\n /**\n * @param {number} [maxConcurrent] The maximum number of concurrent locks.\n */\n constructor(maxConcurrent: number = 1) {\n this.semaphoreInstances = {};\n this.maxConcurrent = maxConcurrent;\n }\n\n private hasSemaphoreInstance(key: string | number = defaultKey) {\n return Boolean(this.semaphoreInstances[key]);\n }\n\n private getSemaphoreInstance(key: string | number = defaultKey) {\n if (!this.hasSemaphoreInstance(key)) {\n this.semaphoreInstances[key] = new SemaphoreItem(this.maxConcurrent);\n }\n return this.semaphoreInstances[key];\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n private tidy(key: string | number = defaultKey): void {\n if (\n this.hasSemaphoreInstance(key) &&\n this.getSemaphoreInstance(key).count === 0\n ) {\n delete this.semaphoreInstances[key];\n }\n }\n\n /**\n * A synchronous function to determine whether a lock can be acquired.\n *\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {boolean} Returns true if the lock on `key` can be acquired, false\n * otherwise.\n */\n canAcquire(key: string | number = defaultKey): boolean {\n return !this.hasSemaphoreInstance(key) ||\n this.getSemaphoreInstance(key).canAcquire;\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n acquire(key: string | number = defaultKey) {\n return this.getSemaphoreInstance(key).acquire();\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n release(key: string | number = defaultKey): void {\n this.getSemaphoreInstance(key).release();\n this.tidy(key);\n }\n\n /**\n * The number of active locks. Will always be less or equal to `max`.\n *\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n count(key: string | number = defaultKey): number {\n if (this.hasSemaphoreInstance(key)) {\n return this.getSemaphoreInstance(key).count;\n } else {\n return 0;\n }\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {boolean} True if the semaphore and key has locks, false otherwise.\n */\n hasTasks(key: string | number = defaultKey): boolean {\n return this.count(key) > 0;\n }\n\n /**\n * @param {Function<T>} fn The function to execute.\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {Promise<T>}\n */\n async request<T>(\n fn: Function,\n key: string | number = defaultKey,\n ): Promise<T> {\n try {\n await this.acquire(key);\n return await fn();\n } finally {\n this.release(key);\n }\n }\n\n /**\n * Asynchronously executes `fn` if a lock can be immediately acquired.\n * Otherwise, returns null.\n *\n * @param {Function<T>} fn The function to execute.\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {Promise<T>}\n */\n async requestIfAvailable<T>(\n fn: Function,\n key: string | number = defaultKey,\n ): Promise<T | null> {\n if (this.canAcquire(key)) {\n return this.request(fn, key);\n } else {\n return null;\n }\n }\n}\n\nexport { Semaphore };\n"],"names":["SemaphoreItem","maxConcurrent","queue","this","count","_proto","prototype","incrementCount","decrementCount","acquire","_this","canAcquire","Promise","resolve","push","release","resolveFunc","shift","setTimeout","key","get","defaultKey","Semaphore","semaphoreInstances","_proto2","hasSemaphoreInstance","Boolean","getSemaphoreInstance","tidy","hasTasks","request","fn","_this2","then","_finallyRethrows","_wasThrown","_result","e","reject","requestIfAvailable"],"mappings":"mSAAMA,eAAa,WASjB,SAAAA,EA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
|
4
4
|
"description": "Limit or throttle the simultaneous execution of asynchronous code in separate iterations of the event loop.",
|
|
5
5
|
"repository": "https://github.com/chriscdn/promise-semaphore",
|
|
6
6
|
"author": "Christopher Meyer <chris@schwiiz.org>",
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
class SemaphoreItem {
|
|
2
|
-
private queue:
|
|
3
|
-
private waitQueue: Array<Function>;
|
|
2
|
+
private queue: Function[];
|
|
4
3
|
private maxConcurrent: number;
|
|
5
4
|
|
|
6
5
|
/**
|
|
@@ -10,7 +9,6 @@ class SemaphoreItem {
|
|
|
10
9
|
|
|
11
10
|
constructor(maxConcurrent: number) {
|
|
12
11
|
this.queue = [];
|
|
13
|
-
this.waitQueue = [];
|
|
14
12
|
this.maxConcurrent = maxConcurrent;
|
|
15
13
|
this.count = 0;
|
|
16
14
|
}
|
|
@@ -25,11 +23,6 @@ class SemaphoreItem {
|
|
|
25
23
|
|
|
26
24
|
private decrementCount() {
|
|
27
25
|
this.count--;
|
|
28
|
-
|
|
29
|
-
if (this.count === 0) {
|
|
30
|
-
this.waitQueue.forEach((resolve) => resolve());
|
|
31
|
-
this.waitQueue = [];
|
|
32
|
-
}
|
|
33
26
|
}
|
|
34
27
|
|
|
35
28
|
acquire(): Promise<void> {
|
|
@@ -51,10 +44,6 @@ class SemaphoreItem {
|
|
|
51
44
|
this.decrementCount();
|
|
52
45
|
}
|
|
53
46
|
}
|
|
54
|
-
|
|
55
|
-
wait(): Promise<void> {
|
|
56
|
-
return new Promise((resolve) => this.waitQueue.push(resolve));
|
|
57
|
-
}
|
|
58
47
|
}
|
|
59
48
|
|
|
60
49
|
const defaultKey = "_default";
|
|
@@ -102,7 +91,8 @@ class Semaphore {
|
|
|
102
91
|
* otherwise.
|
|
103
92
|
*/
|
|
104
93
|
canAcquire(key: string | number = defaultKey): boolean {
|
|
105
|
-
return this.
|
|
94
|
+
return !this.hasSemaphoreInstance(key) ||
|
|
95
|
+
this.getSemaphoreInstance(key).canAcquire;
|
|
106
96
|
}
|
|
107
97
|
|
|
108
98
|
/**
|
|
@@ -176,28 +166,6 @@ class Semaphore {
|
|
|
176
166
|
return null;
|
|
177
167
|
}
|
|
178
168
|
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Wait until the count on `key` is 0 and then resolve.
|
|
182
|
-
*
|
|
183
|
-
* @param key
|
|
184
|
-
* @returns
|
|
185
|
-
*/
|
|
186
|
-
async wait(key: string | number = defaultKey) {
|
|
187
|
-
if (this.hasTasks(key)) {
|
|
188
|
-
return this.getSemaphoreInstance(key).wait();
|
|
189
|
-
} else {
|
|
190
|
-
return Promise.resolve();
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
// globalCount() {
|
|
195
|
-
// return Object.values(this.semaphoreInstances).reduce(
|
|
196
|
-
// (a, instance) => a + instance.count,
|
|
197
|
-
// 0,
|
|
198
|
-
// );
|
|
199
|
-
// }
|
|
200
169
|
}
|
|
201
170
|
|
|
202
|
-
export default Semaphore;
|
|
203
171
|
export { Semaphore };
|