Skip to content

Commit 32de4a9

Browse files
committed
feat(helper): add rate limiter to control command usage
- Implemented `RateLimiter` class to manage rate limiting of commands. - Added `rateLimits` map to track command usage per user. - Introduced `COMMAND_LIMIT` and `TIME_FRAME` for rate limiting constraints. - Implemented `initCleanup` method for periodic cleanup of old rate limit entries. - Added `limit` method to enforce rate limiting based on user command count and time frame. - Set up periodic cleanup task with `CLEANUP_INTERVAL` to remove outdated entries.
1 parent 0cd3f8f commit 32de4a9

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

src/helper/RateLimiter.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
interface RateLimitEntry {
2+
lastCommandTime: number;
3+
commandCount: number;
4+
}
5+
6+
export class RateLimiter {
7+
private static rateLimits: Map<number, RateLimitEntry> = new Map();
8+
private static COMMAND_LIMIT = 5; // Max commands allowed
9+
private static TIME_FRAME = 10000; // Time frame in milliseconds (10 seconds)
10+
private static CLEANUP_INTERVAL = 60000; // Cleanup interval in milliseconds (1 minute)
11+
12+
// Initializes the cleanup task
13+
static initCleanup() {
14+
setInterval(() => {
15+
const currentTime = Date.now();
16+
for (const [userId, entry] of this.rateLimits.entries()) {
17+
if (currentTime - entry.lastCommandTime > this.TIME_FRAME) {
18+
this.rateLimits.delete(userId);
19+
}
20+
}
21+
}, this.CLEANUP_INTERVAL);
22+
}
23+
24+
// Rate limit checking logic
25+
static limit(userId: number): boolean {
26+
const currentTime = Date.now();
27+
const entry = this.rateLimits.get(userId);
28+
29+
if (entry) {
30+
if (currentTime - entry.lastCommandTime > this.TIME_FRAME) {
31+
// Reset if the time frame has passed
32+
this.rateLimits.set(userId, {
33+
lastCommandTime: currentTime,
34+
commandCount: 1,
35+
});
36+
return true;
37+
}
38+
39+
if (entry.commandCount < this.COMMAND_LIMIT) {
40+
// Increment the command count
41+
entry.commandCount += 1;
42+
this.rateLimits.set(userId, entry);
43+
return true;
44+
} else {
45+
// Rate limit exceeded, silently return false
46+
return false;
47+
}
48+
} else {
49+
// First command from the user
50+
this.rateLimits.set(userId, {
51+
lastCommandTime: currentTime,
52+
commandCount: 1,
53+
});
54+
return true;
55+
}
56+
}
57+
}
58+
59+
// Initialize the cleanup task
60+
RateLimiter.initCleanup();

0 commit comments

Comments
 (0)