@chriscdn/promise-semaphore 3.0.0 → 3.0.1
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 +86 -25
- package/lib/group-semaphore.d.ts +25 -0
- package/lib/index.d.ts +2 -57
- 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/lib/semaphore.d.ts +57 -0
- package/package.json +1 -1
- package/src/group-semaphore.ts +46 -0
- package/src/index.ts +2 -171
- package/src/semaphore.ts +173 -0
package/README.md
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# @chriscdn/promise-semaphore
|
|
2
2
|
|
|
3
|
-
Limit or throttle the
|
|
3
|
+
Limit or throttle the concurrent execution of asynchronous code in separate
|
|
4
|
+
iterations of the event loop.
|
|
4
5
|
|
|
5
6
|
## Installing
|
|
6
7
|
|
|
@@ -16,21 +17,28 @@ Using yarn:
|
|
|
16
17
|
yarn add @chriscdn/promise-semaphore
|
|
17
18
|
```
|
|
18
19
|
|
|
19
|
-
##
|
|
20
|
+
## Version 3
|
|
20
21
|
|
|
21
|
-
|
|
22
|
+
Version 3 introduces two main changes:
|
|
23
|
+
|
|
24
|
+
- A new `GroupSemaphore` class has been added. It allows multiple tasks within
|
|
25
|
+
the same group (identified by a key) to run concurrently while ensuring that
|
|
26
|
+
only one group's tasks are active at a time. See below for documentation.
|
|
27
|
+
- The default export has been replaced with a named export.
|
|
28
|
+
|
|
29
|
+
Change:
|
|
22
30
|
|
|
23
31
|
```ts
|
|
24
32
|
import Semaphore from "@chriscdn/promise-semaphore";
|
|
25
33
|
```
|
|
26
34
|
|
|
27
|
-
to
|
|
35
|
+
to:
|
|
28
36
|
|
|
29
37
|
```ts
|
|
30
38
|
import { Semaphore } from "@chriscdn/promise-semaphore";
|
|
31
39
|
```
|
|
32
40
|
|
|
33
|
-
## API
|
|
41
|
+
## API - Semaphore
|
|
34
42
|
|
|
35
43
|
### Create an instance
|
|
36
44
|
|
|
@@ -39,7 +47,10 @@ import { Semaphore } from "@chriscdn/promise-semaphore";
|
|
|
39
47
|
const semaphore = new Semaphore([maxConcurrent]);
|
|
40
48
|
```
|
|
41
49
|
|
|
42
|
-
The `maxConcurrent` parameter is optional and defaults to `1` (making it an
|
|
50
|
+
The `maxConcurrent` parameter is optional and defaults to `1` (making it an
|
|
51
|
+
exclusive lock or _binary semaphore_). An integer greater than `1` can be used
|
|
52
|
+
to allow multiple concurrent executions from separate iterations of the event
|
|
53
|
+
loop.
|
|
43
54
|
|
|
44
55
|
### Acquire a lock
|
|
45
56
|
|
|
@@ -47,7 +58,9 @@ The `maxConcurrent` parameter is optional and defaults to `1` (making it an excl
|
|
|
47
58
|
semaphore.acquire([key]);
|
|
48
59
|
```
|
|
49
60
|
|
|
50
|
-
This returns a `Promise` that resolves once a lock is acquired. The `key`
|
|
61
|
+
This returns a `Promise` that resolves once a lock is acquired. The `key`
|
|
62
|
+
parameter is optional and allows the same `Semaphore` instance to manage locks
|
|
63
|
+
in different contexts. Additional details are provided in the second example.
|
|
51
64
|
|
|
52
65
|
### Release a lock
|
|
53
66
|
|
|
@@ -55,7 +68,8 @@ This returns a `Promise` that resolves once a lock is acquired. The `key` parame
|
|
|
55
68
|
semaphore.release([key]);
|
|
56
69
|
```
|
|
57
70
|
|
|
58
|
-
The `release` method should be called within a `finally` block (whether using
|
|
71
|
+
The `release` method should be called within a `finally` block (whether using
|
|
72
|
+
promises or a `try/catch` block) to ensure the lock is released.
|
|
59
73
|
|
|
60
74
|
### Check if a lock can be acquired
|
|
61
75
|
|
|
@@ -63,7 +77,8 @@ The `release` method should be called within a `finally` block (whether using pr
|
|
|
63
77
|
semaphore.canAcquire([key]);
|
|
64
78
|
```
|
|
65
79
|
|
|
66
|
-
This synchronous method returns `true` if a lock can be immediately acquired,
|
|
80
|
+
This synchronous method returns `true` if a lock can be immediately acquired,
|
|
81
|
+
and `false` otherwise.
|
|
67
82
|
|
|
68
83
|
### `count`
|
|
69
84
|
|
|
@@ -71,7 +86,7 @@ This synchronous method returns `true` if a lock can be immediately acquired, an
|
|
|
71
86
|
semaphore.count([key]);
|
|
72
87
|
```
|
|
73
88
|
|
|
74
|
-
This synchronous
|
|
89
|
+
This function is synchronous, and returns the current number of locks.
|
|
75
90
|
|
|
76
91
|
### `request` method
|
|
77
92
|
|
|
@@ -79,12 +94,13 @@ This synchronous function returns the current number of locks.
|
|
|
79
94
|
const results = await semaphore.request(fn [, key]);
|
|
80
95
|
```
|
|
81
96
|
|
|
82
|
-
This function reduces boilerplate when using `acquire` and `release`. It returns
|
|
97
|
+
This function reduces boilerplate when using `acquire` and `release`. It returns
|
|
98
|
+
a promise that resolves when `fn` completes. It is functionally equivalent to:
|
|
83
99
|
|
|
84
100
|
```js
|
|
85
101
|
try {
|
|
86
102
|
await semaphore.acquire([key]);
|
|
87
|
-
|
|
103
|
+
return await fn();
|
|
88
104
|
} finally {
|
|
89
105
|
semaphore.release([key]);
|
|
90
106
|
}
|
|
@@ -99,12 +115,12 @@ const results = await semaphore.requestIfAvailable(fn [, key]);
|
|
|
99
115
|
This is functionally equivalent to:
|
|
100
116
|
|
|
101
117
|
```js
|
|
102
|
-
|
|
103
|
-
? await semaphore.request(fn, [key])
|
|
104
|
-
: null;
|
|
118
|
+
return semaphore.canAcquire([key]) ? await semaphore.request(fn, [key]) : null;
|
|
105
119
|
```
|
|
106
120
|
|
|
107
|
-
This is useful in scenarios where only one instance of a function block should
|
|
121
|
+
This is useful in scenarios where only one instance of a function block should
|
|
122
|
+
run while discarding additional attempts. For example, handling repeated button
|
|
123
|
+
clicks.
|
|
108
124
|
|
|
109
125
|
## Example 1
|
|
110
126
|
|
|
@@ -119,7 +135,7 @@ semaphore
|
|
|
119
135
|
// This block executes once a lock is acquired.
|
|
120
136
|
// If already locked, it waits and executes after all preceding locks are released.
|
|
121
137
|
//
|
|
122
|
-
// Critical operations
|
|
138
|
+
// Critical operations
|
|
123
139
|
})
|
|
124
140
|
.finally(() => {
|
|
125
141
|
// The lock is released, allowing the next queued block to proceed.
|
|
@@ -130,14 +146,14 @@ semaphore
|
|
|
130
146
|
try {
|
|
131
147
|
await semaphore.acquire();
|
|
132
148
|
|
|
133
|
-
// Critical operations
|
|
149
|
+
// Critical operations
|
|
134
150
|
} finally {
|
|
135
151
|
semaphore.release();
|
|
136
152
|
}
|
|
137
153
|
|
|
138
154
|
// Using the request function
|
|
139
155
|
await semaphore.request(() => {
|
|
140
|
-
// Critical operations
|
|
156
|
+
// Critical operations
|
|
141
157
|
});
|
|
142
158
|
```
|
|
143
159
|
|
|
@@ -159,7 +175,10 @@ const downloadAndSave = async (url) => {
|
|
|
159
175
|
};
|
|
160
176
|
```
|
|
161
177
|
|
|
162
|
-
This approach works as expected until `downloadAndSave()` is called multiple
|
|
178
|
+
This approach works as expected until `downloadAndSave()` is called multiple
|
|
179
|
+
times with the same `url` in quick succession. Without control, it could
|
|
180
|
+
initiate simultaneous downloads that attempt to write to the same file at the
|
|
181
|
+
same time.
|
|
163
182
|
|
|
164
183
|
This issue can be resolved by using a `Semaphore` with the `key` parameter:
|
|
165
184
|
|
|
@@ -172,7 +191,7 @@ const downloadAndSave = async (url) => {
|
|
|
172
191
|
await semaphore.acquire(url);
|
|
173
192
|
|
|
174
193
|
// This block continues once a lock on url is acquired. This
|
|
175
|
-
// permits multiple
|
|
194
|
+
// permits multiple simultaneous downloads for different urls.
|
|
176
195
|
|
|
177
196
|
const filePath = urlToFilePath(url);
|
|
178
197
|
|
|
@@ -198,16 +217,58 @@ const downloadAndSave = (url) => {
|
|
|
198
217
|
|
|
199
218
|
if (await pathExists(filePath)) {
|
|
200
219
|
// The file is already on disk, so no action is required.
|
|
201
|
-
|
|
220
|
+
} else {
|
|
221
|
+
await downloadAndSaveToFilepath(url, filePath);
|
|
202
222
|
}
|
|
203
|
-
|
|
204
|
-
await downloadAndSaveToFilepath(url, filePath);
|
|
205
|
-
|
|
206
223
|
return filePath;
|
|
207
224
|
}, url);
|
|
208
225
|
};
|
|
209
226
|
```
|
|
210
227
|
|
|
228
|
+
## API - GroupSemaphore
|
|
229
|
+
|
|
230
|
+
The `GroupSemaphore` class manages a semaphore for different groups of tasks. A
|
|
231
|
+
group is identified by a key, and the semaphore ensures that only one group can
|
|
232
|
+
run its tasks at a time. The tasks within a group can run concurrently.
|
|
233
|
+
|
|
234
|
+
The `GroupSemaphore` class exposes `acquire` and `release` methods, which have
|
|
235
|
+
the same interface as `Semaphore`. The only difference is that the `key`
|
|
236
|
+
parameter is required.
|
|
237
|
+
|
|
238
|
+
### Example
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
import { GroupSemaphore } from "@chriscdn/promise-semaphore";
|
|
242
|
+
|
|
243
|
+
const groupSemaphore = new GroupSemaphore();
|
|
244
|
+
|
|
245
|
+
const RunA = async () => {
|
|
246
|
+
try {
|
|
247
|
+
await groupSemaphore.acquire("GroupA");
|
|
248
|
+
|
|
249
|
+
// Perform asynchronous operations for group A
|
|
250
|
+
} finally {
|
|
251
|
+
groupSemaphore.release("GroupA");
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const RunB = async () => {
|
|
256
|
+
try {
|
|
257
|
+
await groupSemaphore.acquire("GroupB");
|
|
258
|
+
|
|
259
|
+
// Perform asynchronous operations for group B
|
|
260
|
+
} finally {
|
|
261
|
+
groupSemaphore.release("GroupB");
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
This setup allows `RunA` to be called multiple times, and will run concurrently.
|
|
267
|
+
However, calling `RunB` will wait until all `GroupA` tasks are completed before
|
|
268
|
+
acquiring the lock for `GroupB`. As soon as `GroupB` acquires the lock, any
|
|
269
|
+
subsequent calls to `RunA` will wait until `GroupB` releases the lock before it
|
|
270
|
+
executes.
|
|
271
|
+
|
|
211
272
|
## License
|
|
212
273
|
|
|
213
274
|
[MIT](LICENSE)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GroupSemaphore manages a shared semaphore for different groups of tasks. Each
|
|
3
|
+
* group is identified by a unique key, and the semaphore ensures only one group
|
|
4
|
+
* can run its tasks concurrently.
|
|
5
|
+
*
|
|
6
|
+
* - acquire(key): Increments the active count for the given group. If it's the
|
|
7
|
+
* first task for the group (active count is 0), it acquires the global
|
|
8
|
+
* semaphore, ensuring only one group's tasks can proceed at a time.
|
|
9
|
+
* Subsequent calls in the group increment the count and are permitted to run.
|
|
10
|
+
* - release(key): Decrements the active count for the group. If the last task
|
|
11
|
+
* for that group is released, it releases the global semaphore, allowing
|
|
12
|
+
* other groups to proceed.
|
|
13
|
+
*
|
|
14
|
+
* This ensures that only one group can execute concurrently, but multiple tasks
|
|
15
|
+
* within the same group can run as long as no other tasks from different groups
|
|
16
|
+
* are active.
|
|
17
|
+
*/
|
|
18
|
+
declare class GroupSemaphore {
|
|
19
|
+
private _semaphore;
|
|
20
|
+
private _activeCounts;
|
|
21
|
+
private _groupWaiters;
|
|
22
|
+
acquire(key: string): Promise<void>;
|
|
23
|
+
release(key: string): void;
|
|
24
|
+
}
|
|
25
|
+
export { GroupSemaphore };
|
package/lib/index.d.ts
CHANGED
|
@@ -1,57 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
private maxConcurrent;
|
|
4
|
-
/**
|
|
5
|
-
* @param {number} [maxConcurrent] The maximum number of concurrent locks.
|
|
6
|
-
*/
|
|
7
|
-
constructor(maxConcurrent?: number);
|
|
8
|
-
private hasSemaphoreInstance;
|
|
9
|
-
private getSemaphoreInstance;
|
|
10
|
-
/**
|
|
11
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
12
|
-
*/
|
|
13
|
-
private tidy;
|
|
14
|
-
/**
|
|
15
|
-
* A synchronous function to determine whether a lock can be acquired.
|
|
16
|
-
*
|
|
17
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
18
|
-
* @returns {boolean} Returns true if the lock on `key` can be acquired, false
|
|
19
|
-
* otherwise.
|
|
20
|
-
*/
|
|
21
|
-
canAcquire(key?: string | number): boolean;
|
|
22
|
-
/**
|
|
23
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
24
|
-
*/
|
|
25
|
-
acquire(key?: string | number): Promise<void>;
|
|
26
|
-
/**
|
|
27
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
28
|
-
*/
|
|
29
|
-
release(key?: string | number): void;
|
|
30
|
-
/**
|
|
31
|
-
* The number of active locks. Will always be less or equal to `max`.
|
|
32
|
-
*
|
|
33
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
34
|
-
*/
|
|
35
|
-
count(key?: string | number): number;
|
|
36
|
-
/**
|
|
37
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
38
|
-
* @returns {boolean} True if the semaphore and key has locks, false otherwise.
|
|
39
|
-
*/
|
|
40
|
-
hasTasks(key?: string | number): boolean;
|
|
41
|
-
/**
|
|
42
|
-
* @param {Function<T>} fn The function to execute.
|
|
43
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
44
|
-
* @returns {Promise<T>}
|
|
45
|
-
*/
|
|
46
|
-
request<T>(fn: Function, key?: string | number): Promise<T>;
|
|
47
|
-
/**
|
|
48
|
-
* Asynchronously executes `fn` if a lock can be immediately acquired.
|
|
49
|
-
* Otherwise, returns null.
|
|
50
|
-
*
|
|
51
|
-
* @param {Function<T>} fn The function to execute.
|
|
52
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
53
|
-
* @returns {Promise<T>}
|
|
54
|
-
*/
|
|
55
|
-
requestIfAvailable<T>(fn: Function, key?: string | number): Promise<T | null>;
|
|
56
|
-
}
|
|
57
|
-
export { Semaphore };
|
|
1
|
+
export { Semaphore } from "./semaphore";
|
|
2
|
+
export { GroupSemaphore } from "./group-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.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"
|
|
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}();exports.GroupSemaphore=/*#__PURE__*/function(){function e(){this._semaphore=new r,this._activeCounts={},this._groupWaiters={}}var t=e.prototype;return t.acquire=function(e){try{var t,n,r=this,i=null!=(t=r._activeCounts[e])?t:0;r._activeCounts[e]=i+1;var o=null!=(n=r._groupWaiters[e])?n:r._semaphore.acquire();return r._groupWaiters[e]=o,Promise.resolve(o).then(function(){})}catch(e){return Promise.reject(e)}},t.release=function(e){var t=this._activeCounts[e];1===t?(this._semaphore.release(),delete this._activeCounts[e],delete this._groupWaiters[e]):this._activeCounts[e]=t-1},e}(),exports.Semaphore=r;
|
|
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: 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,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AAAb,EAUKe,mBAAA,SACJR,EACAZ,QAAAA,IAAAA,IAAAA,EAAuBE,GAAU,IAEjC,OAAIlB,KAAKQ,WAAWQ,GAClBP,QAAAC,QADEV,KACU2B,QAAQC,EAAIZ,IAExBP,QAAAC,QAAO,KAEX,CAAC,MAAAwB,UAAAzB,QAAA0B,OAAAD,KAAAf,CAAA,CArHY"}
|
|
1
|
+
{"version":3,"file":"promise-semaphore.cjs","sources":["../src/semaphore.ts","../src/group-semaphore.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(\n this.maxConcurrent,\n );\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","import { Semaphore } from \"./semaphore\";\n\n/**\n * GroupSemaphore manages a shared semaphore for different groups of tasks. Each\n * group is identified by a unique key, and the semaphore ensures only one group\n * can run its tasks concurrently.\n *\n * - acquire(key): Increments the active count for the given group. If it's the\n * first task for the group (active count is 0), it acquires the global\n * semaphore, ensuring only one group's tasks can proceed at a time.\n * Subsequent calls in the group increment the count and are permitted to run.\n * - release(key): Decrements the active count for the group. If the last task\n * for that group is released, it releases the global semaphore, allowing\n * other groups to proceed.\n *\n * This ensures that only one group can execute concurrently, but multiple tasks\n * within the same group can run as long as no other tasks from different groups\n * are active.\n */\nclass GroupSemaphore {\n private _semaphore = new Semaphore();\n private _activeCounts: Record<string, number> = {};\n private _groupWaiters: Record<string, Promise<void>> = {};\n\n async acquire(key: string) {\n const activeCount = this._activeCounts[key] ?? 0;\n this._activeCounts[key] = activeCount + 1;\n const waiter = this._groupWaiters[key] ?? this._semaphore.acquire();\n this._groupWaiters[key] = waiter;\n await waiter;\n }\n\n release(key: string) {\n const activeCount = this._activeCounts[key];\n\n if (activeCount === 1) {\n this._semaphore.release();\n delete this._activeCounts[key];\n delete this._groupWaiters[key];\n } else {\n this._activeCounts[key] = activeCount - 1;\n }\n }\n}\n\nexport { GroupSemaphore };\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","GroupSemaphore","_semaphore","_activeCounts","_groupWaiters","_this$_activeCounts$k","_this$_groupWaiters$k","activeCount","waiter"],"mappings":"mSAAMA,eAAa,WASf,SAAAA,EAAYC,GARJC,KAAAA,kBACAD,mBAAa,EAAAE,KAKdC,WAGH,EAAAD,KAAKD,MAAQ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AAd2C,EAAqC,OAA1BF,EAAGlC,EAAKgC,cAAcvB,IAAIyB,EAAI,EAC/ClC,EAAKgC,cAAcvB,GAAO2B,EAAc,EACxC,IAAMC,EAAgCF,OAA1BA,EAAGnC,EAAKiC,cAAcxB,IAAI0B,EAAInC,EAAK+B,WAAWhC,UACzB,OAAjCC,EAAKiC,cAAcxB,GAAO4B,EAAOnC,QAAAC,QAC3BkC,GAAMd,KAChB,WAAA,EAAA,CAAC,MAAAI,GAAAzB,OAAAA,QAAA0B,OAAAD,EAAAhC,CAAAA,EAAAA,EAEDU,QAAA,SAAQI,GACJ,IAAM2B,EAAc3C,KAAKuC,cAAcvB,GAEnB,IAAhB2B,GACA3C,KAAKsC,WAAW1B,iBACLZ,KAACuC,cAAcvB,UACnBhB,KAAKwC,cAAcxB,IAE1BhB,KAAKuC,cAAcvB,GAAO2B,EAAc,CAEhD,EAACN,CAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
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};
|
|
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}}class n{constructor(){this._semaphore=new s,this._activeCounts={},this._groupWaiters={}}async acquire(e){var t,s;const n=null!=(t=this._activeCounts[e])?t:0;this._activeCounts[e]=n+1;const r=null!=(s=this._groupWaiters[e])?s:this._semaphore.acquire();this._groupWaiters[e]=r,await r}release(e){const t=this._activeCounts[e];1===t?(this._semaphore.release(),delete this._activeCounts[e],delete this._groupWaiters[e]):this._activeCounts[e]=t-1}}export{n as GroupSemaphore,s as Semaphore};
|
|
2
2
|
//# sourceMappingURL=promise-semaphore.modern.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"promise-semaphore.modern.js","sources":["../src/
|
|
1
|
+
{"version":3,"file":"promise-semaphore.modern.js","sources":["../src/semaphore.ts","../src/group-semaphore.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(\n this.maxConcurrent,\n );\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","import { Semaphore } from \"./semaphore\";\n\n/**\n * GroupSemaphore manages a shared semaphore for different groups of tasks. Each\n * group is identified by a unique key, and the semaphore ensures only one group\n * can run its tasks concurrently.\n *\n * - acquire(key): Increments the active count for the given group. If it's the\n * first task for the group (active count is 0), it acquires the global\n * semaphore, ensuring only one group's tasks can proceed at a time.\n * Subsequent calls in the group increment the count and are permitted to run.\n * - release(key): Decrements the active count for the group. If the last task\n * for that group is released, it releases the global semaphore, allowing\n * other groups to proceed.\n *\n * This ensures that only one group can execute concurrently, but multiple tasks\n * within the same group can run as long as no other tasks from different groups\n * are active.\n */\nclass GroupSemaphore {\n private _semaphore = new Semaphore();\n private _activeCounts: Record<string, number> = {};\n private _groupWaiters: Record<string, Promise<void>> = {};\n\n async acquire(key: string) {\n const activeCount = this._activeCounts[key] ?? 0;\n this._activeCounts[key] = activeCount + 1;\n const waiter = this._groupWaiters[key] ?? this._semaphore.acquire();\n this._groupWaiters[key] = waiter;\n await waiter;\n }\n\n release(key: string) {\n const activeCount = this._activeCounts[key];\n\n if (activeCount === 1) {\n this._semaphore.release();\n delete this._activeCounts[key];\n delete this._groupWaiters[key];\n } else {\n this._activeCounts[key] = activeCount - 1;\n }\n }\n}\n\nexport { GroupSemaphore };\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","GroupSemaphore","_semaphore","_activeCounts","_groupWaiters","_this$_activeCounts$k","_this$_groupWaiters$k","activeCount","waiter"],"mappings":"AAAA,MAAMA,EASFC,WAAAA,CAAYC,GAAqBC,KARzBC,WAAK,EAAAD,KACLD,mBAAa,EAAAC,KAKdE,WAGH,EAAAF,KAAKC,MAAQ,GACbD,KAAKD,cAAgBA,EACrBC,KAAKE,MAA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B,KAAKoB,qBAAqBF,GAAKhB,MAGzC,CACL,CAMAoB,QAAAA,CAASJ,EAAuBJ,GAC5B,OAAWd,KAACE,MAAMgB,GAAO,CAC7B,CAOA,aAAMK,CACFC,EACAN,EAAuBJ,GAEvB,IAEI,aADUd,KAACM,QAAQY,SACNM,GAChB,CAAA,QACGxB,KAAKU,QAAQQ,EAChB,CACL,CAUA,wBAAMO,CACFD,EACAN,EAAuBJ,GAEvB,OAAId,KAAKG,WAAWe,GACLlB,KAACuB,QAAQC,EAAIN,GAEjB,IAEf,ECtJJ,MAAMQ,EAAc5B,WAAAA,GAAAE,KACR2B,WAAa,IAAIZ,OACjBa,cAAwC,CAAE,OAC1CC,cAA+C,CAAA,CAAE,CAEzD,aAAMvB,CAAQY,GAAW,IAAAY,EAAAC,EACrB,MAAMC,EAAqCF,OAA1BA,EAAG9B,KAAK4B,cAAcV,IAAIY,EAAI,EAC/C9B,KAAK4B,cAAcV,GAAOc,EAAc,EACxC,MAAMC,EAAgC,OAA1BF,EAAG/B,KAAK6B,cAAcX,IAAIa,EAAI/B,KAAK2B,WAAWrB,UAC1DN,KAAK6B,cAAcX,GAAOe,QACpBA,CACV,CAEAvB,OAAAA,CAAQQ,GACJ,MAAMc,EAAchC,KAAK4B,cAAcV,GAEnB,IAAhBc,GACAhC,KAAK2B,WAAWjB,iBACTV,KAAK4B,cAAcV,UACnBlB,KAAK6B,cAAcX,IAE1BlB,KAAK4B,cAAcV,GAAOc,EAAc,CAEhD"}
|
|
@@ -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.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};
|
|
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}(),i=/*#__PURE__*/function(){function e(){this._semaphore=new r,this._activeCounts={},this._groupWaiters={}}var t=e.prototype;return t.acquire=function(e){try{var t,n,r=this,i=null!=(t=r._activeCounts[e])?t:0;r._activeCounts[e]=i+1;var o=null!=(n=r._groupWaiters[e])?n:r._semaphore.acquire();return r._groupWaiters[e]=o,Promise.resolve(o).then(function(){})}catch(e){return Promise.reject(e)}},t.release=function(e){var t=this._activeCounts[e];1===t?(this._semaphore.release(),delete this._activeCounts[e],delete this._groupWaiters[e]):this._activeCounts[e]=t-1},e}();export{i as GroupSemaphore,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: 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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,qBAAqBR,GAAKV,SACxC,EAACe,EAKDT,QAAA,SAAQI,QAAAA,IAAAA,IAAAA,EAAuBE,GAC7BlB,KAAKwB,qBAAqBR,GAAKJ,UAC/BZ,KAAKyB,KAAKT,EACZ,EAACK,EAODpB,MAAA,SAAMe,GACJ,YADIA,IAAAA,IAAAA,EAAuBE,GACvBlB,KAAKsB,qBAAqBN,GACjBhB,KAACwB,qBAAqBR,GAAKf,MAE/B,CAEX,EAACoB,EAMDK,SAAA,SAASV,GACP,gBADOA,IAAAA,EAAuBE,GACvBlB,KAAKC,MAAMe,GAAO,CAC3B,EAACK,EAOKM,iBACJC,EACAZ,QAAAA,IAAAA,IAAAA,EAAuBE,GAAU,QAAAW,EAGzB7B,KAAIS,OAAAA,QAAAC,gCADRD,QAAAC,QACImB,EAAKvB,QAAQU,IAAIc,uBAAArB,QAAAC,QACVkB,IAAI,4FADPG,CADR,EAGHC,SAAAA,EAAAC,GACmB,GAAlBJ,EAAKjB,QAAQI,GAAKgB,EAAAC,MAAAA,SAAAA,CAAA,GAEtB,CAAC,MAAAC,UAAAzB,QAAA0B,OAAAD,KAAAb,EAUKe,mBAAA,SACJR,EACAZ,QAAAA,IAAAA,IAAAA,EAAuBE,GAAU,IAEjC,OAAIlB,KAAKQ,WAAWQ,GAClBP,QAAAC,QADEV,KACU2B,QAAQC,EAAIZ,IAExBP,QAAAC,QAAO,KAEX,CAAC,MAAAwB,UAAAzB,QAAA0B,OAAAD,KAAAf,CAAA,CArHY"}
|
|
1
|
+
{"version":3,"file":"promise-semaphore.module.js","sources":["../src/semaphore.ts","../src/group-semaphore.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(\n this.maxConcurrent,\n );\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","import { Semaphore } from \"./semaphore\";\n\n/**\n * GroupSemaphore manages a shared semaphore for different groups of tasks. Each\n * group is identified by a unique key, and the semaphore ensures only one group\n * can run its tasks concurrently.\n *\n * - acquire(key): Increments the active count for the given group. If it's the\n * first task for the group (active count is 0), it acquires the global\n * semaphore, ensuring only one group's tasks can proceed at a time.\n * Subsequent calls in the group increment the count and are permitted to run.\n * - release(key): Decrements the active count for the group. If the last task\n * for that group is released, it releases the global semaphore, allowing\n * other groups to proceed.\n *\n * This ensures that only one group can execute concurrently, but multiple tasks\n * within the same group can run as long as no other tasks from different groups\n * are active.\n */\nclass GroupSemaphore {\n private _semaphore = new Semaphore();\n private _activeCounts: Record<string, number> = {};\n private _groupWaiters: Record<string, Promise<void>> = {};\n\n async acquire(key: string) {\n const activeCount = this._activeCounts[key] ?? 0;\n this._activeCounts[key] = activeCount + 1;\n const waiter = this._groupWaiters[key] ?? this._semaphore.acquire();\n this._groupWaiters[key] = waiter;\n await waiter;\n }\n\n release(key: string) {\n const activeCount = this._activeCounts[key];\n\n if (activeCount === 1) {\n this._semaphore.release();\n delete this._activeCounts[key];\n delete this._groupWaiters[key];\n } else {\n this._activeCounts[key] = activeCount - 1;\n }\n }\n}\n\nexport { GroupSemaphore };\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","GroupSemaphore","_semaphore","_activeCounts","_groupWaiters","_this$_activeCounts$k","_this$_groupWaiters$k","activeCount","waiter"],"mappings":"mSAAMA,eAAa,WASf,SAAAA,EAAYC,GARJC,KAAAA,kBACAD,mBAAa,EAAAE,KAKdC,WAGH,EAAAD,KAAKD,MAAQ,GACbC,KAAKF,cAAgBA,EACrBE,KAAKC,MAAQ,CACjB,CAAC,QAAAC,EAAAL,EAAAM,iBAAAD,EAMOE,eAAA,WACJJ,KAAKC,OACT,EAACC,EAEOG,eAAA,WACJL,KAAKC,OACT,EAACC,EAEDI,QAAA,WAAOC,IAAAA,OACH,OAAIP,KAAKQ,YACLR,KAAKI,iBACEK,QAAQC,eAEJD,QAAQ,SAACC,UAAYH,EAAKR,MAAMY,KAAKD,EAAQ,EAEhE,EAACR,EAEDU,QAAA,WACI,IAAMC,EAAcb,KAAKD,MAAMe,QAE3BD,EAEAE,WAAWF,EAAa,GAExBb,KAAKK,gBAEb,IAACR,KAAAmB,CAAAA,CAAAA,iBAAAC,IA9BD,WACI,OAAOjB,KAAKC,MAAQD,KAAKF,aAC7B,iPA+BJ,CAhDmB,GAgDboB,EAAa,WAEbC,eAAS,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B,EAAc,CAEhD,EAACN,CAAA"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
declare class Semaphore {
|
|
2
|
+
private semaphoreInstances;
|
|
3
|
+
private maxConcurrent;
|
|
4
|
+
/**
|
|
5
|
+
* @param {number} [maxConcurrent] The maximum number of concurrent locks.
|
|
6
|
+
*/
|
|
7
|
+
constructor(maxConcurrent?: number);
|
|
8
|
+
private hasSemaphoreInstance;
|
|
9
|
+
private getSemaphoreInstance;
|
|
10
|
+
/**
|
|
11
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
12
|
+
*/
|
|
13
|
+
private tidy;
|
|
14
|
+
/**
|
|
15
|
+
* A synchronous function to determine whether a lock can be acquired.
|
|
16
|
+
*
|
|
17
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
18
|
+
* @returns {boolean} Returns true if the lock on `key` can be acquired, false
|
|
19
|
+
* otherwise.
|
|
20
|
+
*/
|
|
21
|
+
canAcquire(key?: string | number): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
24
|
+
*/
|
|
25
|
+
acquire(key?: string | number): Promise<void>;
|
|
26
|
+
/**
|
|
27
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
28
|
+
*/
|
|
29
|
+
release(key?: string | number): void;
|
|
30
|
+
/**
|
|
31
|
+
* The number of active locks. Will always be less or equal to `max`.
|
|
32
|
+
*
|
|
33
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
34
|
+
*/
|
|
35
|
+
count(key?: string | number): number;
|
|
36
|
+
/**
|
|
37
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
38
|
+
* @returns {boolean} True if the semaphore and key has locks, false otherwise.
|
|
39
|
+
*/
|
|
40
|
+
hasTasks(key?: string | number): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* @param {Function<T>} fn The function to execute.
|
|
43
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
44
|
+
* @returns {Promise<T>}
|
|
45
|
+
*/
|
|
46
|
+
request<T>(fn: Function, key?: string | number): Promise<T>;
|
|
47
|
+
/**
|
|
48
|
+
* Asynchronously executes `fn` if a lock can be immediately acquired.
|
|
49
|
+
* Otherwise, returns null.
|
|
50
|
+
*
|
|
51
|
+
* @param {Function<T>} fn The function to execute.
|
|
52
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
53
|
+
* @returns {Promise<T>}
|
|
54
|
+
*/
|
|
55
|
+
requestIfAvailable<T>(fn: Function, key?: string | number): Promise<T | null>;
|
|
56
|
+
}
|
|
57
|
+
export { Semaphore };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chriscdn/promise-semaphore",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.1",
|
|
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>",
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { Semaphore } from "./semaphore";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* GroupSemaphore manages a shared semaphore for different groups of tasks. Each
|
|
5
|
+
* group is identified by a unique key, and the semaphore ensures only one group
|
|
6
|
+
* can run its tasks concurrently.
|
|
7
|
+
*
|
|
8
|
+
* - acquire(key): Increments the active count for the given group. If it's the
|
|
9
|
+
* first task for the group (active count is 0), it acquires the global
|
|
10
|
+
* semaphore, ensuring only one group's tasks can proceed at a time.
|
|
11
|
+
* Subsequent calls in the group increment the count and are permitted to run.
|
|
12
|
+
* - release(key): Decrements the active count for the group. If the last task
|
|
13
|
+
* for that group is released, it releases the global semaphore, allowing
|
|
14
|
+
* other groups to proceed.
|
|
15
|
+
*
|
|
16
|
+
* This ensures that only one group can execute concurrently, but multiple tasks
|
|
17
|
+
* within the same group can run as long as no other tasks from different groups
|
|
18
|
+
* are active.
|
|
19
|
+
*/
|
|
20
|
+
class GroupSemaphore {
|
|
21
|
+
private _semaphore = new Semaphore();
|
|
22
|
+
private _activeCounts: Record<string, number> = {};
|
|
23
|
+
private _groupWaiters: Record<string, Promise<void>> = {};
|
|
24
|
+
|
|
25
|
+
async acquire(key: string) {
|
|
26
|
+
const activeCount = this._activeCounts[key] ?? 0;
|
|
27
|
+
this._activeCounts[key] = activeCount + 1;
|
|
28
|
+
const waiter = this._groupWaiters[key] ?? this._semaphore.acquire();
|
|
29
|
+
this._groupWaiters[key] = waiter;
|
|
30
|
+
await waiter;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
release(key: string) {
|
|
34
|
+
const activeCount = this._activeCounts[key];
|
|
35
|
+
|
|
36
|
+
if (activeCount === 1) {
|
|
37
|
+
this._semaphore.release();
|
|
38
|
+
delete this._activeCounts[key];
|
|
39
|
+
delete this._groupWaiters[key];
|
|
40
|
+
} else {
|
|
41
|
+
this._activeCounts[key] = activeCount - 1;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export { GroupSemaphore };
|
package/src/index.ts
CHANGED
|
@@ -1,171 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
private maxConcurrent: number;
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* The number of locks.
|
|
7
|
-
*/
|
|
8
|
-
public count: number;
|
|
9
|
-
|
|
10
|
-
constructor(maxConcurrent: number) {
|
|
11
|
-
this.queue = [];
|
|
12
|
-
this.maxConcurrent = maxConcurrent;
|
|
13
|
-
this.count = 0;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
get canAcquire(): boolean {
|
|
17
|
-
return this.count < this.maxConcurrent;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
private incrementCount() {
|
|
21
|
-
this.count++;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
private decrementCount() {
|
|
25
|
-
this.count--;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
acquire(): Promise<void> {
|
|
29
|
-
if (this.canAcquire) {
|
|
30
|
-
this.incrementCount();
|
|
31
|
-
return Promise.resolve();
|
|
32
|
-
} else {
|
|
33
|
-
return new Promise((resolve) => this.queue.push(resolve));
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
release(): void {
|
|
38
|
-
const resolveFunc = this.queue.shift();
|
|
39
|
-
|
|
40
|
-
if (resolveFunc) {
|
|
41
|
-
// Give the micro task queue a small break instead of calling resolveFunc() directly
|
|
42
|
-
setTimeout(resolveFunc, 0);
|
|
43
|
-
} else {
|
|
44
|
-
this.decrementCount();
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
const defaultKey = "_default";
|
|
50
|
-
|
|
51
|
-
class Semaphore {
|
|
52
|
-
private semaphoreInstances: Record<string | number, SemaphoreItem>;
|
|
53
|
-
private maxConcurrent: number;
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* @param {number} [maxConcurrent] The maximum number of concurrent locks.
|
|
57
|
-
*/
|
|
58
|
-
constructor(maxConcurrent: number = 1) {
|
|
59
|
-
this.semaphoreInstances = {};
|
|
60
|
-
this.maxConcurrent = maxConcurrent;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
private hasSemaphoreInstance(key: string | number = defaultKey) {
|
|
64
|
-
return Boolean(this.semaphoreInstances[key]);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
private getSemaphoreInstance(key: string | number = defaultKey) {
|
|
68
|
-
if (!this.hasSemaphoreInstance(key)) {
|
|
69
|
-
this.semaphoreInstances[key] = new SemaphoreItem(this.maxConcurrent);
|
|
70
|
-
}
|
|
71
|
-
return this.semaphoreInstances[key];
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
76
|
-
*/
|
|
77
|
-
private tidy(key: string | number = defaultKey): void {
|
|
78
|
-
if (
|
|
79
|
-
this.hasSemaphoreInstance(key) &&
|
|
80
|
-
this.getSemaphoreInstance(key).count === 0
|
|
81
|
-
) {
|
|
82
|
-
delete this.semaphoreInstances[key];
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* A synchronous function to determine whether a lock can be acquired.
|
|
88
|
-
*
|
|
89
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
90
|
-
* @returns {boolean} Returns true if the lock on `key` can be acquired, false
|
|
91
|
-
* otherwise.
|
|
92
|
-
*/
|
|
93
|
-
canAcquire(key: string | number = defaultKey): boolean {
|
|
94
|
-
return !this.hasSemaphoreInstance(key) ||
|
|
95
|
-
this.getSemaphoreInstance(key).canAcquire;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
100
|
-
*/
|
|
101
|
-
acquire(key: string | number = defaultKey) {
|
|
102
|
-
return this.getSemaphoreInstance(key).acquire();
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
107
|
-
*/
|
|
108
|
-
release(key: string | number = defaultKey): void {
|
|
109
|
-
this.getSemaphoreInstance(key).release();
|
|
110
|
-
this.tidy(key);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* The number of active locks. Will always be less or equal to `max`.
|
|
115
|
-
*
|
|
116
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
117
|
-
*/
|
|
118
|
-
count(key: string | number = defaultKey): number {
|
|
119
|
-
if (this.hasSemaphoreInstance(key)) {
|
|
120
|
-
return this.getSemaphoreInstance(key).count;
|
|
121
|
-
} else {
|
|
122
|
-
return 0;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/**
|
|
127
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
128
|
-
* @returns {boolean} True if the semaphore and key has locks, false otherwise.
|
|
129
|
-
*/
|
|
130
|
-
hasTasks(key: string | number = defaultKey): boolean {
|
|
131
|
-
return this.count(key) > 0;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* @param {Function<T>} fn The function to execute.
|
|
136
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
137
|
-
* @returns {Promise<T>}
|
|
138
|
-
*/
|
|
139
|
-
async request<T>(
|
|
140
|
-
fn: Function,
|
|
141
|
-
key: string | number = defaultKey,
|
|
142
|
-
): Promise<T> {
|
|
143
|
-
try {
|
|
144
|
-
await this.acquire(key);
|
|
145
|
-
return await fn();
|
|
146
|
-
} finally {
|
|
147
|
-
this.release(key);
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Asynchronously executes `fn` if a lock can be immediately acquired.
|
|
153
|
-
* Otherwise, returns null.
|
|
154
|
-
*
|
|
155
|
-
* @param {Function<T>} fn The function to execute.
|
|
156
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
157
|
-
* @returns {Promise<T>}
|
|
158
|
-
*/
|
|
159
|
-
async requestIfAvailable<T>(
|
|
160
|
-
fn: Function,
|
|
161
|
-
key: string | number = defaultKey,
|
|
162
|
-
): Promise<T | null> {
|
|
163
|
-
if (this.canAcquire(key)) {
|
|
164
|
-
return this.request(fn, key);
|
|
165
|
-
} else {
|
|
166
|
-
return null;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export { Semaphore };
|
|
1
|
+
export { Semaphore } from "./semaphore";
|
|
2
|
+
export { GroupSemaphore } from "./group-semaphore";
|
package/src/semaphore.ts
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
class SemaphoreItem {
|
|
2
|
+
private queue: Function[];
|
|
3
|
+
private maxConcurrent: number;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The number of locks.
|
|
7
|
+
*/
|
|
8
|
+
public count: number;
|
|
9
|
+
|
|
10
|
+
constructor(maxConcurrent: number) {
|
|
11
|
+
this.queue = [];
|
|
12
|
+
this.maxConcurrent = maxConcurrent;
|
|
13
|
+
this.count = 0;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
get canAcquire(): boolean {
|
|
17
|
+
return this.count < this.maxConcurrent;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
private incrementCount() {
|
|
21
|
+
this.count++;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
private decrementCount() {
|
|
25
|
+
this.count--;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
acquire(): Promise<void> {
|
|
29
|
+
if (this.canAcquire) {
|
|
30
|
+
this.incrementCount();
|
|
31
|
+
return Promise.resolve();
|
|
32
|
+
} else {
|
|
33
|
+
return new Promise((resolve) => this.queue.push(resolve));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
release(): void {
|
|
38
|
+
const resolveFunc = this.queue.shift();
|
|
39
|
+
|
|
40
|
+
if (resolveFunc) {
|
|
41
|
+
// Give the micro task queue a small break instead of calling resolveFunc() directly
|
|
42
|
+
setTimeout(resolveFunc, 0);
|
|
43
|
+
} else {
|
|
44
|
+
this.decrementCount();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const defaultKey = "_default";
|
|
50
|
+
|
|
51
|
+
class Semaphore {
|
|
52
|
+
private semaphoreInstances: Record<string | number, SemaphoreItem>;
|
|
53
|
+
private maxConcurrent: number;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {number} [maxConcurrent] The maximum number of concurrent locks.
|
|
57
|
+
*/
|
|
58
|
+
constructor(maxConcurrent: number = 1) {
|
|
59
|
+
this.semaphoreInstances = {};
|
|
60
|
+
this.maxConcurrent = maxConcurrent;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private hasSemaphoreInstance(key: string | number = defaultKey) {
|
|
64
|
+
return Boolean(this.semaphoreInstances[key]);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private getSemaphoreInstance(key: string | number = defaultKey) {
|
|
68
|
+
if (!this.hasSemaphoreInstance(key)) {
|
|
69
|
+
this.semaphoreInstances[key] = new SemaphoreItem(
|
|
70
|
+
this.maxConcurrent,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
return this.semaphoreInstances[key];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
78
|
+
*/
|
|
79
|
+
private tidy(key: string | number = defaultKey): void {
|
|
80
|
+
if (
|
|
81
|
+
this.hasSemaphoreInstance(key) &&
|
|
82
|
+
this.getSemaphoreInstance(key).count === 0
|
|
83
|
+
) {
|
|
84
|
+
delete this.semaphoreInstances[key];
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* A synchronous function to determine whether a lock can be acquired.
|
|
90
|
+
*
|
|
91
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
92
|
+
* @returns {boolean} Returns true if the lock on `key` can be acquired, false
|
|
93
|
+
* otherwise.
|
|
94
|
+
*/
|
|
95
|
+
canAcquire(key: string | number = defaultKey): boolean {
|
|
96
|
+
return !this.hasSemaphoreInstance(key) ||
|
|
97
|
+
this.getSemaphoreInstance(key).canAcquire;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
102
|
+
*/
|
|
103
|
+
acquire(key: string | number = defaultKey) {
|
|
104
|
+
return this.getSemaphoreInstance(key).acquire();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
109
|
+
*/
|
|
110
|
+
release(key: string | number = defaultKey): void {
|
|
111
|
+
this.getSemaphoreInstance(key).release();
|
|
112
|
+
this.tidy(key);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The number of active locks. Will always be less or equal to `max`.
|
|
117
|
+
*
|
|
118
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
119
|
+
*/
|
|
120
|
+
count(key: string | number = defaultKey): number {
|
|
121
|
+
if (this.hasSemaphoreInstance(key)) {
|
|
122
|
+
return this.getSemaphoreInstance(key).count;
|
|
123
|
+
} else {
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
130
|
+
* @returns {boolean} True if the semaphore and key has locks, false otherwise.
|
|
131
|
+
*/
|
|
132
|
+
hasTasks(key: string | number = defaultKey): boolean {
|
|
133
|
+
return this.count(key) > 0;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* @param {Function<T>} fn The function to execute.
|
|
138
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
139
|
+
* @returns {Promise<T>}
|
|
140
|
+
*/
|
|
141
|
+
async request<T>(
|
|
142
|
+
fn: Function,
|
|
143
|
+
key: string | number = defaultKey,
|
|
144
|
+
): Promise<T> {
|
|
145
|
+
try {
|
|
146
|
+
await this.acquire(key);
|
|
147
|
+
return await fn();
|
|
148
|
+
} finally {
|
|
149
|
+
this.release(key);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Asynchronously executes `fn` if a lock can be immediately acquired.
|
|
155
|
+
* Otherwise, returns null.
|
|
156
|
+
*
|
|
157
|
+
* @param {Function<T>} fn The function to execute.
|
|
158
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
159
|
+
* @returns {Promise<T>}
|
|
160
|
+
*/
|
|
161
|
+
async requestIfAvailable<T>(
|
|
162
|
+
fn: Function,
|
|
163
|
+
key: string | number = defaultKey,
|
|
164
|
+
): Promise<T | null> {
|
|
165
|
+
if (this.canAcquire(key)) {
|
|
166
|
+
return this.request(fn, key);
|
|
167
|
+
} else {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export { Semaphore };
|