@chriscdn/promise-semaphore 3.1.2 → 4.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/lib/index.d.ts +90 -2
- package/lib/index.js +179 -0
- package/lib/index.js.map +1 -0
- package/package.json +9 -14
- package/lib/group-semaphore.d.ts +0 -25
- package/lib/promise-semaphore.cjs +0 -2
- package/lib/promise-semaphore.cjs.map +0 -1
- package/lib/promise-semaphore.modern.js +0 -2
- package/lib/promise-semaphore.modern.js.map +0 -1
- package/lib/promise-semaphore.module.js +0 -2
- package/lib/promise-semaphore.module.js.map +0 -1
- package/lib/semaphore.d.ts +0 -64
package/lib/index.d.ts
CHANGED
|
@@ -1,2 +1,90 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
type KeyPrimitive = string | number;
|
|
2
|
+
type Key = KeyPrimitive | {
|
|
3
|
+
key?: KeyPrimitive;
|
|
4
|
+
};
|
|
5
|
+
type KeyOptions = Key & {
|
|
6
|
+
priority?: number;
|
|
7
|
+
};
|
|
8
|
+
declare class Semaphore {
|
|
9
|
+
private semaphoreInstances;
|
|
10
|
+
private maxConcurrent;
|
|
11
|
+
/**
|
|
12
|
+
* @param {number} [maxConcurrent] The maximum number of concurrent locks.
|
|
13
|
+
*/
|
|
14
|
+
constructor(maxConcurrent?: number);
|
|
15
|
+
private hasSemaphoreInstance;
|
|
16
|
+
private getSemaphoreInstance;
|
|
17
|
+
/**
|
|
18
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
19
|
+
*/
|
|
20
|
+
private tidy;
|
|
21
|
+
/**
|
|
22
|
+
* A synchronous function to determine whether a lock can be acquired.
|
|
23
|
+
*
|
|
24
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
25
|
+
* @returns {boolean} Returns true if the lock on `key` can be acquired, false
|
|
26
|
+
* otherwise.
|
|
27
|
+
*/
|
|
28
|
+
canAcquire(key?: Key): boolean;
|
|
29
|
+
/**
|
|
30
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
31
|
+
*/
|
|
32
|
+
acquire(key?: KeyOptions): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
35
|
+
*/
|
|
36
|
+
release(key?: Key): void;
|
|
37
|
+
/**
|
|
38
|
+
* The number of active locks. Will always be less or equal to `max`.
|
|
39
|
+
*
|
|
40
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
41
|
+
*/
|
|
42
|
+
count(key?: Key): number;
|
|
43
|
+
/**
|
|
44
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
45
|
+
* @returns {boolean} True if the semaphore and key has locks, false otherwise.
|
|
46
|
+
*/
|
|
47
|
+
hasTasks(key?: Key): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* @param {Function<T>} fn The function to execute.
|
|
50
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
51
|
+
* @returns {Promise<T>}
|
|
52
|
+
*/
|
|
53
|
+
request<T>(fn: Function, key?: KeyOptions): Promise<T>;
|
|
54
|
+
/**
|
|
55
|
+
* Asynchronously executes `fn` if a lock can be immediately acquired.
|
|
56
|
+
* Otherwise, returns null.
|
|
57
|
+
*
|
|
58
|
+
* @param {Function<T>} fn The function to execute.
|
|
59
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
60
|
+
* @returns {Promise<T>}
|
|
61
|
+
*/
|
|
62
|
+
requestIfAvailable<T>(fn: Function, key?: KeyOptions): Promise<T | null>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* GroupSemaphore manages a shared semaphore for different groups of tasks. Each
|
|
67
|
+
* group is identified by a unique key, and the semaphore ensures only one group
|
|
68
|
+
* can run its tasks concurrently.
|
|
69
|
+
*
|
|
70
|
+
* - acquire(key): Increments the active count for the given group. If it's the
|
|
71
|
+
* first task for the group (active count is 0), it acquires the global
|
|
72
|
+
* semaphore, ensuring only one group's tasks can proceed at a time.
|
|
73
|
+
* Subsequent calls in the group increment the count and are permitted to run.
|
|
74
|
+
* - release(key): Decrements the active count for the group. If the last task
|
|
75
|
+
* for that group is released, it releases the global semaphore, allowing
|
|
76
|
+
* other groups to proceed.
|
|
77
|
+
*
|
|
78
|
+
* This ensures that only one group can execute concurrently, but multiple tasks
|
|
79
|
+
* within the same group can run as long as no other tasks from different groups
|
|
80
|
+
* are active.
|
|
81
|
+
*/
|
|
82
|
+
declare class GroupSemaphore {
|
|
83
|
+
private _semaphore;
|
|
84
|
+
private _activeCounts;
|
|
85
|
+
private _groupWaiters;
|
|
86
|
+
acquire(key: string): Promise<void>;
|
|
87
|
+
release(key: string): void;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export { GroupSemaphore, Semaphore };
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// src/semaphore.ts
|
|
2
|
+
var defaultKey = "_default";
|
|
3
|
+
var _isPrimitiveKey = (item) => ["string", "number"].includes(typeof item);
|
|
4
|
+
var resolveKey = (item) => (_isPrimitiveKey(item) ? item : item.key) ?? defaultKey;
|
|
5
|
+
var resolvePriority = (item) => (_isPrimitiveKey(item) ? 0 : item.priority) ?? 0;
|
|
6
|
+
var SemaphoreItem = class {
|
|
7
|
+
queue;
|
|
8
|
+
maxConcurrent;
|
|
9
|
+
/**
|
|
10
|
+
* The number of locks.
|
|
11
|
+
*/
|
|
12
|
+
count;
|
|
13
|
+
constructor(maxConcurrent) {
|
|
14
|
+
this.queue = [];
|
|
15
|
+
this.maxConcurrent = maxConcurrent;
|
|
16
|
+
this.count = 0;
|
|
17
|
+
}
|
|
18
|
+
get canAcquire() {
|
|
19
|
+
return this.count < this.maxConcurrent;
|
|
20
|
+
}
|
|
21
|
+
incrementCount() {
|
|
22
|
+
this.count++;
|
|
23
|
+
}
|
|
24
|
+
decrementCount() {
|
|
25
|
+
this.count--;
|
|
26
|
+
}
|
|
27
|
+
acquire(priority) {
|
|
28
|
+
if (this.canAcquire) {
|
|
29
|
+
this.incrementCount();
|
|
30
|
+
return Promise.resolve();
|
|
31
|
+
} else {
|
|
32
|
+
return new Promise((resolve) => {
|
|
33
|
+
this.queue.push({ resolve, priority });
|
|
34
|
+
this.queue.sort((a, b) => b.priority - a.priority);
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
release() {
|
|
39
|
+
const resolveFunc = this.queue.shift();
|
|
40
|
+
if (resolveFunc) {
|
|
41
|
+
setTimeout(resolveFunc.resolve, 0);
|
|
42
|
+
} else {
|
|
43
|
+
this.decrementCount();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
var Semaphore = class {
|
|
48
|
+
semaphoreInstances;
|
|
49
|
+
maxConcurrent;
|
|
50
|
+
/**
|
|
51
|
+
* @param {number} [maxConcurrent] The maximum number of concurrent locks.
|
|
52
|
+
*/
|
|
53
|
+
constructor(maxConcurrent = 1) {
|
|
54
|
+
this.semaphoreInstances = {};
|
|
55
|
+
this.maxConcurrent = maxConcurrent;
|
|
56
|
+
if (maxConcurrent < 1) {
|
|
57
|
+
throw new Error("The maxConcurrent must be 1 or greater.");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
hasSemaphoreInstance(key = defaultKey) {
|
|
61
|
+
return Boolean(this.semaphoreInstances[key]);
|
|
62
|
+
}
|
|
63
|
+
getSemaphoreInstance(key = defaultKey) {
|
|
64
|
+
if (!this.hasSemaphoreInstance(key)) {
|
|
65
|
+
this.semaphoreInstances[key] = new SemaphoreItem(
|
|
66
|
+
this.maxConcurrent
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
return this.semaphoreInstances[key];
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
73
|
+
*/
|
|
74
|
+
tidy(key = defaultKey) {
|
|
75
|
+
if (this.hasSemaphoreInstance(key) && this.getSemaphoreInstance(key).count === 0) {
|
|
76
|
+
delete this.semaphoreInstances[key];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A synchronous function to determine whether a lock can be acquired.
|
|
81
|
+
*
|
|
82
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
83
|
+
* @returns {boolean} Returns true if the lock on `key` can be acquired, false
|
|
84
|
+
* otherwise.
|
|
85
|
+
*/
|
|
86
|
+
canAcquire(key = defaultKey) {
|
|
87
|
+
const _key = resolveKey(key);
|
|
88
|
+
return !this.hasSemaphoreInstance(_key) || this.getSemaphoreInstance(_key).canAcquire;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
92
|
+
*/
|
|
93
|
+
acquire(key = defaultKey) {
|
|
94
|
+
const _key = resolveKey(key);
|
|
95
|
+
const _priority = resolvePriority(key);
|
|
96
|
+
return this.getSemaphoreInstance(_key).acquire(_priority);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
100
|
+
*/
|
|
101
|
+
release(key = defaultKey) {
|
|
102
|
+
const _key = resolveKey(key);
|
|
103
|
+
this.getSemaphoreInstance(_key).release();
|
|
104
|
+
this.tidy(_key);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The number of active locks. Will always be less or equal to `max`.
|
|
108
|
+
*
|
|
109
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
110
|
+
*/
|
|
111
|
+
count(key = defaultKey) {
|
|
112
|
+
const _key = resolveKey(key);
|
|
113
|
+
return this.hasSemaphoreInstance(_key) ? this.getSemaphoreInstance(_key).count : 0;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
117
|
+
* @returns {boolean} True if the semaphore and key has locks, false otherwise.
|
|
118
|
+
*/
|
|
119
|
+
hasTasks(key = defaultKey) {
|
|
120
|
+
return this.count(key) > 0;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* @param {Function<T>} fn The function to execute.
|
|
124
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
125
|
+
* @returns {Promise<T>}
|
|
126
|
+
*/
|
|
127
|
+
async request(fn, key = defaultKey) {
|
|
128
|
+
try {
|
|
129
|
+
await this.acquire(key);
|
|
130
|
+
return await fn();
|
|
131
|
+
} finally {
|
|
132
|
+
this.release(key);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Asynchronously executes `fn` if a lock can be immediately acquired.
|
|
137
|
+
* Otherwise, returns null.
|
|
138
|
+
*
|
|
139
|
+
* @param {Function<T>} fn The function to execute.
|
|
140
|
+
* @param {string | number} [key]- Optional, the semaphore key.
|
|
141
|
+
* @returns {Promise<T>}
|
|
142
|
+
*/
|
|
143
|
+
async requestIfAvailable(fn, key = defaultKey) {
|
|
144
|
+
if (this.canAcquire(key)) {
|
|
145
|
+
return this.request(fn, key);
|
|
146
|
+
} else {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// src/group-semaphore.ts
|
|
153
|
+
var GroupSemaphore = class {
|
|
154
|
+
_semaphore = new Semaphore();
|
|
155
|
+
_activeCounts = {};
|
|
156
|
+
_groupWaiters = {};
|
|
157
|
+
async acquire(key) {
|
|
158
|
+
const activeCount = this._activeCounts[key] ?? 0;
|
|
159
|
+
this._activeCounts[key] = activeCount + 1;
|
|
160
|
+
const waiter = this._groupWaiters[key] ?? this._semaphore.acquire();
|
|
161
|
+
this._groupWaiters[key] = waiter;
|
|
162
|
+
await waiter;
|
|
163
|
+
}
|
|
164
|
+
release(key) {
|
|
165
|
+
const activeCount = this._activeCounts[key];
|
|
166
|
+
if (activeCount === 1) {
|
|
167
|
+
this._semaphore.release();
|
|
168
|
+
delete this._activeCounts[key];
|
|
169
|
+
delete this._groupWaiters[key];
|
|
170
|
+
} else {
|
|
171
|
+
this._activeCounts[key] = activeCount - 1;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
export {
|
|
176
|
+
GroupSemaphore,
|
|
177
|
+
Semaphore
|
|
178
|
+
};
|
|
179
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/semaphore.ts","../src/group-semaphore.ts"],"sourcesContent":["const defaultKey = \"_default\";\n\ntype KeyPrimitive = string | number;\n\ntype Key = KeyPrimitive | { key?: KeyPrimitive };\ntype KeyOptions = Key & { priority?: number };\n\nconst _isPrimitiveKey = (item: Key): item is KeyPrimitive =>\n [\"string\", \"number\"].includes(typeof item);\n\nconst resolveKey = (item: Key): KeyPrimitive =>\n (_isPrimitiveKey(item) ? item : item.key) ?? defaultKey;\n\nconst resolvePriority = (item: KeyOptions) =>\n (_isPrimitiveKey(item) ? 0 : item.priority) ?? 0;\n\nclass SemaphoreItem {\n private queue: Array<{\n resolve: Function;\n priority: number;\n }>;\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(priority: number): Promise<void> {\n if (this.canAcquire) {\n this.incrementCount();\n return Promise.resolve();\n } else {\n return new Promise((resolve) => {\n this.queue.push({ resolve, priority });\n this.queue.sort((a, b) => b.priority - a.priority);\n });\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.resolve, 0);\n // queueMicrotask(() => resolveFunc.resolve());\n } else {\n this.decrementCount();\n }\n }\n}\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 if (maxConcurrent < 1) {\n throw new Error(\"The maxConcurrent must be 1 or greater.\");\n }\n }\n\n private hasSemaphoreInstance(key: KeyPrimitive = defaultKey) {\n return Boolean(this.semaphoreInstances[key]);\n }\n\n private getSemaphoreInstance(key: KeyPrimitive = defaultKey) {\n if (!this.hasSemaphoreInstance(key)) {\n this.semaphoreInstances[key] = new SemaphoreItem(\n this.maxConcurrent,\n );\n }\n return this.semaphoreInstances[key] as SemaphoreItem;\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n private tidy(key: KeyPrimitive = 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: Key = defaultKey): boolean {\n const _key = resolveKey(key);\n\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: KeyOptions = defaultKey) {\n const _key = resolveKey(key);\n const _priority = resolvePriority(key);\n\n return this.getSemaphoreInstance(_key).acquire(_priority);\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n release(key: Key = defaultKey): void {\n const _key = resolveKey(key);\n\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: Key = defaultKey): number {\n const _key = resolveKey(key);\n\n return (this.hasSemaphoreInstance(_key))\n ? this.getSemaphoreInstance(_key).count\n : 0;\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: Key = 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: KeyOptions = 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: KeyOptions = 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] as number;\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"],"mappings":";AAAA,IAAM,aAAa;AAOnB,IAAM,kBAAkB,CAAC,SACrB,CAAC,UAAU,QAAQ,EAAE,SAAS,OAAO,IAAI;AAE7C,IAAM,aAAa,CAAC,UACf,gBAAgB,IAAI,IAAI,OAAO,KAAK,QAAQ;AAEjD,IAAM,kBAAkB,CAAC,UACpB,gBAAgB,IAAI,IAAI,IAAI,KAAK,aAAa;AAEnD,IAAM,gBAAN,MAAoB;AAAA,EACR;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAKD;AAAA,EAEP,YAAY,eAAuB;AAC/B,SAAK,QAAQ,CAAC;AACd,SAAK,gBAAgB;AACrB,SAAK,QAAQ;AAAA,EACjB;AAAA,EAEA,IAAI,aAAsB;AACtB,WAAO,KAAK,QAAQ,KAAK;AAAA,EAC7B;AAAA,EAEQ,iBAAiB;AACrB,SAAK;AAAA,EACT;AAAA,EAEQ,iBAAiB;AACrB,SAAK;AAAA,EACT;AAAA,EAEA,QAAQ,UAAiC;AACrC,QAAI,KAAK,YAAY;AACjB,WAAK,eAAe;AACpB,aAAO,QAAQ,QAAQ;AAAA,IAC3B,OAAO;AACH,aAAO,IAAI,QAAQ,CAAC,YAAY;AAC5B,aAAK,MAAM,KAAK,EAAE,SAAS,SAAS,CAAC;AACrC,aAAK,MAAM,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;AAAA,MACrD,CAAC;AAAA,IACL;AAAA,EACJ;AAAA,EAEA,UAAgB;AACZ,UAAM,cAAc,KAAK,MAAM,MAAM;AAErC,QAAI,aAAa;AAEb,iBAAW,YAAY,SAAS,CAAC;AAAA,IAErC,OAAO;AACH,WAAK,eAAe;AAAA,IACxB;AAAA,EACJ;AACJ;AAEA,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AO;AACH,WAAK,cAAc,GAAG,IAAI,cAAc;AAAA,IAC5C;AAAA,EACJ;AACJ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,29 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chriscdn/promise-semaphore",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
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>",
|
|
7
7
|
"license": "MIT",
|
|
8
8
|
"type": "module",
|
|
9
|
-
"
|
|
10
|
-
"main": "./lib/promise-semaphore.cjs",
|
|
11
|
-
"module": "./lib/promise-semaphore.module.js",
|
|
12
|
-
"__unpkg": "./lib/promise-semaphore.umd.js",
|
|
13
|
-
"exports": {
|
|
14
|
-
"types": "./lib/index.d.ts",
|
|
15
|
-
"require": "./lib/promise-semaphore.cjs",
|
|
16
|
-
"default": "./lib/promise-semaphore.modern.js"
|
|
17
|
-
},
|
|
9
|
+
"main": "./lib/index.js",
|
|
18
10
|
"types": "./lib/index.d.ts",
|
|
11
|
+
"exports": "./lib/index.js",
|
|
19
12
|
"scripts": {
|
|
20
|
-
"build": "
|
|
21
|
-
"
|
|
13
|
+
"build": "tsup",
|
|
14
|
+
"watch": "yarn build --watch",
|
|
22
15
|
"test": "vitest"
|
|
23
16
|
},
|
|
24
17
|
"devDependencies": {
|
|
25
|
-
"
|
|
26
|
-
"
|
|
18
|
+
"@tsconfig/strictest": "^2.0.8",
|
|
19
|
+
"tsup": "^8.5.1",
|
|
20
|
+
"typescript": "^5.9.3",
|
|
21
|
+
"vitest": "^4.0.8"
|
|
27
22
|
},
|
|
28
23
|
"files": [
|
|
29
24
|
"lib"
|
package/lib/group-semaphore.d.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
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 };
|
|
@@ -1,2 +0,0 @@
|
|
|
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 r=t.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var t="_default",r=function(e){return["string","number"].includes(typeof e)},n=function(e){var n;return null!=(n=r(e)?e:e.key)?n:t},i=/*#__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 r,n,i=t.prototype;return i.incrementCount=function(){this.count++},i.decrementCount=function(){this.count--},i.acquire=function(e){var t=this;return this.canAcquire?(this.incrementCount(),Promise.resolve()):new Promise(function(r){t.queue.push({resolve:r,priority:e}),t.queue.sort(function(e,t){return t.priority-e.priority})})},i.release=function(){var e=this.queue.shift();e?setTimeout(e.resolve,0):this.decrementCount()},r=t,(n=[{key:"canAcquire",get:function(){return this.count<this.maxConcurrent}}])&&function(t,r){for(var n=0;n<r.length;n++){var i=r[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,e(i.key),i)}}(r.prototype,n),Object.defineProperty(r,"prototype",{writable:!1}),r}(),o=/*#__PURE__*/function(){function e(e){if(void 0===e&&(e=1),this.semaphoreInstances=void 0,this.maxConcurrent=void 0,this.semaphoreInstances={},this.maxConcurrent=e,e<1)throw new Error("The maxConcurrent must be 1 or greater.")}var o=e.prototype;return o.hasSemaphoreInstance=function(e){return void 0===e&&(e=t),Boolean(this.semaphoreInstances[e])},o.getSemaphoreInstance=function(e){return void 0===e&&(e=t),this.hasSemaphoreInstance(e)||(this.semaphoreInstances[e]=new i(this.maxConcurrent)),this.semaphoreInstances[e]},o.tidy=function(e){void 0===e&&(e=t),this.hasSemaphoreInstance(e)&&0===this.getSemaphoreInstance(e).count&&delete this.semaphoreInstances[e]},o.canAcquire=function(e){void 0===e&&(e=t);var r=n(e);return!this.hasSemaphoreInstance(r)||this.getSemaphoreInstance(r).canAcquire},o.acquire=function(e){void 0===e&&(e=t);var i,o,s=n(e),u=null!=(o=r(i=e)?0:i.priority)?o:0;return this.getSemaphoreInstance(s).acquire(u)},o.release=function(e){void 0===e&&(e=t);var r=n(e);this.getSemaphoreInstance(r).release(),this.tidy(r)},o.count=function(e){void 0===e&&(e=t);var r=n(e);return this.hasSemaphoreInstance(r)?this.getSemaphoreInstance(r).count:0},o.hasTasks=function(e){return void 0===e&&(e=t),this.count(e)>0},o.request=function(e,r){void 0===r&&(r=t);try{var n=this;return Promise.resolve(function(t,i){try{var o=Promise.resolve(n.acquire(r)).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,t){if(n.release(r),e)throw t;return t}))}catch(e){return Promise.reject(e)}},o.requestIfAvailable=function(e,r){void 0===r&&(r=t);try{return this.canAcquire(r)?Promise.resolve(this.request(e,r)):Promise.resolve(null)}catch(e){return Promise.reject(e)}},e}();exports.GroupSemaphore=/*#__PURE__*/function(){function e(){this._semaphore=new o,this._activeCounts={},this._groupWaiters={}}var t=e.prototype;return t.acquire=function(e){try{var t,r,n=this,i=null!=(t=n._activeCounts[e])?t:0;n._activeCounts[e]=i+1;var o=null!=(r=n._groupWaiters[e])?r:n._semaphore.acquire();return n._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=o;
|
|
2
|
-
//# sourceMappingURL=promise-semaphore.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"promise-semaphore.cjs","sources":["../src/semaphore.ts","../src/group-semaphore.ts"],"sourcesContent":["const defaultKey = \"_default\";\n\ntype KeyPrimitive = string | number;\n\ntype Key = KeyPrimitive | { key?: KeyPrimitive };\ntype KeyOptions = Key & { priority?: number };\n\nconst _isPrimitiveKey = (item: Key): item is KeyPrimitive =>\n [\"string\", \"number\"].includes(typeof item);\n\nconst resolveKey = (item: Key): KeyPrimitive =>\n (_isPrimitiveKey(item) ? item : item.key) ?? defaultKey;\n\nconst resolvePriority = (item: KeyOptions) =>\n (_isPrimitiveKey(item) ? 0 : item.priority) ?? 0;\n\nclass SemaphoreItem {\n private queue: Array<{\n resolve: Function;\n priority: number;\n }>;\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(priority: number): Promise<void> {\n if (this.canAcquire) {\n this.incrementCount();\n return Promise.resolve();\n } else {\n return new Promise((resolve) => {\n this.queue.push({ resolve, priority });\n this.queue.sort((a, b) => b.priority - a.priority);\n });\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.resolve, 0);\n } else {\n this.decrementCount();\n }\n }\n}\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 if (maxConcurrent < 1) {\n throw new Error(\"The maxConcurrent must be 1 or greater.\");\n }\n }\n\n private hasSemaphoreInstance(key: KeyPrimitive = defaultKey) {\n return Boolean(this.semaphoreInstances[key]);\n }\n\n private getSemaphoreInstance(key: KeyPrimitive = 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: KeyPrimitive = 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: Key = defaultKey): boolean {\n const _key = resolveKey(key);\n\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: KeyOptions = defaultKey) {\n const _key = resolveKey(key);\n const _priority = resolvePriority(key);\n\n return this.getSemaphoreInstance(_key).acquire(_priority);\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n release(key: Key = defaultKey): void {\n const _key = resolveKey(key);\n\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: Key = defaultKey): number {\n const _key = resolveKey(key);\n\n return (this.hasSemaphoreInstance(_key))\n ? this.getSemaphoreInstance(_key).count\n : 0;\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: Key = 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: KeyOptions = 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: KeyOptions = 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":["defaultKey","_isPrimitiveKey","item","includes","resolveKey","_ref","key","SemaphoreItem","maxConcurrent","queue","this","count","_proto","prototype","_createClass","incrementCount","decrementCount","acquire","priority","_this","canAcquire","Promise","resolve","push","sort","a","b","release","resolveFunc","shift","setTimeout","get","Semaphore","semaphoreInstances","Error","_proto2","hasSemaphoreInstance","Boolean","getSemaphoreInstance","tidy","_key","_ref2","_priority","hasTasks","request","fn","_this2","then","_finallyRethrows","_wasThrown","_result","e","reject","requestIfAvailable","GroupSemaphore","_semaphore","_activeCounts","_groupWaiters","_this$_activeCounts$k","_this$_groupWaiters$k","activeCount","waiter"],"mappings":"+RAAA,IAAMA,EAAa,WAObC,EAAkB,SAACC,GAAS,MAC9B,CAAC,SAAU,UAAUC,gBAAgBD,EAAK,EAExCE,EAAa,SAACF,GAASG,IAAAA,SACe,OADfA,EACxBJ,EAAgBC,GAAQA,EAAOA,EAAKI,KAAGD,EAAKL,CAAU,EAKrDO,eAAa,WAYf,SAAAA,EAAYC,GAXJC,KAAAA,kBAIAD,mBAAa,EAAAE,KAKdC,WAAK,EAGRD,KAAKD,MAAQ,GACbC,KAAKF,cAAgBA,EACrBE,KAAKC,MAAQ,CACjB,CAAC,QAAAC,EAAAL,EAAAM,UAmCAC,OAnCAF,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N,GAAU,IAE5B,OAAIU,KAAKU,WAAWd,GAChBe,QAAAC,QADAZ,KACYkC,QAAQC,EAAIvC,IAExBe,QAAAC,QAAO,KAEf,CAAC,MAAA6B,GAAA9B,OAAAA,QAAA+B,OAAAD,EAAAnB,CAAAA,EAAAA,CAAA,CA3HD,2DC1DgBsB,IAAA5C,KACR6C,WAAa,IAAIvB,EAAWtB,KAC5B8C,cAAwC,CAAE,EAAA9C,KAC1C+C,cAA+C,EAAE,CAAA,IAAA7C,EAAA0C,EAAAzC,UAoBxDyC,OApBwD1C,EAEnDK,iBAAQX,GAAW,QAAAoD,EAAAC,EAAAxC,EACDT,KAAdkD,EAAqC,OAA1BF,EAAGvC,EAAKqC,cAAclD,IAAIoD,EAAI,EAC/CvC,EAAKqC,cAAclD,GAAOsD,EAAc,EACxC,IAAMC,EAAgCF,OAA1BA,EAAGxC,EAAKsC,cAAcnD,IAAIqD,EAAIxC,EAAKoC,WAAWtC,UACzB,OAAjCE,EAAKsC,cAAcnD,GAAOuD,EAAOxC,QAAAC,QAC3BuC,GAAMd,KAChB,WAAA,EAAA,CAAC,MAAAI,GAAA9B,OAAAA,QAAA+B,OAAAD,EAAAvC,CAAAA,EAAAA,EAEDe,QAAA,SAAQrB,GACJ,IAAMsD,EAAclD,KAAK8C,cAAclD,GAEnB,IAAhBsD,GACAlD,KAAK6C,WAAW5B,iBACLjB,KAAC8C,cAAclD,UACnBI,KAAK+C,cAAcnD,IAE1BI,KAAK8C,cAAclD,GAAOsD,EAAc,CAEhD,EAACN,CAAA"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e="_default",t=e=>["string","number"].includes(typeof e),s=s=>{var r;return null!=(r=t(s)?s:s.key)?r:e};class r{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(e){return this.canAcquire?(this.incrementCount(),Promise.resolve()):new Promise(t=>{this.queue.push({resolve:t,priority:e}),this.queue.sort((e,t)=>t.priority-e.priority)})}release(){const e=this.queue.shift();e?setTimeout(e.resolve,0):this.decrementCount()}}class n{constructor(e=1){if(this.semaphoreInstances=void 0,this.maxConcurrent=void 0,this.semaphoreInstances={},this.maxConcurrent=e,e<1)throw new Error("The maxConcurrent must be 1 or greater.")}hasSemaphoreInstance(t=e){return Boolean(this.semaphoreInstances[t])}getSemaphoreInstance(t=e){return this.hasSemaphoreInstance(t)||(this.semaphoreInstances[t]=new r(this.maxConcurrent)),this.semaphoreInstances[t]}tidy(t=e){this.hasSemaphoreInstance(t)&&0===this.getSemaphoreInstance(t).count&&delete this.semaphoreInstances[t]}canAcquire(t=e){const r=s(t);return!this.hasSemaphoreInstance(r)||this.getSemaphoreInstance(r).canAcquire}acquire(r=e){const n=s(r),i=null!=(o=t(a=r)?0:a.priority)?o:0;var a,o;return this.getSemaphoreInstance(n).acquire(i)}release(t=e){const r=s(t);this.getSemaphoreInstance(r).release(),this.tidy(r)}count(t=e){const r=s(t);return this.hasSemaphoreInstance(r)?this.getSemaphoreInstance(r).count:0}hasTasks(t=e){return this.count(t)>0}async request(t,s=e){try{return await this.acquire(s),await t()}finally{this.release(s)}}async requestIfAvailable(t,s=e){return this.canAcquire(s)?this.request(t,s):null}}class i{constructor(){this._semaphore=new n,this._activeCounts={},this._groupWaiters={}}async acquire(e){var t,s;const r=null!=(t=this._activeCounts[e])?t:0;this._activeCounts[e]=r+1;const n=null!=(s=this._groupWaiters[e])?s:this._semaphore.acquire();this._groupWaiters[e]=n,await n}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{i as GroupSemaphore,n as Semaphore};
|
|
2
|
-
//# sourceMappingURL=promise-semaphore.modern.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"promise-semaphore.modern.js","sources":["../src/semaphore.ts","../src/group-semaphore.ts"],"sourcesContent":["const defaultKey = \"_default\";\n\ntype KeyPrimitive = string | number;\n\ntype Key = KeyPrimitive | { key?: KeyPrimitive };\ntype KeyOptions = Key & { priority?: number };\n\nconst _isPrimitiveKey = (item: Key): item is KeyPrimitive =>\n [\"string\", \"number\"].includes(typeof item);\n\nconst resolveKey = (item: Key): KeyPrimitive =>\n (_isPrimitiveKey(item) ? item : item.key) ?? defaultKey;\n\nconst resolvePriority = (item: KeyOptions) =>\n (_isPrimitiveKey(item) ? 0 : item.priority) ?? 0;\n\nclass SemaphoreItem {\n private queue: Array<{\n resolve: Function;\n priority: number;\n }>;\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(priority: number): Promise<void> {\n if (this.canAcquire) {\n this.incrementCount();\n return Promise.resolve();\n } else {\n return new Promise((resolve) => {\n this.queue.push({ resolve, priority });\n this.queue.sort((a, b) => b.priority - a.priority);\n });\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.resolve, 0);\n } else {\n this.decrementCount();\n }\n }\n}\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 if (maxConcurrent < 1) {\n throw new Error(\"The maxConcurrent must be 1 or greater.\");\n }\n }\n\n private hasSemaphoreInstance(key: KeyPrimitive = defaultKey) {\n return Boolean(this.semaphoreInstances[key]);\n }\n\n private getSemaphoreInstance(key: KeyPrimitive = 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: KeyPrimitive = 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: Key = defaultKey): boolean {\n const _key = resolveKey(key);\n\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: KeyOptions = defaultKey) {\n const _key = resolveKey(key);\n const _priority = resolvePriority(key);\n\n return this.getSemaphoreInstance(_key).acquire(_priority);\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n release(key: Key = defaultKey): void {\n const _key = resolveKey(key);\n\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: Key = defaultKey): number {\n const _key = resolveKey(key);\n\n return (this.hasSemaphoreInstance(_key))\n ? this.getSemaphoreInstance(_key).count\n : 0;\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: Key = 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: KeyOptions = 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: KeyOptions = 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":["defaultKey","_isPrimitiveKey","item","includes","resolveKey","_ref","key","SemaphoreItem","constructor","maxConcurrent","queue","this","count","canAcquire","incrementCount","decrementCount","acquire","priority","Promise","resolve","push","sort","a","b","release","resolveFunc","shift","setTimeout","Semaphore","semaphoreInstances","Error","hasSemaphoreInstance","Boolean","getSemaphoreInstance","tidy","_key","_priority","_ref2","hasTasks","request","fn","requestIfAvailable","GroupSemaphore","_semaphore","_activeCounts","_groupWaiters","_this$_activeCounts$k","_this$_groupWaiters$k","activeCount","waiter"],"mappings":"AAAA,MAAMA,EAAa,WAObC,EAAmBC,GACrB,CAAC,SAAU,UAAUC,gBAAgBD,GAEnCE,EAAcF,QAASG,EAAA,OACeA,OADfA,EACxBJ,EAAgBC,GAAQA,EAAOA,EAAKI,KAAGD,EAAKL,GAKjD,MAAMO,EAYFC,WAAAA,CAAYC,QAXJC,WAAK,EAAAC,KAILF,mBAAa,EAAAE,KAKdC,WAGH,EAAAD,KAAKD,MAAQ,GACbC,KAAKF,cAAgBA,EACrBE,KAAKC,MAAQ,CACjB,CAEA,cAAIC,GACA,OAAOF,KAAKC,MAAQD,KAAKF,aAC7B,CAEQK,cAAAA,GACJH,KAAKC,OACT,CAEQG,cAAAA,GACJJ,KAAKC,OACT,CAEAI,OAAAA,CAAQC,GACJ,OAAIN,KAAKE,YACLF,KAAKG,iBACEI,QAAQC,WAEJ,IAAAD,QAASC,IAChBR,KAAKD,MAAMU,KAAK,CAAED,UAASF,aAC3BN,KAAKD,MAAMW,KAAK,CAACC,EAAGC,IAAMA,EAAEN,SAAWK,EAAEL,WAGrD,CAEAO,OAAAA,GACI,MAAMC,EAAcd,KAAKD,MAAMgB,QAE3BD,EAEAE,WAAWF,EAAYN,QAAS,GAEhCR,KAAKI,gBAEb,EAGJ,MAAMa,EAOFpB,WAAAA,CAAYC,EAAwB,GAIhC,GAJiCE,KAN7BkB,wBAAkB,EAAAlB,KAClBF,mBAMJ,EAAAE,KAAKkB,mBAAqB,CAAA,EAC1BlB,KAAKF,cAAgBA,EAEjBA,EAAgB,EAChB,MAAM,IAAIqB,MAAM,0CAExB,CAEQC,oBAAAA,CAAqBzB,EAAoBN,GAC7C,OAAOgC,QAAQrB,KAAKkB,mBAAmBvB,GAC3C,CAEQ2B,o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IAAIf,OACjBgB,cAAwC,CAAE,OAC1CC,cAA+C,CAAA,CAAE,CAEzD,aAAM7B,CAAQV,GAAW,IAAAwC,EAAAC,EACrB,MAAMC,EAAqCF,OAA1BA,EAAGnC,KAAKiC,cAActC,IAAIwC,EAAI,EAC/CnC,KAAKiC,cAActC,GAAO0C,EAAc,EACxC,MAAMC,EAAgC,OAA1BF,EAAGpC,KAAKkC,cAAcvC,IAAIyC,EAAIpC,KAAKgC,WAAW3B,UAC1DL,KAAKkC,cAAcvC,GAAO2C,QACpBA,CACV,CAEAzB,OAAAA,CAAQlB,GACJ,MAAM0C,EAAcrC,KAAKiC,cAActC,GAEnB,IAAhB0C,GACArC,KAAKgC,WAAWnB,iBACTb,KAAKiC,cAActC,UACnBK,KAAKkC,cAAcvC,IAE1BK,KAAKiC,cAActC,GAAO0C,EAAc,CAEhD"}
|
|
@@ -1,2 +0,0 @@
|
|
|
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 r=t.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var t="_default",r=function(e){return["string","number"].includes(typeof e)},n=function(e){var n;return null!=(n=r(e)?e:e.key)?n:t},i=/*#__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 r,n,i=t.prototype;return i.incrementCount=function(){this.count++},i.decrementCount=function(){this.count--},i.acquire=function(e){var t=this;return this.canAcquire?(this.incrementCount(),Promise.resolve()):new Promise(function(r){t.queue.push({resolve:r,priority:e}),t.queue.sort(function(e,t){return t.priority-e.priority})})},i.release=function(){var e=this.queue.shift();e?setTimeout(e.resolve,0):this.decrementCount()},r=t,(n=[{key:"canAcquire",get:function(){return this.count<this.maxConcurrent}}])&&function(t,r){for(var n=0;n<r.length;n++){var i=r[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,e(i.key),i)}}(r.prototype,n),Object.defineProperty(r,"prototype",{writable:!1}),r}(),o=/*#__PURE__*/function(){function e(e){if(void 0===e&&(e=1),this.semaphoreInstances=void 0,this.maxConcurrent=void 0,this.semaphoreInstances={},this.maxConcurrent=e,e<1)throw new Error("The maxConcurrent must be 1 or greater.")}var o=e.prototype;return o.hasSemaphoreInstance=function(e){return void 0===e&&(e=t),Boolean(this.semaphoreInstances[e])},o.getSemaphoreInstance=function(e){return void 0===e&&(e=t),this.hasSemaphoreInstance(e)||(this.semaphoreInstances[e]=new i(this.maxConcurrent)),this.semaphoreInstances[e]},o.tidy=function(e){void 0===e&&(e=t),this.hasSemaphoreInstance(e)&&0===this.getSemaphoreInstance(e).count&&delete this.semaphoreInstances[e]},o.canAcquire=function(e){void 0===e&&(e=t);var r=n(e);return!this.hasSemaphoreInstance(r)||this.getSemaphoreInstance(r).canAcquire},o.acquire=function(e){void 0===e&&(e=t);var i,o,s=n(e),u=null!=(o=r(i=e)?0:i.priority)?o:0;return this.getSemaphoreInstance(s).acquire(u)},o.release=function(e){void 0===e&&(e=t);var r=n(e);this.getSemaphoreInstance(r).release(),this.tidy(r)},o.count=function(e){void 0===e&&(e=t);var r=n(e);return this.hasSemaphoreInstance(r)?this.getSemaphoreInstance(r).count:0},o.hasTasks=function(e){return void 0===e&&(e=t),this.count(e)>0},o.request=function(e,r){void 0===r&&(r=t);try{var n=this;return Promise.resolve(function(t,i){try{var o=Promise.resolve(n.acquire(r)).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,t){if(n.release(r),e)throw t;return t}))}catch(e){return Promise.reject(e)}},o.requestIfAvailable=function(e,r){void 0===r&&(r=t);try{return this.canAcquire(r)?Promise.resolve(this.request(e,r)):Promise.resolve(null)}catch(e){return Promise.reject(e)}},e}(),s=/*#__PURE__*/function(){function e(){this._semaphore=new o,this._activeCounts={},this._groupWaiters={}}var t=e.prototype;return t.acquire=function(e){try{var t,r,n=this,i=null!=(t=n._activeCounts[e])?t:0;n._activeCounts[e]=i+1;var o=null!=(r=n._groupWaiters[e])?r:n._semaphore.acquire();return n._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{s as GroupSemaphore,o as Semaphore};
|
|
2
|
-
//# sourceMappingURL=promise-semaphore.module.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"promise-semaphore.module.js","sources":["../src/semaphore.ts","../src/group-semaphore.ts"],"sourcesContent":["const defaultKey = \"_default\";\n\ntype KeyPrimitive = string | number;\n\ntype Key = KeyPrimitive | { key?: KeyPrimitive };\ntype KeyOptions = Key & { priority?: number };\n\nconst _isPrimitiveKey = (item: Key): item is KeyPrimitive =>\n [\"string\", \"number\"].includes(typeof item);\n\nconst resolveKey = (item: Key): KeyPrimitive =>\n (_isPrimitiveKey(item) ? item : item.key) ?? defaultKey;\n\nconst resolvePriority = (item: KeyOptions) =>\n (_isPrimitiveKey(item) ? 0 : item.priority) ?? 0;\n\nclass SemaphoreItem {\n private queue: Array<{\n resolve: Function;\n priority: number;\n }>;\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(priority: number): Promise<void> {\n if (this.canAcquire) {\n this.incrementCount();\n return Promise.resolve();\n } else {\n return new Promise((resolve) => {\n this.queue.push({ resolve, priority });\n this.queue.sort((a, b) => b.priority - a.priority);\n });\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.resolve, 0);\n } else {\n this.decrementCount();\n }\n }\n}\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 if (maxConcurrent < 1) {\n throw new Error(\"The maxConcurrent must be 1 or greater.\");\n }\n }\n\n private hasSemaphoreInstance(key: KeyPrimitive = defaultKey) {\n return Boolean(this.semaphoreInstances[key]);\n }\n\n private getSemaphoreInstance(key: KeyPrimitive = 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: KeyPrimitive = 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: Key = defaultKey): boolean {\n const _key = resolveKey(key);\n\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: KeyOptions = defaultKey) {\n const _key = resolveKey(key);\n const _priority = resolvePriority(key);\n\n return this.getSemaphoreInstance(_key).acquire(_priority);\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n release(key: Key = defaultKey): void {\n const _key = resolveKey(key);\n\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: Key = defaultKey): number {\n const _key = resolveKey(key);\n\n return (this.hasSemaphoreInstance(_key))\n ? this.getSemaphoreInstance(_key).count\n : 0;\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: Key = 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: KeyOptions = 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: KeyOptions = 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":["defaultKey","_isPrimitiveKey","item","includes","resolveKey","_ref","key","SemaphoreItem","maxConcurrent","queue","this","count","_proto","prototype","_createClass","incrementCount","decrementCount","acquire","priority","_this","canAcquire","Promise","resolve","push","sort","a","b","release","resolveFunc","shift","setTimeout","get","Semaphore","semaphoreInstances","Error","_proto2","hasSemaphoreInstance","Boolean","getSemaphoreInstance","tidy","_key","_ref2","_priority","hasTasks","request","fn","_this2","then","_finallyRethrows","_wasThrown","_result","e","reject","requestIfAvailable","GroupSemaphore","_semaphore","_activeCounts","_groupWaiters","_this$_activeCounts$k","_this$_groupWaiters$k","activeCount","waiter"],"mappings":"+RAAA,IAAMA,EAAa,WAObC,EAAkB,SAACC,GAAS,MAC9B,CAAC,SAAU,UAAUC,gBAAgBD,EAAK,EAExCE,EAAa,SAACF,GAASG,IAAAA,SACe,OADfA,EACxBJ,EAAgBC,GAAQA,EAAOA,EAAKI,KAAGD,EAAKL,CAAU,EAKrDO,eAAa,WAYf,SAAAA,EAAYC,GAXJC,KAAAA,kBAIAD,mBAAa,EAAAE,KAKdC,WAAK,EAGRD,KAAKD,MAAQ,GACbC,KAAKF,cAAgBA,EACrBE,KAAKC,MAAQ,CACjB,CAAC,QAAAC,EAAAL,EAAAM,UAmCAC,OAnCAF,EAMOG,eAAA,WACJL,KAAKC,OACT,EAACC,EAEOI,eAAA,WACJN,KAAKC,OACT,EAACC,EAEDK,QAAA,SAAQC,GAAgB,IAAAC,EAAAT,KACpB,OAAIA,KAAKU,YACLV,K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B,OAAAD,EAAAnB,CAAAA,EAAAA,CAAA,CA3HD,GC1DEsB,mCAAcA,IAAA5C,KACR6C,WAAa,IAAIvB,EAAWtB,KAC5B8C,cAAwC,CAAE,EAAA9C,KAC1C+C,cAA+C,EAAE,CAAA,IAAA7C,EAAA0C,EAAAzC,UAoBxDyC,OApBwD1C,EAEnDK,iBAAQX,GAAW,QAAAoD,EAAAC,EAAAxC,EACDT,KAAdkD,EAAqC,OAA1BF,EAAGvC,EAAKqC,cAAclD,IAAIoD,EAAI,EAC/CvC,EAAKqC,cAAclD,GAAOsD,EAAc,EACxC,IAAMC,EAAgCF,OAA1BA,EAAGxC,EAAKsC,cAAcnD,IAAIqD,EAAIxC,EAAKoC,WAAWtC,UACzB,OAAjCE,EAAKsC,cAAcnD,GAAOuD,EAAOxC,QAAAC,QAC3BuC,GAAMd,KAChB,WAAA,EAAA,CAAC,MAAAI,GAAA9B,OAAAA,QAAA+B,OAAAD,EAAAvC,CAAAA,EAAAA,EAEDe,QAAA,SAAQrB,GACJ,IAAMsD,EAAclD,KAAK8C,cAAclD,GAEnB,IAAhBsD,GACAlD,KAAK6C,WAAW5B,iBACLjB,KAAC8C,cAAclD,UACnBI,KAAK+C,cAAcnD,IAE1BI,KAAK8C,cAAclD,GAAOsD,EAAc,CAEhD,EAACN,CAAA"}
|
package/lib/semaphore.d.ts
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
type KeyPrimitive = string | number;
|
|
2
|
-
type Key = KeyPrimitive | {
|
|
3
|
-
key?: KeyPrimitive;
|
|
4
|
-
};
|
|
5
|
-
type KeyOptions = Key & {
|
|
6
|
-
priority?: number;
|
|
7
|
-
};
|
|
8
|
-
declare class Semaphore {
|
|
9
|
-
private semaphoreInstances;
|
|
10
|
-
private maxConcurrent;
|
|
11
|
-
/**
|
|
12
|
-
* @param {number} [maxConcurrent] The maximum number of concurrent locks.
|
|
13
|
-
*/
|
|
14
|
-
constructor(maxConcurrent?: number);
|
|
15
|
-
private hasSemaphoreInstance;
|
|
16
|
-
private getSemaphoreInstance;
|
|
17
|
-
/**
|
|
18
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
19
|
-
*/
|
|
20
|
-
private tidy;
|
|
21
|
-
/**
|
|
22
|
-
* A synchronous function to determine whether a lock can be acquired.
|
|
23
|
-
*
|
|
24
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
25
|
-
* @returns {boolean} Returns true if the lock on `key` can be acquired, false
|
|
26
|
-
* otherwise.
|
|
27
|
-
*/
|
|
28
|
-
canAcquire(key?: Key): boolean;
|
|
29
|
-
/**
|
|
30
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
31
|
-
*/
|
|
32
|
-
acquire(key?: KeyOptions): Promise<void>;
|
|
33
|
-
/**
|
|
34
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
35
|
-
*/
|
|
36
|
-
release(key?: Key): void;
|
|
37
|
-
/**
|
|
38
|
-
* The number of active locks. Will always be less or equal to `max`.
|
|
39
|
-
*
|
|
40
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
41
|
-
*/
|
|
42
|
-
count(key?: Key): number;
|
|
43
|
-
/**
|
|
44
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
45
|
-
* @returns {boolean} True if the semaphore and key has locks, false otherwise.
|
|
46
|
-
*/
|
|
47
|
-
hasTasks(key?: Key): boolean;
|
|
48
|
-
/**
|
|
49
|
-
* @param {Function<T>} fn The function to execute.
|
|
50
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
51
|
-
* @returns {Promise<T>}
|
|
52
|
-
*/
|
|
53
|
-
request<T>(fn: Function, key?: KeyOptions): Promise<T>;
|
|
54
|
-
/**
|
|
55
|
-
* Asynchronously executes `fn` if a lock can be immediately acquired.
|
|
56
|
-
* Otherwise, returns null.
|
|
57
|
-
*
|
|
58
|
-
* @param {Function<T>} fn The function to execute.
|
|
59
|
-
* @param {string | number} [key]- Optional, the semaphore key.
|
|
60
|
-
* @returns {Promise<T>}
|
|
61
|
-
*/
|
|
62
|
-
requestIfAvailable<T>(fn: Function, key?: KeyOptions): Promise<T | null>;
|
|
63
|
-
}
|
|
64
|
-
export { Semaphore };
|