@icgio/icg-utils 1.9.35 → 1.9.36
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/rate-limiter.js +53 -11
- package/package.json +1 -1
package/lib/rate-limiter.js
CHANGED
|
@@ -3,25 +3,67 @@ class RateLimiter {
|
|
|
3
3
|
this.max_concurrent = settings.max_concurrent ? settings.max_concurrent : null
|
|
4
4
|
this.interval_concurrent = settings.interval_concurrent ? settings.interval_concurrent : null
|
|
5
5
|
this.abandon_tx = settings.abandon_tx ? settings.abandon_tx : false
|
|
6
|
+
this.only_same_args = settings.only_same_args ? settings.only_same_args : false
|
|
6
7
|
this.count = 0
|
|
8
|
+
this.keyToState = new Map()
|
|
7
9
|
}
|
|
8
10
|
process(func, ...args) {
|
|
9
11
|
if (!this.max_concurrent || !this.interval_concurrent) {
|
|
10
12
|
func(...args)
|
|
11
13
|
return
|
|
12
14
|
}
|
|
13
|
-
if (this.
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
if (this.only_same_args) {
|
|
16
|
+
const key = this._serializeArgs(args)
|
|
17
|
+
let state = this.keyToState.get(key)
|
|
18
|
+
if (!state) {
|
|
19
|
+
state = { count: 0, timerId: null }
|
|
20
|
+
this.keyToState.set(key, state)
|
|
21
|
+
}
|
|
22
|
+
if (state.count === 0) {
|
|
23
|
+
state.timerId = setTimeout(() => {
|
|
24
|
+
state.count = 0
|
|
25
|
+
state.timerId = null
|
|
26
|
+
// cleanup to avoid unbounded growth
|
|
27
|
+
this.keyToState.delete(key)
|
|
28
|
+
}, this.interval_concurrent)
|
|
29
|
+
}
|
|
30
|
+
if (state.count < this.max_concurrent) {
|
|
31
|
+
state.count++
|
|
32
|
+
func(...args)
|
|
33
|
+
} else if (!this.abandon_tx) {
|
|
34
|
+
setTimeout(() => {
|
|
35
|
+
this.process(func, ...args)
|
|
36
|
+
}, this.interval_concurrent)
|
|
37
|
+
}
|
|
38
|
+
} else {
|
|
39
|
+
if (this.count === 0) {
|
|
40
|
+
setTimeout(() => {
|
|
41
|
+
this.count = 0
|
|
42
|
+
}, this.interval_concurrent)
|
|
43
|
+
}
|
|
44
|
+
if (this.count < this.max_concurrent) {
|
|
45
|
+
this.count++
|
|
46
|
+
func(...args)
|
|
47
|
+
} else if (!this.abandon_tx) {
|
|
48
|
+
setTimeout(() => {
|
|
49
|
+
this.process(func, ...args)
|
|
50
|
+
}, this.interval_concurrent)
|
|
51
|
+
}
|
|
17
52
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
53
|
+
}
|
|
54
|
+
_serializeArgs(args) {
|
|
55
|
+
try {
|
|
56
|
+
return JSON.stringify(args)
|
|
57
|
+
} catch (e) {
|
|
58
|
+
return args
|
|
59
|
+
.map((a) => {
|
|
60
|
+
try {
|
|
61
|
+
return JSON.stringify(a)
|
|
62
|
+
} catch (_) {
|
|
63
|
+
return String(a)
|
|
64
|
+
}
|
|
65
|
+
})
|
|
66
|
+
.join('|')
|
|
25
67
|
}
|
|
26
68
|
}
|
|
27
69
|
}
|