token-bucket.ts 0.0.0 → 1.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/LICENSE +25 -0
- package/README.md +157 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +125 -0
- package/package.json +32 -7
package/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
BSD 2-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) [2026], [Beeno Tung (Tung Cheung Leong)]
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted provided that the following conditions are met:
|
|
8
|
+
|
|
9
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
10
|
+
list of conditions and the following disclaimer.
|
|
11
|
+
|
|
12
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
13
|
+
this list of conditions and the following disclaimer in the documentation
|
|
14
|
+
and/or other materials provided with the distribution.
|
|
15
|
+
|
|
16
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
17
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
18
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
19
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
20
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
21
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
22
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
23
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
24
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
25
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
package/README.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# token-bucket.ts
|
|
2
|
+
|
|
3
|
+
A simple, lightweight token bucket rate limiter for TypeScript/JavaScript.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/token-bucket.ts)
|
|
6
|
+
[](https://bundlephobia.com/package/token-bucket.ts)
|
|
7
|
+
[](https://bundlephobia.com/package/token-bucket.ts)
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- Zero dependencies
|
|
12
|
+
- Continuous refill (lazy evaluation, no timers)
|
|
13
|
+
- Per-key buckets (rate limit by IP, user ID, etc.)
|
|
14
|
+
- Optional cooldown (minimum time between consumes)
|
|
15
|
+
- TypeScript with full type definitions
|
|
16
|
+
- Works in Node.js and browsers
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install token-bucket.ts
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
You can also install with [pnpm](https://pnpm.io/), [yarn](https://yarnpkg.com/), or [slnpm](https://github.com/beenotung/slnpm)
|
|
25
|
+
|
|
26
|
+
## Usage
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { TokenBucket } from 'token-bucket.ts'
|
|
30
|
+
|
|
31
|
+
// Create a bucket: 5 tokens capacity, refill 1 token per second
|
|
32
|
+
let bucket = new TokenBucket({
|
|
33
|
+
capacity: 5, // max number of token for each key
|
|
34
|
+
initial: 3, // can be different from capacity
|
|
35
|
+
interval: 1000, // ms, refill interval for each token
|
|
36
|
+
cooldown: 1000, // ms, minimum time between successful consumes,
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
// Consume a token
|
|
40
|
+
let { wait_time } = bucket.consume('user:123')
|
|
41
|
+
if (wait_time > 0) {
|
|
42
|
+
// Rate limited - wait_time ms until a token is available
|
|
43
|
+
throw new Error(`Rate limited. Try again in ${Math.ceil(wait_time / 1000)}s`)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Check without consuming
|
|
47
|
+
let result = bucket.check('user:123')
|
|
48
|
+
|
|
49
|
+
// Consume multiple tokens
|
|
50
|
+
bucket.consume('user:123', 3)
|
|
51
|
+
|
|
52
|
+
// Reset a specific key, you don't need to reset it manually, but you can
|
|
53
|
+
bucket.reset('user:123')
|
|
54
|
+
|
|
55
|
+
// Reset all keys
|
|
56
|
+
bucket.reset_all()
|
|
57
|
+
|
|
58
|
+
// Get number of tracked buckets
|
|
59
|
+
console.log(bucket.size)
|
|
60
|
+
|
|
61
|
+
// Remove fully-recovered buckets to free memory
|
|
62
|
+
bucket.prune()
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## API
|
|
66
|
+
|
|
67
|
+
### `new TokenBucket(options)`
|
|
68
|
+
|
|
69
|
+
| Option | Type | Default | Description |
|
|
70
|
+
| ---------- | ------ | -------- | --------------------------------------------- |
|
|
71
|
+
| `capacity` | number | required | Maximum tokens in bucket |
|
|
72
|
+
| `interval` | number | required | Refill interval in milliseconds |
|
|
73
|
+
| `refill` | number | 1 | Tokens to add per interval |
|
|
74
|
+
| `initial` | number | capacity | Starting tokens for new buckets |
|
|
75
|
+
| `cooldown` | number | 0 | Minimum time (ms) between successful consumes |
|
|
76
|
+
|
|
77
|
+
### Methods
|
|
78
|
+
|
|
79
|
+
| Method | Description |
|
|
80
|
+
| ----------------------- | ---------------------------------------------------------------------------------------------------- |
|
|
81
|
+
| `check(key, amount?)` | Check if tokens available (doesn't consume). `amount` defaults to 1, can be 0 to check only cooldown |
|
|
82
|
+
| `consume(key, amount?)` | Consume tokens if available. `amount` defaults to 1, must be > 0 |
|
|
83
|
+
| `reset(key)` | Reset a specific key's bucket |
|
|
84
|
+
| `reset_all()` | Reset all buckets |
|
|
85
|
+
| `prune()` | Remove fully-recovered buckets. Returns number removed. Only works when `initial >= capacity` |
|
|
86
|
+
| `size` | Get number of tracked buckets |
|
|
87
|
+
|
|
88
|
+
### Return Value
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
{
|
|
92
|
+
wait_time: number
|
|
93
|
+
} // 0 = allowed, >0 = wait this many ms
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Validation
|
|
97
|
+
|
|
98
|
+
Both `check` and `consume` throw errors for invalid amounts:
|
|
99
|
+
|
|
100
|
+
- `amount must be a number` - NaN provided
|
|
101
|
+
- `amount must be >= 0` (check) or `amount must be > 0` (consume)
|
|
102
|
+
- `amount must be <= capacity` - Cannot request more than bucket capacity
|
|
103
|
+
|
|
104
|
+
## Examples
|
|
105
|
+
|
|
106
|
+
### API Rate Limiting
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
let apiLimit = new TokenBucket({ capacity: 60, interval: 1000 })
|
|
110
|
+
|
|
111
|
+
function handleRequest(ip: string) {
|
|
112
|
+
let { wait_time } = apiLimit.consume(ip)
|
|
113
|
+
if (wait_time > 0) {
|
|
114
|
+
return { status: 429, message: 'Too many requests' }
|
|
115
|
+
}
|
|
116
|
+
// Process request...
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### SMS Verification with Cooldown
|
|
121
|
+
|
|
122
|
+
```typescript
|
|
123
|
+
let smsLimit = new TokenBucket({
|
|
124
|
+
capacity: 5, // Allow burst of 5
|
|
125
|
+
interval: 60000, // Refill 1 per minute
|
|
126
|
+
cooldown: 60000, // Minimum 60s between sends
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
function sendSMS(phone: string) {
|
|
130
|
+
let { wait_time } = smsLimit.consume(phone)
|
|
131
|
+
if (wait_time > 0) {
|
|
132
|
+
throw new Error(`Please wait ${Math.ceil(wait_time / 1000)} seconds`)
|
|
133
|
+
}
|
|
134
|
+
// Send SMS...
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Gradual Trust (Lower Initial Tokens)
|
|
139
|
+
|
|
140
|
+
```typescript
|
|
141
|
+
let newUserLimit = new TokenBucket({
|
|
142
|
+
capacity: 10,
|
|
143
|
+
interval: 1000,
|
|
144
|
+
initial: 3, // New users start with fewer tokens
|
|
145
|
+
})
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## License
|
|
149
|
+
|
|
150
|
+
This project is licensed with [BSD-2-Clause](./LICENSE)
|
|
151
|
+
|
|
152
|
+
This is free, libre, and open-source software. It comes down to four essential freedoms [[ref]](https://seirdy.one/2021/01/27/whatsapp-and-the-domestication-of-users.html#fnref:2):
|
|
153
|
+
|
|
154
|
+
- The freedom to run the program as you wish, for any purpose
|
|
155
|
+
- The freedom to study how the program works, and change it so it does your computing as you wish
|
|
156
|
+
- The freedom to redistribute copies so you can help others
|
|
157
|
+
- The freedom to distribute copies of your modified versions to others
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export type TokenBucketOptions = {
|
|
2
|
+
capacity: number;
|
|
3
|
+
interval: number;
|
|
4
|
+
refill?: number;
|
|
5
|
+
initial?: number;
|
|
6
|
+
cooldown?: number;
|
|
7
|
+
};
|
|
8
|
+
export type TokenBucketResult = {
|
|
9
|
+
/**
|
|
10
|
+
* - in milliseconds
|
|
11
|
+
* - if zero, means no wait is needed
|
|
12
|
+
*/
|
|
13
|
+
wait_time: number;
|
|
14
|
+
};
|
|
15
|
+
export declare class TokenBucket {
|
|
16
|
+
capacity: number;
|
|
17
|
+
interval: number;
|
|
18
|
+
refill: number;
|
|
19
|
+
initial: number;
|
|
20
|
+
cooldown: number;
|
|
21
|
+
private buckets;
|
|
22
|
+
constructor(options: TokenBucketOptions);
|
|
23
|
+
private get_bucket;
|
|
24
|
+
private refill_bucket;
|
|
25
|
+
private calc_token_wait_time;
|
|
26
|
+
private calc_cooldown_wait_time;
|
|
27
|
+
check(key: string, amount?: number): TokenBucketResult;
|
|
28
|
+
consume(key: string, amount?: number): TokenBucketResult;
|
|
29
|
+
reset(key: string): void;
|
|
30
|
+
reset_all(): void;
|
|
31
|
+
get size(): number;
|
|
32
|
+
/**
|
|
33
|
+
* Remove stale buckets that have fully recovered.
|
|
34
|
+
* Only prunes if initial >= capacity to avoid losing accumulated tokens.
|
|
35
|
+
* A bucket is pruned when it has full capacity and cooldown has passed.
|
|
36
|
+
* @returns number of buckets removed
|
|
37
|
+
*/
|
|
38
|
+
prune(): number;
|
|
39
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TokenBucket = void 0;
|
|
4
|
+
class TokenBucket {
|
|
5
|
+
capacity;
|
|
6
|
+
interval; // in milliseconds
|
|
7
|
+
refill;
|
|
8
|
+
initial;
|
|
9
|
+
cooldown; // in milliseconds
|
|
10
|
+
buckets = new Map();
|
|
11
|
+
constructor(options) {
|
|
12
|
+
this.capacity = options.capacity;
|
|
13
|
+
this.interval = options.interval;
|
|
14
|
+
this.refill = options.refill ?? 1;
|
|
15
|
+
this.initial = options.initial ?? this.capacity;
|
|
16
|
+
this.cooldown = options.cooldown ?? 0;
|
|
17
|
+
}
|
|
18
|
+
get_bucket(key) {
|
|
19
|
+
let bucket = this.buckets.get(key);
|
|
20
|
+
if (!bucket) {
|
|
21
|
+
bucket = {
|
|
22
|
+
tokens: this.initial,
|
|
23
|
+
last_refill: Date.now(),
|
|
24
|
+
last_consume: -Infinity,
|
|
25
|
+
};
|
|
26
|
+
this.buckets.set(key, bucket);
|
|
27
|
+
}
|
|
28
|
+
return bucket;
|
|
29
|
+
}
|
|
30
|
+
refill_bucket(bucket) {
|
|
31
|
+
let now = Date.now();
|
|
32
|
+
let elapsed = now - bucket.last_refill;
|
|
33
|
+
let refill_amount = (elapsed / this.interval) * this.refill;
|
|
34
|
+
bucket.tokens = Math.min(this.capacity, bucket.tokens + refill_amount);
|
|
35
|
+
bucket.last_refill = now;
|
|
36
|
+
}
|
|
37
|
+
calc_token_wait_time(tokens, amount) {
|
|
38
|
+
if (tokens >= amount)
|
|
39
|
+
return 0;
|
|
40
|
+
let needed = amount - tokens;
|
|
41
|
+
return (needed / this.refill) * this.interval;
|
|
42
|
+
}
|
|
43
|
+
calc_cooldown_wait_time(bucket) {
|
|
44
|
+
if (this.cooldown === 0)
|
|
45
|
+
return 0;
|
|
46
|
+
let now = Date.now();
|
|
47
|
+
let elapsed = now - bucket.last_consume;
|
|
48
|
+
if (elapsed >= this.cooldown)
|
|
49
|
+
return 0;
|
|
50
|
+
return this.cooldown - elapsed;
|
|
51
|
+
}
|
|
52
|
+
check(key, amount = 1) {
|
|
53
|
+
if (Number.isNaN(amount)) {
|
|
54
|
+
throw new Error('amount must be a number');
|
|
55
|
+
}
|
|
56
|
+
if (amount < 0) {
|
|
57
|
+
throw new Error('amount must be >= 0');
|
|
58
|
+
}
|
|
59
|
+
if (amount > this.capacity) {
|
|
60
|
+
throw new Error('amount must be <= capacity');
|
|
61
|
+
}
|
|
62
|
+
let bucket = this.get_bucket(key);
|
|
63
|
+
this.refill_bucket(bucket);
|
|
64
|
+
let cooldown_wait = this.calc_cooldown_wait_time(bucket);
|
|
65
|
+
let token_wait = this.calc_token_wait_time(bucket.tokens, amount);
|
|
66
|
+
return {
|
|
67
|
+
wait_time: Math.max(cooldown_wait, token_wait),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
consume(key, amount = 1) {
|
|
71
|
+
if (Number.isNaN(amount)) {
|
|
72
|
+
throw new Error('amount must be a number');
|
|
73
|
+
}
|
|
74
|
+
if (amount <= 0) {
|
|
75
|
+
throw new Error('amount must be > 0');
|
|
76
|
+
}
|
|
77
|
+
if (amount > this.capacity) {
|
|
78
|
+
throw new Error('amount must be <= capacity');
|
|
79
|
+
}
|
|
80
|
+
let bucket = this.get_bucket(key);
|
|
81
|
+
this.refill_bucket(bucket);
|
|
82
|
+
let cooldown_wait = this.calc_cooldown_wait_time(bucket);
|
|
83
|
+
let token_wait = this.calc_token_wait_time(bucket.tokens, amount);
|
|
84
|
+
let wait_time = Math.max(cooldown_wait, token_wait);
|
|
85
|
+
if (wait_time === 0) {
|
|
86
|
+
bucket.tokens -= amount;
|
|
87
|
+
bucket.last_consume = Date.now();
|
|
88
|
+
}
|
|
89
|
+
return { wait_time };
|
|
90
|
+
}
|
|
91
|
+
reset(key) {
|
|
92
|
+
this.buckets.delete(key);
|
|
93
|
+
}
|
|
94
|
+
reset_all() {
|
|
95
|
+
this.buckets.clear();
|
|
96
|
+
}
|
|
97
|
+
get size() {
|
|
98
|
+
return this.buckets.size;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Remove stale buckets that have fully recovered.
|
|
102
|
+
* Only prunes if initial >= capacity to avoid losing accumulated tokens.
|
|
103
|
+
* A bucket is pruned when it has full capacity and cooldown has passed.
|
|
104
|
+
* @returns number of buckets removed
|
|
105
|
+
*/
|
|
106
|
+
prune() {
|
|
107
|
+
let capacity = this.capacity;
|
|
108
|
+
if (this.initial < capacity) {
|
|
109
|
+
console.warn("TokenBucket.prune(): initial < capacity, won't prune to avoid losing accumulated tokens");
|
|
110
|
+
return 0; // Don't prune - would lose accumulated tokens
|
|
111
|
+
}
|
|
112
|
+
let removed = 0;
|
|
113
|
+
for (let [key, bucket] of this.buckets) {
|
|
114
|
+
this.refill_bucket(bucket);
|
|
115
|
+
let cooldown_wait = this.calc_cooldown_wait_time(bucket);
|
|
116
|
+
if (bucket.tokens < capacity || cooldown_wait > 0) {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
this.buckets.delete(key);
|
|
120
|
+
removed++;
|
|
121
|
+
}
|
|
122
|
+
return removed;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
exports.TokenBucket = TokenBucket;
|
package/package.json
CHANGED
|
@@ -1,26 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "token-bucket.ts",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"type": "commonjs",
|
|
5
|
-
"description": "",
|
|
6
|
-
"keywords": [
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
"description": "A simple, lightweight token bucket rate limiter for TypeScript/JavaScript.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"token-bucket",
|
|
8
|
+
"rate-limit",
|
|
9
|
+
"rate-limiter",
|
|
10
|
+
"throttle",
|
|
11
|
+
"throttling",
|
|
12
|
+
"api-limit",
|
|
13
|
+
"cooldown",
|
|
14
|
+
"typescript"
|
|
15
|
+
],
|
|
16
|
+
"author": "Beeno Tung <aabbcc1241@yahoo.com.hk> (https://beeno-tung.surge.sh)",
|
|
17
|
+
"license": "BSD-2-Clause",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/beenotung/token-bucket.ts.git"
|
|
21
|
+
},
|
|
22
|
+
"homepage": "https://github.com/beenotung/token-bucket.ts#readme",
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/beenotung/token-bucket.ts/issues"
|
|
25
|
+
},
|
|
9
26
|
"main": "dist/index.js",
|
|
10
27
|
"types": "dist/index.d.ts",
|
|
11
28
|
"files": [
|
|
12
29
|
"dist"
|
|
13
30
|
],
|
|
14
31
|
"scripts": {
|
|
15
|
-
"test": "tsc --noEmit",
|
|
32
|
+
"test": "npm run mocha && tsc --noEmit",
|
|
16
33
|
"clean": "rimraf dist",
|
|
17
34
|
"build": "rimraf dist && tsc -p . && rimraf dist/tsconfig.tsbuildinfo dist/*.test.d.ts dist/*.test.js dist/*.spec.d.ts dist/*.spec.js",
|
|
18
35
|
"tsc": "tsc -p .",
|
|
19
|
-
"dev": "tsc -p . --watch"
|
|
36
|
+
"dev": "tsc -p . --watch",
|
|
37
|
+
"mocha": "ts-mocha \"src/**/*.{test,spec}.ts\""
|
|
20
38
|
},
|
|
21
39
|
"devDependencies": {
|
|
40
|
+
"@types/chai": "^4.3.20",
|
|
41
|
+
"@types/mocha": "^10.0.10",
|
|
22
42
|
"@types/node": "^24.10.9",
|
|
43
|
+
"@types/sinon": "^21.0.0",
|
|
44
|
+
"chai": "^4.5.0",
|
|
45
|
+
"mocha": "^11.7.5",
|
|
23
46
|
"rimraf": "^6.1.2",
|
|
47
|
+
"sinon": "^21.0.1",
|
|
48
|
+
"ts-mocha": "^11.1.0",
|
|
24
49
|
"ts-node": "^10.9.2",
|
|
25
50
|
"ts-node-dev": "^2.0.0",
|
|
26
51
|
"typescript": "^5.9.3"
|