-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrateLimiter.js
68 lines (55 loc) · 1.92 KB
/
rateLimiter.js
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
// rateLimiter.js
const db = require('./database');
const userRequests = {}; // In-memory store for request counts
const userTokens = {}; //In-memory store for token counts.
async function checkRateLimit(user) {
const now = Date.now();
const minute = 60 * 1000;
const userId = user.id;
if (!userRequests[userId]) {
userRequests[userId] = { count: 0, lastReset: now };
userTokens[userId] = { count: 0, lastReset: now };
}
// Reset counts if a minute has passed
if (now - userRequests[userId].lastReset > minute) {
userRequests[userId] = { count: 0, lastReset: now };
userTokens[userId] = { count: 0, lastReset: now};
}
if (userRequests[userId].count >= user.requestsPerMinute) {
return false; // Rate limit exceeded (requests)
}
return true; // Rate limit not exceeded
}
async function updateRequestCount(user) {
const userId = user.id;
if (userRequests[userId]) { //Although it's checked previously, it's good to check it again.
userRequests[userId].count++;
}
}
async function checkTokenLimit(user, tokens) {
const now = Date.now();
const minute = 60 * 1000;
const userId = user.id;
if(!userTokens[userId]) {
userTokens[userId] = { count: 0, lastReset: now };
}
// Reset counts if a minute has passed
if (now - userTokens[userId].lastReset > minute) {
userTokens[userId] = { count: 0, lastReset: now};
}
if (userTokens[userId].count + tokens >= user.tokensPerMinute) {
return false; // Rate limit exceeded (tokens)
}
return true;
}
async function updateTokenCount(user, tokens) {
const userId = user.id;
if(userTokens[userId]) { // Double check for safety
userTokens[userId].count += tokens;
}
}
async function updateUserCost(user, cost) {
user.totalCost += cost;
await user.save();
}
module.exports = { checkRateLimit, updateRequestCount, checkTokenLimit, updateTokenCount, updateUserCost };