-
Notifications
You must be signed in to change notification settings - Fork 0
/
counting-governor.ts
70 lines (60 loc) · 1.49 KB
/
counting-governor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { Governor } from "./governor.js";
export class CountingGovernor extends Governor {
#capacity: number;
#acquired: number = 0;
#wait: PromiseWithResolvers<void> | null = null;
#idleListeners: (() => void)[] = [];
constructor(capacity: number) {
if ((capacity >>> 0) !== capacity) {
throw new TypeError("capacity must be an integer");
}
if (capacity < 0) {
throw new RangeError("capacity must be non-negative");
}
super();
this.#capacity = capacity;
}
async acquire() {
while (this.#acquired >= this.#capacity) {
if (!this.#wait) {
this.#wait = Promise.withResolvers<void>();
}
await this.#wait.promise;
}
++this.#acquired;
let hasReleased = false;
const dispose = () => {
if (hasReleased) {
throw new Error("Already released");
}
hasReleased = true;
--this.#acquired;
if (this.#wait) {
this.#wait.resolve();
this.#wait = null;
} else if (this.#acquired === 0) {
this.#notifyIdleListeners();
}
};
return {
release: dispose,
[Symbol.dispose]: dispose,
};
}
addIdleListener(cb: () => void) {
this.#idleListeners.push(cb);
}
removeIdleListener(cb: () => void) {
const idx = this.#idleListeners.indexOf(cb);
if (idx >= 0) {
this.#idleListeners.splice(idx, 1);
}
}
#notifyIdleListeners() {
for (const cb of this.#idleListeners) {
try {
cb();
} catch {}
}
}
}